0

I need to initialize vector in class this way

vector<string> test("hello","world");

But when I do it, compiler recognize it as an function and give me errors like error: expected identifier before string constant etc.

When I do it this way

vector<string> test = ("hello","world") 

it is ok.. Is there some way how to do it in vector<string> test("xx") way?

1
  • 6
    Are you sure, that vector<string> test = ("hello","world") does what you think it does? Commented Nov 30, 2012 at 18:03

1 Answer 1

5

There is no such constructor in std::vector that would allow you to initialize it like that. And your second example evaluates to "world" (that's what the , operator does) which is what ends up in the vector.

If you want to initialize the vector at declaration time, use an initializer list:

vector<string> test = {"hello", "world"};

Make sure you build your source code in C++-11 mode for this to work. If you don't have a C++-11 compatible compiler, then you must add the values to the vector afterwards:

vector<string> test;
test.push_back("hello");
test.push_back("world");
Sign up to request clarification or add additional context in comments.

4 Comments

or just string arr[] = {"hello","world"}; and vector<string> test(arr,arr + 2);
Actually, the comma operator doesn't do what you think it does either. His second example evaluates to "world".
string fonoArgs[] = {"1","2","3"}; vector<string> fonoS(fonoClass::fonoArgs,fonoClass::fonoArgs+3); This is giving me errors error: ‘fonoClass::fonoArgs’ is not a type
@user1751550 I've no idea what fonoClass is supposed to be. Anyway, don't use that approach as it introduces a copy of your vector in the form of a plain array. Which is a waste. Just use an initializer list (you didn't mention what compiler you're using.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.