Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Skipping for-each with a while Loop

If you don't want to call a separate function, you have a couple of other approaches at your disposal. For one, you can skip the for_each algorithm altogether, and instead use a while loop. The following code accomplishes the same thing as the preceding example, but uses a more common approach (note that I'm making use of the two typedefs defined in the preceding example):

void demoMapWhile() {
  PhoneList phones;
  phones[string("Jeff")] = string("110-555-1234");
  phones[string("Angie")] = string("800-123-4567");
  phones[string("Dylan")] = string("123-867-5309");
  phones[string("Amy")] = string("888-111-1111");
  
  PhoneList::iterator iter = phones.begin();
  while (iter != phones.end()) {
    cout << iter->first << " : " << 
      iter->second << endl;
    iter++;
  }
}

This code fills a map again and then grabs out an iterator, which is a thingamabob that you use for iterating through each item in the map. The call to begin() gets an iterator that points to the first pair in the map. You dereference the iterator to get to the pair (thus the use of *iter) and then you increment iter to get to the next pair in the map. The output of this is identical to the output of the preceding example function: demoMapAlgo.

But if you'll excuse me for just one moment, I need to launch into an editorial. I'm not fond of this approach, even though it's the most common. Having used many languages over the years, I've seen a lot of really great ways to iterate through lists. And I think the preceding is extremely counterintuitive.

My basic problem, dare I admit this, is that I have to look up an example every single time I want to use it. Okay, that's not true. In April of 2004, I successfully typed in code like this straight from memory, and it compiled on the first shot without me having to go find an iterator example. I took all my noncomputer friends out to dinner to celebrate, even though they didn't understand.

But the reason I have problems with this approach is because the iter variable conceptually represents two different types of beasts. First, it represents an iterator that climbs through the container and includes Boolean comparisons to detect the end point. Second, if I dereference iter, it transforms dimensions within an Einsteinian space-time continuum and becomes the actual item in the container. Whoa. Even if I had spent my formative years in the '60s, that would probably still trip me out. Nevertheless, the crazy thing works, and I do make use of it. Enough editorializing.

  • + Share This
  • 🔖 Save To Your Account