为什么这些C 元组不相等

Why are these c++ tuples not equal?

本文关键字:元组 不相等 为什么      更新时间:2023-10-16

如果左侧的每个字符串变量肯定包含了后者的字面等价物,那为什么我不收到我的消息?

if (make_tuple(this->currentState, inputSymbol, stackTop) == make_tuple("q0", "a", "0"))
    cout << "These tuples are equal" << endl;

我问的原因是因为我使用的是带有元组作为钥匙的地图,当我尝试使用find()时,它的行为就好像键在映射中不存在,我确定它是因为我使用迭代器浏览了地图,并显示了所有键(元组中的每个元素)。我怀疑该错误与上述代码有关,因为这些代码应该相等,但事实并非如此。(我正在使用map.find(make_tuple(blah,blah,blah)),并将其与map.end.end())思想进行比较?

这是我对您的问题的最佳猜测:

const char input[] = "hello";
if (std::make_tuple(input) == std::make_tuple("hello")) {
    // won't get here
    std::cout << "equaln";
} 

原因是 tuple<>::operator==只是元素平等。在这种情况下,我们有两个tuple<const char*>,但是尽管它们指出的字符串相同,但实际的指针本身是不同的,我们只是在比较指针。

如果您希望它能起作用,则需要左侧是一种具有正确功能的operator==的类型。例如,std::string

const char input[] = "hello";
if (std::make_tuple(std::string(input)) == std::make_tuple("hello")) {
    // now it happens
    std::cout << "equaln";
}

或,由于您使用的是std::map,因此您将不是想要使用默认的tuple<>::operator<,而是提供使用strcmp而不是原始指针<