How to print out the contents of a vector?

后端 未结 19 1175
旧时难觅i
旧时难觅i 2020-11-22 03:46

I want to print out the contents of a vector in C++, here is what I have:

#include 
#include 
#include 
#include         


        
19条回答
  •  终归单人心
    2020-11-22 04:32

    I think the best way to do this is to just overload operator<< by adding this function to your program:

    #include 
    using std::vector;
    #include 
    using std::ostream;
    
    template
    ostream& operator<< (ostream& out, const vector& v) {
        out << "{";
        size_t last = v.size() - 1;
        for(size_t i = 0; i < v.size(); ++i) {
            out << v[i];
            if (i != last) 
                out << ", ";
        }
        out << "}";
        return out;
    }
    

    Then you can use the << operator on any possible vector, assuming its elements also have ostream& operator<< defined:

    vector  s = {"first", "second", "third"};
    vector    b = {true, false, true, false, false};
    vector     i = {1, 2, 3, 4};
    cout << s << endl;
    cout << b << endl;
    cout << i << endl;
    

    Outputs:

    {first, second, third}
    {1, 0, 1, 0, 0}
    {1, 2, 3, 4}
    

提交回复
热议问题