Thread: Break for loop after vector's last element

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    12

    Break for loop after vector's last element

    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;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Code:
            for(int j=0; j<blocksize; j++)
            {
                temp+=number[i];
                i++;
            }
    The problem is, you're messing around with the other loops control variable, and not checking the range.

    Try say
    Code:
            for(int j=0, k = i ; j<blocksize && k < number.size() ; j++, k++ )
            {
                temp+=number[k];
            }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    I've done something like this before

    Quote Originally Posted by hss1194 View Post
    Code:
        [&]()
        {
          for(int i=0; i<number.size(); i++)        //NEED THE FUNCTION IN THIS AREA
          {
              for(int j=0; j<blocksize; j++)
              {
                  temp+=number[i];
                  // if you need to break from here, simply return
                  i++;
              }
              returner.push_back(temp);
              temp=0;
              i=i-blocksize;
          }
        }();
    if you have a C++11 compiler, you can simply put that in place of your nested for loop, and returning from the lambda will break out of both loops

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    if(killer>queen)
    {
        queen=killer;
    You're not a Queen fan by any chance are you? Just curious.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Novice
    Join Date
    Jul 2009
    Posts
    568
    Had some fun with iterators. I think the sub-sum part came out very neat. Disregarding the ugly conditional inclusions...

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <utility>
    #include <algorithm>
    
    
    #if __cplusplus < 199711L
    #error "It looks like you're using an antiquated compiler. Would you like help?"
    #endif
    
    
    bool cmp(const std::pair<int, int> &p1, const std::pair<int, int> &p2)
    {
        return (p1.second < p2.second);
    }
    
    
    int main()
    {
        std::ifstream file;
        file.open("numbers.txt");
        if (!file) {
            std::cerr << "!> could not open input file" << std::endl;
            return 1;
        }
        
        std::vector<int> numbers;
        int a;
        while (file >> a)
            numbers.push_back(a);
        
        int block_size;
        std::cout << "Enter block size: ";
        std::cin >> block_size;
        if (block_size <= 0 || block_size > numbers.size())
            block_size = numbers.size();
        
        #if __cplusplus >= 201103L
        std::vector<std::pair<int, int>> block_sums;
        auto iter = numbers.begin();
        #elif __cplusplus >= 199711L
        std::vector<std::pair<int, int> > block_sums;
        std::vector<int>::iterator iter = numbers.begin();
        #endif
        int block_sum;
        while (numbers.end() - iter >= block_size) {
            block_sum = 0;
            for (int i = 0; i < block_size; ++i) {
                block_sum += *(iter + i);
            }
            #if __cplusplus >= 201103L
            auto pair = std::make_pair(iter - numbers.begin(), block_sum);
            #elif __cplusplus >= 199711L
            std::pair<int, int> pair;
            pair = std::make_pair(iter - numbers.begin(), block_sum);
            #endif
            block_sums.push_back(pair);
            iter++;
        }
        
        
        #if __cplusplus >= 201103L
        for (const auto &pair : block_sums)
            std::cout << "(" << pair.first << "; "
                             << pair.second << ")"
                             << std::endl;
        #elif __cplusplus >= 199711L
        std::vector<std::pair<int, int> >::iterator sums_iter;
        for (sums_iter = block_sums.begin();
             sums_iter != block_sums.end(); sums_iter++) {
            std::cout << "(" << sums_iter->first << "; "
                             << sums_iter->second << ")"
                             << std::endl;
             
        }
        #endif
        
        #if __cplusplus >= 201103L
        auto max_at = std::max_element(block_sums.begin(), block_sums.end(), cmp);
        #elif __cplusplus >= 199711L
        std::vector<std::pair<int, int> >::iterator max_at;
        max_at = std::max_element(block_sums.begin(), block_sums.end(), cmp);
        #endif
        std::cout << "Greatest sum: "
                  << max_at->second
                  << " @ "
                  << max_at->first
                  << std::endl;
    }
    Disclaimer: This post shows my ignorance at the time of its making. I claim ownership of but not responsibility for all errors in it. Reference at your own peril.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Break the Loop.
    By Lord Slytherin in forum C Programming
    Replies: 3
    Last Post: 09-14-2011, 11:39 PM
  2. vector<vector<int> > access element.
    By nimitzhunter in forum C++ Programming
    Replies: 0
    Last Post: 01-23-2011, 05:14 AM
  3. vector remove element of element
    By Ducky in forum C++ Programming
    Replies: 6
    Last Post: 09-12-2010, 03:24 PM
  4. Can you break; for for loop?
    By DavidDobson in forum C Programming
    Replies: 4
    Last Post: 09-24-2008, 12:59 PM
  5. max element in vector
    By acosgaya in forum C++ Programming
    Replies: 3
    Last Post: 10-23-2006, 04:07 PM