将对值分配给映射键时出错

时间:2017-07-23 23:03:59

标签: c++ stdmap std-pair

摘自我的代码:

std::map<int, std::pair< const int, const std::vector<POINT_3d> > > m_srcHitData;
void addHit( const int edgeId, const int hit )
{
  m_srcHitData[edgeId] = std::make_pair( hit, std::vector<POINT_3d>() );
}

我一直收到错误:

   stl_pair.h(180): error: no operator "=" matches these operands
                operand types are: const std::vector<POINT_3d, std::allocator<POINT_3d>> = const std::vector<POINT_3d, std::allocator<POINT_3d>>
              second = __p.second;
                     ^
    detected during instantiation of "std::pair<_T1, _T2> &std::pair<_T1, _T2>::operator=(const std::pair<_U1, _U2> &)

这是什么意思?我尝试了不同的方法,但仍然得到这个或类似的错误。谢谢!

2 个答案:

答案 0 :(得分:2)

好吧,m_srcHitData[edgeId]是一对const向量成员。你不能简单地分配它,因为这意味着分配给const向量,这是不可能的......

至于你可以做些什么,请参阅:

How to create a std::map of constant values which is still accessible by the [] operator?

正如@FrancisCugler建议的那样,例如,可以写作:

m_srcHitData[edgeId].insert( std::make_pair( hit, std::vector<POINT_3d>() );

但是,如果您的矢量很长,您可能实际上并不想复制所有数据。

答案 1 :(得分:1)

这段代码看起来很难看......

std::map<int, std::pair< const int, const std::vector<POINT_3d> > > m_srcHitData;

您可以稍微尝试重构代码。

struct Pair {
    unsigned int key_;
    std::vector<POINT_3d> points_;

    Pair() {} // Empty Default
    Pair( const unsigned int& key, const std::vector<POINT_3d>& points ) :
        key_(key),
        points_( points ) 
    {}
};

则...

std::map<unsigned, Pair> m_srcHitData;

void addHit( const int edgeId, const int hit ) {
    m_srcHitData[edgeId] = Pair( hit, std::vector<POINT_3d>() );
}

我制作了这个简短的程序来模拟一个类似的结构,只使用strings来代替std::vector<POINT_3d>

#include <string>
#include <iostream>
#include <map>

struct Pair {
    unsigned key_;
    std::string value_;

    Pair() {}
    Pair( const unsigned int& key, const std::string& value ) :
        key_( key ),
        value_( value ) {}
};

class MyClass {
public:
    std::map<unsigned, Pair> myMap_;

    void addValue( const unsigned int& key, const std::string& value ) {
        myMap_[key] = Pair( key, value );
    }
};

int main() {

    MyClass myClass;
    myClass.addValue( 1, "Hello" );
    myClass.addValue( 2, "World" );

    typedef std::map<unsigned, Pair>::iterator Iter;
    Iter it = myClass.myMap_.begin();

    for ( ; it != myClass.myMap_.end(); ++it ) {
        std::cout << "Key: " << it->first << " Pair-Key: " << it->second.key_ << " Pair-value: " << it->second.value_ << std::endl;
    }


    std::cout << "\nPress any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;
}

除了用vector<T>替换strings的对象外,您可以使用上述内容。

我还在structclass上使用了公共界面,以简化演示。通常,class中的容器可以是带有附件功能的protectedprivate

编辑这是为了帮助首先构建地图。一旦您使用了地图,您就可以修改它以在需要时添加const存储类型,但它们可能很难处理。请参阅einpoklum的答案中的链接。

如果您正在使用较新版本的C ++,则可以更改以下代码行:

typedef std::map<unsigned, Pair>::iterator Iter;
Iter it = myClass.myMap_.begin();

进入这个:

auto it = myClass.myMap_.begin();