简体   繁体   中英

Getting array from std:vector

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)

  • be wary about holding pointers to this data, as the pointer can be invalidated if the vector is modified.
std::vector<char> chars;
char* char_arr = chars.data(); // &chars[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM