Random Access in multimap's value, or should I just use map of vector
I was wondering, is there any way to perform random access in multimap's values.
#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?
st开发者_开发问答d::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();
}
Since random access to map's values is one of the requirement, is it better to use map of vector then?
std::multimap<>
's iterators are strictly bidirectional (§23.3.2/1), so no, random-access between values with the same key is not possible.
精彩评论