我有一对int对的向量。假设Itr是我向量的迭代器。
我想迭代向量并决定是否从向量中删除元素。如果向量的元素是9001,3
,那么我想从itr->first
为9001的向量中删除所有元素(无关或itr->second
是什么)。
问题:
vec.erase(std::remove(vec.begin(), vec.end(), Itr->first=9001), vec.end());
(current element being pointer by vector) - 10
和
和(current element being pointed by vector)+10
一样? 实施例:vec.erase(std::remove(Itr-10, Itr+10, Itr->first=9001), vec.end());
如果矢量大小本身小于10,那么Itr + 10 ot Itr-10可能会导致分段错误。那么如何处理这种情况呢?
vector<pair<int,int> > vec;
vec.push_back(pair<int,int>(9001,1));
vec.push_back(pair<int,int>(9001,2));
vec.push_back(pair<int,int>(9001,3));
vec.push_back(pair<int,int>(9001,4));
vec.push_back(pair<int,int>(9002,1));
vec.push_back(pair<int,int>(9002,2));
vec.push_back(pair<int,int>(9002,3));
vec.push_back(pair<int,int>(9002,4));
vec.push_back(pair<int,int>(9002,5));
vector<pair<int,int> >::iterator Itr;
for(Itr=vec.begin();Itr!=vec.end();++Itr)
cout<<vecItr->first<<" "<<vecItr->second;
// vec.erase(std::remove(Itr-10, Itr+10, Itr->first=9001), vec.end()); //This doest work
for(Itr=vec.begin();Itr!=vec.end();++Itr)
cout<<Itr->first<<" "<<Itr->second;
答案 0 :(得分:3)
如何删除此int对矢量。以下不会起作用:
将lambda或自定义比较器与remove_if
算法一起使用:
vec.erase(std::remove_if(vec.begin(), vec.end(),
[](auto& elem){ return elem.first == 9001;} ),
vec.end());
使用自定义比较器:
struct elem_equals
{
typedef std::pair<int,int> elem_t
const int value;
elem_equals(int v) : value(v) {}
bool operator()(elem_t& elem)
{
return elem.first == value;
}
};
//...
vec.erase(std::remove_if(vec.begin(), vec.end(),
elem_equals(9001) ),
vec.end());
我可以将vec.begin作为
(current element being pointer by vector) - 10
和ve.end as (current element being pointed by vector)+10
给出,而不是将范围作为vec.begin()提供给vec.end()吗?
是。矢量迭代器支持指针算术,所以很容易。
如果矢量大小本身小于10,那么Itr + 10 ot Itr-10可能会导致分段错误。那么如何处理这种情况呢?
如果在迭代器之前或之后没有足够的元素,请钳制范围:
//iter is an iterator to vector
//vec is instance of std::vector
//replace auto with std::vector<std::pair<int,int> >::iterator for non C++11 compilers
auto begin = iter - std::min(10, iter - vec.begin());
auto end = iter + std::min(10, vec.end() - iter);