I have two vectors vector a and vector b and I want to sort them both with the condition that a[i]/b[i]>a[i+1]/b[b+1]. How do I implement the code in C++ for that?
Asked
Active
Viewed 110 times
-2
-
Can you share the program which you made to solve this problem? – Nik Oct 04 '16 at 06:34
1 Answers
3
Say you start with
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a{2, 7, 3};
std::vector<int> b{4, 2, 1};
Create a vector of indices, inds
:
std::vector<std::size_t> inds;
for(std::size_t i = 0; i < a.size(); ++i)
inds.push_back(i);
also create a comparison function describing the criteria in your question:
auto cmp = [&](std::size_t lhs, std::size_t rhs) {
return static_cast<double>(a[lhs]) / b[lhs] > static_cast<double>(a[rhs]) / b[rhs];
};
and sort according to it:
std::sort(std::begin(inds), std::end(inds), cmp);
}
At this point, inds
will be organized according to your criteria.
Finally, use the answers in reorder a vector using a vector of indices to reorder each of a
and b
according to inds
.

Community
- 1
- 1

Ami Tavory
- 74,578
- 11
- 141
- 185