天天看點

C++ STL非更易型算法 查找兩個連續且相等的元素adjacent_find使用例子:

C++ STL非更易型算法 查找兩個連續且相等的元素adjacent_find使用例子:

傳回[_First,_Last)區間内第一對連續兩個相等元素中的第一進制素位置
C++ STL非更易型算法 查找兩個連續且相等的元素adjacent_find使用例子:

傳回[_First,_Last)區間内第一對連續兩個元素均造成_Pred(elem,nextElem)結果為true的第一進制素位置.

如果沒有找到比對元素,傳回end

複雜度:線性,最多比較numElems次

使用例子:

template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
	cout << optcstr;
	for (auto elem : coll)
	{
		cout << elem << ' ';
	}
	cout << endl;

}
bool doubled(int elem1, int elem2)
{
	return elem1 * 2 == elem2;
}

int main()
{
	vector<int>coll;
	coll.push_back(1);
	coll.push_back(3);
	coll.push_back(2);
	coll.push_back(4);
	coll.push_back(5);
	coll.push_back(5);
	coll.push_back(0);

	PRINT_ELEMENTS(coll, "coll: ");

	auto pos = adjacent_find(coll.begin(), coll.end());

	if (pos != coll.end())
	{
		cout << "first two elements with equal value have position " << distance(coll.begin(), pos) + 1 << endl;
	}
	pos = adjacent_find(coll.begin(), coll.end(), doubled);
	if (pos != coll.end())
	{
		cout << "first two elements with second value twice the " << "first have pos. " << distance(coll.begin(), pos) + 1 << endl;
	}

}
           
C++ STL非更易型算法 查找兩個連續且相等的元素adjacent_find使用例子:

繼續閱讀