简体   繁体   English

初始化 Pair 的向量<int,int>带有 emplace_back</int,int>

[英]Initilize a vector of Pair<int,int> with emplace_back

I want to initialize a vector of integer pairs while specifying its size (I have to use this structure).我想在指定其大小的同时初始化 integer 对的向量(我必须使用此结构)。 I tried:我试过了:

vector<pair<int, int>> container;
container.emplace_back(size);

And:和:

container.emplace_back(size, make_pair(0, 0));

But I keep having this error:但我一直有这个错误:

error: no matching function for call to 'std::pair<int, int>::pair(long long unsigned int&, std::pair<int, int>)'

Is there any solution or different approach?有什么解决方案或不同的方法吗?

Thank you!谢谢!

emplace_back forwards its parameters to the elements constructor. emplace_back将其参数转发给元素构造函数。 std::pair<int,int> has no constructor that takes a size and a pair, hence the error. std::pair<int,int>没有采用大小和对的构造函数,因此出现错误。 To emplace an element:放置一个元素:

std::vector<std::pair<int, int>> container;
container.emplace_back(0,0);

However, if you want to construct a vector of certain size upfront, you need not emplace elements, because they are already there:但是,如果您想预先构造一个特定大小的向量,则不需要放置元素,因为它们已经存在:

std::vector<std::pair<int, int>> container(size);
container[42] = make_pair(1,2);   // 42 < size   !

I'm guessing what you really want is something like:你真正想要的是:

vector<pair<int, int>> container(size);

This will initialize the vector constainer with size number of default-constructed elements.这将使用默认构造元素的size数初始化向量constainer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM