Robert
Robert

Reputation: 203

std::sort a class that's implemented a move constructor

Is it possible to use std::sort without using the whole element?

std::vector<std::pair<int, myclass> > unsorted_vec;
for (some_iterations) {
    unsorted_vec.emplace_back(rand(), std::move(instance_of_myclass));
}
std::sort(unsorted_vec.begin(), unsorted_vec.end(), 
          [](auto & l, auto & r) { return l.first < r.first; });

The above code gives the following compilation bug unless the std::sort line is commented out.

error: use of deleted function 'myclass & myclass::operator=(const myclass &)' is 
       implicitly declared as delete because 'myclass' declares a move constructor.

Now I did declare a move constructor for myclass, and furthermore, I actually want the reference constructor deleted. My question is, how do I sort this array? Is it possible to get a reference to the first part of my pair without touching the second part?

Upvotes: 1

Views: 486

Answers (1)

Galik
Galik

Reputation: 48635

According to this reference on std::sort your class needs to be both move constructable and move assignable in order to be sortable.

If your class is not inherently moveble then something like this should work fine:

class myclass
{
public:
    myclass(myclass const&) = delete; // or implement
    myclass(myclass&& other) { /* stuff to construct */ }

    myclass& operator=(myclass const&) = delete; // or implement
    myclass& operator=(myclass&& other) { /* stuff to assign */ return *this; }

};

Upvotes: 3

Related Questions