如果你想允许大小相同的字符串在你的地图,但不关心他们的相对顺序,然后std::multimap
是一种替代解决方案:
#include <map>
#include <iostream>
#include <string>
struct cmp {
bool operator()(const std::string& a, const std::string& b) const {
return a.size() > b.size();
}
};
int main() {
std::multimap<std::string, int, cmp> mp;
mp.emplace("eee", 5);
mp.emplace("aaa", 1);
mp.emplace("bbb", 2);
mp.emplace("cccc", 3);
mp.emplace("dd", 4);
auto const elements_of_size_3 = mp.equal_range("aaa");
for (auto iter = elements_of_size_3.first; iter != elements_of_size_3.second; ++iter)
{
std::cout << iter->first << " -> " << iter->second << '\n';
}
}
输出:
eee -> 5
aaa -> 1
bbb -> 2
从std::multimap<std::string, int, cmp>
的观点,"eee"
,"aaa"
和"bbb"
都是完全相等的,std::multimap
允许不同的键相等。实际上它们的相对顺序保证了自C++ 11以来的插入顺序。
明白了,谢谢! – Seraph