How to print out the contents of a vector?

后端 未结 19 1579
旧时难觅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:20

    Using std::copy but without extra trailing separator

    An alternative/modified approach using std::copy (as originally used in @JoshuaKravtiz answer) but without including an additional trailing separator after the last element:

    #include 
    #include 
    #include 
    #include 
    
    template 
    void print_contents(const std::vector& v, const char * const separator = " ")
    {
        if(!v.empty())
        {
            std::copy(v.begin(),
                      --v.end(),
                      std::ostream_iterator(std::cout, separator));
            std::cout << v.back() << "\n";
        }
    }
    
    // example usage
    int main() {
        std::vector v{1, 2, 3, 4};
        print_contents(v);      // '1 2 3 4'
        print_contents(v, ":"); // '1:2:3:4'
        v = {};
        print_contents(v);      // ... no std::cout
        v = {1};
        print_contents(v);      // '1'
        return 0;
    }
    

    Example usage applied to container of a custom POD type:

    // includes and 'print_contents(...)' as above ...
    
    class Foo
    {
        int i;
        friend std::ostream& operator<<(std::ostream& out, const Foo& obj);
    public:
        Foo(const int i) : i(i) {}
    };
    
    std::ostream& operator<<(std::ostream& out, const Foo& obj)
    {
        return out << "foo_" << obj.i; 
    }
    
    int main() {
        std::vector v{1, 2, 3, 4};
        print_contents(v);      // 'foo_1 foo_2 foo_3 foo_4'
        print_contents(v, ":"); // 'foo_1:foo_2:foo_3:foo_4'
        v = {};
        print_contents(v);      // ... no std::cout
        v = {1};
        print_contents(v);      // 'foo_1'
        return 0;
    }
    

提交回复
热议问题