我有一个 int 向量
vector<int> p;
现在我想删除它等于 3 的项目之一。没有像 p.remove(3) 这样的删除
但有一个擦除,但起初我应该找到它。stackoverflow 中有两个关于此的问题。他们都说我们应该找到它
std::remove(p.begin(), p.end(), 3)
但是这段代码没有被编译。它说函数不接受 3 个参数。
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
int main()
{
using namespace std;
vector<int> v = {1, 2, 3, 3, 4};
v.erase(find(begin(v), end(v), 3)); // remove first 3
// v.erase(remove(begin(v), end(v), 3), end(v)); // remove all 3
copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
}
Vectorserase
方法需要一个或两个迭代器。第一个,擦除从指定位置到结束的所有内容。
std::remove
from<algorithm>
将所有匹配的元素移动到序列的末尾,并将迭代器返回到新末尾的位置。您可以将此迭代器用于erase
. 如果要删除第一个匹配元素,请使用std::find
检索第一个元素的迭代器并将其传递给erase
.
remove_if
在下面找到使用algorithm
给定一个开始和结束迭代器以及一个谓词,您可以删除任何导致谓词评估为真的元素。我将同时包含 C++03 和 C++11 示例。
C++03:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
#include <ctime>
template <typename T>
struct
is_equal
{
T val;
is_equal (const T& v) : val (v) { }
bool
operator() (const T& test)
{
return (val == test);
}
};
struct
is_odd
{
bool
operator() (int test)
{
return (test % 2 == 1);
}
};
template <typename T>
std::ostream&
operator<< (std::ostream& os, const std::vector <T>& v)
{
typedef typename std::vector <T>::const_iterator itr;
for (itr i = v.begin (); i != v.end (); ++i)
os << *i << " ";
return os;
}
int
main (int argc, char* argv[])
{
srand (time (NULL));
std::vector <int> vec (10); // vector has size of 10
std::generate (vec.begin (), vec.end (), rand); // populate with random numbers
std::cout << vec << std::endl;
vec.erase (std::remove_if (vec.begin (), vec.end (), is_odd ()), // removes all odd elements
vec.end ());
std::cout << vec << std::endl;
return 0;
}
C++11:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
#include <cstdlib>
template<typename T>
std::ostream&
operator<< (std::ostream& os, const std::vector <T>& v)
{
for (auto i : v)
os << i << " ";
return os;
}
int
main(int argc, char* argv[])
{
std::vector <int> vec(10); // vector has size of 10
std::iota (vec.begin(), vec.end(), 1); // populate with [1, 2, 3, ...]
std::cout << vec << std::endl;
vec.erase (std::remove_if (vec.begin(), vec.end(),
[](int i){ return (i == 3); }),
vec.end ());
std::cout << vec << std::endl;
return 0;
}
对于使用 STL 的任何问题,我个人咨询http://en.cppreference.com/w/和http://www.cplusplus.com/reference/
std::vector::erase
结合使用std::find
。
您可以在此处查看文档: