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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…