Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error on using find function on map [duplicate]

Tags:

c++

I am defining map using my own class A as the data value for the key of map. I am also using find() function of the map. But I am getting the error.

#include<iostream>
#include<map>
using namespace std;
class A{
    public:
        int x;
        A(int a){
            x=a;
        }

};
int main(){
    map<int,A> m;
    m[0]=A(3);
    m[1]=A(5);
    m[2]=A(6);
    if(m.find(3) == m.end())
        cout<<"none"<<endl;
    else
        cout<<"done"<<endl;
}

Error

In file included from /usr/include/c++/4.6/map:61:0,
                 from temp.cpp:2:
/usr/include/c++/4.6/bits/stl_map.h: In member function ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int, _Tp = A, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, A> >, std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = A, std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]’:
temp.cpp:14:5:   instantiated from here
/usr/include/c++/4.6/bits/stl_map.h:453:11: error: no matching function for call to ‘A::A()’
/usr/include/c++/4.6/bits/stl_map.h:453:11: note: candidates are:
temp.cpp:7:3: note: A::A(int)
temp.cpp:7:3: note:   candidate expects 1 argument, 0 provided
temp.cpp:4:7: note: A::A(const A&)
temp.cpp:4:7: note:   candidate expects 1 argument, 0 provided
like image 777
user3747190 Avatar asked Aug 03 '26 04:08

user3747190


1 Answers

The problem is that you're using the operator[] to access the map, the documentation says:

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

thus you need a default constructor if you intend to use it: that operator needs it to return a reference to the newly default-constructed and inserted element.

Otherwise you can do this:

m.insert(std::pair<int,A>(0,A(3)));

which doesn't need a default constructor available.

like image 114
Marco A. Avatar answered Aug 04 '26 20:08

Marco A.