use template to print all the data of any container

后端 未结 2 1165
隐瞒了意图╮
隐瞒了意图╮ 2021-01-28 05:02

I plan to write a function which can print all the data of any container. In other words, I can use with different containers type like vector, deque or list and that I can call

2条回答
  •  情深已故
    2021-01-28 05:30

    As noted in the comments, std::list actually has more than one template parameter (the second parameter is the allocator). Moreover, there is no need for print to take two template parameters; you can simply parameterize it over the overall container type:

    #include 
    #include 
    #include 
    using namespace std;
    
    template 
    void print(const C &data){
        for(auto it=begin(data);it!=end(data);++it){
            cout<<*it<<" ";
        }
        cout< data;
        for(int i=0;i<4;i++){
            data.push_back(i);
        }
        print(data);
        return 0;
    }
    

    Demo.

    As pointed out in the other answer, if you can use C++11 features, a range-for loop is better than the explicit iterator use above. If you can't (which means no auto or std::begin or std::end either), then:

    template 
    void print(const C &data){
        for(typename C::const_iterator it=data.begin();it!= data.end();++it){
            cout<<*it<<" ";
        }
        cout<

    Note that since we take data by const reference, we need to use const_iterator.

提交回复
热议问题