加到一对向量上

Adding to a vector of pair

本文关键字:向量      更新时间:2023-10-16

我有pairvector,类似于:

vector<pair<string,double>> revenue;

我想从这样的地图中添加一个字符串和一个替身:

revenue[i].first = "string";
revenue[i].second = map[i].second;

但由于收入没有初始化,它会出现一个越界错误。所以我试着这样使用vector::push_back

revenue.push_back("string",map[i].second);

但这不能包含两个论点。那么,我如何添加到pairvector

使用std::make_pair:

revenue.push_back(std::make_pair("string",map[i].second));

IMHO,一个非常好的解决方案是使用c++11 template_back函数:

revenue.emplace_back("string", map[i].second);

它只是在适当的位置创建了一个新元素。

revenue.pushback("string",map[i].second);

但这不能包含两个论点。那么我怎样才能把它加到这个向量对上呢?

你走在正确的道路上,但要想一想;你的向量是什么?它当然不会在一个位置上包含字符串和int,而是包含Pair。所以…

revenue.push_back( std::make_pair( "string", map[i].second ) );     

或者您可以使用初始化列表:

revenue.push_back({"string", map[i].second});

阅读以下文档:

http://cplusplus.com/reference/std/utility/make_pair/

http://en.cppreference.com/w/cpp/utility/pair/make_pair

我认为这会有所帮助。这些网站是C++的好资源,尽管后者似乎是目前的首选参考。

revenue.push_back(pair<string,double> ("String",map[i].second));

这会奏效的。

您可以使用std::make_pair

revenue.push_back(std::make_pair("string",map[i].second));

尝试使用另一个临时对:

pair<string,double> temp;
vector<pair<string,double>> revenue;
// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);

使用emplace_back函数比任何其他方法都要好,因为它创建了一个对象来代替类型为Tvector<T>,而push_back需要您提供实际值。

vector<pair<string,double>> revenue;
// make_pair function constructs a pair objects which is expected by push_back
revenue.push_back(make_pair("cash", 12.32));
// emplace_back passes the arguments to the constructor
// function and gets the constructed object to the referenced space
revenue.emplace_back("cash", 12.32);

正如许多人建议的那样,您可以使用std::make_pair

但我想指出另一种同样的方法:

revenue.push_back({"string",map[i].second});

push_back((只接受一个参数,所以可以使用"{}"来实现这一点!