Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Can';t遍历std::map_C++_Stdmap - Fatal编程技术网

C++ Can';t遍历std::map

C++ Can';t遍历std::map,c++,stdmap,C++,Stdmap,自从我开始使用std::map以来,每当我单击按钮时,就会收到断言错误。我想清除my_map中的所有内容,并在每次单击按钮时重新开始添加 my.cpp typedef std::map<str, MyClass> mapper; mapper my_map; void add_map(const str& name, MyClass* l) { /...../ } void invoke_me() { MyClass button; button.on_clicked

自从我开始使用
std::map
以来,每当我单击按钮时,就会收到断言错误。我想清除
my_map
中的所有内容,并在每次单击按钮时重新开始添加

my.cpp

typedef std::map<str, MyClass> mapper;
mapper my_map;

void add_map(const str& name, MyClass* l) { /...../ }

void invoke_me()
{
MyClass button;

button.on_clicked = [&] {
    clear_map();
    add_map("MyButton", &button);
};
while (RUNNING)
    invoke_me();
这应该可以很好地清除我的地图,但我认为这做得不对

void clear_map()
{
    my_map.clear();
}
实施者.h

struct MyClass
{
    std::function<void()> on_clicked;
};
实际上,on_click是一个回调,它必须通过
invoke_me
函数调用

main.cpp

typedef std::map<str, MyClass> mapper;
mapper my_map;

void add_map(const str& name, MyClass* l) { /...../ }

void invoke_me()
{
MyClass button;

button.on_clicked = [&] {
    clear_map();
    add_map("MyButton", &button);
};
while (RUNNING)
    invoke_me();

我想说,这是因为地图大小不正确,这就是为什么即使超出边界,它也会继续循环,或者可能是我损坏或弄乱了地图。

可能还有更多问题,但这似乎是主要问题:

button.on_clicked = [&] {
    clear_map();
    add_map("MyButton", &button);
};
您正在清除映射,并且在迭代时调用此函数:

for (const auto& it : my_map)
{
    // Assert error: map/set iterator not incrementable
    const MyClass& l = it.second;
    l.on_clicked();
}

您的迭代器正在被清除无效。

您是指(const auto&it:my_map)?在for循环之前,不需要检查映射是否为空。一个简短完整的真实代码示例将大大有助于我们帮助您。有几种常见的错误可能会导致与您看到的症状相同的症状,但仅凭片段很难判断。它会在清除之前返回以前的大小,这是不可能的。请提供。我将
my_map
作为全局变量而不是成员类变量,因为我不想重置它。这里使用的指针和实例也存在奇怪的不匹配。如果您的地图存储实例,那么您可能创建了将指针传递到的对象的副本。耸耸肩编辑并没有真正增加任何清晰度。
按钮在被点击的
中使用之前是否超出了范围?您通过引用捕获,然后在将其添加到地图时复制它。是的,如果代码实际是这样工作的,那么就可以了。猜得好,我希望是对的。