实现简单的map

#include <iostream>
#include <string>
#include <vector>

class SimpleMap {
private:
    std::vector<std::pair<std::string, int>> data;

public:
    void insert(const std::string& key, int value) {
        // 查找是否已经存在相同的键
        for (auto& entry : data) {
            if (entry.first == key) {
                entry.second = value;  // 更新值
                return;
            }
        }
        // 如果不存在,则插入新的键值对
        data.push_back(std::make_pair(key, value));
    }

    int getValue(const std::string& key) {
        // 查找并返回对应键的值,如果找不到返回一个默认值(例如 -1)
        for (const auto& entry : data) {
            if (entry.first == key) {
                return entry.second;
            }
        }
        return -1; // 默认值
    }
};

int main() {
    SimpleMap myMap;

    myMap.insert("apple", 5);
    myMap.insert("banana", 3);
    myMap.insert("orange", 7);

    std::cout << "Number of apples: " << myMap.getValue("apple") << std::endl;
    std::cout << "Number of bananas: " << myMap.getValue("banana") << std::endl;

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
map是STL库中的一个关联容器,它能够把一些键值和其关联起来。在C++中,可以通过创建一个map对象来使用这个容器,以实现快速且方便的数据查找和存储。 在实现map的过程中,我们需要注意以下几点: 1. 头文件 使用map时需要引入C++中的map头文件,即#include<map>。 2. 命名空间 因为map属于STL库,所以在使用时需要在命名空间std中定义。 3. 关键字 map的关键字是唯一的,需要用unique的关键字来约束。 下面是一个简单实现map的例子,包括了定义、插入、遍历等操作: #include <iostream> #include <map> using namespace std; int main() { //定义一个map map<int, string> myMap; //在map中插入元素 myMap.insert(pair<int, string>(1, "apple")); myMap.insert(pair<int, string>(2, "banana")); myMap.insert(pair<int, string>(3, "orange")); myMap.insert(pair<int, string>(4, "grape")); //遍历map中的所有元素 for(map<int, string>::iterator it = myMap.begin(); it != myMap.end(); it++) { cout << it->first << ": " << it->second << endl; } //通过key访问value cout << "The value of key 3 is: " << myMap[3] << endl; //通过key修改value myMap[3] = "lemon"; cout << "After modified, the value of key 3 is: " << myMap[3] << endl; //删除指定的元素 myMap.erase(2); //再次遍历map中的所有元素 for(map<int, string>::iterator it = myMap.begin(); it != myMap.end(); it++) { cout << it->first << ": " << it->second << endl; } return 0; } 运行结果如下所示: 1: apple 2: banana 3: orange 4: grape The value of key 3 is: orange After modified, the value of key 3 is: lemon 1: apple 3: lemon 4: grape 以上就是一个简单map实现的例子。通过使用map,我们可以快速有效地存储和查询数据,实现了高效的数据管理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值