C++ vector of pairs initialization
Asked Answered
A

3

40

I have

vector< pair<int, int>> myVec (N);

I want to have all pairs initialized to -1,-1.

Ataghan answered 19/6, 2012 at 14:54 Comment(0)
I
61

Here you go:

#include <utility>

vector<pair<int, int>> myVec (N, std::make_pair(-1, -1));

The second argument to that constructor is the initial value that the N pairs will take.

Immerse answered 19/6, 2012 at 14:55 Comment(4)
Worked beautifully, thanks! I have to wait 12 minutes to accept answer though.Ataghan
is it possible to initialize vector to different values, i.e. provide pair for each vector element?Mockheroic
Yes, using initializer lists: vector<pair<int, int>> myVec = { {-1, -1}, {2, 5}, {3, 10} };Immerse
initializer lists requires c++0x standard.Plummy
T
31

Just to add some additional info (not quite what the Asker wanted, but asked for in the comments of the accepted answer):

Individual initialization can be done with (C++11):

std::vector<std::pair<int, int> > vec1 = { {1, 0}, {2,0}, {3,1} };

std::vector<std::pair<int, int> > vec2 = {std::make_pair(1, 0),
                                           std::make_pair(2, 0),
                                           std::make_pair(3, 0)};

In old C++ standards, something like this would work:

const std::pair<int,int> vals[3] = {std::make_pair(1, 0),
                                    std::make_pair(2, 0),
                                    std::make_pair(3, 0)};
std::vector<std::pair<int, int> > vec2 (&vals[0], &vals[0] + 3);
Teaspoon answered 8/8, 2017 at 8:48 Comment(0)
C
2

If you want to initialize all pairs, maybe you can do something like this:

vector<pair<int, int>> directions {
    {1, 0},
    {-1, 0},
    {0, 1},
    {0, -1},    
};

Here, 4 pairs have been initialized as such.

Creepie answered 25/5, 2021 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.