Thread: iterator prob in for loop

  1. #1
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124

    iterator prob in for loop

    A snippet of my code:

    Code:
        // cycle through list of words
        for(list<string>::iterator i = inputFile.begin(); i != inputFile.end(); i++) {
            string word = *i;
            // compare to words in dictionary
            for(list<string>::iterator j = loadedDictionary.begin(); j != loadedDictionary.end(); j+=2) {
                string dicWord = *j;
                
                if(word.compare(dicWord) == 0) { // if words are equal - fix
                    *i = *(j+1);
                    break;
                }
            }   
        }
    I get the following errors and I'm not quite sure why:

    error: no match for 'operator+=' in 'j += 2'
    error: no match for 'operator+' in 'j + 1'
    The nexted for loop is required to look at every second string in the list. If a string math is found, then the dereferenced iterator (*i) must equal the j+1 dereferenced element in the list. What is wrong with the pointer arithmetic?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Iterator addition is only available in random access iterators. std::list only supports bidirectional iterators.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You can use std::advance instead of +=.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >You can use std::advance instead of +=.
    Or look at your design and determine if you really do need a list. The need for random access here suggests that there might be a need elsewhere too, and a list might not be the best container.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed