Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting array from std:vector

Tags:

c++

arrays

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?

like image 336
SkypeMeSM Avatar asked Nov 27 '10 01:11

SkypeMeSM


People also ask

Is std::vector an array?

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.

How do you pass an array of vectors to a function in C++?

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 (*) ?.


1 Answers

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.
like image 53
econoclast Avatar answered Sep 21 '22 07:09

econoclast