在地图内配对-如何foreach

pair inside map - how to foreach

本文关键字:如何 foreach 地图      更新时间:2023-10-16

我有这个代码:

typedef std::map<const char *, std::pair<const char *, const char *> > MyMap;
MyMap the_map;
the_map.insert(std::make_pair("Text1", std::make_pair("Text2", "Text3")));

显然,目的是以这种方式存储信息:

"Text1"->"Text2"->"Text3"

问题:如何预先处理第一个键的每个元素(如"Text1")并更改每个内部键的值(如"Text3")。

谢谢。

std::对没有begin()end()函数。

你只需要一个循环:

for (const auto& it : the_map) {
        std::cout << it.first << " " << it.second.first 
                  << " " << it.second.second << std::endl;
}

您可以使用映射的迭代器来抛出所有元素:

for (std::map<const char *, std::pair<const char *, const char *> >::iterator ii = the_map.begin(), e = the_map.end(); ii != e; ii++) {
    // ii.first  - key value
    // ii.second - stored value (in your case a pair)
    //
    // ii.second.first  - key value of pair stored in map under ii.first
    // ii.second.second - stored value of pair stored in map under ii.first
}