문제

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?

도움이 되었습니까?

해결책

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

다른 팁

Because you are not removing your smallest person from the old array when you put it into the new one. Consider the values [5,4,3,2,1]

Your algorithm will on the first value for i find that the smallest is j=4 (value 1) and push 1 onto the new array, then it will do this for i=2 and so on until you have only [1,1,1,1,1]

Here is what you are doing, where the bold numbers are the ones being looped over, and the second array is the output array.

Pass 1:
[5 ,4, 3, 2, 1]
[1]

Pass 2:
[5, 4, 3, 2, 1]
[1,1]

Pass 3:
[5, 4, 3, 2, 1]
[1,1,1]

Pass 4:
[5, 4, 3, 2, 1]
[1,1,1,1]

Pass 5:
[5, 4, 3, 2, 1]
[1,1,1,1,1]

Just remove the item that you just found to be the smallest from the old vector when you add it to the new one each time. Of course as other people have pointed out it would actually be better to just use std's sorting algorithms

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top