#34196: C++ map iterator 解


alex950301 (alex0301)

學校 : 新北市立新莊高級中學
編號 : 141423
來源 : [140.117.194.239]
最後登入時間 :
2025-10-01 22:51:46

這題使用map比較方便

Ex :

cin >> a >> b ;

map< int , int > mp ;

mp[a] += b ; // a 代表鍵值 , b 代表值

 

要排序時交給map就好了,map內建紅黑樹,可以用迭代器不用自己排

Ex1 :

for( map< int , int > ::iterator it = mp.begin() ; it != mp.end() ; ++it) {

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

}

Ex2 : 

for( const auto& [key , value] : mp ) {

    cout << key << " " << value << endl ;

}