Adding to a vector of pair

后端 未结 10 1416
悲哀的现实
悲哀的现实 2021-01-30 05:19

I have a vector of pair like such:

vector> revenue;

I want to add a string and a doub

相关标签:
10条回答
  • 2021-01-30 05:31

    Using emplace_back function is way better than any other method since it creates an object in-place of type T where vector<T>, whereas push_back expects an actual value from you.

    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);
    
    0 讨论(0)
  • 2021-01-30 05:34

    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.

    0 讨论(0)
  • 2021-01-30 05:35

    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);
    
    0 讨论(0)
  • 2021-01-30 05:36

    Use std::make_pair:

    revenue.push_back(std::make_pair("string",map[i].second));
    
    0 讨论(0)
  • 2021-01-30 05:38

    You can use std::make_pair

    revenue.push_back(std::make_pair("string",map[i].second));
    
    0 讨论(0)
  • 2021-01-30 05:43
    revenue.push_back(pair<string,double> ("String",map[i].second));
    

    this will work.

    0 讨论(0)
提交回复
热议问题