I have a std::vector
called foo_vec
containing objects of class Foo
. Suppose that Foo
has a member variable int x
, and I also implemented a function CompareInts(int a, int b)
which returns the minimum of a
and b
. Then, I could do an std::sort
the vector in terms of the object's x
values.
However, what if these x
values are not member variables of Foo
, but are in another std::vector
called x_vec
. Here, the first element of x_vec
corresponds to the first element of foo_vec
, and so on. How can I perform an std::sort
on foo_vec
based on the corresponding values in x_vec
?
This type of sorting can be achieved using simple “ sort() ” function. By default the sort function sorts the vector elements on basis of first element of pairs. Case 2 : Sorting the vector elements on the basis of second element of pairs in ascending order.
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.
For example to sort two vectors i would use descending bubble sort method and vector pairs. For descending bubble sort, i would create a function that requires a vector pair. After that i would put your 2 vector values into one vector pair.
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.
You can make a third vector of indexes and sort that indirectly. After it's sorted, you can access the original vector through the sorted indexes:
std::vector<Foo> foo_vec = /* ... */;
std::vector<int> x_vec = /* ... */;
std::vector<std::size_t> index_vec;
assert(foo_vec.size() == x_vec.size());
for (std::size_t i = 0; i != foo_vec.size(); ++i) { index_vec.push_back(i); }
std::sort(
index_vec.begin(), index_vec.end(),
[&](std::size_t a, std::size_t b) { return x_vec[a] < x_vec[b]; });
for (std::size_t i = 0; i != index_vec.size(); ++i)
{
std::cout << "Sorted element " << i << " is "
<< foo_vec[index_vec[i]] << "\n";
}
Note that this operation is entirely non-invasive, since everything happens indirectly.
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