0

trying to sort a dynamic array sum_array but the function is not working.also my loop used to self terminate if i dont put the size of array as 1 could there be something with my declaration

**#include<bits/stdc++.h>
#include<algorithm>
#include<vector>

using namespace std;

int main(){

  vector <int> sum_array (1);
  int n;
  cin>>n;
  int sum,marks;
  for (int i = 0; i < 5; i++) {
    cout<<"turn now is ="<<i<<endl;
    sum=0;
    for (int k = 0; k < (n-1); k++) {
    cin>>marks;
    sum=sum+marks;
    cout<<"sum="<<sum<<endl;
    }
  sum_array[i]=sum;
  }
  for (int i = 0; i < 5; i++) {
    cout<<sum_array[i]<<endl;
  }
  sort(sum_array.begin(),sum_array.end());
  cout<<"after"<<endl;
  for (int i = 0; i < 5; i++) {
    cout<<sum_array[i]<<endl;
  }
    return 0;
}**
ash1102
  • 409
  • 4
  • 20
  • You create `sum_array` with one element but then set `sum_array[i]` with `i` in the range [0, 5) without ever resizing. That's undefined behaviour. It also means `sort` will only consider that one item. – G.M. Apr 20 '19 at 12:50
  • `sum_array` is given a size of one element, but elements `0` to `4` are assigned. Assigning elements like that does not implicitly resize. Instead, your code has undefined behaviour. – Peter Apr 20 '19 at 12:51
  • i thought vector was a dynamic array that doubles up on its own.if its showing me elements from 0 to 4 that means they were fitted by resizing the array then why is it undefined when i try to sort them. how do i fix it? – ash1102 Apr 20 '19 at 12:58
  • Do not `#include `, [see why](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – n. m. could be an AI Apr 21 '19 at 05:40

1 Answers1

2

You're creating a vector of one integer:

std::vector<int> sum_array(1);

Then you access elements out of bounds of the vector (which is undefined behaviour).

for (int i = 0; i < 5; i++) {
  // ...
  sum_array[i] = sum;
}

std::sort is only sorting a vector of one element so it isn't doing anything.

Since you do not know the size of the vector, you should initialize it as an empty vector:

std::vector<int> sum_array;

and push the elements into the sum_array:

sum_array.push_back(sum);    
Samleo
  • 605
  • 5
  • 16
Indiana Kernick
  • 5,041
  • 2
  • 20
  • 50