gpt4 book ai didi

c++ - 无法访问 std::map 中的结构值

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:13:49 25 4
gpt4 key购买 nike

<分区>

DISCLAIMER: I crafted the MCVE to demonstrate an issue I had with a much larger project that has nothing to do with the weather. I chose the MCVE's names and program goal only to demonstrate the problem in an easy-to-understand way. I know this design would suck for a real-life forecast program.

我正在使用 std::map 来存储结构,使用 std::string 作为键。

struct Temps
{
//Temps(int l = 0, int h = 0)
Temps(int l, int h)
:low(l), high(h)
{}
int low;
int high;
};

int main()
{
std::map<std::string, Temps> forecast;
forecast.emplace("Monday", Temps(49, 40));
forecast.emplace("Tuesday", Temps(66, 35));
forecast.emplace("Wednesday", Temps(78, 40));

return 0;
}

但是,我遇到了一个问题。正如预期的那样,我可以使用迭代器访问映射中那些结构的内容...

std::map<std::string, Temps>::iterator it;

it = forecast.find("Monday");
if(it != forecast.end())
{
std::cout << "Monday's high is " << it->second.high << "." << std::endl;
}

但是当我尝试在 map 上使用 [] 运算符访问时,我遇到了一个错误...

if(forecast.find("Tuesday") != forecast.end())
{
std::cout << "Tuesday's high is " << forecast["Tuesday"].high << std::endl;
}

我遇到了一个巨大的、可怕的错误,总结为...

/usr/include/c++/5/tuple|1172|error: no matching function for call to ‘Temps::Temps()’|

我知道问题既不在结构也不在数据。怎么回事?

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