如何使用基于范围的循环创建自定义类以循环STL容器中的连续项目对?
这是我想要的语法和输出:
std::list<int> number_list;
number_list.push_back(1);
number_list.push_back(2);
number_list.push_back(3);
auto paired_list = Paired(number_list);
for (const auto & pair : paired_list) {
std::printf("The pair is (%d, %d)\n", *(pair[0]), *(pair[1]));
// or
//std::printf("The pair is (%d, %d)\n", *(pair.first), *(pair.second));
}
// output:
// The pair is (1, 2)
// The pair is (2, 3)
Run Code Online (Sandbox Code Playgroud)
我知道这些(以及更多)是必需的,但我无法弄清楚:
template <class T>
class Paired {
???
class iterator {
???
}
iterator begin() {
...
}
iterator end() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
不要担心const修饰符.
没有提升.
请勿修改或复制容器中的对象.