How do I use for_each to output to cout?

后端 未结 5 1462
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 14:58

Is there a more straight-forward way to do this?

for_each(v_Numbers.begin(), v_Numbers.end(), bind1st(operator<<, cout));

Without an expli

5条回答
  •  -上瘾入骨i
    2020-12-23 15:42

    yup, using lambda expression (C++ 11) we can inline printing of each element of a STL container to cout.

    #include    // cout
    #include      // vector
    #include   // for_each
    #include    // istream_iterator
    using namespace std;
    
    int main()
    {
       std::vector v(10,2);
       std::for_each(v.begin(), v.end(), [](int i)->void {std::cout << i <

    For reading "n" values from cin to vector,

     int main()
     {
       std::vector v;
    
       int elementsToRead;
       cin>>elementsToRead;  // Number of elements to copy
    
       // Reading from istream
       std::istream_iterator ii2(std::cin);
       std::copy_n(ii2, elementsToRead, std::back_inserter(v));
    
       // printing updated vector
       std::for_each(v.begin(), v.end(), [](int i)->void {cout << i <

    (or) by using Lambda expression

    std::for_each(std::istream_iterator(cin),std::istream_iterator(),[&v](int i)->void { v.push_back(i);});
    

    To know more about Lambda expression @ What is a lambda expression in C++11?

提交回复
热议问题