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?
std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed.
void gridlist(std::vector<int> *grid, int rows, int cols){ ..... } int rows=4; int cols=5; std::vector<int> grid[rows][cols]; gridlist(grid,rows,cols); The only method which has worked for me to pass arrays to a function was by pointer (*) ?.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With