Reputation: 35
I am a fresh about C++, I have met an issue, I want to use the following codes (from Cplusplus ) but to output my result to a new file or use a vector to keep it(i prefer to use a vector), what should I do? Thanks!
// ostream_iterator example
#include <iostream> // std::cout
#include <iterator> // std::ostream_iterator
#include <vector> // std::vector
#include <algorithm> // std::copy
int main () {
std::vector<int> myvector;
for (int i=1; i<10; ++i) myvector.push_back(i*10);
std::ostream_iterator<int> out_it (std::cout,", ");
std::copy ( myvector.begin(), myvector.end(), out_it );
return 0;
}
Upvotes: 2
Views: 4986
Reputation: 206707
You can use a std::ofstream
in place of std::cout
.
Here's your code modified to write the output to a file.
// ostream_iterator example
#include <iostream> // std::cout
#include <iterator> // std::ostream_iterator
#include <vector> // std::vector
#include <algorithm> // std::copy
#include <fstream> // std::ofstream
int main () {
std::vector<int> myvector;
for (int i=1; i<10; ++i) myvector.push_back(i*10);
std::ofstream of("myoutput.txt");
std::ostream_iterator<int> out_it (of,", ");
std::copy ( myvector.begin(), myvector.end(), out_it );
return 0;
}
To copy the output to a vector
, use a back_inserter
.
std::vector<int> foo;
std::copy (myvector.begin(), myvector.end(), std::back_inserter(foo));
You can also make direct copy:
std::vector<int> foo = myvector;
Upvotes: 5