copy(arr, arr + sizeof(arr), out) ;

// main.cpp
// Demonstration for pointer + int error

#include
<iterator>
#include
<iostream>
#include
<algorithm>
using namespace std ;

int main()
{
// Total seven elements
int arr[] = {1, 2, 3, 4, 5, 6, 7,} ;

// output
ostream_iterator<int> out(cout, " ") ;
copy(arr, arr
+ sizeof(arr), out) ; // You know what's going wrong?

return 0 ;
}

分析:

   问题在于copy(arr, arr + sizeof(arr), out) ; 一个指针 + 一个整数 的结果是指针偏移值加上整数所代表其元素的偏移值. 因此,

   正确的写法是:

              copy(arr, arr + sizeof(arr)/sizeof(arr[0]), out) ;

posted @ 2011-05-05 19:34  walfud  阅读(259)  评论(0编辑  收藏  举报