如何获取std :: vector指向原始数据的指针? [英] How to get std::vector pointer to the raw data?

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

问题描述

我想使用std :: vector作为一个字符数组。

Im trying to use the std::vector as a char array.

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

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 use 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 or etc).

我试过:

process_data(&something);

并且:

process_data(&something.begin());

但是它返回一个指向乱码数据的指针,后者给出警告:警告C4238:使用非标准扩展名:类别值用作左值

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指向原始数据的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