Re: copying Vector elements into Dynamic Array
On Jul 24, 1:39 pm, arnuld <geek.arn...@gmail.com> wrote:
On Tue, 24 Jul 2007 12:51:12 +0200, Bo Persson wrote:
Even cleaner code would be
std::copy(ivec.begin(), ivec.end(), pdarr);
Let the standard library decide how to do a copy properly.
WOW man, it works .... what can be the code for printing
the elements of that array to std::cout ?
There is an ostream_iterator, which would allow:
std::copy( v.begin(), v.end(),
std::ostream_iterator< int >( std::cout, "\n" ) ) ;
In practice, it's not very useful, because you usually need to
handle additional formatting chores: only 10 to a line,
separator, rather than terminator, etc. Which means you end up
with something like:
int inLineCount = 0 ;
for ( std::vector< int >::const_iterator it = v.begin() ;
it != v.end() ;
++ it ) {
if ( inLineCount == 0 ) {
std::cout << lineHeader ;
} else {
std::cout << inlineSeparator ;
}
std::cout << *it ;
++ inLineCount ;
if ( inLineCount == maxInLine ) {
std::cout << completeLineTermiator ;
inLineCount = 0 ;
}
}
if ( inLineCount != 0 ) {
std::cout << partialLineTerminator ;
}
If you want to use something like a comma separator, attached to
the preceding element, then you'll also need logic to handle
that (something that checks whether (it + 1) == v.end() in the
loop).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34