C ++: index out of range

Here comes the function with which I have a problem:

ivec sort_index( vec list, int length ) {  //UNSORTED VECTOR OF INPUT VALUEAS

 ivec index;
 index = zeros_i(N);
 float temp = 0;
 int temp2 = 0;

 for ( int j = 0 ; j<N ; j++){
      index[j]=j; // VALUES IN INCREASING ORDER
 }

 int i = 1;
 while ( i < length ){
       for (int k = i; list[k - 1] > list[k]; k--){
            temp = list[k - 1];  //BUBBLE SORT
            list[k - 1] = list[k];
            list[k] = temp;

            temp2 = index[k - 1];  //IN THE SAME MOMENT - DATA IS BEING SHUFFLED
            index[k - 1] = index[k];
            index[k] = temp2;
          } 
        i++;
    }

 return index;  //FUNCTION RETURNS VECTOR WITH SHUFFLED VALUES 

Nmatches lengthand is the lengthlist

I debugged this code in Visual Studio 2012, and I found that there is a problem in the line:

for (int k = i; list[k - 1] > list[k]; k--){

The problem is the Out Of Range error.

I can provide a call stack if necessary.

Can someone help me change this loop whileand forto keep the functionality of the function sort_index()?

Yours faithfully,

Jr

+3
source share
2 answers

In the second iteration

for (int k = i; list[k - 1] > list[k]; k--){

k is 0, and list[k - 1]will throw an exception

+3
source

Of course, this should be:

for (int k = i; (k> 0) && (list [k - 1]> list [k]); k -) {

, k .

+2

All Articles