2016-09-25 42 views
-3

如何在C++中爲地圖中的特定鍵創建矢量以及如何訪問它們? 假設我在此格式在C++中存儲地圖中的鍵的向量,並通過遍歷地圖訪問鍵的向量

100 6 7 
    56 7 8 
    100 90 8 
    100 8 9 

這裏100和在第一柱56是鍵接受數據和用於鑰匙100我需要創建包含元素6 7 90 8 8 9 和用於鍵56的載體,載體應我們如何在C++中做到這一點,並在同一時間如何訪問C++中的某個鍵的向量? 我試圖用這種方法插入矢量鍵,但無法通過迭代地圖來訪問鍵的矢量。

int k; 
cin>>k; 
for(int i=1;i<=k;i++){ 
    int r,c1,c2; 
    cin>>r>>c1>>c2; 
    mymap[r].push_back(c1); 
    mymap[r].push_back(c2); 

} 

怎樣才能在C++中使用map?

+0

你確實是知道如何遍歷一個['的std :: map'(http://en.cppreference.com/w/cpp/container/map)?你知道迭代器「指向」一個['std :: pair'](http://en.cppreference.com/w/cpp/utility/pair)?你能否詳細說明你遇到的問題?如果可能的話,請嘗試創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)並向我們展示。 –

+0

@JoachimPileborg我發現很難訪問矢量的關鍵。你可以寫一個代碼,如何獲取一個鍵的元素?對於鍵100,我應該有矢量6 7 90 8 8 9以獲得打印 – yellowpanda

+0

您似乎已經知道'mymap [r]'可以訪問矢量,因此您可以在其上調用'push_back'。如何嘗試'mymap [r] .begin()'和'mymap [r] .end()'? –

回答

0

如果你想使用地圖,那麼你想要做的就是繼續添加到與關鍵字相關的向量。

下面的示例演示如何做到這一點:

#include <map> 
#include <vector> 
#include <string> 
#include <sstream> 

typedef std::map<int, std::vector<int>> MapV; 

using namespace std; 

int main() 
{ 
    MapV mymap; 
    string line; 

    // get one line of data 
    while (getline(cin, line)) 
    { 
     // use a string stream to parse the data 
     istringstream strm(line); 
     int key, data; 

     // first value is the key 
     strm >> key; 

     // all other values are the data 
     while (strm >> data) 
     { 
      // the magic is here. 
      auto pr = mv.insert(make_pair(key, std::vector<int>())); 

      // add item to the vector 
      pr.first->second.push_back(data); 
     } 
    } 
} 

代碼的最重要的部分是這一行:

auto pr = mv.insert(make_pair(key, std::vector<int>())); 

std::map::insert函數會返回一個std::pair,表示該迭代器插入的項目作爲對的first,或者如果密鑰存在,則將現有迭代器添加到已存在的密鑰中。

然後,我們需要做的就是獲取該返回值,訪問該向量上的second(它是向量),並且僅訪問push_back

看到這個live example