C++ - "replace" 和 "replace_copy" 区别

"replace" 和 "replace_copy" 区别

 

两个函数"replace"和"replace_copy"都是标准库算法中的函数.

replace是替代某一个元素, replace_copy是复制并且替代某一个元素.

 

示例(VS2012):

#include <iostream>     // std::cout
#include <algorithm>    // std::replace
#include <vector>       // std::vector

int main () {
	int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };

	/*replace*/
	std::vector<int> myvector1 (myints, myints+8);            // 10 20 30 30 20 10 10 20
	std::replace (myvector1.begin(), myvector1.end(), 20, 99); // 10 99 30 30 99 10 10 99
	std::cout << "replace() myvector1:";
	for(const auto i : myvector1)
		std::cout << i << " ";
	std::cout << std::endl;

	/*replace_copy*/
	std::vector<int> myvector2 (8);
	std::replace_copy (myints, myints+8, myvector2.begin(), 20, 78);
	std::cout << "replace_copy() myvector2:";
	for(const auto i : myvector2)
		std::cout << i << " ";
	std::cout << std::endl;

	return 0;
}


C++ - "replace" 和 "replace_copy" 区别_第1张图片

你可能感兴趣的:(Algorithm,C++,replace,Mystra,replace_copy)