I have a double for loop that helps me determine the highest sum in a block of numbers inside a text file. All the numbers are inputted into a vector, but eventually the vector reaches its end, and if the code goes past, I get a "vector subscript out of range" error.
I need to know how to break the for loops if it passes the vector's last element.
Code:#include<iostream> #include<conio.h> #include"U:\C++\WordClass2\WordClass2\WordClass.cpp" #include<fstream> #include<vector> using namespace std; int main() { WordClass pie; int blocksize, temp=0; ifstream inFile; inFile.open("numbers.txt"); int numero; vector<int> number; vector<int> returner; while(inFile>>numero) { number.push_back(numero); } cout<<"Enter block size: "; cin>>blocksize; for(int i=0; i<number.size(); i++) //NEED THE FUNCTION IN THIS AREA { for(int j=0; j<blocksize; j++) { temp+=number[i]; i++; } returner.push_back(temp); temp=0; i=i-blocksize; } int killer=0, queen=0, save=0; for(int i=0; i<returner.size(); i++) { killer=returner[i]; if(killer>queen) { queen=killer; save=i+1; } } cout<<endl<<"The biggest sum of numbers is: "<<queen<<endl; cout<<"This sum occurs at block #"<<save<<endl; getch(); return 0; }



2Likes
LinkBack URL
About LinkBacks




I used to be an adventurer like you... then I took an arrow to the knee.
I think the sub-sum part came out very neat. Disregarding the ugly conditional inclusions...