我有一个 map
并且我希望第一列 i.e (*it).first
被推回一个 vector 然后 (*it)->second
被推回到另一个 vector 中
这是最好的方法吗?
std::vector<std::string>test;
for ( it=mymap.begin() ; it != mymap.end(); it++ )
{
test.push_back((*it).first);
}
我的另一个问题是如果我有一个循环即
我如何将所有整数 i
插入到 (*it).first
中?
for(int i = 0; i < 10; i++)
{
// 1 - 10 will go in (*it).first
}
我想在 (*it).first
中有一些整数,并在 (*it).second;
中有相关值
最佳答案
使用 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;
}
然后使用std::transform
来自 <algorithm>
具有将 map 转换为 vector
的功能 key 或vector
的值(value)。
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;
}
输出:
Keys:
alice
bob
Values:
555-2701
555-2702
关于c++ - 将 C++ 映射复制到键和值 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9908591/