2

どうすればそのようなマップのキーを取得できますmap<string,vector<string>>mymapmymap["index"]={"val1","val2"}?私はここでのような法線マップの解決策を見つけましたmap<string,string>が、これについてはそれを行う方法がわかりません。

4

2 に答える 2

7

マップ内のすべての値(ペア)を反復処理し、それらの最初の要素と2番目の要素を参照して、それぞれキーとマップされた値を取得できます。

#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;
        // ...
    }
}

もちろん、std::for_each代わりに次を使用して同じことを実現できます。

#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;
        // ...
    });
}

最後に、for私は個人的にこれはあまり慣用的ではないと考えていますが、独自の手動ループをロールすることもできます。

#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;
        // ...
    }
}

これは、上記の最後の例がC ++ 03でどのように見えるかを示しています。ここでは、型の推定autoはサポートされていません。

#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 に答える