How to print out the contents of a vector?

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

    How about for_each + lambda expression:

    #include 
    #include 
    ...
    std::vector vec;
    ...
    std::for_each(
                  vec.cbegin(),
                  vec.cend(),
                  [] (const char c) {std::cout << c << " ";} 
                  );
    ...
    

    Of course, a range-based for is the most elegant solution for this concrete task, but this one gives many other possibilities as well.

    Explanation

    The for_each algorithm takes an input range and a callable object, calling this object on every element of the range. An input range is defined by two iterators. A callable object can be a function, a pointer to function, an object of a class which overloads () operator or as in this case, a lambda expression. The parameter for this expression matches the type of the elements from vector.

    The beauty of this implementation is the power you get from lambda expressions - you can use this approach for a lot more things than just printing the vector.

提交回复
热议问题