+ Reply to Thread
Results 1 to 2 of 2

Thread: std::list fails if I use ++ operator.

  1. #1

    std::list fails if I use ++ operator.

    Following code does not compile:

    Code:
    void MyFunction()
    {
    	std::list<int> myList ;
    	for (int i=0; i<10; i++)
    	{
    		myList.push_back(i) ;
    	}
    	
    	std::list<int>::iterator itr = myList.begin() ;
    
    	for (; itr != myList.end(); myList++)
    	{
    		char szMessage[1024] ;
    		sprintf(szMessage, "Value : %d\n", *itr) ;
    		OutputDebugString(szMessage) ;
    	}
    }
    It displays following error:

    error C2676: binary '++' : 'class std::list<int,class std::allocator<int> >' does not define this operator or a conversion to a type acceptable to the predefined operator

    What is it and how to resolve this?

    Help.

  2. #2
    std::list is not a random access container.

    Random access container have this functionality to increment/decrement iterator.

    So you can use std::advance algorithm to increment the position of the std:list.

    Example:

    Code:
    void MyFunction()
    {
    	std::list<int> myList ;
    	for (int i=0; i<10; i++)
    	{
    		myList.push_back(i) ;
    	}
    	
    	std::list<int>::iterator itr = myList.begin() ;
    	std::advance(itr, 6) ;
    
    	char szMessage[100] ;
    	sprintf(szMessage, "Value : %d\n", *itr) ;
    	OutputDebugString(szMessage) ;
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts