Tuesday, June 03, 2008

C++: copy magic

Say if you have a vector and you want to print it . Then instead of the normal for loop and cout call inside the loop you can do the following :

if you have a vector "v"

copy(v.begin(), v.end(), ostream_iterator(cout, "\n"));

this will print the entire vector .

To generalize this you could use something like this :

template
OutputIterator copy(const Container& c, OutputIterator result){
return std::copy(c.begin(), c.end(), result);
}

No comments: