Reorder vector using a vector of indices

前端 未结 14 1917
耶瑟儿~
耶瑟儿~ 2020-11-28 06:15

I\'d like to reorder the items in a vector, using another vector to specify the order:

char   A[]     = { \'a\', \'b\', \'c\' };
size_t ORDER[] = { 1, 0, 2 }         


        
14条回答
  •  悲哀的现实
    2020-11-28 06:53

    Here is the correct code

    void REORDER(vector& vA, vector& vOrder)  
    {   
        assert(vA.size() == vOrder.size());
    
        // for all elements to put in place
        for( int i = 0; i < va.size() - 1; ++i )
        { 
            // while the element i is not yet in place 
            while( i != vOrder[i] )
            {
                // swap it with the element at its final place
                int alt = vOrder[i];
                swap( vA[i], vA[alt] );
                swap( vOrder[i], vOrder[alt] );
            }
        }
    }
    

    note that you can save one test because if n-1 elements are in place the last nth element is certainly in place.

    On exit vA and vOrder are properly ordered.

    This algorithm performs at most n-1 swapping because each swap moves the element to its final position. And we'll have to do at most 2N tests on vOrder.

提交回复
热议问题