Derek
Derek

Reputation: 858

Sorting a vector alongside another vector in C++

I am writing a function in C++ which will take in 2 vectors of doubles called xvalues and yvalues. My aim is to create an interpolation with these inputs. However, it would be really convenient if the (x,y) pairs were sorted so that the x-values were in increasing order and the y-values still corresponded to the correct x-value.

Does anyone know how I can do this efficiently?

Upvotes: 2

Views: 1437

Answers (4)

Jörg Beyer
Jörg Beyer

Reputation: 3671

The idea is easy: implement a sort algorithm (e.g. quicksort is easy, short an OK for most use cases - there are a lot implementations available: http://www.java-samples.com/showtutorial.php?tutorialid=445 ).

  • Do the compare on your x-vector and
  • do the swap on both vectors.

The sort method has to take both vectors a input, but that should be a minor issue.

Upvotes: 1

ezdazuzena
ezdazuzena

Reputation: 6790

Or you use a vector of pairs, which you then can sort easily with the stl sort algorithm, or you write your own sort method. Therefore you've several options. Within your own sorting algorithm you can then take care of not only sorting your x-vector but also the y-vector respectively.

Here as an example using bubble sort for your two vectors (vec1 and vec2).

bool bDone = false;
while (!done) {
    done = true;
    for(unsigned int i=0; i<=vec1.size()-1; ++i) {
        if ( vec1.at(i) > vec1.at(i+1) ) {
            double tmp   = vec1.at(i);
            vec1.at(i)   = vec1.at(i+1);
            vec1.at(i+1) = tmp;
            tmp          = vec2.at(i);
            vec2.at(i)   = vec2.at(i+1);
            vec2.at(i+1) = tmp;
            done = false;
        }
    }
}

But again, as others pointed out here, you should defenitely use std::vector< std::pair<double, double> > and the just sort it.

Upvotes: 1

PlasmaHH
PlasmaHH

Reputation: 16046

As an alternative, you could write some kind of iterator adaptor that internally holds two iterators and increases/decreases/assigns them simultaneously. They dereference to a special type that on swap, swaps the two values in both vectors, but on compare only compare one. This might be some work (extra swap,op<, class ), but when done as a template, and you need this more often, could pay out.

Upvotes: 2

John3136
John3136

Reputation: 29266

I would probably create a vector of pairs and sort that by whatever means necessary.

It sounds like your data abstraction (2 separate collections for values that are actually "linked" is wrong).

Upvotes: 3

Related Questions