简体   繁体   中英

Assigning a vector from an array (pointer)

Is there a standard way to accomplish this that is better than a for loop?

If I had an array type supposedly I can do this:

double d_array[] = { 1.0, 2.0, 3.0 };
std::vector<double> d_vector(d_array, d_array+3);

But I can't do this when I only have a double * and an int indicating its length.

Edit: Actually, I think I actually can do this. The error messages are quite a handful, though, if you get your type parameters wrong (which is why it didn't work for me at first).

Of course you can do it the same way

int length;
double *d;
//allocate memory and data to pointer
std::vector<double> d_vector(d, d+length);

Yep. You should be able to do this. The relevant constructor is template <class InputIterator> vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() ); - and pointers are iterators too (since you can do integer arithmetic on them).

That being said, all that the vector is doing is iterating over the elements of d_array , so don't expect the performance to be significantly better than the for loop version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM