#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;
}
实现简单的map
最新推荐文章于 2024-07-25 14:10:57 发布