Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort vector of vectors

Tags:

c++

stl

vector

I have

    vector<vector<int>> vec 

in my c++ app.

Every vector of integers as an element of "big" vector has 4 INT values. I want to sort vec basing on third value of it's content vectors of ints (I mean every "inside" vector third element) - is it possible?

EDIT

Let's say I've got a function

COST(vector<int>)

which calculates me some value based on my vector values - can I use it in comparation parameter too? It'd help me a lot more.

like image 463
pawel Avatar asked Jan 19 '13 22:01

pawel


People also ask

Can we sort vector of vectors?

In C++, we can sort particular rows in the 2D vector using sort() function, by default the sort() functions sorts the vector in ascending order.

Can we sort vector of vector in 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.

Can you sort a vector of pairs?

We can sort the vector of pairs using the generic sorting algorithm provided by STL. The std::sort function takes two iterators of the range to be sorted, and it rearranges the elements in non-descending order by default. In the case of pairs, the vector is sorted by the first element of each pair.

How do you sort vectors of objects?

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.


1 Answers

Sure it is. std::sort can take a third parameter which is the comparison function to use when sorting. For example, you could use a lambda function:

std::vector<std::vector<int>> vec;
// Fill it

std::sort(vec.begin(), vec.end(),
          [](const std::vector<int>& a, const std::vector<int>& b) {
  return a[2] < b[2];
});

Alternatively, you can pass anything else callable with signature bool(const std::vector<int>&, const std::vector<int>&), such as a functor or function pointer.


Response to edit: Simply apply your COST function to a and b:

std::sort(vec.begin(), vec.end(),
          [](const std::vector<int>& a, const std::vector<int>& b) {
  return COST(a) < COST(b);
});
like image 100
Joseph Mansfield Avatar answered Sep 18 '22 02:09

Joseph Mansfield