c++ sort keeping track of indices

后端 未结 4 690
忘了有多久
忘了有多久 2020-11-27 03:44

do you have some efficient routine for returning array with indices for sorted elements in a array? I think that some convenient way exists using stl vector. Do you have alr

4条回答
  •  -上瘾入骨i
    2020-11-27 04:35

    For C++03, I think this guru of the week can help you :

    namespace Solution3
    {
      template
      struct CompareDeref
      {
        bool operator()( const T& a, const T& b ) const
          { return *a < *b; }
      };
    
    
      template
      struct Pair2nd
      {
        const U& operator()( const std::pair& a ) const
          { return a.second; }
      };
    
    
      template
      void sort_idxtbl( IterIn first, IterIn last, IterOut out )
      {
        std::multimap > v;
        for( int i=0; first != last; ++i, ++first )
          v.insert( std::make_pair( first, i ) );
        std::transform( v.begin(), v.end(), out,
                        Pair2nd() );
      }
    }
    
    #include 
    
    int main()
    {
      int ai[10] = { 15,12,13,14,18,11,10,17,16,19 };
    
      std::cout << "#################" << std::endl;
      std::vector aidxtbl( 10 );
    
    
      // use another namespace name to test a different solution
      Solution3::sort_idxtbl( ai, ai+10, aidxtbl.begin() );
    
    
      for( int i=0; i<10; ++i )
      std::cout << "i=" << i
                << ", aidxtbl[i]=" << aidxtbl[i]
                << ", ai[aidxtbl[i]]=" << ai[aidxtbl[i]]
                << std::endl;
      std::cout << "#################" << std::endl;
    }
    

    The original article is here.

提交回复
热议问题