你可以使用一個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