Question

Declared a map early on:

map<char*,char*>    rtable; // used to store routing information

Now I'm attempting to display the contents of the map:

void Routes::viewroutes(){
    typedef map<char*, char*>::const_iterator iter;
    for (iter=rtable.begin(); iter != rtable.end(); ++iter) {
        cout << iter->second << " " << iter->first << endl;
    }
}

Receiving the error "expected primary-expression before '!=' token and for '->' token. Can't seem to understand the error I'm making here. Any ideas?

Was it helpful?

Solution

iter is a type in your code. Should be a variable.

typedef map<char*,char*> my_map_t;  // alias for a specialized map

// declare a variable of needed type
my_map_t    rtable;

// declare iter of type my_map_t::const_iterator
for (my_map_t::const_iterator iter=rtable.begin(); iter != rtable.end(); ++iter) {
    cout << iter->second << " " << iter->first << endl;
}
// scope of the iter variable will be limited to the loop above

OTHER TIPS

Remove the typedef. You're not declaring a variable with that statement, you're defining a type and then assigning to it. That's what the error is.

Declare a variable of type iter:

void Routes::viewroutes(){
    typedef map<char*, char*>::const_iterator iter;
    for (iter i =rtable.begin(); i != rtable.end(); ++i) {
        cout << i->second << " " << i->first << endl;
    }
}

Just for fun :), you can use the following functions which I wrote to stream the contents of a map or a multimap to any standard stream whether it is the standard output, a file stream. It deals with all types of streams like cout or wcout for example:

    template <class Container, class Stream>
    Stream& printPairValueContainer(Stream& outputstream, const Container& container)
    {
        typename Container::const_iterator beg = container.begin();

        outputstream << "[";

        while(beg != container.end())
        {
            outputstream << " " << "<" << beg->first << " , " << beg->second << ">";
            beg++;
        }

        outputstream << " ]";

        return outputstream;
    }

template
    < class Key, class Value
    , template<class KeyType, class ValueType, class Traits = std::less<KeyType>,
    class Allocator = std::allocator<std::pair<const KeyType, ValueType> > > 
    class Container
    , class Stream
    >
Stream& operator<<(Stream& outputstream, const Container<Key, Value>& container)
{
    return printPairValueContainer(outputstream, container);
}

I always access my map iterators like so (*iter).first and (*iter).second.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top