Search code examples
c++c++11c++17stdvectorstd-pair

How to update recently entered element in std::vector<pair<int, int>>?


How can one update the value for pairs in any vector class of pair type?

Example :

V.push_back(make_pair(1, 3));

If I wish to update 3 to say 5 or something, how do I achieve that?


Solution

  • Assuming that you want to update the last std::pair input just after inserting to the std::vector<std::pair<int, int>>.

    In you can make use of second overload of std::vector::emplace_back, which returns a reference to the element inserted:

    #include <vector>
    
    std::vector<std::pair<int, int>> vec;
    auto &pair = vec.emplace_back(1, 3); // construct in-place and get the reference to the inserted element
    pair.second = 5;                     // change the value directly like this
    

    Update:

    In , the same can be achieved by the std::vector::insert member, which returns iterator pointing to the inserted element.

    #include <vector>
    
    std::vector<std::pair<int, int>> vec;
    // insert the element to vec and get the iterator pointing to the element
    const auto iter = vec.insert(vec.cend(), { 1, 3 });
    iter->second = 5; // change the value