c++ - 打印一个 map 的值,它有两个字符串作为键和 vector 作为值

标签 c++ loops dictionary vector io

我有一张 map ,其中有两个字符串作为键,一个 vector 作为值 我怎样才能打印 map 的值(value)。

下面是我的方法,不好,有人可以帮我提前谢谢

注意:我想按键打印而不是在 vector 上迭代

int main()
{
        vector<string>value;
        std::map<std::pair<string,string> ,vector<string>> myMap;
        string input1,input2,MyvectorValue;
        for(int i=0;i<5;++i)
        {
                cin>>input1;
                cin>>input2;
                cin>>MyvectorValue;
                myMap[std::make_pair(input1,input2)].push_back(MyvectorValue);
        }
        int j=0;
        for( auto it = myMap.begin(); it != myMap.end(); ++it )
        {
                std::vector<std::string>& value = it->second.at(j++);
               cout<<value  // This is bad

           //how can i print all map value ??
        }
}

最佳答案

映射的值是一个 vector ,假设你可以使用 C++11,下面的代码就可以满足你的需要。

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

int main()
{
    std::vector< std::string >value;
    std::map< std::pair<std::string , std::string> ,    std::vector<std::string> > myMap;
    std::string input1,input2,MyvectorValue;
    for(int i=0;i<5;++i)
    {

        std::cin>>input1;
        std::cin>>input2;
        std::cin>>MyvectorValue;
        myMap[std::make_pair(input1,input2)].push_back(MyvectorValue);
    }

    //If you have a particular key (string1, string2), and want to print the values for that specific key...
    auto particularKey = std::make_pair("stringA", "stringB");
    for(auto val : myMap[particularKey])
        std::cout << val << " ";
    std::cout << std::endl;

    // If you want to iterate through all keys of your map
    for(auto &elem : myMap)
    {
        std::cout << "for the pair with key (" << elem.first.first << "," << elem.first.second << "), the value is the following vector" << std::endl;
        for(auto s : elem.second)
        {
            std::cout << s << " ";
        }
        std::cout << std::endl << std::endl;
    }
    return 0;
}

关于c++ - 打印一个 map 的值,它有两个字符串作为键和 vector 作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619305/

相关文章:

c++ - 当我不知道类型时如何将参数传递给函数

c++ - 在 C++ 函数中声明输入数组的大小

c++ - 在 Windows 中渲染背景桌面的实时预览

c - 加速循环执行 unsigned long long 模运算的性能

java - 将 for 循环外的值传递给变量 - java::processing

JavaScript - 通过对象递归循环

python - 解析嵌套的Python字典

c++ - 如何在 Qt 子类中处理信号?

python - 如何在 python 中将值列表转换为字典?

python 将字典数组映射到字典?