- 工作中需要用到一个有序的map,自定义一个
- 调用方法
int main() {
OrderedMap<std::string, bool> myMap;
myMap.insert("2e74a2da-9ccd-4a11-adb0-0f1f03332a36", true);
myMap.insert("b2f18d05-9196-4ae3-a046-d0db2d4e3dff", true);
myMap.insert("13a40337-ba54-4578-88b4-333fb00bb3a0", false);
myMap.insert("6fc2aa81-5f16-49ac-b156-e3b52452f6e2", true);
// 输出插入顺序
for (const auto& pair : myMap.getData()) {
std::cout << pair.first << ": " << std::boolalpha << pair.second << std::endl;
}
// 通过 key 查找 value
std::cout << "Value of '13a40337-ba54-4578-88b4-333fb00bb3a0': " << std::boolalpha << myMap.at("13a40337-ba54-4578-88b4-333fb00bb3a0") << std::endl;
return 0;
}
-
输出效果
-
类的定义
template <typename Key, typename Value>
class OrderedMap {
public:
void insert(const Key& key, const Value& value) {
// 检查 key 是否已存在
auto it = keyToIndex.find(key);
if (it != keyToIndex.end()) {
// 如果存在则更新 value
data[it->second].second = value;
}
else {
// 如果不存在则添加新的 key-value 对
data.emplace_back(key, value);
keyToIndex[key] = data.size() - 1;
}
}
const Value& at(const Key& key) const {
// 通过 key 查找元素下标
auto it = keyToIndex.find(key);
if (it == keyToIndex.end()) {
throw std::out_of_range("Key not found");
}
return data[it->second].second;
}
bool find(const Key& key) const {
// 通过 key 查找元素下标
auto it = keyToIndex.find(key);
return it != keyToIndex.end();
}
const std::vector<std::pair<Key, Value>>& getData() const {
return data;
}
void swap(OrderedMap& other) {
using std::swap;
swap(data, other.data);
swap(keyToIndex, other.keyToIndex);
}
size_t size() const {
return data.size();
}
private:
std::vector<std::pair<Key, Value>> data;
std::unordered_map<Key, size_t> keyToIndex;
};