我有一个int
的向量vector<int> p;
现在我要删除其中一个等于3的项目。 没有删除像p.remove(3)
但是有一个擦除但是起初我应该找到它。 stackoverflow中有两个关于这个的问题。他们两个都说我们应该通过
找到它std::remove(p.begin(), p.end(), 3)
但是这段代码没有编译。它说函数不需要3个参数。
答案 0 :(得分:2)
#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, " "));
}
Vectors erase
方法需要一个或两个迭代器。第一个,擦除从指定位置到结束的everthing。
来自std::remove
的{{1}}将所有匹配元素移动到序列的末尾,并将迭代器返回到新结束的位置。您可以将此迭代器用于<algorithm>
。
如果要删除第一个匹配元素,请使用erase
检索第一个元素的迭代器并将其传递给std::find
。
答案 1 :(得分:1)
使用remove_if
algorithm
给定一个开始和结束迭代器以及一个谓词,您可以删除任何导致谓词评估为true的元素。我将包括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/
答案 2 :(得分:0)
将std::vector::erase
与std::find
结合使用。
您可以在此处查看文档: