2015-05-22 38 views
-2

我嘗試使用std對象的矢量找到::找到以下向量:的std ::與重載==操作符

std::vector<LoopDetectorData *> Vec_loopDetectors; 

這是我如何使用它:

const LoopDetectorData *searchFor = new LoopDetectorData((*it).c_str(), "", vehicleName.c_str()); 
std::vector<LoopDetectorData *>::iterator counter = std::find(Vec_loopDetectors.begin(), Vec_loopDetectors.end(), searchFor); 

這是帶有operator ==重載的LoopDetectorData類的定義。

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

看來,std :: find即使項目存在於向量中也找不到項目。

+0

您不能重載運算符的內置類型,其中包括指針。 –

+0

您的'vector'包含'LoopDetectorData *',所以'std :: find'將比較指針是否相等,並且'searchFor'永遠不會與任何已經在'vector'中的指針進行比較。很有可能,你應該使用'std :: vector Vec_loopDetectors;' – Praetorian

+0

由於您剛剛創建了'searchFor',因此它的指針不可能位於向量中。 –

回答

1

std::find()按價值搜索。所以它會比較存儲在你的向量中的指針和你剛剛創建的指針作爲搜索參數。這被認爲是失敗的:你比較指針而不是對象所傾向的值。

您應使用std::find_if()代替:

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

find_if使用謂詞是這裏的ad-hoc拉姆達函數比較值通過取消引用指針指向。如果你對lambda表達不滿意,你可以使用函數poitner。

這裏有一個live demo這個替代方案,與你的臨時嘗試進行比較。