In: Computer Science
(Code in C++)
1. We can dynamically resize vectors so that they may grow and shrink. While this is very convenient, it is inefficient. It is best to know the number of elements that you need for your vector when you create it. However, you might come across a situation someday where you do not know the number of elements in advance and need to implement a dynamic vector.
Rewrite the following program so that the user can enter any number of purchases, instead of just 10. (Hint: use push_back().)
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<double> purchases(10);
for (int i = 0; i < 10; i++)
{
cout << "Enter a purchase amount";
cin >> purchases[i];
}
return (0);
}
You these input values to test your program: 6.3, 5.4, 12.3, 1234.45, 89.9, 34.56, 12.6
2. Now add to the code from the previous part to print out the vector in reverse order and remove each element after it is printed.
Answer:
Give me a thumbs up if you like my work !!!
I have written the below code based on your requirements.
The below code has no-error and it is working perfectly.
Here, I have used push_back() to insert as many elements that we want to insert.
And I'm printing the elements in reverse order.
After printing the elements, it will remove them.
I have also attached the Output Screenshot that I got by running the below program.
Output:
Code:
#include<vector>
#include<iostream>
using namespace std;
int main()
{
vector<double> purchases;
double temp;
for(int i=0;i<7;i++)
{
cout<<"Enter a purchase
amount ";
cin>>temp;
purchases.push_back(temp);
}
cout<<"\nPrinting in Reverse Order :
\n\n";
while(purchases.size() > 0)
{
vector<double>:: iterator
it=purchases.end();
it--;
cout<<purchases[purchases.size() - 1]<<" ";
purchases.erase(it);
}
return 0;
}