C++ STL算法includes(40)

2022/1/14 17:06:53

本文主要是介绍C++ STL算法includes(40),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

函数原型

//不带谓词
template<class _InIt1, class _InIt2>
_NODISCARD inline bool includes(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _InIt2 _Last2)

//带谓词
template<class _InIt1, class _InIt2, class _Pr>
_NODISCARD inline bool includes(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _InIt2 _Last2, _Pr _Pred)

比较两个元素的集合,如果第一个集合中的全部元素都来自第二个集合,它会返回 true。如果第二个集合是空的集合,它也返回 true。

不带谓词

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include <iterator>
#include <array>
#include <sstream>

int main()
{	
	// All elements in the two vectors are unique
	std::vector<int> v1 = { 10, 20, 3, 5 };
	std::vector<int> v2 = { 10, 5, 3 };
	std::sort(std::begin(v1), std::end(v1));
	std::sort(std::begin(v2), std::end(v2));
	bool rtn = std::includes(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2));
	if (rtn)
	{
		std::cout << "YES\n";
	}
	else
	{
		std::cout << "NO\n";
	}

	 When elements in the two vectors are duplicate
	std::vector<int> v3 = { 10, 20, 3, 5, 20 };
	std::vector<int> v4 = { 20, 10, 5, 3, 5 };
	std::sort(v3.begin(), v3.end());
	std::sort(v4.begin(), v4.end());
	if (std::includes(v3.begin(), v3.end(), v4.begin(), v4.end()))
	{
		std::cout << "YES\n";
	}
	else
	{
		std::cout << "NO\n";
	}

	std::vector<int> v5;
	if (std::includes(v3.begin(), v3.end(), v5.begin(), v5.end()))
	{
		std::cout << "YES\n";
	}
	else
	{
		std::cout << "NO\n";
	}

	return -1;
}

//输出
YES
NO
YES

带谓词

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include <iterator>
#include <array>
#include <sstream>

int main()
{	
	// All elements in the two vectors are unique
	std::vector<int> v1 = { 10, 20, 3, 5 };
	std::vector<int> v2 = { 10, 5, 3 };
	std::sort(std::begin(v1), std::end(v1));
	std::sort(std::begin(v2), std::end(v2));
	bool rtn = std::includes(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2), std::less<int>());
	if (rtn)
	{
		std::cout << "YES\n";
	}
	else
	{
		std::cout << "NO\n";
	}

	 When elements in the two vectors are duplicate
	std::vector<int> v3 = { 10, 20, 3, 5, 20 };
	std::vector<int> v4 = { 20, 10, 5, 3, 5 };
	std::sort(v3.begin(), v3.end());
	std::sort(v4.begin(), v4.end());
	if (std::includes(v3.begin(), v3.end(), v4.begin(), v4.end(), std::less<int>()))
	{
		std::cout << "YES\n";
	}
	else
	{
		std::cout << "NO\n";
	}

	std::vector<int> v5;
	if (std::includes(v3.begin(), v3.end(), v5.begin(), v5.end()))
	{
		std::cout << "YES\n";
	}
	else
	{
		std::cout << "NO\n";
	}

	return -1;
}

//输出
YES
NO
YES



这篇关于C++ STL算法includes(40)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程