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

Error while assigning a pair value to a map key

这是我的代码的摘录:

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> &)

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

嗯,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>() );

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

你代码中的这部分看起来有点丑...

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

您可以使用上面的方法,除了用 strings 替换 vector<T> 的对象。

为了简化演示,我还在 structclass 上使用了 public 接口。通常 class 中的容器将是 protectedprivate 具有辅助功能。

EDIT 这是为了帮助先构建地图。地图工作后,您可以根据需要修改它以添加 const 存储类型,但使用它们可能会很棘手。参考einpoklum的回答中的link。

如果您使用的是较新版本的 C++,您可以更改这些代码行:

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

进入这个:

auto it = myClass.myMap_.begin();