Code Question
Posted in Code
First watch, 4 bells (10:21 pm)

Anybody know why I can't do this?


class Room {
  typedef boost::shared_ptr<Room> RoomPointer;
  typedef std::map<std::string, RoomPointer> RoomList;

And in another object, reference it like this:

RoomList mRoomList;
if((Room::RoomList::iterator it = mRoomList.find("name")) != mRoomList.end()) {
   return it->second;

I always get error: ‘::iterator’ has not been declared back from the compiler.

If I do this, it works fine:

Room::RoomList::iterator it = mRoomList.find("name");
if(it != mRoomList.end()) {
   return it->second;

I ask because Nicolai Josuttis (in The C++ Standard Library) recommends comparing the iterator against the end() condition on the same line because of type conversion of various unsigned types that may be used.

1 Comment »

One Response to “Code Question”

  1. Scurvy Jake says:

    The official answer is that the iterator is only in scope inside the parenthesis, and is out of scope by the time you get inside the if block.

    So, the following would work just fine:

    Room::RoomList::iterator it;
    if((it = mRoomList.find("name")) != mRoomList.end()) {
       return it->second;

Leave a Reply