我们可以使用以下不同的方法遍历map和unordered_map。
使用基于范围的for循环
map
// CPP program to traverse a map using range
// based for loop
#include
using namespace std;
int main()
{
int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
map m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
cout << "Element Frequency" << endl;
for (auto i : m)
cout << i.first << " " << i.second
<< endl;
return 0;
}
unordered_map
// CPP program to traverse a unordered_map using
// range based for loop
#include
using namespace std;
int main()
{
int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
unordered_map m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
cout << "Element Frequency" << endl;
for (auto i : m)
cout << i.first << " " << i.second
<< endl;
return 0;
}
map
// CPP program to traverse a map using iterators
#include
using namespace std;
int main()
{
int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
map m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
cout << " Element Frequency" << endl;
for (auto i = m.begin(); i != m.end(); i++)
cout << i->first << " " << i->second
<< endl;
return 0;
}
unordered_map
// CPP program to traverse a unordered_map
// using iterators
#include
using namespace std;
int main()
{
int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
unordered_map m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
cout << " Element Frequency" << endl;
for (auto i = m.begin(); i != m.end(); i++)
cout << i->first << " " << i->second
<< endl;
return 0;
}
输出[注意:对于unordered_map,可以将输出行
以任何顺序]
Element Frequency
1 4
2 1
3 2
4 1
使用begin()和end()遍历
地图
// CPP program to traverse a map using iterators
#include
using namespace std;
int main()
{
int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
map m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
cout << " Element Frequency" << endl;
for (auto i = m.begin(); i != m.end(); i++)
cout << i->first << " " << i->second
<< endl;
return 0;
}
unordered_map
// CPP program to traverse a unordered_map
// using iterators
#include
using namespace std;
int main()
{
int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
unordered_map m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
cout << " Element Frequency" << endl;
for (auto i = m.begin(); i != m.end(); i++)
cout << i->first << " " << i->second
<< endl;
return 0;
}
输出[注意:对于unordered_map,可以将输出行
以任何顺序]
Element Frequency
1 4
2 1
3 2
4 1
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。