unordered_map的4种遍历方式(C++)

c++ unordered_map4种遍历方式

此处我通过移到LeetCode上的一道题来演示unordered_map的用法:题目链接
首先看一下题目题解:

int longestPalindrome(string s) {
   unordered_map<char, int> map;
    int ans = 0;
    int flag = 0;
    for(int i = 0; i < s.size(); i++){
        map[s[i]]++;
    }
    for(auto [_, v] : map){
        if(v % 2 == 0){
            ans += v;
        } else{
            flag = 1;
            ans += v - 1;
        }
    }
    if(flag == 1){
        ans += 1;
    }
    return ans;
}

这里定义了一个unordered_map:

for(int i = 0; i < s.size(); i++){
	map[s[i]]++;
}

方式一:值传递遍历

for(pair<char, int> kv : map){
	cout << kv.first << kv.second << endl;
}

可以使用aotu取代pair:

for(auto kv : map){
	cout << kv.first << kv.second << endl;
}

方式二:引用传递遍历

此处需要添加const

for(const pair<char, int>& kv : map){
	cout << kv.first << kv.second << endl;
}

for(pair<const char, int>& kv : map){
	cout << kv.first << kv.second << endl;
}

可以使用aotu取代pair:

for(auto& kv : map){
	cout << kv.first << kv.second << endl;
}

方式三:使用迭代器遍历

for(unordered_map<char, int>::iterator it = map.begin(); it != map.end(); it++){
	cout << it->first << it->second << endl;
}

使用迭代器的话auto会更简洁:

for(auto it = map.begin(); it != map.end(); it++){
	cout << it->first << it->second << endl;
}

方式四:结构化绑定(c++17特性)

值传递:

for(auto [k,v] : map){
	cout << k << v << endl;
}

引用传递:

for(auto& [k,v] : map){
	cout << k << v << endl;
}
for(auto& [_,v] : map){
	cout << v << endl;
}
for(auto& [k,_] : map){
	cout << k << endl;
}

你可能感兴趣的:(C++学习之路,c++,leetcode,unordered_map遍历)