简体   繁体   中英

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

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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