在使用auto
的for
循环中,迭代器迭代unordered_map
。像这样:
using RuleIndex = std::unordered_map<uint, Symbol*>;
RuleIndex rule_index;
for(const auto & rule_pair : rule_index ) {
std::cout << rule_pair.first << ": ";
printList(rule_pair.second, 0);
std::cout << std::endl;
}
假设所有变量都已正确定义,因为代码运行良好。我的问题是,如何排除第一次迭代?例如, map 包含 3 行,当前循环迭代 0、1、2。我只想迭代 1 和 2。
最佳答案
bool is_first_iteration = true;
for(const auto & rule_pair : rule_index) {
if (std::exchange(is_first_iteration, false)) continue;
std::cout << rule_pair.first << ": ";
printList(rule_pair.second, 0);
std::cout << std::endl;
}
std::exchange
调用将 false
赋值给 is_first_iteration
并返回之前的值。这实际上是 the paper proposing std::exchange
for C++14 中讨论的用例之一。 .该论文还展示了一个引用实现,如果您坚持使用 C++11,则可以使用。
关于c++ - 跳过 unordered_map 的第一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30182680/