2013-01-08 54 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] 
相關問題