c++ - 发现元素何时插入到 std::map

标签 c++ visual-studio-2010 debugging dictionary

我的程序正在向 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/

相关文章:

c++ - std::atomic 的标准特化不应该缺少值构造函数吗

c# - 如何删除file.txt的最后一行

visual-studio-2010 - 无法在Visual Studio 2010中打开.rpt Crystal Reports文件

c# - 在 WinForms 中增加一个带有计时器的 ProgressBar

debugging - 可以从调试器停止并继续执行吗?

powershell - Powershell Core 模块的适当调试工作流程是什么?

c++ - 我有一个现有的 C++ 项目,我想在 Visual C++ 中添加一个新的头文件。我收到无数错误

c++ - 如何正确使用 MultiByteToWideChar

python - 如何在 pudb 中显示堆栈跟踪?

c++ - 我将如何实现这种蛮力中值搜索算法?