2012-08-06 62 views
1

在PHP我記得我可以這樣做子或打印陣列高達在C++

substr(string,start,length)

的位置NUM現在我宣佈

int array[20];

我怎麼能只打印它的一部分沒有使用for循環

例如。

cout << array[1 to 5] << "Here is the breaking point" << array[15 to 20] << endl;

像這樣的事情

我還記得,如果它是printf會有類似^5或類似說法高達5

+0

您可以使用[漂亮的打印](http://louisdx.github.com/cxx-prettyprint/):'性病::法院<< pretty_print_array(array + 3,6)<< std :: endl;' – 2012-08-06 16:56:39

回答

6

您可以使用ostream_iteratorcopy組合(link to ideone ):

#include <iostream> 
#include <iterator> 
#include <algorithm> 

using namespace std; 

int main() { 
    int array[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; 
    ostream_iterator<int> out_it (cout," "); 
    copy (array+3, array+6, out_it); 
    return 0; 
} 

array+3語法可能看起來很不尋常:這是一個相當於&array[3]的指針表達式,它產生一個指針。由於您可以在C標準庫期望一對迭代器的地方傳遞一對數組指針,因此會產生預期的結果。

3

你可以複製到一個ostream迭代器:

std::copy(array, array+5, std::ostream_iterator(std::cout, " ")); 
std::cout << "Here is the breaking point"; 
std::copy(array+15, array+20, std::ostream_iterator<int>(std::cout, " "));