c++ - 获取 map<string,vector<string>> 的键

标签 c++

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

最佳答案

您可以遍历映射中的所有值(它们是成对的)并引用它们的第一个和第二个元素以分别获取键和映射值:

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

关于c++ - 获取 map<string,vector<string>> 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15321530/

相关文章:

c++ - 在没有任何内存泄漏的情况下初始化 const char *

c++ - 我如何调整 erase-remove 习语来处理 vector 元组?

c++ - 计算大数的幂

c++ - 如何获取源代码(C++)深处的变量值? (例如 haar.cpp、OpenCV 中 stage_sum 的值)

c++ - 如何在 C++ 中重载一元减号运算符?

C++:这个磁盘寻道会对性能造成很大影响吗?

c++ - 不熟悉c++指针,需要帮助

c# - 从 c# 调用 c++ 函数指针

c++ - 将 Bitset 数组转换为 vector <bool>

c++ - static_cast 从基析构函数到指向派生类的指针的安全性