Search code examples
c++sortingvectororganizer

how to organize one vector by placing into another vector using for loop c++


I was wondering how I could possibly organize one vector by placing it into an another. (Note: They are vector of objects). What i have so far is:

double done;
for ( int i = 0; i < id; i++ )
{
    done = guy[i].done();
    int smallest = i;
    for( int j = i + 1; j < id; j++ ){
        if( done > guy[j].done() )
            {
                done = guy[j].done();
                smallest = j;   
            }
        }
    newGuy.push_back( guy[smallest] );
}

This doesn't organize every part of the vector, and sometimes even copies the same guy into the newGuy. Any ideas?


Solution

  • If you are trying to sort the vector, you could define a custom less-than comparator for your objects, and use std::sort.

    bool myComparison(const MyType& lhs, const MyType& rhs) {
      return lhs.done() < rhs.done();
    }
    
    std::vector<MyType> guy = ....;
    std::sort(guy.begin(), guy.end(), myComparison);
    

    If you want it all to go to a new vector, then just copy the original, then sort the copy:

    std::vector<MyType> newGuy = guy;
    std::sort(newGuy.begin(), newGuy.end(), myComparison);