c++ map

#include <iostream>
#include <map>
using namespace std;
int main()
{
   map<int, int> edges;
    bool a;
   edges.insert(pair<int, int>(000, 100));
    a=edges.insert(pair<int, int>(002, 300)).second;
    std::cout<<a<<endl;
   a=edges.insert(pair<int, int>(002, 345)).second;
    std::cout<<a<<endl;
   if(a==false)// insert fail, updata, erase, then insert
   {
      edges.erase(002); 
        a=edges.insert(pair<int, int>(002, 345)).second;
        std::cout<<a<<endl;
   }
   
   map<int, int>::iterator v = edges.begin();
   while (v != edges.end())
   {
      cout << v->first << "," << v->second << endl;
      v++;
   }
   return 0;
}

03-08
### C++ 中 `map` 容器的使用方法 #### 创建和初始化 `map` 在C++中,`map` 是标准模板库(STL)的一部分,用于存储键值对的数据结构。创建一个简单的整数到字符串映射可以如下所示: ```cpp #include <iostream> #include <map> using namespace std; // 初始化 map 的几种方式 void createAndInitializeMap() { // 方式一:通过下标操作符 [] map<int, string> stuMap; stuMap[1001] = "Jason"; // 方式二:使用 insert 方法配合 pair 或 make_pair 插入元素 stuMap.insert(pair<int, string>(1002, "Helen")); stuMap.insert(make_pair(1003, "Steve"))[^2]; } ``` #### 遍历 `map` 为了遍历整个 `map`,可以采用多种方式进行访问。这里展示如何利用范围for循环以及迭代器来实现这一点。 ```cpp // 使用范围 for 循环遍历 map void traverseWithRangeFor(map<int, string>& m) { for (auto& elem : m) { cout << "Key: " << elem.first << ", Value: " << elem.second << endl; } } // 使用迭代器遍历 map 并结合 STL 算法 like std::for_each void traverseWithIterator(map<int, string>& m) { auto callback = [](const pair<const int, string>& p) { cout << "Key: " << p.first << ", Value: " << p.second << endl; }; for_each(m.begin(), m.end(), callback)[^1]; } ``` #### 访问特定项 当需要获取某个具体位置上的值时,可以直接通过键名索引或者find函数查找对应的记录。 ```cpp string getValueByKey(const map<int, string>& m, const int key) { if (m.find(key) != m.cend()) { return (*m.find(key)).second; } else { throw runtime_error("Key not found"); } } ``` 上述代码片段展示了基本的操作模式,包括但不限于定义、填充、检索和遍历关联数组型容器——即 `map`。这些功能使得处理具有唯一性的键与其相关联的信息变得简单而高效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值