0
#include <bits/stdc++.h>

using namespace std; 
typedef pair <int , vector<int> > pairs;
 

void solve () { 
    set <pairs> s ;
    for ( int i =0; i<5; i++){
        vector<int> v ;
        for ( int j = i; j<=i + i; j++){
            v.push_back(j) ;
        }
        s.insert ({i,v}) ;
    }

    

    // printing values of set
    for ( auto &x : s) {
        cout<<x.first<<": ";
        for ( auto i : x.second) 
            cout<<i<<" " ;
        cout<<endl;
    }

    // searching for this <int,vector> pair in set 
    // to modify it
    int val = 2 ;
    vector<int> vf = {2,3,4} ;
    auto it = s.find ( {val, vf} ) ;

    
    if ( it != s.end() ) {

        // printing some random stuff about this set element 
        cout<<(*it).first<<endl ;
        cout<<(*it).second.size()<<endl ;

        // inserting another value at the end of this vector 
        (*it).second.push_back(10001);
    }

}


int main () {
        solve() ;

    return 0;
}

So in this code i m unable to modify the vector present in a set of pair of < int, vector<int> >

I found out that these lines of code works fine :

cout<<(*it).first<<endl ;
cout<<(*it).second.size()<<endl ;

but I m facing error to execute this line :

(*it).second.push_back(10001);

Why isn't push_back() operation not working here ? Any easy way to fix it ?

humbleCodes
  • 109
  • 1
  • 6
  • 2
    Elements of a `std::set` are const, for reasons described [here](https://stackoverflow.com/questions/908949/what-happens-when-you-modify-an-element-of-an-stdset). Essentially, if you could change them, you could invalidate the ordering of the elements the set uses to keep track of things. Perhaps you want an `unordered_map>` instead? – Nathan Pierson Jun 18 '22 at 16:26
  • You can also remove the element from the set, change it, and add it back to the set. A `std::set` is an ordered container - the location of every element is determined by its value, so you can not change an element's value after its location has been determined. – Drew Dormann Jun 18 '22 at 16:50

0 Answers0