Question

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());

}
Était-ce utile?

La solution

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).

Autres conseils

say we have a vector of int

vector<int> myvector;

we can use

for(auto iter : myvector){
    dosomething...
}

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top