std :: find()指向一个向量 [英] std::find() on a vector of pointers

查看:203
本文介绍了std :: find()指向一个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过指针向量来搜索并比较指向 int 的指针。我最初的想法是使用 std :: find(),但是我意识到我无法比较指向 int 。例如:

  if(std :: find(myvector .begin(),myvector.end(),0)!= myvector.end()
{
//做某事
}


$ b myvector 是一个包含指向类对象的指针的向量,即 vector< ; MyClass *> myvector MyClass 包含一个方法 getValue()一个整数值,我基本上想要通过向量和检查每个对象的 getValue()返回值来确定我做什么。

$ p
$ b $ p $ if(std :: find(myvector.begin(),myvector.end (),0)!= myvector.end()
{
//输出0
}
else if(std :: find(myvector.begin(),myvector。 end(),1)!= myvector.end()
{
//输出1
}
else if(std :: find(myvector.begin(),myv ector.end(),2)!= myvector.end()
{
//输出2
}

它几乎就像一个绝对的条件,如果在我的向量中的指针的值是0,我输出零,我输出0.如果没有找到零,我看看是否有是1.如果找到1,我输出1.等等。 std :: find_if()代替。其他答案显示了如何使用谓词的lambda,但只适用于C ++ 11及更高版本。如果您使用的是较早的C ++版本,则可以这样做:

  struct isValue 
{
int m_value;

isValue(int value):m_value(value){}
$ b bool operator()(const MyClass * cls)const
{
return cls-> getValue()== m_value);
}
};如果(std :: find_if(myvector.begin(),myvector.end(),isValue(0))!= myvector.end()返回一个数组,
{
// ...
}


I want to search through a vector of pointers to and compare the pointers to an int. My initial idea was to use std::find() but i realized that I cannot compare a pointer to an int.

Example:

if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
   //do something
}

myvector is a vector containing pointers to a class object, i.e., vector<MyClass*> myvector.MyClass contains a method getValue() which will return an integer value and I basically want to go through the vector and check each object's getValue() return value to determine what i do.

Using the previous example:

if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
   //Output 0
}
else if(std::find(myvector.begin(), myvector.end(), 1) != myvector.end()
{
   //Output 1
}
else if(std::find(myvector.begin(), myvector.end(), 2) != myvector.end()
{
   //Output 2
}

Its almost like an absolute condition where if any pointer's value in my vector is a 0, i output zero, i output 0. If no zero is found, i look to see if there is a 1. If 1 is found, i output 1. Etc, etc..

解决方案

Use std::find_if() instead. The other answers show how to use a lambda for the predicate, but that only works in C++11 and later. If you are using an earlier C++ version, you can do this instead:

struct isValue
{
    int m_value;

    isValue(int value) : m_value(value) {}

    bool operator()(const MyClass *cls) const
    {
        return (cls->getValue() == m_value);
    }
};

...

if (std::find_if(myvector.begin(), myvector.end(), isValue(0)) != myvector.end()
{
    //...
}

这篇关于std :: find()指向一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