2013-04-09 55 views
3

我想做这样的事情。有没有一个stl算法可以轻松做到这一点?如何将矢量中的值转换为C++中的地图?

for each(auto aValue in aVector) 
       { 
       aMap[aValue] = 1; 
       } 
+2

如何'aLabel'相关矢量? – juanchopanza 2013-04-09 21:29:40

+0

我认为你需要详细阐述一下...标签是从哪里来的?你真的想要一张所有值都设置为1的地图吗? – dotcomslashnet 2013-04-09 21:29:59

+0

对不起,它应该是一个值 – 2013-04-10 14:04:18

回答

0

试试这个:

for (auto it = vector.begin(); it != vector.end(); it++) { 
    aMap[aLabel] = it; 
    //Change aLabel here if you need to 
    //Or you could aMap[it] = 1 depending on what you really want. 
} 

我认为这是你正在尝试做的。

编辑:如果要更新aLabel的值,可以在循环中更改它。另外,我回头看原始问题,目前还不清楚他想要什么,所以我添加了另一个版本。

+0

你是对的。我更新了这个答案。 – OGH 2013-04-09 21:38:20

4

也许是这样的:

std::vector<T> v; // populate this 

std::map<T, int> m; 

for (auto const & x : v) { m[x] = 1; } 
+1

+1如果没有关于这个问题的更多细节,这件事情就会变得很好。 – WhozCraig 2013-04-09 21:38:53

6

如果你有对,其中一对中的第一项将是地图的主要的载体,和第二项将与该键关联的值,您可以将数据直接复制到地图插入迭代:

std::vector<std::pair<std::string, int> > values; 

values.push_back(std::make_pair("Jerry", 1)); 
values.push_back(std::make_pair("Jim", 2)); 
values.push_back(std::make_pair("Bill", 3)); 

std::map<std::string, int> mapped_values; 

std::copy(values.begin(), values.end(), 
      std::inserter(mapped_values, mapped_values.begin())); 

,或者你可以从矢量初始化地图:

std::map<std::string, int> m2((values.begin()), values.end()); 
0

矢量假设项目按顺序有关,也许这个例子可以帮助:

#include <map> 
#include <vector> 
#include <string> 
#include <iostream> 

std::map<std::string, std::string> convert_to_map(const std::vector<std::string>& vec) 
{ 
    std::map<std::string, std::string> mp; 
    std::pair<std::string, std::string> par; 

    for(unsigned int i=0; i<vec.size(); i++) 
    { 
     if(i == 0 || i%2 == 0) 
     { 
      par.first = vec.at(i); 
      par.second = std::string(); 
      if(i == (vec.size()-1)) 
      { 
       mp.insert(par); 
      } 
     } 
     else 
     { 
      par.second = vec.at(i); 
      mp.insert(par); 
     } 
    } 

    return mp; 
} 

int main(int argc, char** argv) 
{ 
    std::vector<std::string> vec; 
    vec.push_back("customer_id"); 
    vec.push_back("1"); 
    vec.push_back("shop_id"); 
    vec.push_back("2"); 
    vec.push_back("state_id"); 
    vec.push_back("3"); 
    vec.push_back("city_id"); 

    // convert vector to map 
    std::map<std::string, std::string> mp = convert_to_map(vec); 

    // print content: 
    for (auto it = mp.cbegin(); it != mp.cend(); ++it) 
     std::cout << " [" << (*it).first << ':' << (*it).second << ']'; 

    std::cout << std::endl; 

    return 0; 
} 
相关问题