【问题标题】:std::map<int,bool> wrong result of insert?std::map<int,bool> 插入的错误结果?
【发布时间】:2021-10-11 23:45:18
【问题描述】:
#include <iostream>
#include <map>

using namespace std;

int main()
{
    std::map<int, bool> set;
    
    cout << (int)set.insert({ 5,false }).second << endl;
    return 0;
}

不知道为什么结果是1而不是0,而second是假的。

【问题讨论】:

  • 试试cout &lt;&lt; set.insert({5, false}).first-&gt;second &lt;&lt; endl;
  • 插入的值包含false返回的值包含true。阅读documentation

标签: c++ stl


【解决方案1】:

std::map::insert 的返回值是std::pair&lt;iterator, bool&gt;,其中bool 表示插入是否发生。 cout &lt;&lt; (int)set.insert({ 5,false }).second &lt;&lt; endl; 只会打印插入是否成功。

要做你想做的事,你需要使用返回的std::pair 中的第一个值,它是一个迭代器,然后使用它来检查你插入的新键/值对的值:

#include <iostream>
#include <map>

int main()
{
    std::map<int, bool> set;
    std::cout << set.insert({5, false}).first->second << '\n';
    return 0;
}

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 2013-12-15
    • 2010-09-10
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多