当前位置:  开发笔记 > 编程语言 > 正文

Vector.erase中的SIGSEGV

如何解决《Vector.erase中的SIGSEGV》经验,为你挑选了1个好方法。

当我擦除向量中的元素时,我收到一个奇怪的分段错误错误.这是代码:

int i = 0;
    cout << "SIZE: " << OrderList::sellOrders.size();
    for(vector::iterator it = OrderList::sellOrders.begin(); it != OrderList::sellOrders.end(); it++, i++)
    {
        if(OrderList::sellOrders[i].pThis->usesWamp() == false)
        {
            cout << "Erase element " << i << endl;
            OrderList::sellOrders.erase(it);
        }
    }

输出是这样的:

SIZE: 44
Erase element 0
Erase element 2
Erase element 3
Erase element 4
Erase element 5
Erase element 6
Erase element 7
Erase element 8
Erase element 9
Erase element 10
Erase element 11
Erase element 12
Erase element 13
Erase element 14
Erase element 15
Erase element 16
Erase element 17
Erase element 18
Erase element 19
Erase element 20
Erase element 21
Erase element 22
Erase element 23

Program received signal SIGSEGV, Segmentation fault.
__memmove_ssse3_back () at ../sysdeps/x86_64/multiarch/memcpy-ssse3-back.S:1548
1548    ../sysdeps/x86_64/multiarch/memcpy-ssse3-back.S: No such file or directory.
(gdb)
(gdb) where
#0  __memmove_ssse3_back ()
    at ../sysdeps/x86_64/multiarch/memcpy-ssse3-back.S:1548
#1  0x0000000000485d48 in std::__copy_move::__copy_m (__first=0x7fffe400e4a0, __last=0x7fffe400e470,
    __result=0x7fffe400e488) at /usr/include/c++/4.8/bits/stl_algobase.h:372
#2  0x00000000004807c4 in std::__copy_move_a (
    __first=0x7fffe400e4a0, __last=0x7fffe400e470, __result=0x7fffe400e488)
    at /usr/include/c++/4.8/bits/stl_algobase.h:390
#3  0x000000000047879f in std::__copy_move_a2 > >, __gnu_cxx::__normal_iterator > > > (__first=...,
    __last=..., __result=...) at /usr/include/c++/4.8/bits/stl_algobase.h:428
#4  0x000000000046f9d3 in std::move<__gnu_cxx::__normal_iterator > >, __gnu_cxx::__normal_iterator > > > (__first=..., __last=...,
    __result=...) at /usr/include/c++/4.8/bits/stl_algobase.h:492
#5  0x0000000000467754 in std::vector >::erase (
    this=0x6c7c10 , __position=...)
    at /usr/include/c++/4.8/bits/vector.tcc:138
#6  0x0000000000421320 in OrderList::flush () at ../Bether/OrderList.h:339
#7  0x000000000044b12a in main () at ../Bether/main.cpp:354

因此,您可以看到Vector有44个元素(SIZE: 44)但是在删除元素23时失败.



1> YSC..:

std::vector::erase()使迭代器无效,这意味着以后取消引用it(*it)或增加它(++it)是未定义的行为.

一个很好的和通常的范例是组合std::remove_if()移动容器后面的移除项目std::vector::erase()以实际删除它们:

std::vector v = { 0, 1, 2, 3, 4, 5, 6 };
v.erase( std::remove_if(v.begin(), v.end(), [](int n){ return n%2==0; }), v.end() );
// v is { 1, 3, 5 }

推荐阅读
帆侮听我悄悄说星星
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有