How to print out the contents of a vector?

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

    For people who want one-liners without loops:

    I can't believe that noone has though of this, but perhaps it's because of the more C-like approach. Anyways, it is perfectly safe to do this without a loop, in a one-liner, ASSUMING that the std::vector is null-terminated:

    std::vector test { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0' };
    std::cout << test.data() << std::endl;
    

    But I would wrap this in the ostream operator, as @Zorawar suggested, just to be safe:

    template std::ostream& operator<< (std::ostream& out, std::vector& v)
    {
        v.push_back('\0'); // safety-check!
        out << v.data();
        return out;
    }
    
    std::cout << test << std::endl; // will print 'Hello, world!'
    

    We can achieve similar behaviour by using printf instead:

    fprintf(stdout, "%s\n", &test[0]); // will also print 'Hello, world!'
    

    NOTE:

    The overloaded ostream operator needs to accept the vector as non-const. This might make the program insecure or introduce misusable code. Also, since null-character is appended, a reallocation of the std::vector might occur. So using for-loops with iterators will likely be faster.

提交回复
热议问题