I just learned how to use ostream_iterator
today, but I don't know if this is efficient comparing to the normal for-loop way.
Here is the code:
//The first one
vector<int> v = {1, 2, 3, 4, 5};
ostream_iterator<int> osit(cout, " ");
copy(v.begin(), v.end(), osit);
And
//The second one
vector<int> v = {1, 2, 3, 4, 5};
for (int i : v) cout << i << " ";
Which one is more efficient?
Thank you in advance!
std::copy
is using operator=
from the iterator. It looks something like this
ostream_iterator& operator=(const _Ty& _Val)
{ // insert value into output stream, followed by delimiter
*_Myostr << _Val;
if (_Mydelim != 0)
{
*_Myostr << _Mydelim;
}
return (*this);
}
Looks very similar to the code you have in your for-loop, except for the conditional output of the separator (which takes zero time compared to formatting the integer and outputting it).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.