我知道,如果我使用实现iterator
接口(提供begin()
和end()
函数的c ++容器),则可以使用这样的for循环对其进行迭代: / p>
for (auto element : container) {
process(element);
}
如果我有两个容器类型相同的实例,我可以编写这样的代码
for (auto element : container1) {
process(element);
}
for (auto element : container2) {
process(element);
}
但是,这导致了重复的代码。我正在寻找一种组合两个容器的方法,以便可以一次遍历它们(即让for循环遍历第一个容器,然后继续遍历第二个容器)。像这样:
for (auto element : container1 + container2) {
process(element);
}
我知道,如果碰巧是矢量,我可以使用container1.insert(container1.end(),container2.begin(),container2.end());
之类的东西将它们串联起来,但是我希望能够更普遍地在一行中做到这一点,而无需修改任何一个容器。