Class 通过向量中的一个值查找对象

Class 通过向量中的一个值查找对象,class,stl,vector,find,member,Class,Stl,Vector,Find,Member,我遇到的无法解决的问题是这样的。我有两门课: class1 { private: int identifier; double value; public: setters,getters,etc... } class2 { private: vector<class1> objects; vector<int> some_value; vector<double> other_value; ... } 。。然后我希望找到一种方法,从

我遇到的无法解决的问题是这样的。我有两门课:

class1
{
private:
  int identifier;
  double value;
public:
  setters,getters,etc...
}
class2
{
private:
  vector<class1> objects;
  vector<int> some_value;
  vector<double> other_value;
...
}

。。然后我希望找到一种方法,从找到的迭代器值返回相应的(非常量)成员变量value和其他两个类的_值,但是代码到目前为止还没有编译,因为我很可能搜索错了。有没有一种方法可以通过find(或任何其他算法)实现这一点,或者我应该坚持我以前的工作实现,而不使用任何算法?

如果使用自定义谓词,则需要使用find\u。比如:

int getObj(const int &ident, double &returnedValue, double &returnedOther_value)
{
  int p;
  p = find(objects.begin()->getIdentifier(),objects.end()->getIdentifier(),ident);
  ..
class HasIdentifier:public unary_function<class1, bool>  
{  
public:
    HasIdentifier(int id) : m_id(id) { }  
    bool operator()(const class1& c)const  
    {  
        return (c.getIdentifier() == m_id);  
    }  
private:
    int m_id;  
};  


// Then, to find it:
vector<class1>::iterator itElem = find_if(objects.begin(), objects.end(), HasIdentifier(ident));  
类HasIdentifier:公共一元函数
{  
公众:
HasIdentifier(int-id):m_-id(id){}
布尔运算符()(常量class1&c)常量
{  
返回(c.getIdentifier()==m_id);
}  
私人:
国际货币基金组织;
};  
//然后,要找到它:
向量::迭代器itElem=find_if(objects.begin()、objects.end()、HasIdentifier(ident));
我还没有测试过,所以可能需要调整一下

如果你有C11,我想你可以使用lambdas,但我没有,所以我没有机会学习它们

更新:
我在

中添加了一个示例,您需要将find\u if与自定义谓词一起使用。比如:

int getObj(const int &ident, double &returnedValue, double &returnedOther_value)
{
  int p;
  p = find(objects.begin()->getIdentifier(),objects.end()->getIdentifier(),ident);
  ..
class HasIdentifier:public unary_function<class1, bool>  
{  
public:
    HasIdentifier(int id) : m_id(id) { }  
    bool operator()(const class1& c)const  
    {  
        return (c.getIdentifier() == m_id);  
    }  
private:
    int m_id;  
};  


// Then, to find it:
vector<class1>::iterator itElem = find_if(objects.begin(), objects.end(), HasIdentifier(ident));  
类HasIdentifier:公共一元函数
{  
公众:
HasIdentifier(int-id):m_-id(id){}
布尔运算符()(常量class1&c)常量
{  
返回(c.getIdentifier()==m_id);
}  
私人:
国际货币基金组织;
};  
//然后,要找到它:
向量::迭代器itElem=find_if(objects.begin()、objects.end()、HasIdentifier(ident));
我还没有测试过,所以可能需要调整一下

如果你有C11,我想你可以使用lambdas,但我没有,所以我没有机会学习它们

更新:
我在

中添加了一个示例,您不需要将
int
s作为常量引用传递。它们是按值传递的(因此不能更改原始值),按值传递int没有开销。您不需要将
int
s作为常量引用传递。它们是按值传递的(因此您不能更改原始值),按值传递int不会产生任何开销。这就像一种魅力!非常感谢你。现在我要做的就是找出如何从类2中的另一个_值向量返回值,它对应于在objects向量中找到的值(通过索引)。有没有一种方法不仅可以得到我所问的东西,还可以得到它在向量中的索引?这将彻底解决我的问题。你可以从向量的迭代器中找到元素的索引,如下所示:
size\t index=it-v.begin()谢谢。我从来不知道这是可能的。我猜你每天都会学到新东西这很有魅力!非常感谢你。现在我要做的就是找出如何从类2中的另一个_值向量返回值,它对应于在objects向量中找到的值(通过索引)。有没有一种方法不仅可以得到我所问的东西,还可以得到它在向量中的索引?这将彻底解决我的问题。你可以从向量的迭代器中找到元素的索引,如下所示:
size\t index=it-v.begin()谢谢。我从来不知道这是可能的。我猜你每天都会学到新东西