我正在尝试std::vector用作char数组.
我的函数接受一个void指针:
void process_data(const void *data);
Run Code Online (Sandbox Code Playgroud)
在我刚刚使用此代码之前:
char something[] = "my data here";
process_data(something);
Run Code Online (Sandbox Code Playgroud)
哪个按预期工作.
但现在我需要动态性std::vector,所以我尝试了这个代码:
vector<char> something;
*cut*
process_data(something);
Run Code Online (Sandbox Code Playgroud)
问题是,如何将char矢量传递给我的函数,以便我可以访问矢量原始数据(无论是哪种格式 - 浮点数等)?
我试过这个:
process_data(&something);
Run Code Online (Sandbox Code Playgroud)
还有这个:
process_data(&something.begin());
Run Code Online (Sandbox Code Playgroud)
但是它返回了指向乱码数据的指针,后者发出了警告:warning C4238: nonstandard extension used : class rvalue used as lvalue.
我的问题很简单:std :: vector元素是否保证是连续的?在order word中,我可以使用指向std :: vector的第一个元素的指针作为C数组吗?
如果我的记忆力很好,那么C++标准就没有这样的保证.但是,如果元素不连续,那么std :: vector要求几乎不可能满足它们.
有人可以澄清一下吗?
例:
std::vector<int> values;
// ... fill up values
if( !values.empty() )
{
int *array = &values[0];
for( int i = 0; i < values.size(); ++i )
{
int v = array[i];
// do something with 'v'
}
}
Run Code Online (Sandbox Code Playgroud) 当您想要将std :: vector作为C数组访问时,您可以从至少四种不同的方式中进行选择,如本例中所示:
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(42);
vec.push_back(24024);
{
int* arr = vec.data();
cout << arr << endl; /* output: 0x9bca028 */
cout << arr[3] << endl; /* output : 24024 */
}
{
int* arr = &vec.front();
cout << arr << endl; /* output: 0x9bca028 */
cout << arr[3] << endl; /* output : 24024 */
}
{
int* arr = &vec[0];
cout << arr << endl; /* …Run Code Online (Sandbox Code Playgroud)