1

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.

0

2 Answers 2

5

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"
};
Sign up to request clarification or add additional context in comments.

7 Comments

can we do that in case of int type also?
std::vector<std::string> v { "AAAAAAAA", "ABWBWBWA", "ABWBWBWA", "ABWBWBWA", "ABWBWBWA", "AAAAAAAA" };
it says error: scalar object ‘v’ requires one element in initializer
@fsl4faisal: You need a modern compiler. In GCC, say -std=c++0x.
cc1plus: error: unrecognized command line option "-std=c++0x"
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.