(原創) 如何利用copy() algorithm將array輸出到cout? (C/C++) (STL)
原本以為STL algorithm只能配合STL的Container,但看到侯捷的泛型程式設計與STL的範例,為了精簡,常常跟array搭配,才驚覺原來algorithm也可以搭配array喔!!此範例demo copy() algorithm如何搭配array。
1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
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
13
using namespace std;
14
15
int main () {
16
int ia[] = {1,2,3};
17
copy(ia, ia + sizeof(ia) / sizeof(int), ostream_iterator<int>(cout, " "));
18
19
return 0;
20
}
/* 2
(C) OOMusou 2006 http://oomusou.cnblogs.com3

4
Filename : ArrayWithCopy.cpp5
Compiler : Visual C++ 8.0 / ISO C++6
Description : Demo how to use copy() algorithm 7
and ostream_iterator from array to cout8
Release : 12/07/20069
*/10
#include <iostream>11
#include <algorithm>12

13
using namespace std;14

15
int main () {16
int ia[] = {1,2,3};17
copy(ia, ia + sizeof(ia) / sizeof(int), ostream_iterator<int>(cout, " ")); 18

19
return 0;20
}17行的sizeof(ia) / sizeof(int)寫法,可以動態算出array的element個數,如此就不用另外定個array size常數了,很鼓勵用這種寫法。
執行結果
1
1 2 3
1 2 3


浙公网安备 33010602011771号