简体   繁体   English

c++ 对对象的排序向量,编译错误要求运算符“=”

[英]c++ sort vector of pair objects, compile error asking for operator “=”

I have a vector like this:我有一个这样的向量:

vector<pair<const MyObj&, MyStrut>> alls;

When I do当我做

swap(alls[0], alls[1]);

It complained它抱怨

binary '=': no operator found which takes a left-hand operand of type '_Ty' (or there is no acceptable conversion二进制“=”:未找到采用“_Ty”类型的左侧操作数的运算符(或没有可接受的转换

Why?为什么?

In the process of trying to swap your pair s, it's intrinsically trying to assign from a const reference to a const reference.在尝试交换您的pair的过程中,它本质上是在尝试从const引用分配给const引用。 You can't rebind a reference, so the only thing it could conceivably do is swap the objects referred to by each reference.你不能重新绑定一个引用,所以它唯一能做的就是交换每个引用所引用的对象。 But since these are const references, even that's impossible.但是由于这些是const引用,所以即使这样也是不可能的。

If you think you need to store a reference in a data structure and manipulate the structure containing it in any way, it's usually the case that you actually want to store a pointer of some sort (eg std::shared_ptr ) that would allow you to store it in the data structure and reassign (eg swap ) it within the data structure, while still having an owned pointer to it somewhere else (to preserve the "referenciness" you're relying on).如果您认为需要在数据结构中存储引用并以任何方式操作包含它的结构,通常情况下您实际上想要存储某种类型的指针(例如std::shared_ptr ),它允许您将其存储在数据结构中并在数据结构中重新分配(例如swap )它,同时在其他地方仍然拥有指向它的指针(以保留您所依赖的“参考性”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM