溫馨提示×

怎么用c++迭代器iterator遍歷map

小億
304
2023-10-14 08:32:34
欄目: 編程語言

使用C++迭代器iterator遍歷map的方法如下:

  1. 使用begin()函數獲取map的起始迭代器。

  2. 使用end()函數獲取map的結束迭代器。

  3. 使用循環結構(如for循環、while循環)和迭代器逐個遍歷map中的元素,直到迭代器達到結束位置為止。

  4. 在循環中使用迭代器的first和second成員訪問map中的鍵和值。

以下是一個示例代碼:

#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
// 使用迭代器遍歷map
std::map<int, std::string>::iterator it;
for (it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;
}
return 0;
}

運行結果:

Key: 1 Value: One
Key: 2 Value: Two
Key: 3 Value: Three

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女