I'm trying to find a way to iterate through any STL container. Currently I have this:
std::string range(std::vector<int>& args)
{
for (auto it : args)
// do something
}
I'm looking for a way to be able to pass any type of STL container with any type to the function instead of std::vector<int>& args
. How can I do this?
Use templates.
template<typename Container>
std::string range(Container& args)
{
for (auto it : args)
// do something
}
Probably with overloading for special types (std::map
for example).
Consider that everything in algorithm does this.
You can call copy
, for example, on a list
and on vector
.
It seems like following that pattern is your best bet:
template<class InputIterator>
std::string range(InputIterator first, const InputIterator last)
{
while(first != last){
// do something
++first;
}
}
All that to say it depends on what you're going for but it's very likely that you can use a lambda and one of the find
algorithms or accumulate
to accomplish whatever you're doing in range
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With