Sort two vectors in the same order

This is a discussion on Sort two vectors in the same order within the C++ Programming forums, part of the General Programming Boards category; If I have a string vector and an int vector of the same size, how can I sort the name ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    Sort two vectors in the same order

    If I have a string vector and an int vector of the same size, how can I sort the name vector alphabetically and sort the int vector in the same order? For example, I have string vector with John, Bob, Mike and an int vector with their ages 20, 21, 22, and I want to sort the vectors so it becomes Bob, John, Mike and 21, 20, 22. If I sort their names alphabetically, how can I sort their ages so that they match up?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,644
    I suggest associating the names and ages either with a std::pair (i.e., you sort a vector of std::pair<string,int> by the first member of the pair), or by placing them together in a class (and also providing operator< or a comparator).
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    You could use a map<string, int> instead of 2 vectors, then sorting would be irrelavent. You could also create a struct:
    Code:
    struct NameAge
    {
        std::string  Name,
        int  Age
    };
    Then just create a vector<NameAge> instead of 2 vectors.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 07-05-2010, 10:43 AM
  2. pointers and vectors
    By rwmarsh in forum C++ Programming
    Replies: 6
    Last Post: 04-01-2006, 11:06 PM
  3. Sorting
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 11-10-2003, 04:21 PM
  4. radix sort and radix exchange sort.
    By whatman in forum C Programming
    Replies: 1
    Last Post: 07-31-2003, 12:24 PM
  5. Bubble Sort, Qucik Sort
    By insomniak in forum C Programming
    Replies: 2
    Last Post: 03-15-2003, 03:54 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21