gpt4 book ai didi

c++ - 在 C++ 中打印 std::unordered_multimap 中特定键的多个值

转载 作者:行者123 更新时间:2023-11-30 05:12:28 25 4
gpt4 key购买 nike

我试图在 C++ 中打印与 unordered_multiset 中的特定键关联的所有值,但不幸的是,当我运行下面的代码时,我在 Visual Studio 和在线编译器中得到两个不同的输出 http://cpp.sh/ .Visual Studio 仅提供“红色”作为输出cpp.sh 仅给出“绿色”作为输出

#include <iostream>
#include <string>
#include <unordered_map>

int main()
{
std::unordered_map<std::string, std::string> myumm = {
{ "apple","red" },
{ "apple","green" },
{ "orange","orange" },
{ "strawberry","red" }
};

std::cout << "myumm contains:";
for (auto it = myumm.begin(); it != myumm.end(); ++it)
std::cout << " " << it->first << ":" << it->second;
std::cout << std::endl;

std::cout << "myumm's buckets contain:\n";
for (unsigned i = 0; i < myumm.bucket_count(); ++i) {
std::cout << "bucket #" << i << " contains:";
for (auto local_it = myumm.begin(i); local_it != myumm.end(i); ++local_it)
std::cout << " " << local_it->first << ":" << local_it->second;
std::cout << std::endl;
}
int x = 0;
auto pt = myumm.find("apple");
for (auto it = pt->second.begin(); it != pt->second.end(); ++it) {
std::cout << *it;


}
return 0;
}

我希望为键“apple”同时打印“red”和“green”,但我在 cpp.sh 和 visual studio 中分别得到了 green 或 red 作为输出

myumm contains: orange:orange strawberry:red apple:green apple:red
myumm's buckets contain:
bucket #0 contains:
bucket #1 contains: orange:orange
bucket #2 contains:
bucket #3 contains: strawberry:red apple:green apple:red
bucket #4 contains:
green

最佳答案

正如@PeteBecker 指出的那样,您想要的调用是equal_range。具体来说,成员函数 - 而不是自由函数。

(未经测试的代码)

auto p = myumm.equal_range("apple");
for (auto it = p.first; it != p.second; ++it)
std::cout << " " << it->first << ":" << it->second;

应该做你想做的。

关于c++ - 在 C++ 中打印 std::unordered_multimap 中特定键的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510597/

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