Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a vector using values in another vector

Tags:

c++

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?

like image 303
Karnivaurus Avatar asked Dec 13 '15 01:12

Karnivaurus


People also ask

How do you sort a vector according to another vector?

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.

Can we sort vector of vector?

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 two vectors simultaneously?

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.

How do you sort an array of vectors?

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.


1 Answers

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.

like image 148
Kerrek SB Avatar answered Oct 27 '22 19:10

Kerrek SB