Getting array from std:vector

2019-01-14 14:49发布

问题:

What is the easiest way of getting a char array from a vector?

The way I am doing is getting a string initialized using vector begin and end iterators, and then getting .c_str() from this string. Are there other efficient methods?

回答1:

This was discussed in Scott Meyers' Effective STL, that you can do &vec[0] to get the address of the first element of an std::vector, and since the standard constrains vectors to having contiguous memory, you can do stuff like this.

// some function
void doSomething(char *cptr, int n)
{

}

// in your code
std::vector<char> chars;

if (!chars.empty())
{
    doSomething(&chars[0], chars.size());
}

edit: From the comments (thanks casablanca)

  • be wary about holding pointers to this data, as the pointer can be invalidated if the vector is modified.


回答2:

std::vector<char> chars;
char* char_arr = chars.data(); // &chars[0]