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

标签 c++ dictionary struct

<分区>

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()’|

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

最佳答案

这在技术上可以被认为是 Read the Documentation 的一个案例,我这样做是为了自己解决这个问题。但是,解决方案可能并非一蹴而就。

Forecast 结构体有一个构造函数,但它是一个需要两个参数的构造函数。这会导致与 map 的 [] 运算符的一个主要行为发生冲突,而迭代器访问则没有:

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

因为 Forecast 没有这样的默认构造函数,map 试图调用一个不存在的函数。

如果我在 Forecast 上省略了构造函数,编译器就会为该结构提供一个默认构造函数,一切都会好起来的。但是,由于我定义了一个构造函数,编译器不会那样做。

值得庆幸的是,解决方案非常简单:要么删除构造函数,要么添加默认构造函数。就我而言,我可以设置默认参数。

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

NOTE: Some may argue that the above example is entirely silly - why not just use the iterator? In this case, that would be a very good idea. Using the [] is probably just wasting time, since I'm searching for one anyway to prevent errors. However, there are cases where [] is the best operator for the job, even if this isn't one.

关于c++ - 无法访问 std::map 中的结构值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636610/

相关文章:

iOS。如何在使用此 map 执行每个操作后获取有关当前 map 矩形的信息?

c++ - struct 中的 cin 和 char 数组指针

javascript - 反序列化Json字典obj以显示多个值

python - 将索引处的元素组合在字典内的列表中

c++ - 分配 Union 的字段

c - Qsort() 不适用于结构

c++ - 为什么 floyd warshall 只使用一个距离矩阵?

c++ - C 中的单向哈希函数

c++ - 了解编译器 - 什么都不做的声明?

c++ Singleton with map 原因 "violation reading location"