Thread: sorting problem

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    222

    sorting problem

    Hi,

    let say my situation is the following. I have two vectors one of which is a vector of vectors:


    Code:
    vector<int> v1;
    
    vector<vector<int>> v2;
    in v1 contains index positions of vectors in v2:


    Code:
    v1:
    
    0
    1
    2
    3
    
    
    v2:
    
    0-> 8 5 6 4 2
    1-> 7 6
    2-> 81 1 91 9 1 1 2 3 54 1 
    3-> 1

    what i need to do is to sort v2 according to the size of vectors in it v2[i].size() and accordingly v1 such that:


    Code:
    after sort:
    
    
    v2:
    
    0-> 1
    1-> 7 6
    2-> 8 5 6 4 2
    3-> 81 1 91 9 1 1 2 3 54 1
    
    and v1:
    
    3
    1
    0
    2
    any clever solution to this problem ??

  2. #2
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    You can set your predicate to do exactly what you want...

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I suggest combining each inner vector with its original index:
    Code:
    struct ItemsIndexPair
    {
        std::vector<int> items;
        std::size_t index;
    };
    Then you can do something like this:
    Code:
    std::vector<ItemsIndexPair> all_items;
    all_items.push_back({{8, 5, 6, 4, 2}, all_items.size()});
    all_items.push_back({{7, 6}, all_items.size()});
    // ...
    
    std::sort(
        all_items.begin(),
        all_items.end(),
        [](const ItemsIndexPair& lhs, const ItemsIndexPair& rhs) {
            return lhs.items.size() < rhs.items.size();
        }
    );
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting problem?
    By audinue in forum C Programming
    Replies: 5
    Last Post: 01-06-2009, 02:16 PM
  2. Sorting problem
    By Markeller in forum C Programming
    Replies: 3
    Last Post: 05-22-2008, 11:15 AM
  3. problem with sorting
    By pinkpenguin in forum C Programming
    Replies: 2
    Last Post: 11-18-2005, 11:06 AM
  4. Sorting problem
    By stimpyzu in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2002, 01:07 AM
  5. Can anyone help with sorting problem???
    By DanTheMan in forum C Programming
    Replies: 1
    Last Post: 04-04-2002, 08:58 AM