How to print out the contents of a vector?

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

    A much easier way to do this is with the standard copy algorithm:

    #include 
    #include  // for copy
    #include  // for ostream_iterator
    #include 
    
    int main() {
        /* Set up vector to hold chars a-z */
        std::vector path;
        for (int ch = 'a'; ch <= 'z'; ++ch)
            path.push_back(ch);
    
        /* Print path vector to console */
        std::copy(path.begin(), path.end(), std::ostream_iterator(std::cout, " "));
    
        return 0;
    }
    

    The ostream_iterator is what's called an iterator adaptor. It is templatized over the type to print out to the stream (in this case, char). cout (aka console output) is the stream we want to write to, and the space character (" ") is what we want printed between each element stored in the vector.

    This standard algorithm is powerful and so are many others. The power and flexibility the standard library gives you are what make it so great. Just imagine: you can print a vector to the console with just one line of code. You don't have to deal with special cases with the separator character. You don't need to worry about for-loops. The standard library does it all for you.

提交回复
热议问题