(原創) 如何利用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
4Filename : ArrayWithCopy.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use copy() algorithm
7 and ostream_iterator from array to cout
8Release : 12/07/2006
9*/
10#include <iostream>
11#include <algorithm>
12
13using namespace std;
14
15int 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.com
3
4Filename : ArrayWithCopy.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use copy() algorithm
7 and ostream_iterator from array to cout
8Release : 12/07/2006
9*/
10#include <iostream>
11#include <algorithm>
12
13using namespace std;
14
15int 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常數了,很鼓勵用這種寫法。
執行結果
11 2 3