1

I am very new to C++. I am trying to figure out this sample short hand for loop from my book, it is very long and ugly and was wondering if this can be re written in a cleaner way. Ignore the functions in there like before() and others, they are part of a linked list program I am working on. I just do not understand from my book how to re write the loop in a more "traditional" way. Thanks in advance!

fooExample(string str){

    string s = toLower(str);

    for(books->setEnd();!books->atStart() && (toLower(books->getInfo().getAuthor()).search(s)==string::npos);books->before());

}
user2438839
  • 13
  • 1
  • 4
  • 8
    This is exceptionally awful code; if your book recommends this code then you should get a different book. – Oliver Charlesworth May 31 '13 at 21:06
  • Like one of these [books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – chris May 31 '13 at 21:07
  • @user2438839, Out of curiosity, which one? – chris May 31 '13 at 21:08
  • `books->setEnd()` initializes the loop, so it is called before the loop. Everything before the next ';' is called before every step into the loop, and only if the whole thing returns `true` the loop is entered. `&&` returns true if both parts return true. `books->before()` is then executed to 'step forward' on every 'enter the loop' – flaschenpost May 31 '13 at 21:09
  • Exposing a reverse iterator through `rbegin()` and `rend()` and then using `std::find_if` strikes me as the traditional way here. – chris May 31 '13 at 21:32

3 Answers3

3

The form for for-loops in C++ looks like this:

for(initialisation; condition; incrementation)
{
    //code
}

So you could do something like

for(unsigned int i = 0; i < 10; ++i)
{
    std::cout << "i = " << i << std::endl;
}

The principle in your code is the same; there is an initialisation, a condition, and not really an "incrementation", but something that happens every iteration of the loop(I guess it goes to the previous book).

quamrana
  • 37,849
  • 12
  • 53
  • 71
Anickyan
  • 404
  • 2
  • 10
  • what would I do with the "&&"? I just cannot figure out how to re write this in the normal for loop style. – user2438839 May 31 '13 at 21:10
  • `condition1 && condition2` means that `condition1` **and** `condition2` have to evaluate to true in order for the result to be true. So it is completely valid, and there is nothing wrong with using && in a for-loop. – Anickyan May 31 '13 at 21:11
2

say we have a vector of int

vector<int> myvector;

we can use

for(auto iter : myvector){
    dosomething...
}
Wendy
  • 65
  • 8
0

Shuffling the loop into a more typical state yields:

for(books->setEnd(); !books->atStart(); books->before())
{
     if (toLower(books->getInfo().getAuthor()).search(s) == string::npos)
         break;
}

The author took the body of the loop, which is just a conditional break, and added it to the loop condition.

Wug
  • 12,956
  • 4
  • 34
  • 54