Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying C++ Map into key and value vectors

Tags:

c++

map

vector

I have a map and I want the first column i.e (*it).first to be pushed back into a vector then (*it)->second to be pushed back into another vector

Is this the best way to do it?

std::vector<std::string>test;
for ( it=mymap.begin() ; it != mymap.end(); it++ )
{
    test.push_back((*it).first);
}

My other question is if i have a loop i.e how would I insert all the integers i into (*it).first?

for(int i = 0; i < 10; i++)
{
    // 1 - 10 will go in (*it).first
}

I want to have some integers in (*it).first and have associated values in (*it).second;

like image 449
CodersSC Avatar asked Mar 28 '12 13:03

CodersSC


1 Answers

Use std::transform.

First define two functions key and value which take the pair of strings and return the first or second value, respectively.

#include <map>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>

const std::string& key(const std::pair<std::string, std::string>& keyValue)
{
    return keyValue.first;
}

const std::string& value(const std::pair<std::string, std::string>& keyValue)
{
    return keyValue.second;
}

Then use std::transform from <algorithm> with the functions to transform the map into either a vector of keys or a vector of values.

int main()
{
    using namespace std; // be explicit normally, trying to be brief here

    map<string, string> contacts;

    contacts["alice"] = "555-2701";
    contacts["bob"] = "555-2702";

    vector<string> keys(contacts.size());
    vector<string> values(contacts.size());

    transform(contacts.begin(), contacts.end(), keys.begin(), key);
    transform(contacts.begin(), contacts.end(), values.begin(), value);

    cout << "Keys:\n";
    copy(keys.begin(), keys.end(), ostream_iterator<string>(cout, "\n"));

    cout << "\n";

    cout << "Values:\n";
    copy(values.begin(), values.end(), ostream_iterator<string>(cout, "\n"));

    return 0;
}

Output:

Keys:
alice
bob

Values:
555-2701
555-2702
like image 55
Peter Wood Avatar answered Oct 06 '22 00:10

Peter Wood