मैं std::find
के इंटरफ़ेस के बारे में उलझन में हूं। यह Compare
ऑब्जेक्ट क्यों नहीं लेता है जो बताता है कि दो वस्तुओं की तुलना कैसे करें?एक वस्तु ऑब्जेक्ट का उपयोग करके std :: ढूंढें कैसे करें?
मैं सिर्फ सीधे सूचक मानों की तुलना करने के बजाय एक Compare
वस्तु मैं निम्नलिखित कोड काम कर सकता है, जहां मैं मूल्य से तुलना करने के लिए चाहते हैं, पारित कर सकता है:
typedef std::vector<std::string*> Vec;
Vec vec;
std::string* s1 = new std::string("foo");
std::string* s2 = new std::string("foo");
vec.push_back(s1);
Vec::const_iterator found = std::find(vec.begin(), vec.end(), s2);
// not found, obviously, because I can't tell it to compare by value
delete s1;
delete s2;
निम्नलिखित की सिफारिश की रास्ता है इसे करने के लिए?
template<class T>
struct MyEqualsByVal {
const T& x_;
MyEqualsByVal(const T& x) : x_(x) {}
bool operator()(const T& y) const {
return *x_ == *y;
}
};
// ...
vec.push_back(s1);
Vec::const_iterator found =
std::find_if(vec.begin(), vec.end(),
MyEqualsByVal<std::string*>(s2)); // OK, will find "foo"
धन्यवाद! जिज्ञासा से, 'copy_if' के साथ क्या गलत है? – Frank
@ डेहमान: इसके साथ गलत बात यह है कि यह मानक में नहीं है। एक संपादन दुर्घटना के कारण यह अनिवार्य रूप से बाहर निकल गया। –