2013-01-08 31 views
2

我有一个包含字符串的对一个矢量:如何通过第一个字符串将字符串对的向量分组?

vector<pair<string, string>> list; 

欲组list[n].second串具有相同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; 
} 

考虑这个例子:

(big; table) (normal; chair) (small; computer) (big; door) (small; mouse) 

将导致:

(big; table, door) (normal; chair) (small; computer, mouse) 

你有任何想法如何做到这一点?

+3

为什么不'map'? – leemes

+3

@你的意思是'std :: multimap',但是,是最简单的解决方案。哦,等等,你的意思是'std :: map >',是的,也应该可以工作。 –

+0

@ChristianRau哦,当然是'std :: multimap',而不是'map <...,vector ...>'。对不起;) – leemes

回答

4

你可以使用一个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; 
+1

'std :: multimap'是为此做的。 (当然你的解决方案也可以) – leemes

+2

@leemes我认为这更像是一个keyst_store多个值的情况,而不是_store具有相同key_的多个条目。我发现multimap对于某些任务有点麻烦。 – moooeeeep

+0

我得到错误(auto it = result.begin(); it!= result.end(); ++ it){ - 错误C4430:缺少类型说明符 - int假定。注意:C++不支持default-int - error C2440:'initializing':无法从'std :: _ Vector_iterator <_Ty,_Alloc>'转换为'int' – tchike

3

您可能需要多重映射。

std::multimap<std::string, std::string> items; 
items.insert("Big", "Chair"); 
items.insert("Big", "Table"); 
items.insert("Small", "Person"); 


for(auto i = items.begin(); i!=items.end; i++) 
{ 
    std::cout<<"["<<i->first<<" , "<<i->second<<"]"<<std::endl; 
} 

输出:

[Big, Chair] 
[Big, Table] 
[Small, Person] 
相关问题