c++ - 接收任何可迭代的容器
问题描述
有没有办法接收任何可迭代容器作为参数?
我想要一个能够在能够接收任何容器的同时接收任何容器的begin()
功能end()
。除非我错了,否则每个容器都应该具有这些功能(std::view
不是吗?)。
具体来说,有没有办法接收Container作为参数?
C++20 和/或模板很好。
void do_stuff(any_iterable_collection<int> &coll) {
for (auto it = coll.begin() ; it != coll.end() ; ++it) {
// do stuff with *it
}
}
std::list<int> list;
std::vector<int> vector;
std::set<int> set;
do_stuff(list);
do_stuff(vector);
do_stuff(set);
解决方案
您可以简单地使用标准执行此操作的相同方式:
template <typename Iterator>
void do_stuff(Iterator first, Iterator last) {
for (auto it = first; it != last; it = std::next(it)) {
// do stuff with *it
}
}
int main() {
std::vector<int> vec = {1, 5, 9};
do_stuff(vec.begin(), vec.end());
return EXIT_SUCCESS;
}
如果您坚持使用容器:
template <template<typename> class Container>
void do_stuff(Container<int> &container) {
for (auto it = std::begin(container); it != std::end(container); it = std::next(it)) {
// do stuff with *it
std::cout << *it << std::endl;
}
}
或者对于更一般的容器:
template <template<typename> class Container, typename CType>
void do_stuff(Container<CType> &container) {
for (auto it = std::begin(container); it != std::end(container); it = std::next(it)) {
// do stuff with *it
std::cout << *it << std::endl;
}
}