Reorder vector using a vector of indices

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

    You could do it recursively, I guess - something like this (unchecked, but it gives the idea):

    // Recursive function
    template<typename T>
    void REORDER(int oldPosition, vector<T>& vA, 
                 const vector<int>& vecNewOrder, vector<bool>& vecVisited)
    {
        // Keep a record of the value currently in that position,
        // as well as the position we're moving it to.
        // But don't move it yet, or we'll overwrite whatever's at the next
        // position. Instead, we first move what's at the next position.
        // To guard against loops, we look at vecVisited, and set it to true
        // once we've visited a position.
        T oldVal = vA[oldPosition];
        int newPos = vecNewOrder[oldPosition];
        if (vecVisited[oldPosition])
        {
            // We've hit a loop. Set it and return.
            vA[newPosition] = oldVal;
            return;
        }
        // Guard against loops:
        vecVisited[oldPosition] = true;
    
        // Recursively re-order the next item in the sequence.
        REORDER(newPos, vA, vecNewOrder, vecVisited);
    
        // And, after we've set this new value, 
        vA[newPosition] = oldVal;
    }
    
    // The "main" function
    template<typename T>
    void REORDER(vector<T>& vA, const vector<int>& newOrder)
    {
        // Initialise vecVisited with false values
        vector<bool> vecVisited(vA.size(), false);
    
        for (int x = 0; x < vA.size(); x++)
        {
            REORDER(x, vA, newOrder, vecVisited);
        }
    }
    

    Of course, you do have the overhead of vecVisited. Thoughts on this approach, anyone?

    0 讨论(0)
  • 2020-11-28 06:58

    To iterate through the vector is O(n) operation. Its sorta hard to beat that.

    0 讨论(0)
提交回复
热议问题