use template to print all the data of any container

后端 未结 2 1068
隐瞒了意图╮
隐瞒了意图╮ 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:19

    Using c++11 you can simplify it to:

    template <typename C>
    void print(const C &data){
        for (auto &elem : data)
            cout << elem << " ";
        cout << endl;
    }
    

    and call it with print(data). You could also use std::for_each or copy it directly into cout.

    0 讨论(0)
  • 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 <iostream>
    #include <iterator>
    #include <list>
    using namespace std;
    
    template <typename C>
    void print(const C &data){
        for(auto it=begin(data);it!=end(data);++it){
            cout<<*it<<" ";
        }
        cout<<endl;
    }
    
    
    int main(int argc, char** argv) {
        list<int> 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 <typename C>
    void print(const C &data){
        for(typename C::const_iterator it=data.begin();it!= data.end();++it){
            cout<<*it<<" ";
        }
        cout<<endl;
    }
    

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

    0 讨论(0)
提交回复
热议问题