来自C数组的STL数组无需复制

Toh*_*iko 2 c++

有没有办法在STL容器中封装固定大小的C数组?换句话说,假设我有一个arrC大小的C数组size,我想要一个容器(不涉及复制),它使用arrC但实现了常用的函数和迭代器.这是我正在考虑的用例:

int arrC[] = {1,2,3,4,5,6};
auto myarr = c_array(arrC, 6);   // The data is not saved internally here, just the pointer and the size
for (auto itr=myarr.begin();itr!=myarr.end();++itr)
     std::cout << *itr << std::endl;
Run Code Online (Sandbox Code Playgroud)

当然,我知道这可能是不安全的,因为我可以释放arrC.

编辑:我需要这个的原因是因为我的C++为其他语言(包括Python)提供了一个C接口,我希望能够处理传递给我的C++函数的数据,而不必复制它.

Use*_*ess 5

但实现了通常的功能......

你的意思是一样的阵列过载std::beginstd::end,这使新型for循环自动工作?

...和迭代器

事实上,原始指针是自动RandomAccessIterators,因为这是迭代器的设计方式?


也就是现代成语

int a[] = {1, 2, 3, 4, 5, 6};
// demonstrate that the overloads exist ...
auto b = std::begin(a);
auto e = std::end(a);
// and that b,e work correctly as InputIterators ...
std::cout << "distance=" << (std::distance(b, e)) << '\n';
std::cout << "elements=" << (sizeof(a)/sizeof(a[0])) << '\n';
// and further that they're explicitly described as RandomAccessIterators ...
std::cout << "random access="
    << std::is_same<std::iterator_traits<decltype(b)>::iterator_category,
                    std::random_access_iterator_tag>::value << '\n';
// and finally that new-style for just works ...
std::cout << "{";
for (auto i : a) {
    std::cout << i << ',';
}
std::cout << "}\n";
Run Code Online (Sandbox Code Playgroud)

将给出预期的输出:

distance=6
elements=6
random access=1
{1,2,3,4,5,6,}
Run Code Online (Sandbox Code Playgroud)

如果你想写的话,你运气不好

for (auto i = a.begin(); i != a.end(); ++i)
Run Code Online (Sandbox Code Playgroud)

相反,但为什么你呢?