Thread: Vector pair

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    Vector pair

    Im trying to create a vector of pairs, im kinda stuck here.

    Code:
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    typedef pair<string, int> MyPair;
    
    int main ()
    {
        vector<string> first;
        vector<int> second;
        vector<MyPair>::iterator it;
        vector<MyPair> vPair;
        const char* names[] = { "Sneezy","Dopey",
                                "Sleepy", "Doc",
                                "Happy", "Bashful", "Grumpy"
                              };
    
        for (int i=0; i<7; i++) first.push_back (names[i]);
        for (int i=0; i<7; i++) second.push_back (i*10);
    
        for (int i=0; i<7; i++)
            vPair.push_back(make_pair<first[i], second[i]>);
    
        for (it=first.begin(); it!=first.end(); ++it)
            cout << " " << *it;
    
        cout << endl;
        return 0;
    }
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You should probably #include <string> if you want to use it. And similarly, make_pair is in <utility>, right? Otherwise, what issues are you having?

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Firstly, make_pair would be called like this:

    Code:
    vPair.push_back(make_pair(first[i], second[i]));
    Secondly, are you trying to loop over the vector of strings or vector of pairs here:

    Code:
    for (it=first.begin(); it!=first.end(); ++it)
    If it's the latter than pair doesn't overload operator<<, you'll need to output pair.first and pair.second separately.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Thank you Tabstop and Anon, i managed to work it out.
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed