查找与存储在向量中的对象相对应的迭代器
Finding an iterator corresponding to an object stored in a vector
我有一个向量v,其中包含a类型结构的对象。现在我需要找到存储在这个向量中的特定对象的迭代器。例如:
struct a
{
};
vector<a> v;
struct temp; //initialized
现在,如果我将使用
find(v.begin(),v.end(), temp);
则编译器生成表示运算符CCD_ 1不匹配的错误。
有什么解决方法可以让迭代器与向量中的对象相对应?
您必须为类提供bool operator==(const a& lhs, const a& rhs)
相等运算符,或者将比较函子传递给std::find_if
:
struct FindHelper
{
FindHelper(const a& elem) : elem_(elem) {}
bool operator()(const a& obj) const
{
// implement equality logic here using elem_ and obj
}
const a& elem_;
};
vector<a> v;
a temp;
auto it = std::find_if(v.begin(), v.end(), FindHelper(temp));
或者,在c++11中,您可以使用lambda函数而不是函子。
auto it = std::find_if(v.begin(), v.end(),
[&temp](const a& elem) { /* implement logic here */ });
相关文章:
- 非静态成员引用必须相对于特定对象
- 如何在3D世界中获得对象相对于父母的绝对位置
- 不确定如何修复;非静态成员参考必须相对于特定对象
- 相对于向量对象的两个成员,找到两个向量的相交的有效方法
- 请澄清术语类静态对象(相对于类静态成员)
- 如何根据父对象的相对变化计算子对象的新全局位置
- C++标准库容器相对于所包含对象的线程安全性
- C++非静态成员引用必须相对于特定对象
- 无法理解错误 msg:"非静态成员引用必须相对于特定对象"
- 为什么我的 OpenGL 对象相对于最后一个绘制的对象绘制
- 新的新类对象的函数;错误:非静态成员引用必须相对于特定对象
- CMake:从外部项目链接共享C++对象会生成具有相对路径的二进制文件,而不是绝对路径
- C++非静态成员引用必须相对于特定对象
- 我是否需要使用继承对象(相对于基对象)覆盖我的虚函数?
- 如何使用具有相对路径的fstream对象
- lambda对象相对于函数指针转换的生命周期
- 在另一个类内部构造一个类(非静态成员引用必须相对于特定对象)
- 非静态成员引用必须相对于特定的c++对象单例类
- 错误:非静态成员引用必须相对于特定对象
- 查找与存储在向量中的对象相对应的迭代器