函数原型
//不带谓词 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