Adam
Adam

Reputation: 10046

initializing vectors with variables, C++

I'd like to be able to initialize vectors using variables like this:

    int min,max;
    scanf("%d %d", &min, &max); 
    vector<int> day(min, max, max);

But when I try I get an error message saying:

IntelliSense: no instance of constructor "std::vector<_Ty, _Alloc>::vector [with _Ty=int, _Alloc=std::allocator]" matches the argument list argument types are: (int, int, int)

Is there any way to get around this problem? I'm using Visual Studio 2013 if that matters. Thanks!

Upvotes: 2

Views: 6714

Answers (2)

Ashwani
Ashwani

Reputation: 2052

You can also do like this:

int min,max;
scanf("%d %d", &min, &max);
int temp[] = {min, max, max};
vector<int> day(temp, temp + sizeof(temp) / sizeof(int));

It will cost you a little extra memory. Both C++98 and C++11 support this.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254741

You need list-initialisation to specify the vector's contents, assuming your compiler supports it:

vector<int> day{min, max, max};

Before C++11, it was rather more tedious:

vector<int> day;
day.push_back(min);
day.push_back(max);
day.push_back(max);

Upvotes: 5

Related Questions