Kai-Uwe Bux
12/9/2008 11:13:00 PM
Steve555 wrote:
> On 9 Dec, 20:35, red floyd <no.spam.h...@example.com> wrote:
>> Steve555 wrote:
>> > On 9 Dec, 17:09, James Kanze <james.ka...@gmail.com> wrote:
>> >> On Dec 9, 3:43 pm, Steve555 <foursh...@btinternet.com> wrote:
>>
>> >>> I'm looking for an algorithm that takes 2 vectors and a
>> >>> function pointer as arguments? I want to use the function
>> >>> pointer to calculate a result e.g. the product, and put the
>> >>> result either in place, or in a third vector.
>> >>> I've looked through the list of algorithms and there doesn't
>> >>> appear to be one. transform() is the closest, but alas works
>> >>> on only a single vector.
>> >> There are two versions of std::transform. The following code
>> >> should do the trick:
>> >> assert( v1.size() == v2.size() ) ;
>> >> std::transform( v1.begin(), v1.end(),
>> >> v2.begin(),
>> >> std::back_inserter( v3 ),
>> >> std::multiplies< double >() ) ;
>>
>> >> --
>> >> James Kanze (GABI Software) email:james.ka...@gmail.com
>> >> Conseils en informatique orientée objet/
>> >> Beratung in objektorientierter Datenverarbeitung
>> >> 9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
>>
>> > Thanks James, but I wasn't sure why you used std::back_inserter()?
>>
>> because that will push_back() the results onto the v3. Otherwise, you
>> risk running off the end of the resultant, especially if it's empty.
>
> Thanks Red, but, Doh! This is bad news! I thought the whole point of
> using these smart containers was that they grew to accomodate whatever
> was put in to them?
They do, but you have to actually _put_ an item into them. That is what
push_back(), push_front(), and insert() do. Note that operator[] will _not_
put an item into the container.
> When I use this (and other?) algorithms, they might write in to
> unallocated memory if I don't tell them not to?
Yes, you have to tell them.
> When designing this algorithm, how could it have been seen as a good
> idea for it to default to a behavior that would not allocate the
> correct memory?
You are confused. The algorithm does not even know about the container. The
algorithm only sees the iterators. In the case of an output_iterator, the
file will grow as you write items; in the case of an insert_iterator, the
container will grow; in the case of a vector<T>::iterator, the container
will _not_ grow.
> If you supply an iterator to a new vector to store the
> transform of other vectors, what else could you possibly intend?
How is the algorithm supposed to know that the vector is _new_? All it sees
is a vector<T>::iterator and that means the intend is to overwrite existing
elements.
> (OK, it's not so much trouble to add it, but it does seem like adding
> the redundant instruction DontCrash() ;) )
No.
BTW: You could write a drop in replacement for std::vector<> that makes the
vector grow when iterators move past the end. However, that has an
overhead.
Best
Kai-Uwe Bux