【问题标题】:How to get char[] to work with std::map如何让 char[] 与 std::map 一起工作
【发布时间】:2011-09-06 19:12:16
【问题描述】:

回答后编辑:

< 应提供给std::map。有关最佳实践的更多信息,请参阅 James McNellis 的答案

这个问题中包含的代码写得不好。只是因为我在玩 SPOJ 并且输入的数据是严格有效的。 std::string 方法是我一开始选择的,但结果证明它不够快。

谢谢。


我知道我不能直接将char[] 与地图一起使用,例如map<char[], int>。所以我把它放在一个班级里。但它仍然可以通过编译。怎么处理?


#include <stdio.h>
#include <map>

using namespace std;

class id {
public:
    char v [30];
};

int main () {
    map<id, int> m;
    id a;
    while (gets(a.v)) {
        m[a]++;
    }
    return 0;
}

/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = id]’:
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_map.h:418:   instantiated from ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = id, _Tp = int, _Compare = std::less<id>, _Alloc = std::allocator<std::pair<const id, int> >]’
prog.cpp:15:   instantiated from here
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’

好像和比较有关系,但我还是一头雾水。

【问题讨论】:

    标签: c++ arrays stl map


    【解决方案1】:

    第一件事:永远不要使用gets。它无法安全使用,任何使用它的程序都存在安全漏洞。无法限制gets 可以写入您提供的缓冲区的字符数,因此无法防止缓冲区溢出。如果确实需要使用 C I/O 库,则应使用 fgets,它允许您指定要读取的最大字符数。

    您看到此错误的原因是您使用的密钥类型必须以某种方式具有可比性。默认情况下std::map 使用operator&lt;,您没有为id 定义它,因此会出现编译错误。您要么需要定义operator&lt; 来比较两个id 对象,要么需要编写一个可用于比较两个对象的比较器函子。无论您选择哪个,比较器都必须提供strict-weak ordering

    由于您使用 C++ 进行编程,这里理想的解决方案是使用惯用的 C++:

    std::map<std::string, int> m;
    std::string s;
    while (std::cin >> s) {
        m[s]++;
    }
    

    std::string 已经提供了operator&lt;,它提供了字典顺序,因此您不需要自己定义比较器。

    【讨论】:

    • 否; fgets 是 C 标准库的一部分,因此采用 FILE*,如 stdin
    • 我知道您的方法是最佳实践,这是我第一次尝试,早在我问这个问题之前。但它不断得到“超过时间限制”。非常感谢。 (现在我的回答被危险的gets....接受了)
    【解决方案2】:

    你需要实现&lt;操作符

    class id {
    public:
        char v [30];
        bool operator<(const id &rhs) const{
            return strcmp(v,rhs.v) < 0;
        }
    };
    

    编辑:作为旁注,您的代码是一种非常糟糕的做事方式。请参阅一些答案以了解原因。

    【讨论】:

    • 你的回答正是我想要的。非常感谢。 (有关代码的问题在问题编辑中进行了解释。我希望这是 Stack Overflow 工作的最佳方式。顺便说一句,我的回答终于被接受了。)
    【解决方案3】:

    为了插入地图,地图需要能够比较id。您还没有提供它可以使用的 operator

    1. 在此处提供另一个答案给出的示例。
    2. 改用 std::string。

    我认为你应该使用 std::string。您可以在需要时使用 .c_str() 方法将其转换为 char 数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2011-09-11
      • 2023-02-02
      • 2011-11-12
      • 1970-01-01
      • 2017-06-25
      • 2020-12-13
      相关资源
      最近更新 更多