Vector容器删除元素
程序员文章站
2022-03-21 16:29:36
...
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
上一篇: 查找数组中指定元素