gpt4 book ai didi

c++ - vector.erase 和 std::remove 自定义 vector

转载 作者:行者123 更新时间:2023-11-28 00:07:05 25 4
gpt4 key购买 nike

我有一个整数对 vector 。假设 Itr 作为这个 vector 的迭代器。我想遍历 vector 并决定是否从 vector 中删除元素。如果 vector 的元素是 9001,3 那么我想从 itr->first 是 9001 的 vector 中删除所有元素(不管是什么 itr ->第二个是)。

问题:

  1. 如何删除这个 int 对 vector 。以下是行不通的:vec.erase(std::remove(vec.begin(), vec.end(), Itr->first=9001), vec.end());
  2. 不是给 vec.begin() 到 vec.end() 的范围,我可以给vec.begin as (当前元素是 vector 指针)- 10 和ve.end 为 ( vector 指向的当前元素)+10

示例:vec.erase(std::remove(Itr-10, Itr+10, Itr->first=9001), vec.end());

如果 vector 大小本身小于 10,Itr+10 或 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;

最佳答案

How do i remove this vector of int pairs. The following wouldn't work:

将 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());

Instead of giving a range as vec.begin() to vec.end() is it possible for me to give vec.begin as (current element being pointer by vector) - 10 and ve.end as (current element being pointed by vector)+10 ?

是的。 vector 迭代器支持指针运算,所以很容易。

It might quiet be possible that Itr+10 ot Itr-10 will result in a segmentation fault if the vector size itself is less than 10. So how to deal with this situation?

如果迭代器之前或之后没有足够的元素,则限制你的范围:

//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);

关于c++ - vector.erase 和 std::remove 自定义 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35015868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com