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]
    
    链接地址: http://www.djcxy.com/p/91704.html

    上一篇: 为什么VS2008 std :: string.erase()移动它的缓冲区?

    下一篇: 从std:vector获取数组