gpt4 book ai didi

c++ - 无序 multimap 查找所有值

转载 作者:搜寻专家 更新时间:2023-10-31 01:48:33 25 4
gpt4 key购买 nike

我想看看是否可以看到我们设置的所有值。例如:

#include <iostream>
#include <unordered_map>

using namespace std;


int main () {
unordered_multimap<string,int> hash;

hash.emplace("Hello", 12);
hash.emplace("World", 22);
hash.emplace("Wofh", 25);
for (int i = 1; i < 10; i++) {
hash.emplace("Wofh", i);
}
cout << "Hello " << hash.find("Hello")->second << endl;
cout << "Wofh " << hash.count("Wofh") << endl;
cout << "Wofh " << hash.find("Wofh")->second << endl;

return 0;
}

输出是:

$ ./stlhash
Hello 12
Wofh 10
Wofh 9

而我希望最后一行显示从 25,1,2... 到 9。显然 find 只需要 firstsecond 指针,第一个是值,第二个是对应的值。有什么办法吗?

最佳答案

你需要的操作叫做equal_range

来自 cplusplus.com 的示例:

// unordered_multimap::equal_range
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>

typedef std::unordered_multimap<std::string,std::string> stringmap;

int main ()
{
stringmap myumm = {
{"orange","FL"},
{"strawberry","LA"},
{"strawberry","OK"},
{"pumpkin","NH"}
};

std::cout << "Entries with strawberry:";
auto range = myumm.equal_range("strawberry");
for_each (
range.first,
range.second,
[](stringmap::value_type& x){std::cout << " " << x.second;}
);

return 0;
}

关于c++ - 无序 multimap 查找所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17660011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com