jeudi 25 août 2016

How to skip the first element of the vector and iterate from second using range based for loops

I would like to apologise if this question is really silly, But i have been trying to find a way to iterate through a range based for loop from the second element

int max_subarray(){

std::vector<int> vec;
vec.push_back( 10 );
vec.push_back( 20 );
vec.push_back( -20 );
vec.push_back( -20 );
vec.push_back( -20 );


std::vector<int> vec1;
vec1.push_back( 20 );
vec1.push_back( -20 );
vec1.push_back( -20 );
vec1.push_back( -20 );

int max_ending_here ,max_so_far;
max_ending_here = max_so_far = 10;

for(int x:vec1){
    max_ending_here = std::max(x,max_ending_here + x);
    std::cout<<"max_ending_here = "<<max_ending_here<<"\n";
    max_so_far = std::max(max_so_far, max_ending_here);
    std::cout<<"max_so_far = "<<max_so_far<<"\n";
}
std::cout<<"Max So Far = "<<max_so_far<<"\n";
return 1;
}

i have created a whole new array by copying all the elements except the first

Iam finding a way to do it using range based for loops

A python way of accessing from the second element

for x in A[1:]:
    max_ending_here = max(x, max_ending_here + x)
    max_so_far = max(max_so_far, max_ending_here)
return max_so_far

Thanks T

Aucun commentaire:

Enregistrer un commentaire