我们不希望为只读参数提供额外的拷贝或内存分配。
和std::string_view区别:
#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;
}
页面更新:2024-05-05
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号