473,465 Members | 4,818 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

I'm stuck with the implementation of a generic algorithm.... need some help :P

I need to implement an algorithm that takes as input a container and
write some output in another container.
The containers involved are usually vectors, but I would like not to
rule out the possibility of using lists.
The problem is that I need two versions of it, depending if I'm adding
the generated (by the algorithm) values to the target container or if
I just modify pre-existing values of the target container.
Efficiency is important in this part of the software.
The first solution is to write two versions of the algorithm:
[firstTime, lastTime) define the input range, and firstTarget define
the begin of target container.

// Modify version, here V iterator, will use *firstTarget =
// More precisely V is usually std::vector<double>::iterator taken
from someVector.begin().
template<class V, class T>
void bmPathModify( V firstTarget, T firstTime, T lastTime )

// Append version, here V is the container, will use
firstTarget.push_back()
template<class V, class T>
void bmPathAppend( V& firstTarget, T firstTime, T lastTime )

However this situation is going to repeat itself a lot of times, so I
would like to use just one function and specify the behaviour using a
policy defined by an additional template parameter:

// P is the policy
template<class V, class T, class P>
void bmPathModify( V firstTarget, T firstTime, T lastTime )
{
...
P::Element( target, value );
..
}

class Modify // Policy class
{
public:

template<class V>
static void Element( V target, double value)
{
*target = value;
}

};

The problem is then:
I need to pass the iterator to the starting element of the target
container to cover the Modify case.
But then I can't figure out how to invoke the push_back() function to
the target container starting from this iterator. I suspect I can't.
What would be perfect would be the ability to deference the iterator
two times to get the actual container but I think you can't do
this....
Is there a way to solve this situation using a single function for the
algorithm?

Thank you

StephQ

Aug 1 '07 #1
6 1683

StephQ wrote:
But then I can't figure out how to invoke the push_back() function to
the target container starting from this iterator.
If I understand your problem correctly, you may be looking for a
back_inserter used in conjunction with transform. Typically a
sequence
can be modified (or transformed) and inserted into a new sequence
like this:

#include <algorithm//for transform
#include <iterator//for back_inserter
#include <vector//or list...

Transforming algorithm... Could be functor as well.
Transformed Transformer( const Transformed& item )
{
//... Transform the item and return the result.
}
//...
std::vector<Transformedseq1; //or list...
addItems( seq1 ); //Adds items to be transformed
std::vector<Transformedseq2; //Empty

std::transform( seq1.begin(), seq1.end(), std::back_inserter( seq2 ),
Transformer );

You could also transform a sequence itself, just by using itself as
destination.

std::transform( seq1.begin(), seq1.end(), seq1, Transformer );

Hope this helps. There are of course other ways to achieve the same
effect. Note that
transform assigns the result of transform, causing performance penalty
depending
on the cost of the assignment. For builtin types this is
insignificant.

Hope this helps

Werner

Aug 1 '07 #2
StephQ a écrit :
I need to implement an algorithm that takes as input a container and
write some output in another container.
The containers involved are usually vectors, but I would like not to
rule out the possibility of using lists.
The problem is that I need two versions of it, depending if I'm adding
the generated (by the algorithm) values to the target container or if
I just modify pre-existing values of the target container.
Efficiency is important in this part of the software.
The first solution is to write two versions of the algorithm:
[firstTime, lastTime) define the input range, and firstTarget define
the begin of target container.
[snip]
The problem is then:
I need to pass the iterator to the starting element of the target
container to cover the Modify case.
But then I can't figure out how to invoke the push_back() function to
the target container starting from this iterator. I suspect I can't.
What would be perfect would be the ability to deference the iterator
two times to get the actual container but I think you can't do
this....
Is there a way to solve this situation using a single function for the
algorithm?
Yes. You can use the std::copy algorithm of the STL.

When you want to overwrite, you just use plain iterators; by example:
copy(from.begin(),from.end(),to.begin());

When, you want to append, you use a back_inserter:
copy(from.begin(),from.end(), back_insert_iterator< list<int(to));

