davide l
davide l

Reputation: 177

C++ vector class throwing exceptions

I have created a vector that contains 4 strings, now I want to read each one from the first to the last and store the string in exr. I am using this code, but once j becomes 3 it throws the exception thus not extracting the last value and also the exception is not caught. cc is a string vector. I used the debugger and the strings are inside the vector. With this code I just need to process each string until there are no more that is why when I catch the exception I used break to jump out of the for cycle, index is bigger than the actual elements in the vector.

   std::vector<string> cc;
   std::vector<string>::iterator it;
   it = cc.end();
   // code that stores 4 strings in cc....
   ....
   string exr;
   for (int j = 0; j < index; j++)
   {
       try
       {
           exr = cc.at(j);
       }
       catch (out_of_range d)
       {
           break;
       }
       //other code that use exr...
   }

Upvotes: 0

Views: 6707

Answers (2)

Mr.C64
Mr.C64

Reputation: 42934

You have this code:

for (int j = 0; j < index; j++)

But what is the value of index? Is it equal to the vector size?

You may want to use std::vector::size() in the for loop:

for (size_t j = 0; j < cc.size(); ++j)

Or you can just use a range-based for loop (available since C++11):

// Use const auto& for observing the strings in the vector:
for (const auto& exr : cc) 

Note also that exceptions should be caught by reference to avoid deep-copies:

// Your code:
// catch (out_of_range d)
//
// Better:
catch(const out_of_range& d) 

Upvotes: 2

Steve
Steve

Reputation: 7271

I expect that the vector is not as large as you expect. Instead of checking for range against index, use the size() method of the vector. E.g.:

for (size_t j = 0; j < cc.size(); ++j)

Upvotes: 3

Related Questions