Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an STL vector?

Tags:

c++

sorting

stl

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.

like image 791
NativeCoder Avatar asked May 03 '10 12:05

NativeCoder


People also ask

Can vector be sorted?

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.

How do you sort the structure of a vector?

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

How do you sort a vector of an object?

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.

Which sorting is used in STL?

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.


2 Answers

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;     } }; 
like image 187
avakar Avatar answered Sep 25 '22 12:09

avakar


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

like image 29
Gabe Avatar answered Sep 22 '22 12:09

Gabe