C++使用lower_bound快速查询分段配置

当前在业务中,经常要将配置根据天数进行分段。例如 1-10 天一个配置段,11-20一个配置段。

由于进行了分段,所以查询配置就多了一层查询,即需要先锁定配置所在哪一段。比较习惯的做法是使用遍历,一个一个段去查询。虽然可行,但看着不优雅。

我们可以把段的数值作为map的key,然后使用lower_bound获得较高效率的查询。

下面是一段演示代码:

std::map<int, std::vector<std::string>> day_to_workings_map =
{
	{4, { "study", "sleep", "play" }},// 第4天之前
	{10, { "movie", "travel", "eat" }},// 第5天到第10天
	{20, { "interview", "go home", "watch foot ball" }}, // 第11天到第20天
};

int input_day = 0;
std::cout << "input day: ";
while (std::cin >> input_day)
{
	auto it = day_to_workings_map.lower_bound(input_day);
	if (it != day_to_workings_map.end())
	{
		std::cout << "hit day: " << it->first << std::endl;
		std::cout << "work:";
		for (const auto& work : it->second)
		{
			std::cout << " " << work;
		}
		std::cout << "\n";
	}
	else
	{
		std::cout << "invalid day" << std::endl;
	}

	std::cout << "input day: ";
}

这段代码对理解 lower_bound(val) 也有帮助,它返回一个迭代器it,它指向第一个 val <= *it 位置的值。

比如输入3,那么it->first就是4,如果输入是4,那么it->first还是4,如果是5,it->first就是10,但如果输入21,那么将得到end。

原文地址:https://www.cnblogs.com/demon90s/p/15658800.html