如何按第一个字符串对成对的字符串向量进行分组? [英] How to group a vector of pairs of strings by first string?
问题描述
我有一个包含字符串对的向量:
I have a vector containing pairs of strings:
vector<pair<string, string>> list;
我想对具有相同 list[n].first
const size_t nbElements = list.size();
for (size_t n = 0; n < nbElements ; n++)
{
const string& name = list[n].first;
const string& type = list[n].second;
}
<小时>
考虑这个例子:
Consider this example:
(big; table) (normal; chair) (small; computer) (big; door) (small; mouse)
会导致:
(big; table, door) (normal; chair) (small; computer, mouse)
<小时>
你知道怎么做吗?
Do you have any idea how to do that?
推荐答案
您可以使用 std::map
示例:
#include <boost/algorithm/string/join.hpp>
#include <boost/format.hpp>
#include <iostream>
#include <map>
#include <vector>
int main() {
// define original data
std::vector<std::pair<std::string, std::string> > v =
{{"a", "b"}, {"a", "c"}, {"b", "a"}, {"b", "d"}, {"c", "e"}};
// populate map
std::map<std::string, std::vector<std::string> > grouped;
for (auto it = v.begin(); it != v.end(); ++it) {
grouped[(*it).first].push_back((*it).second);
}
// output
for (auto it = grouped.begin(); it != grouped.end(); ++it) {
std::cout << boost::format("(%s: %s)\n")
% (*it).first
% boost::algorithm::join((*it).second, ", ");
}
}
(a: b, c)
(b: a, d)
(c: e)
<小时>
注意,这段代码使用了 C++11 特性(初始化列表、auto 关键字).查看上面的链接示例以了解成功编译.
Note, this code makes use of C++11 features (initializer lists, auto keyword). Have a look at the linked example above for the successful compilation.
为了自己编译,请确保您使用的编译器支持这些功能或将它们替换为适当的 C++03 等效项.
In order to compile this yourself, make sure that the compiler you use supports these features or replace them with the appropriate C++03 equivalents.
例如,这里是迭代器类型(在上面的代码中使用 auto
关键字进行了美化):
For example, here are the iterator types (that are beautified using the auto
keyword in above code):
// the iterator on the vector `v`
std::vector<std::pair<std::string, std::string> >::iterator it_v;
// the iterator on the map `grouped`
std::map<std::string, std::vector<std::string> >::iterator it_grouped;
这篇关于如何按第一个字符串对成对的字符串向量进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!