有没有办法在STL容器中封装一个固定大小的C数组?
换句话说,假设我有一个 C 数组 arrC
尺寸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;
当然,我知道这可能不安全,因为我可以释放 arrC。
编辑:我需要这个的原因是因为我的 C++ 为其他语言(包括 Python)提供了一个 C 接口(interface),我希望能够处理传递给我的 C++ 函数的数据而不必复制它。
最佳答案
but implements the usual functions ...
你的意思是像 std::begin
的数组重载和 std::end
, 使新式 for
循环自动工作?
...and iterators
事实上,原始指针自动成为 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";
将给出预期的输出:
distance=6
elements=6
random access=1
{1,2,3,4,5,6,}
如果你想写,那你就倒霉了
for (auto i = a.begin(); i != a.end(); ++i)
相反,但你为什么要这么做?
关于c++ - 来自 C 数组的 STL 数组,无需复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43236477/