Re: The most efficient way for fill a vector from an array?
On Mar 8, 6:41 am, towi <towit...@gmail.com> wrote:
I wonder, what is the most efficient STL way to move the values from
an array into a vector of the same kind?
My general idea would be that there might be something like
(pseudocode):
std::vector<int> vec;
int arr[10] = { 1,2,3, 2,3,4, 3,4,5, 10} ;
std::move( vec.begin(), vec.end(), arr, arr+10); // vec := arr
Actually, you're over thinking this.
int arr[] = { 1,2,23,3,34,35,345,34,53 };
std::vector<int> vec( arr, arr + sizeof(arr)/sizeof(int) );
std::vector's ctor does this for you. And your std::move is covered by
std::copy if I understand your intention.
But, if you're into C++0x, g++ 4.4 can do the fallowing:
std::vector<int> vec = { 1,2,3,4,5 };
The C++0x technique might be theoretically more efficient, but I don't
think it makes a difference. Compiling the fallowing:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
#ifdef USE_NO_OX
int x[] = { 1,2,3,4,45,6 };
std::vector<int> vec( x, x + sizeof(x)/sizeof(int) );
#else
std::vector<int> vec = { 1,2,3,4,45,6 };
#endif
std::copy (
vec.begin(), vec.end(),
std::ostream_iterator<int>( std::cout, " " )
);
}
with "g++ main.cpp -std=c++0x [-D USE_NO_OX]; strip a.out". The text
in the brackets was used to define USE_NO_OX on builds where I wanted
to use the previous way. I found that after striping, there was no
difference in the two using any -O level.
I think this is about as efficient as it gets.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]