1

Give two integer vectors in c++ (same size), I'd like to sort one of my vectors from smallest to largest element and change the order of the second vector respectively.

How can I achieve this without using boost library?

Thanks.

5
  • 1
    You mean that if the fourth element of array one goes first, then fourth element of array two should go first too?
    – lodo
    Mar 28, 2015 at 21:47
  • 2
    This isn't an exact duplicate of the other question because this question says "without using boost" while the other one said "preferably using the STL or Boost." Mar 28, 2015 at 22:04
  • @DouglasZare: "Not using Boost" is half of "STL [sic] or Boost", and the accepted answer does not use Boost. In fact, only two of the nine excellent answers refer to Boost (not counting the suggestion of boost::tie and boost::tuple, as they are both now in the C++ Standard Library) but only to the Standard Library. I don't see the problem. This question was asked and answered long ago. Mar 28, 2015 at 22:10
  • Based on the answers for "How do I ..." previous question, you can either pair up the vectors, or place at least one of the vectors in a class and use a function operator (functor) or lambda function for std::sort, that sorts a vector of indices into the first vector, then use those indices to reorder the second vector according to the vector of indices.
    – rcgldr
    Mar 28, 2015 at 23:33
  • Another option is to implement your own sort instead of using std::sort or std::stable_sort, so that the custom sort can work with multiple vectors.
    – rcgldr
    Mar 28, 2015 at 23:36

1 Answer 1

2

You can restructure your code so that, instead of two vectors of integers, it uses a vector of S, where S is a structure containing two integers. Then you can define a specific operator< to be used by the sort function.

This has the advantage that the strict coupling between the two sets of data is clearly stated in the way they are stored.

4
  • Someone voted this down. I'd like to know why, since this is what I do every time I run into this common situation. If there is some reason not to do this, please elaborate. Mar 28, 2015 at 21:59
  • 1
    I don't think this answer directly answers the original question. First answer the original, then give an alternative implementation. If not, an alternative should be left as a comment.
    – CinchBlue
    Mar 28, 2015 at 21:59
  • But this answer solves the problem that is behind the question. And that's the way that problem is almost always solved, because it is simple, clear and efficient.
    – lodo
    Mar 28, 2015 at 22:00
  • It's a good idea and a good approach but indeed you did not answer the question as posed. Mar 28, 2015 at 22:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.