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