Input and termination of elements in vectors

Source: Internet
Author: User

In essential C + + a book after the answer to question 1-6, there is a new discovery.

The topics are summarized as follows:

Write a program that reads an integer from the standard input device and places the integer that is being read into the array and vector, and then iterates through the two containers to find the sum of the values. Outputs the sum and the average to the standard output device.

Answer code:

Solving problems with vectors
#include <iostream>
#include <vector>//head file with vector method
using namespace Std;

int main ()
{
vector<int>ivec; The definition of vector
int ival; What role?
int Sum,average,ix;


while (Cin>>ival)
Ivec.push_back (ival);

? while (Cin>>ival)
Ivec.push_back (ival);
Enter the ival and store it in the middle of the Ivec.
CT Rl+d, then press ENTER to end.
Push_back is a default action function that inserts an element at the tail of the vector, and the value of the element is the value of ival.
We can calculate the sum in real time when the value is entered.
The practice here is to iterate over the elements of the vector and accumulate
For (Sum=0,ix=0;ix<ivec.size (); ++ix)
Sum+=ivec[ix];
Average=sum/ivec.size ();
cout << "Sum of" <<ivec.size ()
<< "Elements:" <<sum
<< ". Average: "<<average<<endl;
return 0;

}

New Knowledge Points:

int ival;

while (Cin>>ival)
Ivec.push_back (ival);
Enter the ival and store it in the middle of the Ivec.
CT Rl+d, then press ENTER to end.
Push_back is a default action function that inserts an element at the tail of the vector, and the value of the element is the value of ival.
We can calculate the sum in real time when the value is entered.

The point is to learn the operation of this function and how to terminate the input start output at execution time.

Input and termination of elements in vectors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.