c++ - 来自 C 数组的 STL 数组,无需复制

标签 c++

有没有办法在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/

相关文章:

c++ - 如何在 C++ 和 Unix 中获得堆栈溢出?

c++ - 0xC0000005 : Access violation reading location 0x0000000000000000

C++11:无法将参数从 'T *const' 转换为 'T *&&'

c++ - auto_ptr 到普通指针的转换

c++ - 二进制数据作为命令行参数

c++ - 当 `this` 变为 nullptr 时,如何在类成员线程中处理 quick_exit?

c++ - 在另一个进程中销毁共享的 std::vector

c++ - QKeySequence::Quit 快捷方式在 Windows 中不起作用

Android:使用 OMXCodec 作为 MediaSource 时 MPEG4Writer 无法启动

c++ - 是否有一些 escaped_list_separator 反向函数?