vector 查找 string 跟 object 对象 辅助类 MAP Multimap查找

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

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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值