【问题标题】:Finding a on object in a vector by one of its values通过其中一个值在向量中查找对象
【发布时间】:2012-03-07 09:42:13
【问题描述】:

我遇到并且无法解决的问题是这样的。我有两个班级:

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

问题是我需要通过 class1 对象中的标识符(来自 class2 的成员函数)来搜索第二类对象中的对象向量。我试过类似的东西:

int getObj(const int &ident, double &returnedValue, double &returnedOther_value)
{
  int p;
  p = find(objects.begin()->getIdentifier(),objects.end()->getIdentifier(),ident);
  ..

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

【问题讨论】:

  • 您不需要将ints 作为常量引用传递。它们是按值传递的(因此您不能更改原始值),并且按值传递 int 没有任何开销。

标签: class stl vector find member


【解决方案1】:

您需要将 find_if 与自定义谓词一起使用。比如:

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

我还没有测试过,所以可能需要一些调整。

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

更新: 我在http://ideone.com/D1DWU中添加了一个示例

【讨论】:

  • 这就像一个魅力!非常感谢。现在我要做的就是弄清楚如何从第二类中的 other_value 向量返回值,该值对应于在对象向量中找到的值(按索引)。有没有办法不仅可以获得我所询问的内容,还可以获得它在向量中的索引?这将彻底解决我的问题。
  • 你可以像这样从它的迭代器中找到一个向量中元素的索引:size_t index = it - v.begin();
  • 谢谢。我从来不知道这是可能的。猜猜你每天都会学到一些新东西。 :)
猜你喜欢
  • 2018-09-02
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 2013-07-10
  • 2012-06-07
  • 2017-12-01
相关资源
最近更新 更多