Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make class sortable inside vector?

I have a class say class stuff{ int id; int ammount; int quality; /*...*/ }; and I have a vector<stuff> items. I want to make my collection sortable by stuff::id and searchable by staff::id. I could do it via find_if and sort using some sorting special stl lambda based function. Yet I want to have it all by default in vector. I heard there is some way to create hashing function yet I searched all around could not find it... So how to make class sortable/searchable inside vector with default vector functions?

like image 703
DuckQueen Avatar asked Nov 28 '13 19:11

DuckQueen


People also ask

How do you sort a class object vector?

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.

How to use inbuilt sort function in vector C++?

Sorting a vector in C++ Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements.

How to sort a vector in C++?

Prerequisites : std::sort in C++, vector in C++, initialize a vector in C++. How to sort in descending order? sort () takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass “greater ()” function to sort in descending order. This function does comparison in a way that puts greater element before.

How do I sort objects of a user-defined class?

Example: This is just a generic example to show how this method is employed In order to sort objects of a user-defined class, a key needs to be set for the sorted method, such that the key will be an indicator of how the objects should be sorted.

How do I sort a list using CSS?

This is done by grouping all related lists with a CSS class, and then pass that class into the sortable function (i.e., connectWith: '#sortable-5, #sortable-6'). Try to drag the items under List 3 to the List 2 or List 1.

What is the sortable method in HTML?

The sortable (options) method declares that an HTML element contains interchangeable elements. The options parameter is an object that specifies the behavior of the elements involved during reordering.


1 Answers

For sorting, implement an operator< that compares two structures:

bool operator<(const stuff& s1, const stuff& s2)
{
    // Your comparison here
}

This is the operator that is used by default for most of all sorting.

For equality checking, create an operator== similarly.

like image 155
Some programmer dude Avatar answered Oct 19 '22 12:10

Some programmer dude