c++ - 在 std::Map 中处理 std::List for operator==,operator!= 等

标签 c++

我正在尝试了解有向图实现(没有经常提到的 Boost 库),只是想学习 C++ 中的东西。这是我在阅读关于不同问题的各种指示时想到的。我想我可以使用 map 来查找图表中的某些位置,并使用列表将链接放在一起。

因此,键可以说是第一个添加到列表中的键,而它链接到的键将是作为列表保存的值

这给出了

关键约翰
列表
list Taylor->Larry->Sarah

#include <iostream>
#include <map>
#include <list>

class Graph {
    public:
        typedef std::map <std::string, std::list<std::string> > MapType;
        MapType am; // adjacency map

        Graph() {
        }

        void addVertex(std::string s) {
            if(!am[s]){ // Trying to check if the key has been defined before
            std::list<std::string> l;
            am[s]=l;
            }       
        }

        void addEdge(std::string s1, std::string s2) {
            addVertex(s1);
            addVertex(s2);
            am[s1].push_back(s2);
        }

};


int main (int argc, char *argv[] ){
    Graph *people;
    people = new Graph();
    people->addVertex("John");
    people->addEdge("John","Taylor");

}

检查映射中的键是否已经为列表定义为值的正确方法是什么?
我知道对于

std::map <std::string, int >

未分配键的默认值是 0,所以我只使用 !am[s] 来检查是否定义了字符串 s。

对于一个列表,它以一个错误开始,指出操作符不匹配,我假设它是在谈论我用作值的列表。

我尝试使用 if(am[s].empty()){,但我认为这无法满足我的需求。

最佳答案

要测试一个key是否存在于一个map中,你应该使用成员函数find() .当您使用 operator[]就像您描述的那样,您最终将不应该在 map 中的元素插入到 map 中(这实际上是垃圾数据,对吧?)

find()成员函数使用您提供的键返回指向元素的迭代器。如果不存在具有该键的元素,它返回结束迭代器(您可以通过调用 end() 成员函数获得它。您使用成员函数 find()

换句话说,考虑使用 std::multimap<std::string, std::string>而不是你的 std::map<std::string, std::list<std::string> > .

关于c++ - 在 std::Map 中处理 std::List for operator==,operator!= 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201232/

相关文章:

c++ - 二维 wchar_t 字符串数组的简单示例

c++ - 串行通信 - 我无法将传入的 char 数组转换为 int

c++ - C++ move 构造函数过时了吗?

c++ - 将纹理传递给 GLSL 着色器而不使用统一?

c++ - boost::coroutine2 与 CoroutineTS

c++ - Windows 注册表有哪些替代方案可用于存储软件配置设置

C++ - 从 std::string 类派生类以添加额外功能?

c++ - Directx 11 与 C++ : Difference between using constant buffers and SetRawValue()?

c++ - 使用 libcurl 更新表单中的字段值

c++ - QTextBrowser 换行后的行间距