Vector容器删除元素

std::vector::erase

 (1) 
iterator erase( iterator pos );
(until C++11)
iterator erase( const_iterator pos );
(since C++11)
 (2) 
iterator erase( iterator first, iterator last );
(until C++11)
iterator erase( const_iterator first, const_iterator last );
(since C++11)
   

Removes specified elements from the container.

1) Removes the element at pos.
2) Removes the elements in the range [first; last).

Invalidates iterators and references at or after the point of the erase, including the end() iterator.

The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferencable) cannot be used as a value for pos.

The iterator first does not need to be dereferenceable if first==last: erasing an empty range is a no-op.

Parameters

pos-iterator to the element to remove
first, last-range of elements to remove
Type requirements
-T must meet the requirements of MoveAssignable.

Return value

Iterator following the last removed element. If the iterator pos refers to the last element, the end() iterator is returned.


注解:

1.删除指定迭代器位置的元素。

2.返回该元素的迭代器地址。

3.循环遍历时迭代器会自动指向下一个位置。举例如下:

    vector<int> vi;
    //vi.assign(100,1024);
    //vi.assign(100,INT_MAX);
    for(int i=1;i<=100;i++)
        vi.push_back(i);
    for(auto pt=vi.begin();pt!=vi.end();){
        if(*pt%2==0){
            auto del = vi.erase(pt);
            cout<<"del-"<<*del<<" ";
        }else{
            ++pt;
            cout<<*pt<<" ";
        }
    }

	
//输出
2 del-3 4 del-5 6 del-7 8 del-9 10 del-11 12 del-13 14 del-15 16 del-17 18 
del-19 20 del-21 22 del-23 24 del-25 26 del-27 28 del-29 30 del-31 32 del-33 34 
del-35 36 del-37 38 del-39 40 del-41 42 del-43 44 del-45 46 del-47 48 del-49 50 
del-51 52 del-53 54 del-55 56 del-57 58 del-59 60 del-61 62 del-63 64 del-65 66 
del-67 68 del-69 70 del-71 72 del-73 74 del-75 76 del-77 78 del-79 80 del-81 82 
del-83 84 del-85 86 del-87 88 del-89 90 del-91 92 del-93 94 del-95 96 del-97 98 del-99 100 del-100





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值