将指针转换为迭代器
convert pointer to iterator
我有 2 个结构,它们相互指向
struct Person{
string name;
string born;
int age;
Id* p_id;
};
struct Id{
string id_number;
Person* p_person;
};
这些结构存储在两个称为vec_id和vec_person的结构的庞特向量中。我需要在vec_person中找到 Person 的函数,然后在向量 vec_id 中删除匹配的 Id。我的问题是将p_id转换为指针。
我的代码示例:
std::vector<Person*> vec_person;
std::vector<Id*> vec_id;
vector <Person*>::iterator lowerb=std::lower_bound (vec_person.begin(), vec_person.end(), Peter, gt);
//gt is matching function which is defined elsewhere
//peter is existing instance of struct Person
// lowerb is iterator, that works fine.
vec_id.erase((*lowerb)->p_id);
//gives error: no matching function for call to ‘std::vector<Person*>::erase(Person*&)’|
//if i can convert pointer (*low)->pnumber to iterator, it would be solved(i guess).
感谢帮助大家
要将迭代器it
转换为指针,请使用表达式 &*it
。
要将指向整数的指针右值(例如,...)转换为vector<int>::iterator
,请使用以下声明:
vector<int>::iterator it(...);
您不能只是从值(在本例中为指针)"转换"到迭代器。您必须在向量中搜索值并将其删除。您可以使用 std::remove_if 算法从范围中删除某些值。如果每个人都链接到一个 id,或者可能使用不同的容器(例如地图),您也可以考虑不保留两个向量。
我刚刚找到了这个解决方案
auto iter = vec.begin() + (pointer - vec.data());
auto p = std::equal_range( vec_person.begin(), vec_person.end(), Peter, gt );
if ( p.first != p.second )
{
vec_id.erase( std::remove( vec_id.begin(), vec_id.end(), *p.first ),
vec_id.end() );
}
相关文章:
- 是否应避免从非常量迭代器转换为常量迭代器?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- C++ 如何为自己的迭代器类从迭代器转换为const_iterator?
- C++将向量迭代器转换为索引
- 从迭代器转换为变量的类型.(C++11 模板)
- 提高迭代器转换const_iterator
- 将字符串::迭代器转换为标准::字符串
- C++将迭代器转换为指针(并将 end() 转换为 nullptr)
- C++Spirit Boost:将输入迭代器转换为前向迭代器
- 将迭代器转换为指针,尤其是在end()处
- Deque索引迭代器转换
- 将多映射迭代器转换为随机访问迭代器
- 将迭代器转换为标量索引
- 无法将uint8_t矢量迭代器转换为常量 uint8_t *
- 如何将列表 STL 的迭代器转换为实例 (C++)
- 适配器,用于将任何迭代器转换为随机访问迭代器
- 将取消引用字符迭代器转换为 int C++
- 如何在C++中将矢量迭代器转换为 int
- c++入门第3章迭代器转换错误
- 将rend迭代器转换为end iteterator