1

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).

Steven Lu
  • 41,389
  • 58
  • 210
  • 364

2 Answers2

4

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);
Steven Lu
  • 41,389
  • 58
  • 210
  • 364
ken
  • 816
  • 1
  • 9
  • 25
1

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.

Matt
  • 10,434
  • 1
  • 36
  • 45
  • It's really quite cool that it's able to transparently use pointers like this. That this **could** in any way have better performance than the for loop version is incredible (though not really of course because a naive for loop would cause the vector to resize itself). Anyway, I like things like this because it helps cuts down on bugs. – Steven Lu Mar 01 '12 at 04:47
  • It may be smart enough to subtract the two pointers to find out how many values it'll be looping over, and allocate enough space for them initially. Default-constructing a vector and inserting the values yourself may require it to reallocate as the vector grows. – Wyzard Mar 01 '12 at 04:49
  • Right, in my naive implementation I needed to figure out whether i wanted to use `resize` or `reserve`... Using the ctor or `assign` with pointers is just so much neater. – Steven Lu Mar 01 '12 at 04:52
  • It's possible it might be smart enough to do a pre-allocation, but it's not guaranteed that it can even make an educated guess. It just takes an InputIterator, and for those there's no guarantee that the iteration is contiguous. You can create an InputIterator that jumps ahead an arbitrary amount - say, 4 * sizeof(double), whatever you want - though it would certainly be possible to optimize, it's a lot of special casing to do so. (though, if I were implementing the standard, I would make that "guess" by pre-allocating the delta and trusting it to resize if my guess was wrong...) – Matt Mar 01 '12 at 06:44