我想知道,有没有办法在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();
}
由于随机访问地图的值是其中一项要求,那么使用矢量地图会更好吗?
答案 0 :(得分:2)
std::multimap<>
的迭代器是严格双向的(§23.3.2/ 1),所以不可能在具有相同键的值之间进行随机访问。