Re: Using vectors as arrays
From: Erik Jälevik (erik.jalevikDELETE_at_ntlworldTHIS.com)
Date: 01/17/04
- Next message: Joec: "Re: Question about arrays in objects"
- Previous message: Jacques Labuschagne: "Re: Question about arrays in objects"
- In reply to: Leor Zolman: "Re: Using vectors as arrays"
- Next in thread: Leor Zolman: "Re: Using vectors as arrays"
- Reply: Leor Zolman: "Re: Using vectors as arrays"
- Reply: Martijn Lievaart: "Re: Using vectors as arrays"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 17 Jan 2004 02:52:59 -0000
"Leor Zolman" <leor@bdsoft.com> wrote in message
news:a6gg00t319pgnemf6a59jjb5g93168htfo@4ax.com...
> On Fri, 16 Jan 2004 19:24:31 -0000, "Erik Jälevik"
> <erik.jalevikDELETE@ntlworldTHIS.com> wrote:
>
> >I had some code using dynamic arrays which I'm now converting to vectors
due
> >to danger of memory leaks in the face of exceptions.
> >
> >Martin pointed out in an earlier post that it was OK to use a vector as a
> >standard array by taking its address.
>
> Not sure who said what, but what you want to do is take the address of
> the first element, _not_ the address of the vector itself:
Yes, of course. Sorry, I didn't express myself clearly, that's what I meant.
> >Is it also OK to use the individual
> >addresses for assigning to like in the following example:
> >
> >vector<double> energy;
> >energy.reserve(100);
> >for (int j = 0; j < 100; j++) {
> > *(&energy[j]) = res[j].GetEnergy();
>
> Looks "OK", but why would you choose to write this instead of plain
> old:
> energy[j] = res[j].GetEnergy();
That works? I just assumed I couldn't do that for some silly reason. Oh
well, thanks for pointing it out.
> push_back will handle the case where the vector has to "grow", while
> directly assigning will not, and will in fact yield undefined behavior
> if you go out of bounds.
Yes OK. But I will always make sure to allocate enough space with reserve
beforehand since efficiency is quite important in my application and I never
want the vector to grow.
> Nothing can really "unpreserve" ordering in a vector; you
> set the order and it would never second-guess you on it!
OK, good. I assumed this would be the case but wasn't sure it was prescribed
by the standard. In fact, I think the Josuttis book mentioned it wasn't
strictly prescribed but that most compilers did it that way.
Erik
- Next message: Joec: "Re: Question about arrays in objects"
- Previous message: Jacques Labuschagne: "Re: Question about arrays in objects"
- In reply to: Leor Zolman: "Re: Using vectors as arrays"
- Next in thread: Leor Zolman: "Re: Using vectors as arrays"
- Reply: Leor Zolman: "Re: Using vectors as arrays"
- Reply: Martijn Lievaart: "Re: Using vectors as arrays"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]