Is there an equivalent to the “for … else” Python loop in C++?

前端 未结 14 2239
野的像风
野的像风 2021-01-31 01:21

Python has an interesting for statement which lets you specify an else clause.

In a construct like this one:

for i in foo:
  if         


        
14条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 02:04

    I am not aware of an elegant way to accomplish this in C/C++ (not involving a flag variable). The suggested other options are much more horrible than that...

    To answer @Kerrek SB about real life usages, I found a few in my code (simplified snippets)

    Example 1: typical find/fail

    for item in elements:
        if condition(item):
            do_stuff(item)
            break
    else: #for else
        raise Exception("No valid item in elements")
    

    Example 2: limited number of attempts

    for retrynum in range(max_retries):
        try:
            attempt_operation()
        except SomeException:
            continue
        else:
            break
    else: #for else
        raise Exception("Operation failed {} times".format(max_retries))
    

提交回复
热议问题