C++ vector of pairs initialization

心已入冬 提交于 2020-05-25 03:23:53

问题


I have

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

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


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/11103652/c-vector-of-pairs-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!