简体   繁体   中英

How to iterate values in set<pair<int,int> >st by using set<pair<int,int> >::iterator it?

I am using pair in set and want to print values and my compiler always shows errors in "code 1" but it runs successfully in "code 2" .

I know that, these two procedure are same to access a set without a pair, but i faced problem using pair into a set.

I am using Windows 10 + Intel and using "codeblocks" IDE.

code 1:

set < pair< int,int> >::iterator it;
for(it=st.begin();it!=st.end();it++){
    cout << *(it.first) << " " << *(it.second) << endl ;//error shows here
}

code 2:

set< pair < int,int > >::iterator it;
for(it : st){
  cout << it.first << " " << it.second << endl ;
}

In "code 2", my program runs successfully but in "code 1" it shows error pointed to the commented line.

it is an iterator refering to a pair, In order to access the pair you need to dereference the iterator first.

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

or better

cout << it->first << " " << it->second << endl ;

EDIT: If you have c++17 support.

for(auto [first, second] : st)
     std::cout<<first<<" "<<second;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM