在C++中获取Vector的一部分,类似于指向C数组中间的指针
Get part of Vector in C++ like pointer to middle of C array
我是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()
将返回向量的实际指针。
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”