如何获得的char []用的std ::地图工作 [英] How to get char[] to work with std::map
问题描述
编辑回答后:
<
应提供的std ::地图
。有关最佳实践的详细信息,请詹姆斯McNellis的答案
在code列入这个问题是写得不好。这只是因为我有SPOJ玩和输入数据是严格有效的。在的std ::字符串
办法是什么,我选择了在第一,但它竟然是不够快。
The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string
approach is what I chose at first, but it turned out to be not fast enough.
感谢您。
我知道我不能使用的char []
直接与地图,如地图<的char [],INT>
。因此,我把它放在一个类。但它仍然可以通过编译。如何处理呢?
I know I cannot use char[]
directly with map, such as map<char[], int>
. Thus I put it in a class. But it still can go through compilation. How to deal with that?
#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’
这似乎它是与比较,但我仍然在黑暗中。
It seems it has something to do with comparison, but I am still in the dark.
推荐答案
您需要执行&LT;
运营商
class id {
public:
char v [30];
bool operator<(const id &rhs) const{
return strcmp(v,rhs.v) < 0;
}
};
编辑:作为一个方面说明你的code是一个做事的非常差的方式。看到一些答案的一个解释这是为什么。
As a side note your code is a very poor way of doing things. See some of the answers for an explanation why.
这篇关于如何获得的char []用的std ::地图工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!