C看图学码stdspan
简介lightweight (= 复制成本低,可以值传递) non-owning (= 不负责内存的申请和释放) 视图 是字符范围或者类字符串对象, 视图不拥有资源。如果对象被称为资源的所有者 (memory, file handle, connection, thread, lock, …) 那么 它要为资源的生命负责 (initialization/creation, finalization/destruction)。 动机
我们不希望为只读参数提供额外的拷贝或内存分配。
和std::string_view区别:span是一个模板,可以使用任何用户定义的或基本类型,但string_view不是,表面上看,string_view等价于span。 string_view是只读视图,string_view更接近于span string_view支持类似std::string操作,如 substr, find, compare , ==,<,>。 #include #include #include #include #include #include int main () { char buff[] = "Hello World"; auto sp = std::span(&buff[0], 5); auto sv = std::string_view(&buff[6], 5); std::transform(sp.begin(), sp.end(), sp.begin(), [](char c) { return std::toupper(c); }); for(auto c : sp) std::cout << c; //Hello std::cout << " "; std::cout << sv << std::endl; //World }
https://wandbox.org/nojs/gcc-head https://wandbox.org/nojs/clang-head创建&&接口#include #include #include #include #include #include void print_ints (std::span sp){ // spans in range-based for loops for(auto c : sp) std::cout << c; //Hello std::cout << std::endl; } int main () { std::vector w {0, 1, 2, 3, 4, 5, 6}; std::array a {0, 1, 2, 3}; // 自动推导类型和长度 std::span sw1 { w }; // span std::span sa1 { a }; // span print_ints(sw1); print_ints(sa1); // 显式声明只读视图 std::span sw2 { std::as_const(w) }; print_ints(sw2); // 显式声明类型参数 std::span sw3 { w }; std::span sa2 { a }; std::span sw4 { w }; print_ints(sw3); print_ints(sa2); print_ints(sw4); // 显式声明类型参数和长度 std::span sa3{ a }; print_ints(sa3); // 基于迭代器 std::span s1 {begin(w)+2, 4}; std::span s2 {begin(w)+2, end(w)}; print_ints(s1); print_ints(s2); // 基于span生成span std::span s = w; auto first3elements = s.first(3); auto last3elements = s.last(3); size_t offset = 2; size_t count = 4; auto subs = s.subspan(offset, count); print_ints(s); print_ints(first3elements); print_ints(last3elements); print_ints(subs); //其他接口 if (!s.empty()) { std::cout << "not empty" << std::endl; } if (s.size() < 1024) { std::cout << "size < 1024" << std::endl; } // 索引访问 s[0] = 8; print_ints(s); // 迭代器访问 auto m1 = std::min_element(s.begin(), s.end()); auto m2 = std::min_element(begin(s), end(s)); // 比较span std::vector j {1,2,3,4}; std::vector k {1,2,3,4}; std::span sj {j}; std::span sk {k}; bool memory_same = sk.data() == sj.data(); // false bool values_same = std::ranges::equal(sj,sk); // true std::cout << memory_same << std::endl; std::cout << values_same << std::endl; }