Thread: Sort two vectors in the same order

  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
    28,413
    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).
    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

  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-02-2006, 12:06 AM
  3. Sorting
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 11-10-2003, 05: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, 04:54 PM