How to cin to a vector

后端 未结 20 2523
萌比男神i
萌比男神i 2020-11-27 14:44

I\'m trying to ask the user to enter numbers that are put into a vector, then using a function call to count the numbers, why is this not working? I am only able to count t

20条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 15:40

    You need a loop for that. So do this:

    while (cin >> input) //enter any non-integer to end the loop!
    {
       V.push_back(input);
    }
    

    Or use this idiomatic version:

    #include  //for std::istream_iterator 
    
    std::istream_iterator begin(std::cin), end;
    std::vector v(begin, end);
    write_vector(v);
    

    You could also improve your write_vector as:

     #include  //for std::copy
    
    template 
    void write_vector(const vector& v)
    {
       cout << "The numbers in the vector are: " << endl;
       std::copy(v.begin(), v.end(), std::ostream_iterator(std::cout, " "));
    }
    

提交回复
热议问题