Michael
Aug 1 '07 #3
On Aug 1, 1:32 pm, werasm <wer...@gmail.comwrote:
StephQ wrote:
But then I can't figure out how to invoke the push_back() function to
the target container starting from this iterator.

If I understand your problem correctly, you may be looking for a
back_inserter used in conjunction with transform. Typically a
sequence
can be modified (or transformed) and inserted into a new sequence
like this:

#include <algorithm//for transform
#include <iterator//for back_inserter
#include <vector//or list...

Transforming algorithm... Could be functor as well.
Transformed Transformer( const Transformed& item )
{
//... Transform the item and return the result.}

//...
std::vector<Transformedseq1; //or list...
addItems( seq1 ); //Adds items to be transformed
std::vector<Transformedseq2; //Empty

std::transform( seq1.begin(), seq1.end(), std::back_inserter( seq2 ),
Transformer );

You could also transform a sequence itself, just by using itself as
destination.

std::transform( seq1.begin(), seq1.end(), seq1, Transformer );

Hope this helps. There are of course other ways to achieve the same
effect. Note that
transform assigns the result of transform, causing performance penalty
depending
on the cost of the assignment. For builtin types this is
insignificant.

Hope this helps

Werner
I think it's better if I expose more details of the problem.
Here is the code for what I need to accomplish using two functions:

// Append version. Target is reference to container.
template<class V, class T>
void bmPath( V& target, double firstValue, T firstTime, T lastTime )
{
assert( target.back() == firstValue ); // Note no insertion of
firstValue.

T cTime;
double bmValue;
for (cTime = ++firstTime ; cTime != lastTime ; ++cTime)
{
bmValue = RandomNumber::generateGaussian( target.back(),
sqrt( *cTime - *boost::prior( cTime ) ) );
target.push_back( bmValue );
}
}

// Modify version. Target is iterator to first element of the storage
of the target container.
template<class V, class T>
void bmPath( V target, double firstValue, T firstTime, T lastTime )
{
*target = firstValue;

T cTime;
double bmValue;
for (cTime = ++firstTime ; cTime != lastTime ; ++cTime)
{
bmValue = RandomNumber::generateGaussian( *target,
sqrt( *cTime - *boost::prior( cTime ) ) );
*(++target) = bmValue;
}
}

I see two problems:
1) I don't act directly on cTime but on square root of differences.
And I need to avoid the creation of a temporary vector to store the
square root of adjacent differences because of allocation penalties.
2) I would need a policy for "firstValue" (different behaviour on the
two versions of the algorithm).

This is exactly what I need to accomplish.
To sum up the goal is:
1) have a single function with the same interface (where I pass an
iterator to the first element of the storage of the target container)
and specify the behaviour using traits.
2) no (or very low) performance penalty compared to the versions here
exposed. Creation of temporary containers is not acceptable in this
part of the code.

I know here the algorithm is very easy, but I have exactly the same
problem for a large class of (quite complex) algorithms where the
only thing that changes is the way I act on the target container.

Thank you very much for your help!

Best Regards
StephQ

Aug 1 '07 #4
On Aug 1, 1:45 pm, Michael DOUBEZ <michael.dou...@free.frwrote:
StephQ a écrit :
I need to implement an algorithm that takes as input a container and
write some output in another container.
The containers involved are usually vectors, but I would like not to
rule out the possibility of using lists.
The problem is that I need two versions of it, depending if I'm adding
the generated (by the algorithm) values to the target container or if
I just modify pre-existing values of the target container.
Efficiency is important in this part of the software.
The first solution is to write two versions of the algorithm:
[firstTime, lastTime) define the input range, and firstTarget define
the begin of target container.
[snip]
The problem is then:
I need to pass the iterator to the starting element of the target
container to cover the Modify case.
But then I can't figure out how to invoke the push_back() function to
the target container starting from this iterator. I suspect I can't.
What would be perfect would be the ability to deference the iterator
two times to get the actual container but I think you can't do
this....
Is there a way to solve this situation using a single function for the
algorithm?

Yes. You can use the std::copy algorithm of the STL.

When you want to overwrite, you just use plain iterators; by example:
copy(from.begin(),from.end(),to.begin());

