C++使用迭代器遍历map<int>和vector<int>

下面是一个使用迭代器遍历std::map<int, int>的示例代码:

 #include <iostream>
 #include <map>
 int main() {    
 // 创建一个 map,键和值都是 int 类型    std::map<int, int> myMap;    // 插入一些键值对    myMap[1] = 100;    
 myMap[2] = 200;    
 myMap[3] = 300;    
 // 使用迭代器遍历 map   
for (std::map<int, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {     
     // it->first 是键,it->second 是值        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;   
      }    
      // 也可以使用 C++11 的范围 for 循环(更简洁)   
       std::cout << "Using range-based for loop:" << std::endl;    
       for (const auto& pair : myMap) {        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;   
        }   
 return 0;
 }

vector:

#include <iostream>
#include <vector>

int main() {
   // 创建一个 vector,存储 int 类型的元素
   std::vector<int> myVector = {10, 20, 30, 40, 50};

   // 使用迭代器遍历 vector
   for (std::vector<int>::iterator it = myVector.begin(); it != myVector.end(); ++it) {
       // 使用 *it 访问当前元素
       std::cout << "Element: " << *it << std::endl;
   }

   // 也可以使用 C++11 的范围 for 循环(更简洁)
   std::cout << "Using range-based for loop:" << std::endl;
   for (const int& element : myVector) {
       std::cout << "Element: " << element << std::endl;
   }

   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值