Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the address of the std::vector buffer start most elegantly?

Tags:

c++

stl

vector

I want to use std::vector for dynamically allocating memory. The scenario is:

int neededLength = computeLength(); // some logic here

// this will allocate the buffer     
std::vector<TCHAR> buffer( neededLength );

// call a function that accepts TCHAR* and the number of elements
callFunction( &(buffer[0]), buffer.size() );

The code above works, but this &(buffer[0]) looks ugly. Is there a more elegant way to achieve the same?

like image 504
sharptooth Avatar asked Aug 27 '09 07:08

sharptooth


People also ask

Is std::vector fast?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

How do you initialize a std::vector?

You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.

What does std::vector Reserve do?

std::vector class provides a useful function reserve which helps user specify the minimum size of the vector.It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory.


1 Answers

It's really odd that nobody know this!!! in C++11 you could use:

buffer.data()

it could get the address of the vector I have test it:

vector<char>buffer;
buffer.push_back('w');
buffer.push_back('h');
buffer.push_back('a');
buffer.push_back('t');
buffer.push_back('\0');
char buf2[10];
memcpy(buf2,buffer.data(),10);

Specification here.

like image 112
hyphen Avatar answered Sep 21 '22 02:09

hyphen