-1

I'm just wondering what would be the closest translation of the python statement:

try:

except StopIteration:

I am fairly new to both C++ and python I think it's been about 3-4weeks now. although I am aware that a general if statement would do relatively the same job, I was just uncertain as how to replicate the StopIteration part. Would a simple break suffice?

EDIT: inside code

try:
   nextread1=myfile1.next()
   nextread2=myfile2.next()
except StopIteration:
   print("error msg")
   sys.exit(2)
CandiedMango
  • 279
  • 4
  • 15
  • You need to use *much* better titles for your questions; you also will need to provide some more context here. What is the code that might raise a `StopIteration` exception? – Martijn Pieters Oct 17 '13 at 10:04
  • `StopIteration` is a signal exception used in iteration; C++ handles iterators entirely differently, so showing *just* the exception is not going to get you anywhere. – Martijn Pieters Oct 17 '13 at 10:05
  • According to this link: http://docs.python.org/2/library/exceptions.html#exceptions.StopIteration `StopIteration` is raised when `next()` method is called on an iterator where there is no further values. Like Martijn said, C++ handles iterator differently, and so you need to paste more of your Python code (i.e., give us the codes *inside* the `try ... except` block). =) – justhalf Oct 17 '13 at 10:07
  • it is used when there is no next read within a file (little complex to go into details it's to do with dna sequencing) so there is a file full of these gene alignments and then it chooses the next one in the try part in the except it does sys.exit(2) – CandiedMango Oct 17 '13 at 10:09
  • Why are you trying to understand python in terms of C++? What do you really want to know? – doctorlove Oct 17 '13 at 10:11
  • i'm not trying to understand it in terms of c++. i'm changing a python program into c++. – CandiedMango Oct 17 '13 at 10:17
  • Edited with code inside now. So does C++ have an End of file exception? As that is effectively what's happening. – CandiedMango Oct 17 '13 at 10:24
  • No, not an exception, but it does have an eof flag, but see here: http://stackoverflow.com/questions/13544245/reading-until-the-end-of-file-in-c – doctorlove Oct 17 '13 at 10:27

2 Answers2

3

StopIteration is a special exception in Python which is thrown by iterators when you try to get a new element but there aren't any more. That is the way how Python detects when to stop a loop like for x in iterator. That basically translates in Python to:

while True:
    try: value = next(iterator)
    except StopIteration: break
    # do something...

However, iterators in the STL of C++ are much different. I am not sure at what level you want to see a C++ translation. If you have similar iterators like in Python, you might be able to translate the code 1:1. But a STL iterator does not behave this way; it does not throw exceptions in the case you try to read a next element when there is none. The behavior is rather undefined and most likely will result in a crash. In STL for all containers, there is always a special end-iterator (which is outside of the container!) and you check wether your iterator is equal to the end-iterator. If that is the case, you know that you must not read any further element. This mostly looks like this:

auto iterator = mylist.begin(); // get the iterator at the start of mylist
while(iterator != mylist.end()) { // check if our iterator is not equal to the end-iterator
    auto value = *iterator; // get the value of the iterator
    // do something with value
    ++iterator; // advances the iterator by one
}

Note that next() in Python does two things: If there is a value, it returns the current value and advances the iterator by one. Otherwise, it raises the StopIteration exception. In C++, the current value is returned via *iterator and the iterator is advanced by ++iterator. Also, in C++, there is no exception, so you have to do the check yourself (that is iterator != mylist.end()).

A shorter and more common way to write this in C++ is:

for(auto iterator = mylist.begin(); iterator != mylist.end(); ++iterator) {
    auto value = *iterator; // get the value of the iterator
    // do something with value
}

Or, even more short:

for(auto value : mylist) {
    // do something with value
}

The code works like this for all STL containers like list, vector, deque, set, multiset. A vector is mostly just an array inside. But the C-array (e.g. int numbers[N];) will not work for the first two code examples, because it is not an object and does not have the begin() and end() functions. However, the last example will also work in that case.

If you write an own container class, you should also implement some begin() and end() functions which makes the above code work like this.


Note that file reading in C++ is again different. In Python, when you use for x in myfile, it automatically generates an iterator over the lines of the file and you are using that iterator. But of course there are also other ways in Python to read a file, e.g. just myfile.read(). The latter has a direct equivalent in C, namely fread() (or also simply read(), but you should rather use fread() because it is more save and you get caching). But there are so many different ways in C/C++ to read a file that I will not list all possibilities here.


sys.exit() is mostly equivalent to the C-function exit(). But you should better just return from all the functions and at the end return from main() so that your application exits.

Albert
  • 65,406
  • 61
  • 242
  • 386
  • this is literally exactly what i wanted but with more information that i expected! thank you. although would that not depend on whether you are getting values from a list/array/vector? – CandiedMango Oct 17 '13 at 12:50
  • The code works like this for all STL containers like `list`, `vector`, `deque`, `set`, `multiset`. A `vector` is mostly just an array inside. But the C-array (e.g. `int numbers[N];`) will not work, because it is not an object and does not have the `begin()` and `end()` functions. Note that the C++11 code `for(auto value : numbers)` would still work. – Albert Oct 17 '13 at 12:56
  • yeah i'm using a library to read from file, but you have been by far the most helpful! i didn't know i could accomplish the same as the try except using a for loop. so there is a library method which i have just found which detects whether there is another read or not and returns true or false so if i had while(librarymethod()==true) that's the same basically but how would i perform the sys.exit method now? would i need an if statement inside the loop? – CandiedMango Oct 17 '13 at 13:18
  • Note that file reading is a bit different in C++ than iterating through a list. You should exit just by returning out of your function. – Albert Oct 17 '13 at 15:17
  • so the library method returns true or false based on whether there is a next read so if i just did if(librarymethod()==false){EOFile1==true}||{exit system somehow} where EOFile1 is a boolean that is declared earlier on and is used withing if statements to end loops etc, that would perform the same kind of job as the try except statement above? – CandiedMango Oct 18 '13 at 08:56
  • Yes, probably, but hard to tell without more details. But just try it out, I guess you understand now the difference. :) – Albert Oct 18 '13 at 09:08
  • yes thanks it was just difficult being new to both languages knowing what was going specially with python as it is so high level. thanks for all the help! – CandiedMango Oct 18 '13 at 09:25
1

In order to break a loop in C++, the break statement is used. Do something like this inside your loop:

try
{
    ...
}
catch(MyException e) //use whatever exception you are trying to catch
{
    ...
    break;
}
digital_revenant
  • 3,274
  • 1
  • 15
  • 24
  • 2
    Except that `StopIteration` is a special kind of exception. It is used to signal that an iterator is exhausted, no more elements will be yielded. That is not an exception that you'll ever find in C++, as iteration handling is entirely different. – Martijn Pieters Oct 17 '13 at 10:06