【问题标题】:discover when the element is inserted to the std::map发现元素何时插入到 std::map
【发布时间】:2012-08-31 19:46:30
【问题描述】:

我的程序正在(使用 [] 运算符])将一些数据 [地址] 插入到 std::map 中。我可以跟踪 137 个元素的插入。它们都插入了有效值。

在某个阶段,我迭代地图并尝试对值[地址]进行一些操作 我在开始迭代地图之前设置了一个断点。 当我在调试器中检查地图时,我仍然看到 137 个元素。但是当我迭代它直到

iterator != map.end我发现地图有 138 个值 - 最后一个是非法的。

我需要找到一种方法来检测何时插入最后一个有问题的值。我使用 VS 2010。

谢谢

【问题讨论】:

  • 那么,你在哪里打电话给insert?你用operator[]吗?显示一些代码。
  • 我用 [] 运算符。是大公司s project.I cant 显示代码
  • 如果你使用operator[],你必须确定你想为那个键插入一个值,因为它返回一个引用。它会很乐意为您插入一个值,并且根据您的值类型,很容易将垃圾放入。

标签: c++ visual-studio-2010 debugging map


【解决方案1】:

仅出于调试目的,您可以将 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[] 将元素插入地图,则必须创建重载。

您还可以打印出诸如__LINE__ 之类的宏来指示插入发生的位置。

请注意,std::map 没有虚拟析构函数,因此如果您正在动态分配映射,那么使用这种方法可能会导致未定义的行为,除非您将所有位置的类型名称替换为 wrap_map

【讨论】:

    【解决方案2】:

    您可以尝试在std::map的插入函数中放置条件断点

    对我来说(使用 VC10),合适的位置是 C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\ 的第 755 行(std::map::insert)和第 767 行(std::map::operator[]) xtree

    您可以在_Mysize == 137 的每个断点上添加一个条件来捕获将map 大小增加到138 的插入。

    最有可能的罪魁祸首可能是operator[],因为很容易误认为它只是一个访问器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多