Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::在重载==运算符的对象的向量上查找_C++_Operator Overloading - Fatal编程技术网

C++ std::在重载==运算符的对象的向量上查找

C++ std::在重载==运算符的对象的向量上查找,c++,operator-overloading,C++,Operator Overloading,我试图在以下向量上使用std::find: std::vector<LoopDetectorData *> Vec_loopDetectors; std::find似乎无法找到项,即使该项存在于向量中。std::find()按值搜索。因此,它会将存储在向量中的指针与刚创建用作搜索参数的指针进行比较。这可能会失败:比较指针,而不是所指向对象的值 您应改用: auto counter = std::find_if (Vec_loopDetectors.begin(),

我试图在以下向量上使用std::find:

std::vector<LoopDetectorData *> Vec_loopDetectors;
std::find似乎无法找到项,即使该项存在于向量中。

std::find()
按值搜索。因此,它会将存储在向量中的指针与刚创建用作搜索参数的指针进行比较。这可能会失败:比较指针,而不是所指向对象的值

您应改用

auto counter = std::find_if (Vec_loopDetectors.begin(),
                             Vec_loopDetectors.end(), 
                             [&searchFor](const LoopDetectorData *f)->bool
                               { return *f == *searchFor; }
                             ); 
find_if使用一个谓词,这里是一个特殊的lambda函数,它通过取消引用指针来比较指向的值。如果您对lambdas不满意,可以使用函数poitner


这里是这个替代方案的一个例子,与您最初的尝试进行比较

您不能为内置类型(包括指针)重载运算符。您的
vector
包含
LoopDetectorData*
,因此
std::find
将比较指针是否相等,而
searchFor
将永远不会与
vector
中已有的任何指针进行相等比较。在所有可能的情况下,您应该使用
std::vector Vec\u检测器
由于您刚刚创建了
搜索
,因此向量中不可能有指向它的指针。谢谢大家。我得到了它。为什么我得到这么多的反对票!:)
class LoopDetectorData
{
  public:
    char detectorName[20];
    char lane[20];
    char vehicleName[20];
    double entryTime;
    double leaveTime;
    double entrySpeed;
    double leaveSpeed;

    LoopDetectorData( const char *str1, const char *str2, const char *str3, double entryT=-1, double leaveT=-1, double entryS=-1, double leaveS=-1 )
    {
        strcpy(this->detectorName, str1);
        strcpy(this->lane, str2);
        strcpy(this->vehicleName, str3);

        this->entryTime = entryT;
        this->leaveTime = leaveT;

        this->entrySpeed = entryS;
        this->leaveSpeed = leaveS;
    }

    friend bool operator== (const LoopDetectorData &v1, const LoopDetectorData &v2);
};
auto counter = std::find_if (Vec_loopDetectors.begin(),
                             Vec_loopDetectors.end(), 
                             [&searchFor](const LoopDetectorData *f)->bool
                               { return *f == *searchFor; }
                             );