简体   繁体   中英

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?

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

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.

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.

The idea is easy: implement a sort algorithm (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM