I declared a map of the form

map<pair<int,int>,int> net;

and inserted elements in the following way

net.insert( make_pair( make_pair(c1,c2 ),cost ));

I could access the second element (cost, in the above code) using iter->second. But, I want to know how to access the two elements that form the first pair in the map(i.e., c1 and c2 in the above example).

Thanks

Dani AI

Generated

originally stored a pair as the map key and hit the compiler error when trying to use the arrow operator twice. The root cause is simple: a map iterator yields a pair-like object (its value_type is pair<const Key, T>), so the key you get from the iterator is an object, not a pointer. That is why using -> on the key fails; the key is a (const) pair and its members must be accessed as members of an object. pointed toward the correct member access approach.

A concise, modern way to extract both key elements and the mapped value is to decompose the iterator entry with structured bindings (C++17+), then decompose the key pair as well:

for (auto const& [key, value] : net) {
    auto const& [c1, c2] = key;
    // use c1, c2 and value here
}

Notes and cautions: the map key is stored const inside the container, so you cannot modify c1/c2 in place through the iterator; to change a key you must remove and reinsert the element. If stuck on older compilers, use a range loop with auto const& or extract a local copy of the key before working on it. See the C++ reference for map value_type details and for structured bindings for more examples and exact rules: [std::map (value_type is pair<const Key, T])](https://en.cppreference.com/w/cpp/container/map) and structured bindings.

Recommended Answers

All 3 Replies

here you go:

iter->first->first; 
iter->first->second;

I tried that, but it didn't work. I got the following error.

error: base operand of ‘->’ has non-pointer type ‘const std::pair<int, int>’

Thanks for the reply.

I'm sorry

iter->first.first;
      iter->first.second;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.