【问题标题】:Error on using find function on map [duplicate]在地图上使用查找功能时出错[重复]
【发布时间】:2014-09-05 23:07:32
【问题描述】:

我正在使用我自己的 A 类作为地图键的数据值来定义地图。我也在使用地图的 find() 函数。但我得到了错误。

#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;
}

错误

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

【问题讨论】:

    标签: c++


    【解决方案1】:

    问题是你使用operator[] 来访问地图,文档说:

    如果 k 不匹配容器中任何元素的键,则 函数使用该键插入一个新元素并返回一个引用 到它的映射值。请注意,这总是会增加容器 大小加一,即使没有为元素分配映射值( 元素是使用其默认构造函数构造的)。

    因此,如果您打算使用它,则需要一个默认构造函数:该运算符需要它来返回对新默认构造和插入的元素的引用。

    否则你可以这样做:

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

    它不需要可用的默认构造函数。

    【讨论】:

    • 使用 map::insert 也是一种选择,如果 OP 对默认构造函数有强烈的感觉
    • @Jason 我已经更新了问题,顺便谢谢
    • 如果我想获得价值怎么办。例如A a= m[0] ?
    • @user3747190 使用A a = m.find( 0 )-&gt;second;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2019-11-26
    • 2014-04-02
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多