添加到对的向量

时间:2011-10-25 23:29:21

标签: c++ vector std-pair

我有vector pair这样的话:

vector<pair<string,double>> revenue;

我想在地图中添加一个字符串和一个double:

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

但由于收入未初始化,因此会出现超出范围的错误。所以我尝试使用vector::push_back这样:

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

但是那说不能采取两个论点。那么我该如何添加vector的{​​{1}}?

10 个答案:

答案 0 :(得分:92)

使用std::make_pair

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

答案 1 :(得分:30)

恕我直言,一个非常好的解决方案是使用c ++ 11 emplace_back函数:

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

它只是创建了一个新元素。

答案 2 :(得分:10)

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

但是那说不能采取两个论点。那么我该如何添加到这个矢量对呢?

你走在正确的道路上,但想一想;你的载体有什么作用?它肯定不会在一个位置包含字符串和int,它包含Pair。所以...

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

答案 3 :(得分:6)

阅读以下文档:

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

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

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

答案 4 :(得分:6)

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

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

答案 5 :(得分:2)

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

这将有效。

答案 6 :(得分:0)

您可以使用std::make_pair

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

答案 7 :(得分:0)

使用emplace_back函数比其他任何方法都要好,因为它可以代替T类型的对象创建其中vector<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);

答案 8 :(得分:0)

许多人建议,您可以使用std::make_pair

但是我想指出另一种方法:

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

push_back()接受一个参数,因此您可以使用“ {}”来实现!

答案 9 :(得分:-1)

尝试使用另一个临时对:

pair<string,double> temp;
vector<pair<string,double>> revenue;

// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);
相关问题