Re: The most efficient way for fill a vector from an array?
On Mar 8, 1:41 pm, towi <towit...@gmail.com> wrote:
Hi,
I wonder, what is the most efficient STL way to move the values from
an array into a vector of the same kind?
<skipped>
The hard fact reason for my question is, that I want to read a file
that I could do with a single read()-call into an array[], but I want
it to go into a vector<>, instead. And because it's huge, I want to do
it without twice the memory and without an unneccessary copy.
Maybe what I am asking is related to how to make vector ROMable?
<skipped>
Hi,
I think the most STL way is to use stl streams and algorithms, for
example:
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
int main(int /*argc*/, char* /*argv[]*/)
{
// source stream (file)
std::istringstream s("1 2 3 4 5");
//std::ifstream s("d:\\test.txt");
// read stream
std::vector<int> v;
std::copy(std::istream_iterator<int>(s), std::istream_iterator<int>
(), std::back_inserter(v));
// check the result
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "
"));
std::cout << std::endl;
return 0;
}
Anyway, if there is a need to use buffers you may use std::vector as
was written earlier:
std::vector<int> v(10);
int* buffer = &v[0]; // use this buffer with fread, memcpy or
something
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]