Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pass any container to function

Tags:

c++

c++11

stl

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?

like image 346
Soapy Avatar asked Dec 19 '22 08:12

Soapy


2 Answers

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).

like image 183
ForEveR Avatar answered Jan 02 '23 18:01

ForEveR


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.

like image 44
Jonathan Mee Avatar answered Jan 02 '23 16:01

Jonathan Mee