Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a pointer to the first element in an std::vector?

Tags:

c++

vector

People also ask

How do you access a pointer to a vector?

An alternative method uses a pointer to access the vector. w = new std::vector<int>(); The new operator creates a new, empty vector of ints and returns a pointer to that vector. We assign that pointer to the pointer variable w , and use w for the remainder of the code to access the vector we created with new .

How do you pop to the beginning of a vector?

To remove first element of a vector, you can use erase() function. Pass iterator to first element of the vector as argument to erase() function.

Which function returns a reference to the first element in a vector?

std::vector::front Returns a reference to the first element in the vector. Unlike member vector::begin, which returns an iterator to this same element, this function returns a direct reference.


C++11 has vec.data() which has the benefit that the call is valid even if the vector is empty.


&mv_vec[0]

or

&my_vec.front()


my_vec.empty() ? 0 : &my_vec.front()

If you would like an std::out_of_range to be thrown if vector is empty, you could use

&my_vec.at(0)

&*my_vec.begin()

or

&mv_vec[0]

By taking the address of the first element, with &vec[0], as the standard (since C++03, I think) demands continous storage of std::vector elements.