如何使用ostream和模板打印任何矢量的内容?

时间:2018-09-26 17:13:44

标签: templates containers ostream

我可以使用模板指定的print_container函数来打印任何矢量的内容。我尝试使用ostream <<代替print_container函数。没用我不知道该如何解决。 请给我建议。

谢谢

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
using namespace std;

template<typename C>
void print_container(const C& c)
{
    for(auto p = c.begin(); p != c.end(); ++p)
    {
        cout << *p << ' ';
    }
    cout << '\n';
}

/*
template<typename C>
ostream& operator<<(ostream& os, const C& c)
{
    for(auto p = c.begin(); p != c.end(); ++p)
    {
        os << *p << ' ';
    }
}
*/

int main(void)
{
    string m {"Mary had a little lamb"};
    print_container(m);
    //cout << m;

    vector<string> vs {"red", "blue", "green", "green", "orange", "green"};
    print_container(vs);
    //cout << vs;

    return 0;
}

0 个答案:

没有答案