When, you want to append, you use a back_inserter:
copy(from.begin(),from.end(), back_insert_iterator< list<int(to));

Michael
See my reply to werasm.
Thank you for your help.

Best Regards
StephQ

Aug 1 '07 #5

StephQ wrote:
Thanks for the reply.
However I got an idea.... what if I use a back_insert_iterator?
This way only one version can cover everything!
Did you not read my first reply (and others). We've mentioned
std::back_inserter there.
I can pass a normal iterator if I want to overwrite or a
back_insert_iterator if I want to append...
Yes, of course - read my first example.
May a back_insert_iterator become invalid if reallocation happens in a
vector?
A back_inserter might cause reallocation if the vector exceeds its
capacity.
This may be prevented by reserving in the destination vector.
Does this means that it's safe to use back_insert_iterator s only with
lists?
No, back inserters always does push_back, and should not care whether
iterators are invalidated or not. On the other hand, if your functor
stores
iterators while you traverse and pushback, then those may be
invalidated.
(but that is a bad idea anyway)

Werner

Aug 1 '07 #6
On Aug 1, 6:10 pm, werasm <wer...@gmail.comwrote:
StephQ wrote:
Thanks for the reply.
However I got an idea.... what if I use a back_insert_iterator?
This way only one version can cover everything!

Did you not read my first reply (and others). We've mentioned
std::back_inserter there.
Yes I did. But I was stupid enough not to think of using it outside
the copy/transform algorithms.... :P
>
I can pass a normal iterator if I want to overwrite or a
back_insert_iterator if I want to append...

Yes, of course - read my first example.
May a back_insert_iterator become invalid if reallocation happens in a
vector?

A back_inserter might cause reallocation if the vector exceeds its
capacity.
This may be prevented by reserving in the destination vector.
Yes I'm fine with that. I was worried with back_insert_iterator
becoming invalidated. But an examination of the actual source code
revealed that it's not really an iterator, and the problem does not
exists.
>
Does this means that it's safe to use back_insert_iterator s only with
lists?

No, back inserters always does push_back, and should not care whether
iterators are invalidated or not. On the other hand, if your functor
stores
iterators while you traverse and pushback, then those may be
invalidated.
(but that is a bad idea anyway)
Thank you again. It seems that I finally solved my issue :)

Cheers
StephQ
>
Werner

Aug 1 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

31
by: Scott Robert Ladd | last post by:
I've posted my revised C++ implementation of the Mersenne Twister at: http://www.coyotegulch.com/libcoyote/TwistedRoad/TwistedRoad.html This is "free-as-in-liberty" and "free-as-in-beer" code....
4
by: Ben | last post by:
Hi, I was writing a expression template for string concatenation latetly. When writing it, I started to feel curious that why there's not any generic et lib that can save me from wring each...
4
by: Tarique Jawed | last post by:
Alright I needed some help regarding a removal of a binary search tree. Yes its for a class, and yes I have tried working on it on my own, so no patronizing please. I have most of the code working,...
13
by: buda | last post by:
I had some spare time and decided to try to implement the standard library qsort. This is a pretty simpleminded attempt, but it seems to be working. I have to point out that efficiency is not at...
23
by: Peter Row | last post by:
Hi, I am currently working on a VB.NET project that has been going for quite a while. In the past it has been developed with a lot of compatibility VB6 functions and constants, e.g Left(),...
8
by: Jef Driesen | last post by:
I'm working on an image segmentation algorithm. An essential part of the algorithm is a graph to keep track of the connectivity between regions. At the moment I have a working implementation, but...
37
by: jortizclaver | last post by:
Hi, I'm about to develop a new framework for my corporative applications and my first decision point is what kind of strings to use: std::string or classical C char*. Performance in my system...
4
by: Harold Howe | last post by:
I am running into a situation where the compiler complains that it cannot infer the type parameters of a generic method when one of the function arguments is an anonymous method. Here is a...
7
by: Dave | last post by:
I've got these declarations: public delegate void FormDisplayResultsDelegate<Type>(Type displayResultsValue); public FormDisplayResultsDelegate<stringdisplayMsgDelegate; instantiation:...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.