Md Faisal
Md Faisal

Reputation: 2991

Conversion of string array to vector of string type

I want to initialize a vector with following data of arr for that i have to initialize an array of string type and copy its value to vector string this is how i am doing it

it gives lots of errors

string arr[6][8]={
"AAAAAAAA",
"ABWBWBWA",
"ABWBWBWA",
"ABWBWBWA",
"ABWBWBWA",
"AAAAAAAA"};
vector<string> v(arr,arr+sizeof(arr)/sizeof(string));   

I have done it for int array and vector of int type. Like this,

int vv[]={0,0,0,8};
vector<int> v(vv,vv+sizeof(vv)/sizeof(int));        

and it works perfectly for this type but for string type its not working.

Upvotes: 1

Views: 4345

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153860

The type of arr is actually not string but char[6][8] (it is odd this compiles because you are initializing the members of this array with char[9] objects: the string literals include a terminating '\0' character). To properly get the size of a statically size arrays I always recommend not to use this C hack of using sizeof(). Instead, use a function template like this (in fact, I just included the size() template because you used the size; using begin() and end() to get iterators is superior):

template <typename T, int Size> int size(T (&array)[Size]) { return Size; }
template <typename T, int Size> T* begin(T (&array)[Size]) { return array; }
template <typename T, int Size> T* end(T (&array)[Size])   { return array + Size; }
...
std::vector<std::string> v(begin(arr), end(arr));

In C++2011 begin() and end() functions are part of the standand C++ library. Of course, with C++2011 you could directly use initializer lists.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477150

Your array makes no sense. It should be:

std::string arr[] = {
  "AAAAAAAA",
  "ABWBWBWA",
  "ABWBWBWA",
  "ABWBWBWA",
  "ABWBWBWA",
  "AAAAAAAA" };

Then

std::vector<std::string> v(arr, arr + sizeof(arr) / sizeof(std::string));

should work as expected.

Alternatively you can fix the 6 and say v(arr, arr + 6);.

In modern C++, however, you would just say,

std::vector<std::string> v {
  "AAAAAAAA",
  "ABWBWBWA",
  "ABWBWBWA",
  "ABWBWBWA",
  "ABWBWBWA",
  "AAAAAAAA"
};

Upvotes: 5

Related Questions