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?
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?
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)
std::vector<char> chars;
char* char_arr = chars.data(); // &chars[0]