stl算法之replace,replace_if,replace_copy,replace_copy_if

1.replace

自己实现源码

template<typename iteratorty,typename type>
void replace_ty(iteratorty first, iteratorty last, const type & oldvalue, const type & newvalue)
{
	for (; first != last;first++)
	{
		if (*first == oldvalue)
		{
			//将所有等于oldvalue的全部替换为newvalue
			*first = newvalue;
		}
	}
}

使用示例:

void main()
{
	std::vector<int> m_vc{ 1, 2, 3, 2, 5, 6 };
	cout << "替换前:\n";
	for_each(m_vc.begin(), m_vc.end(), [](int x){cout << x << " "; });
	cout << endl;
	//等于2的全部替换为2000
	replace_ty(m_vc.begin(), m_vc.end(), 2, 2000);
	cout << "replace替换(2->2000)后:\n";
	for_each(m_vc.begin(), m_vc.end(), [](int x){cout << x << " "; });
	cout << endl;
}

结果:
stl算法之replace,replace_if,replace_copy,replace_copy_if_第1张图片

2.replace_if

将满足条件的全部替换为设置的值

void main()
{
//大于4的全部替换为1000
	std::vector<int> m_vc{ 1, 2, 3, 4, 5, 6, 7 };
	cout << "替换前:";
	for (auto node :m_vc)
	{ 
		cout << node << " ";
	}
	cout << endl;
	int n = 4;
	cout << "replace_if(替换大于4的元素)后:";
	replace_if(m_vc.begin(), m_vc.end(), [n](int x){return x > n; },1000);
	for_each(m_vc.begin(), m_vc.end(), [](int x){cout << x << " "; });
	cout << endl;
system("pause");
}

结果:
stl算法之replace,replace_if,replace_copy,replace_copy_if_第2张图片

3.replace_copy

源码:

template <class Inputerator, class Outputerator, class T>
Outputerator replace_copy(ForwardIterator first, ForwardIterator last, Outputerator result, const T & old_value, const T& new_value)
{//范围内所有等于old_value者都以new_value放置新区域
//不符合者原值放入新区域
    for( ; first != last; ++first, ++result)
    {
        *result = *first == old_value ? new_value : *first;
    }
}

将[First, Last]区间中的元素复制到_Dest为起点的目标区,同时将其中与_oldval相等的所有元素替换为_Newval

示例:

void main()
{
std::vector<int> m_vvvc{1,2,3,4,2,6,7};
	std::vector<int> m_oldvc(7,0);//一定要提前有空间,要不报错

	replace_copy(m_vvvc.begin(), m_vvvc.end(), m_oldvc.begin(), 2, 200);
	
	cout << "使用replace_copy后:\n";
	cout << "m_vvvc:";
	for_each(m_vvvc.begin(), m_vvvc.end(), [](int x){cout << x << " "; });
	cout << endl;

	cout << "m_oldvc:";
	for_each(m_oldvc.begin(), m_oldvc.end(), [](int x){cout << x << " "; });
	cout << endl;
	}

结果:
stl算法之replace,replace_if,replace_copy,replace_copy_if_第3张图片

4.replace_copy_if

将满足某一条件的所有元素都替换了

void main()
{
std:vector<int> m_vcx{ 1, 2, 3, 4, 5, 6, 7, 8 };
	std::vector<int> m_oldvcx(8,0);
	replace_copy_if(m_vcx.begin(), m_vcx.end(), m_oldvcx.begin(), [](int x){return x > 4; }, 2021);
	cout << "使用replace_copy_if(大于4的全部替换为2021)后:\n";
	cout << "m_vcx:";
	for_each(m_vcx.begin(), m_vcx.end(), [](int x){cout << x << " "; });
	cout << endl;

	cout << "m_oldvcx:";
	for_each(m_oldvcx.begin(), m_oldvcx.end(), [](int x){cout << x << " "; });
	cout << endl;
	
}

结果:
stl算法之replace,replace_if,replace_copy,replace_copy_if_第4张图片

你可能感兴趣的:(STL)