多重地图值中的随机访问,或者我应该只使用矢量地图

Random Access in multimap's value, or should I just use map of vector

本文关键字:地图 我应该 或者 访问 随机      更新时间:2023-10-16

我想知道,是否有任何方法在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 %sn", 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 %sn", find[1].c_str());
    find++;
    printf ("2nd Food is %sn", find->second.c_str());
    getchar();
}

既然随机访问map的值是一个要求,那么使用map of vector更好吗?

std::multimap<>的迭代器是严格双向的(§23.3.2/1),所以不,具有相同键的值之间的随机访问是不可能的。