Vector pair

This is a discussion on Vector pair within the C++ Programming forums, part of the General Programming Boards category; Im trying to create a vector of pairs, im kinda stuck here. Code: #include <iostream> #include <algorithm> #include <vector> using ...

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

    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;
    }
    Compiler MSVC++ 2013 with Code::Blocks.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    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
    812
    Thank you Tabstop and Anon, i managed to work it out.
    Compiler MSVC++ 2013 with Code::Blocks.

Popular pages Recent additions subscribe to a feed

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