Reorder vector using a vector of indices

前端 未结 14 1808
耶瑟儿~
耶瑟儿~ 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:33

    It is not clear by the title and the question if the vector should be ordered with the same steps it takes to order vOrder or if vOrder already contains the indexes of the desired order. The first interpretation has already a satisfying answer (see chmike and Potatoswatter), I add some thoughts about the latter. If the creation and/or copy cost of object T is relevant

    template 
    void reorder( std::vector & data, std::vector & order )
    {
     std::size_t i,j,k;
      for(i = 0; i < order.size() - 1; ++i) {
        j = order[i];
        if(j != i) {
          for(k = i + 1; order[k] != i; ++k);
          std::swap(order[i],order[k]);
          std::swap(data[i],data[j]);
        }
      }
    }
    

    If the creation cost of your object is small and memory is not a concern (see dribeas):

    template 
    void reorder( std::vector & data, std::vector const & order )
    {
     std::vector tmp;         // create an empty vector
     tmp.reserve( data.size() ); // ensure memory and avoid moves in the vector
     for ( std::size_t i = 0; i < order.size(); ++i ) {
      tmp.push_back( data[order[i]] );
     }
     data.swap( tmp );          // swap vector contents
    }
    

    Note that the two pieces of code in dribeas answer do different things.

提交回复
热议问题