I would like to sort a vector
vector<myClass> object;
Where myclass
contains many int
variables. How can I sort my vector
on any specific data variable of myClass
.
A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions.
Note: To sort vector in descending order, just change the '<' to '>' in the lambda expression. Instead of defining the Lambda Expression inside the std::sort() function, we can define lambda expression as a separate function. After defining the lambda function, we pass it as a parameter to std::sort().
You can sort a vector of custom objects using the C++ STL function std::sort. The sort function has an overloaded form that takes as arguments first, last, comparator. The first and last are iterators to first and last elements of the container.
In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By default, it uses QuickSort but if QuickSort is doing unfair partitioning and taking more than N*logN time, it switches to HeapSort and when the array size becomes really small, it switches to InsertionSort.
std::sort(object.begin(), object.end(), pred());
where, pred()
is a function object defining the order on objects of myclass
. Alternatively, you can define myclass::operator<
.
For example, you can pass a lambda:
std::sort(object.begin(), object.end(), [] (myclass const& a, myclass const& b) { return a.v < b.v; });
Or if you're stuck with C++03, the function object approach (v
is the member on which you want to sort):
struct pred { bool operator()(myclass const & a, myclass const & b) const { return a.v < b.v; } };
Overload less than operator, then sort. This is an example I found off the web...
class MyData { public: int m_iData; string m_strSomeOtherData; bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; } }; std::sort(myvector.begin(), myvector.end());
Source: here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With