我的程序正在向 std::map 中插入(使用 [] 运算符])一些数据[地址]。我可以跟踪 137 个元素的插入。它们都插入了有效值。
在某个阶段我迭代 map 并尝试对值[地址]进行一些操作 我在开始迭代 map 之前设置了一个断点。 当我在调试器中检查 map 时,我仍然看到 137 个元素。但是当我迭代它直到
iterator != map.end
我发现, map 有 138 个值 - 最后一个是非法的。
我需要找到一种方法来检测何时插入最后一个有问题的值。我使用 VS 2010。
谢谢
最佳答案
为了调试,您可以将 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;
}
输出:
Inserted: [10] : Hello, World!
Hello, World!
您必须为 std::map::insert
的任何其他重载创建重载您在代码中使用的,以及 std::map::operator[]
如果您使用它来将元素插入 map 。
您还可以打印出诸如 __LINE__
之类的宏以指示插入发生的位置。
请注意 std::map
没有虚拟析构函数,因此如果您动态分配映射,那么使用此方法可能会导致未定义的行为,除非您将类型名称替换为wrap_map
.
关于c++ - 发现元素何时插入到 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12221648/