How to get char [] to work with std :: map

EDIT after the answer:

<must be provided for std::map. For more information on best practices, open an answer for James McNellis .

The code contained in this question is poorly written. This is simply because I play with SPOJ and the input is strictly correct. The approach std::stringis what I chose at the beginning, but it was not fast enough.

Thank.


I know that I can’t use it char[]directly with a card, for example map<char[], int>. So I put it in a class. But he can still compile. How to deal with it?


#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 foroperator<’ in ‘__x < __y’

It seems to have something to do with comparison, but I'm still in the dark.

+1
3

<

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

EDIT: - -. . , .

+3

: , gets. , , , . , gets , , . / C, fgets, .

, , , , , - . std::map operator<, id, , . operator< id , . , , - .

++, ++:

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

std::string operator<, , .

+6

To insert into the card, the card must be able to compare identifiers. You did not provide an implementation for the operator <what it can use. You have two options:

  • Provide one example, for example, another answer.
  • Use std :: string instead.

I think you should use std :: string. You can use the .c_str () method to convert it to a char array when you need to.

0
source

All Articles