对初始化的 C++ 向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11103652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:51:25  来源:igfitidea点击:

C++ vector of pairs initialization

c++vectorstd-pair

提问by MyNameIsKhan

I have

我有

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

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

我想将所有对初始化为 -1,-1。

回答by mfontanini

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.

该构造函数的第二个参数是 N 对将采用的初始值。

回答by DomTomCat

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

可以使用 (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:

在旧的 C++ 标准中,这样的事情会起作用:

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