How to iterate through a std::map<string,int> and std::vector<int> using single for loop?

早过忘川 提交于 2019-12-07 03:49:28

If you know there's both the same length, use something like:

auto vit = begin(value);
auto mit = begin(data);
for (; vit != end(value); ++mit, ++vit) {
    // Use mit and vit
}

How about a do-while? Provided that your containers aren't empty.

auto iv = std::begin(value);
auto id = std::begin(data);

do {
    // Use those iterators
} while(++iv != std::end(value) && ++id != std::end(data))

Or use while if you'd like to handle empty containers too.

auto iv = std::begin(value);
auto id = std::begin(data);

while(iv != std::end(value) && id != std::end(data)) {
    // Use those iterators

    iv++; id++;
}
Chen OT

Consider boost::zip_iterator discussed in this answer https://stackoverflow.com/a/8513803/2210478

You can iterate over both the map and the vector and make sure to check the iterators against the end of the corresponding container.

auto map_iter = data.begin();
auto vec_iter = value.begin();
for (; map_iter != data.end() && vec_iter != value.end();
       ++map_iter, ++vec_iter) {
    // Use map_iter and vec_iter
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!