this is my code
#include <iostream>
#include<conio.h>
#include <vector>
using namespace std;
int main() {
int n,sum=0;
cout<<"Input n:";
cin>>n;
vector<int> x(n);
cout<<"input of elements";
for(int i=0;i<x.size();i++) {
cout<<x[i]<<endl;
sum+=x[i];
}
cout<<"sum"<<sum<<endl;
getch ();
return 0;
}
this program is running but ı want to sum of elements
You've allocated memory to the std::vector<int> x but haven't actually put any values in it's cells. This needs to be done (hint: push_back()) and then the elements of the vector can be summed through a loop as you've shown for by using std::accumulate (#include <algorithm>)
it does that.
you read in the size of a vector
then you create the vector of that size
then you loop over the vector and write out the uninitialized values and sum them
then you write out the sum
what you don't do is read in the vector elements or assign them something simple.
try this..
vector<int> x(n, 2);
sum written should be 2*n now.
you should be able to adapt from there to do whatever it is you want (maybe cin each entry THEN add it up??)
Line 9 reserves n elements. It does not initialize them.
Lines 12-13 are in the wrong order. You want to push the value onto the vector before trying to cout the value.
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.