如何获取指向原始数据的 std::vector 指针?

时间:2023-05-08
本文介绍了如何获取指向原始数据的 std::vector 指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用 std::vector 作为 char 数组.

I'm trying to use std::vector as a char array.

我的函数接受一个空指针:

My function takes in a void pointer:

void process_data(const void *data);

之前我只是简单地使用这个代码:

Before I simply just used this code:

char something[] = "my data here";
process_data(something);

按预期工作.

但是现在我需要std::vector的动态性,所以我尝试了这个代码:

But now I need the dynamicity of std::vector, so I tried this code instead:

vector<char> something;
*cut*
process_data(something);

问题是,如何将字符向量传递给我的函数,以便我可以访问向量原始数据(无论它是哪种格式 - 浮点数等)?

The question is, how do I pass the char vector to my function so I can access the vector raw data (no matter which format it is – floats, etc.)?

我试过了:

process_data(&something);

还有这个:

process_data(&something.begin());

但是它返回了一个指向乱码数据的指针,后者给出了警告:warning C4238: nonstandard extension used : class rvalue used as lvalue.

But it returned a pointer to gibberish data, and the latter gave warning: warning C4238: nonstandard extension used : class rvalue used as lvalue.

推荐答案

&something 为您提供 std::vector 对象的地址,而不是它持有的数据.&something.begin() 为您提供 begin() 返回的迭代器的地址(正如编译器警告的那样,这在技术上是不允许的,因为 something.begin() 是一个右值表达式,所以不能取它的地址.

&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken).

假设容器中至少有一个元素,则需要获取容器的初始元素的地址,可以通过

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via

  • &something[0]&something.front()(索引 0 处元素的地址),或

  • &something[0] or &something.front() (the address of the element at index 0), or

&*something.begin()(begin() 返回的迭代器所指向的元素地址).

&*something.begin() (the address of the element pointed to by the iterator returned by begin()).

在 C++11 中,std::vector 添加了一个新的成员函数:data().这个成员函数返回容器中初始元素的地址,就像&something.front().这个成员函数的优点是即使容器为空也可以调用它.

In C++11, a new member function was added to std::vector: data(). This member function returns the address of the initial element in the container, just like &something.front(). The advantage of this member function is that it is okay to call it even if the container is empty.

这篇关于如何获取指向原始数据的 std::vector 指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:初始化二维 std::vector 下一篇:将文件读入 std::vector<char> 的有效方法?

相关文章