[英]Comparator for lower_bound for vector of pairs
我想為對向量制作lower_bound
但我只想將它用於對的第一個元素。 我試圖像這樣制作自己的比較器:
bool find(const std::string& key) const {
auto finder = std::lower_bound(words_.begin(), words_.end(), key,
[](const std::string& key, std::vector<std::pair<std::string, std::string>>::iterator it)
{return key != it->first;});
}
但它不起作用。 我應該如何使用比較器只比較對的第一個元素?
您的 lambda 是lower_bound()
的錯誤簽名和比較。 預計將容器元素與提供的值進行比較。 這意味着它根本不接受iterator
作為輸入。
lambda的第1個參數需要接受容器元素,第2個參數需要接受輸入值。 因此,您可能正在尋找更像這樣的東西:
bool find(const std::string& key) const {
auto finder = std::lower_bound(words_.begin(), words_.end(),
key,
[](const std::pair<std::string, std::string> &elem, const std::string &value) {
return elem.first < value;
}
);
...
}
話雖如此,如果您要做的只是找到與指定key
的完全匹配,則std::find_if()
會更有意義:
bool find(const std::string& key) const {
auto finder = std::find_if(words_.begin(), words_.end(),
[&key](const std::pair<std::string, std::string> &elem) {
return elem.first == key;
}
);
...
}
lower_bound
function (見這里)將比較器(又名謂詞)定義為接受兩個值進行比較(在您的情況下,兩個 const std::string &)。 將謂詞從接受const std::string &
和迭代器更改:
[](const std::string& key, std::vector<std::pair<std::string, std::string>>::iterator it) {...}
到接受兩個const std::string &
的 lambda :
[](const std::string& first, const std::string &second) {...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.