Sign in to follow this  
valla2

copy doesn't work

Recommended Posts

why the output i get is different when i use copy()? It's like copy() doesn't write to the file anything :(
set<int> answer;
.....

    ofstream out ( "OUTPUT.TXT" );
    out << answer.size() << endl;

   for( set<int>::iterator it = answer.begin(); it != answer.end(); ++it )
        out << *it << endl;
    //copy( answer.begin(), answer.end(), ostream_iterator<int>( out, "\n" ) );
//if i use copy() insread of the for loop it doesn't work :(



what's the problem? thx

Share this post


Link to post
Share on other sites
This might sound stupid but... Are you flushing the stream after you write to it?

copy( answer.begin(), answer.end(), ostream_iterator<int>( out, "\n" ) );
out.flush();

I suspect if you do that you will see something in the file.

Share this post


Link to post
Share on other sites
i made the modification and it still doesn' work :(

It should be flushed when the object out gets out of scope anyways...

?

Share this post


Link to post
Share on other sites
It should be.

I don't know, it might have to do with some other part of the code... I just made this simple test program here:


#include <iostream>
#include <set>

#include <time.h>

using namespace std;

void main() {
srand((unsigned int) time(NULL));

set<int> answer;
set<int>::iterator iter;

for (int i = 0; i < 10; i++) {
answer.insert(rand() % 255);
}

cout << "For loop:" << endl;

for (iter = answer.begin(); iter != answer.end(); iter++) {
cout << (*iter) << endl;
}

cout << endl << endl;

cout << "copy():" << endl;

copy(answer.begin(), answer.end(), ostream_iterator<int>(cout, "\n"));
}




Works perfectly fine, and seems to be equivalent to what you posted.

Share this post


Link to post
Share on other sites
Why not try:

copy( answer.begin(), answer.end(), ostream_iterator<int>( cout, "\n" ) );

And see what it spits out onto the console?

Share this post


Link to post
Share on other sites
it works now! i dont' know what happened before but now it works, without any modifications! It seems in my code i had
ostream_iterator<int>( cout, "\n" )
instead of
ostream_iterator<int>( out, "\n" )

...

thx guys and sorry for being an idiot :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this