如何让char []与std :: map一起使用

Dan*_*ode 1 c++ arrays stl map

编辑后回答:

<应该提供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;
}
Run Code Online (Sandbox Code Playgroud)
/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’
Run Code Online (Sandbox Code Playgroud)

它似乎与比较有关,但我仍处于黑暗中.

Jam*_*lis 6

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

您看到此错误的原因是您使用的密钥类型必须以某种方式进行比较.默认std::map使用operator<,您没有定义id,因此编译错误.您需要定义operator<以比较两个id对象,或者您需要编写可用于比较两个对象的比较器仿函数.无论您选择哪种,比较器都必须提供严格的弱排序.

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

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

std::string已经提供operator<了提供字典顺序,因此您不需要自己定义比较器.