在C++中获取Vector的一部分,类似于指向C数组中间的指针

Get part of Vector in C++ like pointer to middle of C array

本文关键字:数组 指针 中间 类似于 C++ 获取 Vector 一部分      更新时间:2023-10-16

我是C++的新手(尽管我也是C的新手),我已经写了一些代码,在这些代码中,我将文件读取为char Vector。然后,我需要使用这个向量的块,并将下一个块传递给适当的类进行处理。

在C中,我只需要制作一个char数组,然后沿着块移动一个指针。基本上,为了处理类,我可以将指针位置视为一个"新"数组,而且它很有效,因为我根本不需要复制数据。

例如:

char arr[100];
char *pa = &arr[0];
char *pa_half = &arr[50];
//pass pa somewhere and pa_half elsewhere for processing

我或多或少想要C++中的这种行为。每次都需要初始化新的矢量吗?如果是,这是否意味着我必须复制数据?

非常感谢!

您可以用std::vector:做同样的事情

std::vector<char> arr(100);
char *pa = &arr[0];
char *pa_half = &arr[50];
//pass pa somewhere and pa_half elsewhere for processing

或者如果您使用iterator:

std::vector<char> arr(100);
auto pa = arr.begin();
auto pa_half = pa + 50;
//pass pa somewhere and pa_half elsewhere for processing

请注意,如果std::vector被销毁或重建,指针或迭代器将变为无效。

您可以使用std::string来存储从文件中读取的数据,这对于存储字符串数据来说是直观的。永远记住,任何c++STL数据结构都假设在扩展时调整底层数据的大小和重新定位,并使之前的任何指针/迭代器无效。因此,在STL数据结构内部获取指针/迭代器,修改数据结构并期望指针/迭代器有效是不正确的。

所以,只要您在从文件中读取字符串后不更改其内容。下面的代码应该可以正常工作。

std::string arr;
arr.reserve(MAX_FILE_SIZE); // for efficient read to avoid frequent relocation.
.... read file in the std::string arr...
char *pa = arr.c_str() + 0;
char *pa_half = arr.c_str() + 50;
.... pa and pa_half are valid till you do not change string arr or relocation does not happen, if array is std::string or std::vector ... 
//pass pa somewhere and pa_half elsewhere for processing

如果您想使用指针本身。&vec.front()将返回向量的实际指针。