#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
template<typename T>
class find_vec_string_exist_handle
{
public:
find_vec_string_exist_handle(const std::basic_string< T >& str)
: str_(str) {}
bool operator()(const std::basic_string< T >& strSrc)
{
return strSrc == str_;
}
bool operator()(const T* strSrc)
{
return strSrc == str_;
}
private:
std::basic_string< T > str_;
};
class MyClass {
public:
MyClass(int value) : value_(value) {}
int getValue() const {
return value_;
}
bool operator ==(const MyClass& other) const
{
return value_ == other.value_;
}
private:
int value_;
};
template<typename T>
class findif_vector_obj_exist_handler
{
public:
findif_vector_obj_exist_handler(T obj)
: obj_(obj) {}
bool operator()(const T& obj)
{
return obj == obj_;
}
bool operator()(const T* obj)
{
return obj == obj_;
}
private:
T obj_;
};
int main() {
std::vector<std::string> strVec = { "apple", "banana", "orange" };
std::string target = "banana";
// 使用 find_vec_string_exist_handle 作为 std::find_if 的谓词
auto it = std::find_if(strVec.begin(), strVec.end(), find_vec_string_exist_handle<char>(target));
if (it != strVec.end()) {
std::cout << "String found: " << *it << std::endl;
}
else {
std::cout << "String not found." << std::endl;
}
std::vector<MyClass> objVec;
objVec.emplace_back(10);
objVec.emplace_back(20);
objVec.emplace_back(30);
MyClass target1(20);
// 使用 findif_vector_obj_exist_handler 作为 std::find_if 的谓词
auto it1 = std::find_if(objVec.begin(), objVec.end(), findif_vector_obj_exist_handler<MyClass>(target1));
if (it1 != objVec.end()) {
std::cout << "Object found: " << it1->getValue() << std::endl;
}
else {
std::cout << "Object not found." << std::endl;
}
return 0;
}
![](https://img-blog.csdnimg.cn/direct/03cf75e1e65a4289806030f72d79b3b5.png)
template<class M>
auto MapGetValuePtr(M& map, typename M::key_type const& key)
{
auto itr = map.find(key);
if constexpr (std::is_pointer_v<typename M::mapped_type>)
return itr != map.end() ? itr->second : nullptr;
else
return itr != map.end() ? &itr->second : nullptr;
}
template<class K, class V, template<class, class, class...> class M, class... Rest>
void MultimapErasePair(M<K, V, Rest...>& multimap, K const& key, V const& value)
{
auto range = multimap.equal_range(key);
for (auto itr = range.first; itr != range.second;)
{
if (itr->second == value)
itr = multimap.erase(itr);
else
++itr;
}
}