Thread: pointer arithmetic.. why doesn't this work?

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    244

    pointer arithmetic.. why doesn't this work?

    hey all, I'm trying to compare a node in an STL linked list to the next node in the list.

    I have this line to compare:

    Code:
    if(*pos == *(pos + 1)) // compare to the next node
    where pos is a list<int>::iterator.

    this seems like it should work to me, but my compiler (MetroWerks CodeWarrior IDE 4.1, MacOS9.1) gives me "Illegal operand" as an error.

    I probably just don't understand pointer arithmetic like I thought: what can I do? Thanks!

  2. #2
    Registered User
    Join Date
    Jan 2002
    Posts
    552
    Well for one, + operator isnt defined for linked list iterators. Its only defined for iterators where the data structure its iterating over is stored contiguously in memory (an array). For example, if you have a list node N, whose to say the next node in the list is at mem location N+1? In most cases it wont be.

    Although in a way it would kinda make sense for the + operator to just move the iterator down the list, that behavior isnt what somone would normally associate with "pointer arithmetic", which is what the iterators are supposed to model.
    C Code. C Code Run. Run Code Run... Please!

    "Love is like a blackhole, you fall into it... then you get ripped apart"

  3. #3
    Registered User
    Join Date
    Jan 2002
    Posts
    552
    to get around this youll probably have to create a temporary iterator that points to the element just before the current element:

    prev = list.begin();
    curr = prev;
    ++curr;

    if (*prev == *curr)

    then just increment both if you want to check down the entire list
    C Code. C Code Run. Run Code Run... Please!

    "Love is like a blackhole, you fall into it... then you get ripped apart"

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Hey, thanks a lot. I wasn't aware that the + operator didn't work for list iterators!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer to global arithmetic operator?
    By m37h0d in forum C++ Programming
    Replies: 8
    Last Post: 01-30-2009, 08:40 PM
  2. Question about pointer arithmetic and types
    By brooksbp in forum C Programming
    Replies: 4
    Last Post: 08-22-2008, 01:53 PM
  3. Pointer arithmetic question
    By moneil in forum C Programming
    Replies: 6
    Last Post: 03-25-2004, 11:45 PM
  4. pointer arithmetic
    By xyz4rm in forum C Programming
    Replies: 3
    Last Post: 03-21-2004, 12:56 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM