C++ 多重映射中的随机存取&x27;s值,还是应该使用向量的映射

C++ 多重映射中的随机存取&x27;s值,还是应该使用向量的映射,c++,stl,C++,Stl,我想知道,有没有办法对multimap的值执行随机访问 #include <map> #include <vector> #include <string> int main() { std::map<std::string, std::vector<std::string>> m0; m0["Food"].push_back("Ice Cream"); m0["Food"].push_back("Pizza

我想知道,有没有办法对multimap的值执行随机访问

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

int main() {
    std::map<std::string, std::vector<std::string>> m0;

    m0["Food"].push_back("Ice Cream");
    m0["Food"].push_back("Pizza");

    // Random access to Pizza. Nice!
    printf ("2nd Food is %s\n", m0["Food"][1].c_str());

    std::multimap<std::string, std::string> m1;
    m1.insert(std::pair<std::string, std::string>("Food", "Ice Cream"));
    m1.insert(std::pair<std::string, std::string>("Food", "Pizza"));

    // Is there any way to perform random access in multimap?
    std::multimap<std::string, std::string>::const_iterator find = m1.find("Food");

    // Sequential access to Pizza. Bad :(
    // I wish to have something
    // printf ("2nd Food is %s\n", find[1].c_str());
    find++;
    printf ("2nd Food is %s\n", find->second.c_str());

    getchar();
}
#包括
#包括
#包括
int main(){
std::map m0;
m0[“食物”]。向后推(“冰淇淋”);
m0[“食物”]。向后推(“比萨饼”);
//随意获取比萨饼,很好!
printf(“第二种食物是%s\n”,m0[“食物”][1].c_str());
std::multimap m1;
m1.插入(标准:成对(“食品”、“冰淇淋”);
m1.插入(标准:成对(“食品”、“比萨饼”);
//有没有办法在multimap中执行随机访问?
std::multimap::const_迭代器find=m1.find(“食物”);
//按顺序访问比萨饼。错误:(
//我想要点东西
//printf(“第二种食物是%s\n”,查找[1].c_str());
查找++;
printf(“第二种食物是%s\n”,find->second.c_str());
getchar();
}

既然随机访问映射值是一项要求,那么使用向量映射更好吗?
std::multimap
的迭代器是严格双向的(§23.3.2/1),因此不可能使用相同的键在值之间进行随机访问。

multimap与向量映射不同你的第一个例子没有什么问题,为什么你想用不同的方式来做呢?