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;
}**
4
  • 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. Commented Apr 20, 2019 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. Commented Apr 20, 2019 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? Commented Apr 20, 2019 at 12:58
  • Do not #include <bits/stdc++.h>, see why Commented Apr 21, 2019 at 5:40

1 Answer 1

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);    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.