Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a std container to a function

Tags:

c++

containers

I came up with the following:

template <typename T> inline void printcontainer( std::vector<T> container )
{
    for( auto it = container.begin(); it != container.end(); it++ )
    {
        std::cout << *it << std::endl;
    }
}


int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> v;
    v.push_back(5);
    v.push_back(4);
    v.push_back(3);
    printcontainer(v);

    return 0;
}

(Sorry for the push_backs, visual studio doesn't accept initializer lists...ugh!!)

now this function is limited to std::vector, how can I make it so that I can pass other containers, like std::list arrays etc...

like image 961
snoopy Avatar asked Jan 01 '16 23:01

snoopy


1 Answers

Simply don't template on the type stored by the container, but on the type of the container itself:

template <typename Container>
inline void printcontainer(const Container &container)

Note that I changed the argument to const reference to avoid an unnecessary copy.

You can generalize your print function to C arrays by using the non-member std::begin and std::end or by using a range based for loop:

template <typename Container>
inline void printcontainer(const Container &container) {
    for (const auto &v : container)
        std::cout << v << "\n";
}

OT remark: You probably do not need the inline here.

like image 140
Baum mit Augen Avatar answered Sep 18 '22 07:09

Baum mit Augen