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.
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.
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.
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.
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.
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);
});
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