Adding to a vector of pair

可紊 提交于 2019-12-03 01:36:06

问题


I have a vector of pair like such:

vector<pair<string,double>> revenue;

I want to add a string and a double from a map like this:

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

But since revenue isn't initialized, it comes up with an out of bounds error. So I tried using vector::push_back like this:

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

But that says cannot take two arguments. So how can I add to this vector of pair?


回答1:


Use std::make_pair:

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



回答2:


IMHO, a very nice solution is to use c++11 emplace_back function:

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

It just creates a new element in place.




回答3:


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

But that says cannot take two arguments. So how can I add to this vector pair?

You're on the right path, but think about it; what does your vector hold? It certainly doesn't hold a string and an int in one position, it holds a Pair. So...

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



回答4:


Or you can use initialize list:

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



回答5:


Read the following documentation:

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

or

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

I think that will help. Those sites are good resources for C++, though the latter seems to be the preferred reference these days.




回答6:


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

this will work.




回答7:


You can use std::make_pair

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



回答8:


Try using another temporary pair:

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

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


来源:https://stackoverflow.com/questions/7897050/adding-to-a-vector-of-pair

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