devxlogo

The includes() Algorithm

The includes() Algorithm

You can use the includes() algorithm to determine if every element within a specified range of a sequence container is completely contained within a specified range of another sequence conatainer.

	int iArr [] {0, 2, 3, 4, 5, 6, 7, 8, 9};	vector vecInt (iArr, iArr + 9);	int iArr_1 [] = {2, 10, 6, 5};

However, you must sort both containers before using includes():

	sort (iArr_1, iArr + 4);// 

Now iArr_1 has this sequence {2, 5, 6, 10} because sort() sorts in ascending order:

	bool isIn = include (vecInt.begin(), vecInt.end(), iArr_1, iArr_1 + 4); // isIn = false

Here, includes() return false because 10 is not contained in the vecInt. In the following code, include() returns true because it's considering elements from the zero position to the second position of vecInt.

	isIn = include (vecInt.begin(), vecInt.end(), iArr_1, iArr_1 + 3); // isIn = true

Be aware that this version of includes() will help only if you have sorted your containers in ascending order.

Suppose you sort the containers in descending order by using the pre-defined, relational function object greater() or by using your own written function object. You would then need to use the second overloaded version of includes() to determine the element ordering. This second overloaded version takes four parameters. So, you need to pass the function object used for sorting containers as its fourth argument to let it determine the ordering of elements:

	int iArr_2 [] = {8, 9, 3, 7};	#include  //for greater()	sort (iArr_2, iArr2 + 4, greater());// so now iArr_2 has this sequence {8, 9, 7, 3}	sort (vecInt.begin(), vecInt.end(), greater()); // vecInt has this sequence now 9,8, 7, 6, 5, 4, 3, 2, 0	isIn = includes (vecInt.begin(), vecInt.end(), iArr_2, iArr_2 + 4); // isIn = false

includes() returned false because the containers are sorted in descending order and the code is using the first version of includes(), which assumes that the containers are sorted in ascending order.

Here's what it looks like to use the second overloaded version of includes():

	isIn = includes (vecInt.begin(), vecInt.end(), iArr_2, iArr_2 + 4, greater()); // isIn = true
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist