2

map<string,vector<string>>mymap假设我怎样才能得到这样一张地图的钥匙mymap["index"]={"val1","val2"}?我在这里找到了像法线贴图这样的解决方案,map<string,string>但为此我不知道该怎么做。

4

2 回答 2

7

You can iterate through all the values in the map (which are pairs) and refer their first and second element to obtain, respectively, the key and the mapped value:

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

int main()
{
    std::map<std::string, std::vector<std::string>> m;
    // ...
    for (auto& p : m)
    {
        std::string const& key = p.first;
        // ...

        std::vector<std::string>& value = p.second;
        // ...
    }
}

Of course, you could achieve the same using std::for_each instead:

#include <map>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    std::map<std::string, std::vector<std::string>> m;
    // ...
    std::for_each(begin(m), end(m), [] (
        std::pair<std::string const, std::vector<std::string>>& p
        //                    ^^^^^
        //                    Mind this: the key is constant. Omitting this would
        //                    cause the creation of a temporary for each pair
        )
    {
        std::string const& key = p.first;
        // ...

        std::vector<std::string>& value = p.second;
        // ...
    });
}

Finally, you may also roll your own manual for loop, although I personally consider this less idiomatic:

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

int main()
{
    std::map<std::string, std::vector<std::string>> m;
    // ...
    for (auto i = begin(m); i != end(m); ++i)
    {
        std::string const& key = i->first;
        // ...

        std::vector<std::string>& value = i->second;
        // ...
    }
}

This is how the last example above would look like in C++03, where type deduction through auto is not supported:

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

int main()
{
    typedef std::map<std::string, std::vector<std::string>> my_map;
    my_map m;

    // ...
    for (my_map::iterator i = m.begin(); i != m.end(); ++i)
    {
        std::string const& key = i->first;
        // ...

        std::vector<std::string>& value = i->second;
        // ...
    }
}
于 2013-03-10T11:10:54.700 回答
3

地图在std::pair<key_type, mapped_type>内部保存,因此在地图上进行迭代可以让您通过 访问键it->first,其中it是迭代器。

std::map<std::string, std::vector<string>> m;

for (auto it = m.cbegin(), it != m.cend(); ++it)
  std::cout << "key " << it->first << std::endl;

基于范围的循环版本是

for (const auto& stuff : m)
  std::cout << "key " << stuff.first << std::endl;
于 2013-03-10T11:07:18.957 回答