📄 fig20_29.cpp
字号:
// Fig. 20.29: fig20_29.cpp
// Demonstrates Standard Library functions replace, replace_if
// replace_copy and replace_copy_if
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool greater9( int );
int main()
{
const int SIZE = 10;
int a[ SIZE ] = { 10, 2, 10, 4, 16, 6, 14, 8, 12, 10 };
ostream_iterator< int > output( cout, " " );
// Replace 10s in v1 with 100
vector< int > v1( a, a + SIZE );
cout << "Vector v1 before replacing all 10s:\n";
copy( v1.begin(), v1.end(), output );
replace( v1.begin(), v1.end(), 10, 100 );
cout << "\nVector v1 after replacing all 10s with 100s:\n";
copy( v1.begin(), v1.end(), output );
// copy from v2 to c1, replacing 10s with 100s
vector< int > v2( a, a + SIZE );
vector< int > c1( SIZE );
cout << "\n\nVector v2 before replacing all 10s "
<< "and copying:\n";
copy( v2.begin(), v2.end(), output );
replace_copy( v2.begin(), v2.end(),
c1.begin(), 10, 100 );
cout << "\nVector c1 after replacing all 10s in v2:\n";
copy( c1.begin(), c1.end(), output );
// Replace values greater than 9 in v3 with 100
vector< int > v3( a, a + SIZE );
cout << "\n\nVector v3 before replacing values greater"
<< " than 9:\n";
copy( v3.begin(), v3.end(), output );
replace_if( v3.begin(), v3.end(), greater9, 100 );
cout << "\nVector v3 after replacing all values greater"
<< "\nthan 9 with 100s:\n";
copy( v3.begin(), v3.end(), output );
// Copy v4 to c2, replacing elements greater than 9 with 100
vector< int > v4( a, a + SIZE );
vector< int > c2( SIZE );
cout << "\n\nVector v4 before replacing all values greater"
<< "\nthan 9 and copying:\n";
copy( v4.begin(), v4.end(), output );
replace_copy_if( v4.begin(), v4.end(), c2.begin(),
greater9, 100 );
cout << "\nVector c2 after replacing all values greater"
<< "\nthan 9 in v4:\n";
copy( c2.begin(), c2.end(), output );
cout << endl;
return 0;
}
bool greater9( int x )
{
return x > 9;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -