将C++ Map复制到键和值向量中

Cod*_*sSC 5 c++ vector map

我有一个map,我希望第一列i.e (*it).first被推回到一个向量然后(*it)->second被推回另一个向量

这是最好的方法吗?

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

我的另一个问题是,如果我有一个循环,即如何将所有整数i插入(*it).first

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

我希望有一些整数,(*it).first并有相关的值(*it).second;

Pet*_*ood 5

使用std::transform.

首先定义两个函数key,value它们分别获取一对字符串并返回第一个或第二个值.

#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;
}
Run Code Online (Sandbox Code Playgroud)

然后使用std::transformfrom <algorithm>函数将地图转换vector为键或vector值.

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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Keys:
alice
bob

Values:
555-2701
555-2702
Run Code Online (Sandbox Code Playgroud)


Rob*_*obᵩ 2

您的第一个问题“如何将地图的第一列推入一个向量并将第二列推入另一个向量”因此得到解决:

std::map<std::string, std::string> mymap;
std::vector<std::string> keys;
std::vector<std::string> values;
for ( std::map<std::string,std::string>::iterator it=mymap.begin() ; it != mymap.end(); ++it )
{
  keys.push_back(it->first);
  values.push_back(it->second);
}
Run Code Online (Sandbox Code Playgroud)

你的第二个问题,“如何将所有整数插入i(*it).first” 就这样解决了:

std::map<int, int> mymap2;
for(int i = 0; i < 10; i++)
{
  // Insert default value into map
  // This sets '(*it).first' to 'i' and
  // '(*it).second' to a default value (in
  // this case, 0).
  mymap2[i];
}
Run Code Online (Sandbox Code Playgroud)

或者

std::map<int, int> mymap3;
for(int i = 0; i < 10; i++)
{
  // Insert specified value into map
  // this sets '(*it).first' to 'i', and
  // '(*it).second' to the value returned from the function.
  maymap3[i] = ChooseSpecificValue(i);
}
Run Code Online (Sandbox Code Playgroud)