原本以為STL algorithm只能配合STL的Container,但看到侯捷的泛型程式設計與STL的範例,為了精簡,常常跟array搭配,才驚覺原來algorithm也可以搭配array喔!!此範例demo copy() algorithm如何搭配array。
1
/**/
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
4
Filename : ArrayWithCopy.cpp
5
Compiler : Visual C++ 8.0 / ISO C++
6
Description : Demo how to use copy() algorithm
7
and ostream_iterator from array to cout
8
Release : 12/07/2006
9
*/
10
#include
<
iostream
>
11
#include
<
algorithm
>
12![None.gif](/Images/OutliningIndicators/None.gif)
13
using
namespace
std;
14![None.gif](/Images/OutliningIndicators/None.gif)
15![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
int
main ()
{
16![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int ia[] =
{1,2,3};
17
copy(ia, ia + sizeof(ia) / sizeof(int), ostream_iterator<int>(cout, " "));
18![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
19
return 0;
20
}
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
2
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
3
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
4
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
5
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
6
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
7
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
8
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
9
![ExpandedBlockEnd.gif](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
10
![None.gif](/Images/OutliningIndicators/None.gif)
11
![None.gif](/Images/OutliningIndicators/None.gif)
12
![None.gif](/Images/OutliningIndicators/None.gif)
13
![None.gif](/Images/OutliningIndicators/None.gif)
14
![None.gif](/Images/OutliningIndicators/None.gif)
15
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
![dot.gif](/Images/dot.gif)
16
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![ContractedSubBlock.gif](/Images/OutliningIndicators/ContractedSubBlock.gif)
![dot.gif](/Images/dot.gif)
17
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
18
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
19
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
20
![ExpandedBlockEnd.gif](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
17行的sizeof(ia) / sizeof(int)寫法,可以動態算出array的element個數,如此就不用另外定個array size常數了,很鼓勵用這種寫法。
執行結果
1
1
2
3
![None.gif](/Images/OutliningIndicators/None.gif)