您可以仅为了调试而替换std::map
带有隐藏的包装类std::map::insert
具有打印出调试信息的成员函数。
#include <map>
#include <iostream>
#include <utility>
#include <string>
template<class Key,
class Value,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, Value>>>
struct wrap_map : std::map<Key, Value, Compare, Allocator>
{
typedef std::map<Key, Value, Compare, Allocator> base_type;
std::pair<iterator,bool> insert( const value_type& value )
{
std::cout << "Inserted: [" << value.first << "] : " << value.second << std::endl;
return base_type::insert( value );
}
};
int main()
{
wrap_map<int, std::string> mymap;
mymap.insert( std::make_pair( 10, std::string( "Hello, World!" ) ) );
std::cout << mymap[10] << std::endl;
}
Output:
Inserted: [10] : Hello, World!
Hello, World!
您必须为任何其他重载创建重载std::map::insert您在代码中使用的,以及std::map::operator[]
如果你用它来将元素插入到地图中。
您还可以打印出宏,例如__LINE__
指示插入发生的位置。
注意std::map
没有虚拟析构函数,因此如果您动态分配映射,那么使用此方法可能会导致未定义的行为,除非您将各处的类型名称替换为wrap_map
.