Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inspecting the content of a map while debugging

For debugging, I need to see the content of a map (std::unordered_map or std::map), which the Eclipse CDT debugger does not give me in a readable form, e.g. {1: 2, 3:4, ...}

What is the best way to inspect the content of a map while debugging?

Do I have to go back to debugging with print-statements? If yes, how would a concise macro or function look like that prints the content of any map as a string?

like image 236
clstaudt Avatar asked Dec 17 '12 10:12

clstaudt


1 Answers

Do I have to go back to debugging with print-statements? If yes, how would a concise macro or function look like that prints the content of any map as a string?

I don't know if you do or not - I don't use Eclipse, but printing a map is very easy:

template <typename K, typename V>
std::ostream& operator<<(std::ostream& os, const std::map<K, V>& m)
{
    os << "{ ";
    for (typename std::map<K, V>::const_iterator i = m.begin(); i != m.end(); ++i)
    {
        if (i != m.begin()) os << ", ";
        os << i->first << ": " << i->second;
    }
    return os << " }";
}

Then you can just use << my_map. Note though that in a large code base there's a chance that someone else will have had the same "bright" idea, so you might want to put your helper function in your own namespace, or give it a more localised name. Things like the choice of surrounding "{ " and " }" and ", " separators are arbitrary and may not suit all users - some may want automatic string quoting/escaping etc., so putting this in a global namespace would be dubious at the best of times, and in this case it might even be reserved for possible inclusion in a future C++ Standard or something - after all, it's kind of liking adding your own names into the std:: namespace. Check the Standard if you care.

like image 145
Tony Delroy Avatar answered Oct 02 '22 01:10

Tony Delroy