📄 fig20_30.cpp
字号:
// Fig. 20.30: fig20_30.cpp
// Examples of mathematical algorithms in the Standard Library.
#include <iostream>
#include <algorithm>
#include <numeric> // accumulate is defined here
#include <vector>
using namespace std;
bool greater9( int );
void outputSquare( int );
int calculateCube( int );
int main()
{
const int SIZE = 10;
int a1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector< int > v( a1, a1 + SIZE );
ostream_iterator< int > output( cout, " " );
cout << "Vector v before random_shuffle: ";
copy( v.begin(), v.end(), output );
random_shuffle( v.begin(), v.end() );
cout << "\nVector v after random_shuffle: ";
copy( v.begin(), v.end(), output );
int a2[] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 };
vector< int > v2( a2, a2 + SIZE );
cout << "\n\nVector v2 contains: ";
copy( v2.begin(), v2.end(), output );
int result = count( v2.begin(), v2.end(), 8 );
cout << "\nNumber of elements matching 8: " << result;
result = count_if( v2.begin(), v2.end(), greater9 );
cout << "\nNumber of elements greater than 9: " << result;
cout << "\n\nMinimum element in Vector v2 is: "
<< *( min_element( v2.begin(), v2.end() ) );
cout << "\nMaximum element in Vector v2 is: "
<< *( max_element( v2.begin(), v2.end() ) );
cout << "\n\nThe total of the elements in Vector v is: "
<< accumulate( v.begin(), v.end(), 0 );
cout << "\n\nThe square of every integer in Vector v is:\n";
for_each( v.begin(), v.end(), outputSquare );
vector< int > cubes( SIZE );
transform( v.begin(), v.end(), cubes.begin(),
calculateCube );
cout << "\n\nThe cube of every integer in Vector v is:\n";
copy( cubes.begin(), cubes.end(), output );
cout << endl;
return 0;
}
bool greater9( int value ) { return value > 9; }
void outputSquare( int value ) { cout << value * value << ' '; }
int calculateCube( int value ) { return value * value * value; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -