你可以使用一个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的特征(初始化列表,自动关键字) 。查看上面的链接示例以获得成功的编译。
为了自己编译它,请确保您使用的编译器支持这些功能或将它们替换为适当的C++ 03等效项。
例如,这里是迭代器类型(即使用在上面的代码auto
关键字美化):
// 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;
为什么不'map'? – leemes
@你的意思是'std :: multimap',但是,是最简单的解决方案。哦,等等,你的意思是'std :: map>',是的,也应该可以工作。 –
@ChristianRau哦,当然是'std :: multimap',而不是'map <...,vector ...>'。对不起;) – leemes