给定一个向量,任务是使用delete()和reverse_iterator从该向量中删除一个元素。
例子:
Input: vector = {1, 4, 7, 10, 13, 16, 19}, element = 16
Output: 1 4 7 10 13 19
Input: vector = {99, 89, 79, 69, 59}, element = 89
Output: 99 79 69 59
方法:
- 获取向量和要删除的元素
- 在向量上初始化反向迭代器
- 借助base()和delete()擦除所需的元素
使用base()的原因: delete()将有效的迭代器返回到元素的新位置,该元素位于刚删除的元素之后,位于该元素之后。因此,在使用反向迭代器时,我们不能使用相同的过程,因为我们想要反向而不是向前。而且我们也不能将反向迭代器作为参数传递给delete()函数,否则它将产生编译错误。
reverse_iterator只是一个迭代器适配器,可以反转给定迭代器的方向。 reverse_iterator上的所有操作实际上都在该基础迭代器上进行。我们可以使用reverse_iterator :: base()函数获得该迭代器。实际上,itr.base()和itr之间的关系为:
&*(reverse_iterator(itr))==&*(itr-1)
下面是上述方法的实现:
// C++ program to delete an element of a vector
// using erase() and reverse iterator.
#include
#include
using namespace std;
// Function to delete element
// 'num' from vector 'vec'
vector delete_ele(vector vec, int num)
{
// initializing a reverse iterator
vector::reverse_iterator itr1;
for (itr1 = vec.rbegin(); itr1 < vec.rend(); itr1++) {
if (*itr1 == num) {
// erasing element = 16
vec.erase((itr1 + 1).base());
}
}
return vec;
}
// Driver code
int main()
{
vector vec = { 1, 4, 7, 10, 13, 16, 19 };
// we want to delete element = 16
int num = 16;
vector::iterator itr1;
cout << "Vector originally: \n";
for (itr1 = vec.begin(); itr1 < vec.end(); itr1++) {
// printing the original elements of vector
cout << *itr1 << " ";
}
cout << "\n\nElement to be deleted: "
<< num << "\n\n";
// reinitializing vector 'vec'
// after deleting 'num'
// from the vector
// and keeping other remaining
// elements as they are
vec = delete_ele(vec, num);
vector::iterator itr2;
cout << "Vector after deletion: \n";
for (itr2 = vec.begin(); itr2 < vec.end(); itr2++) {
// printing the remaining elements of vector
cout << *itr2 << " ";
}
return 0;
}
// This code is contributed by supratik_mitra
输出:
Vector originally:
1 4 7 10 13 16 19
Element to be deleted: 16
Vector after deletion:
1 4 7 10 13 19
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。