473,791 Members | 3,074 Online
Bytes | Software Development & Data Engineering Community
+ 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<dou ble>::iterator taken
from someVector.begi n().
template<class V, class T>
void bmPathModify( V firstTarget, T firstTime, T lastTime )

// Append version, here V is the container, will use
firstTarget.pus h_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 1703

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<Tra nsformedseq1; //or list...
addItems( seq1 ); //Adds items to be transformed
std::vector<Tra nsformedseq2; //Empty

std::transform( seq1.begin(), seq1.end(), std::back_inser ter( 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(),t o.begin());

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

Michael
Aug 1 '07 #3
On Aug 1, 1:32 pm, werasm <wer...@gmail.c omwrote:
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<Tra nsformedseq1; //or list...
addItems( seq1 ); //Adds items to be transformed
std::vector<Tra nsformedseq2; //Empty

std::transform( seq1.begin(), seq1.end(), std::back_inser ter( 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::g enerateGaussian ( target.back(),
sqrt( *cTime - *boost::prior( cTime ) ) );
target.push_bac k( 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::g enerateGaussian ( *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(),t o.begin());

When, you want to append, you use a back_inserter:
copy(from.begin (),from.end(), back_insert_ite rator< 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_ite rator?
This way only one version can cover everything!
Did you not read my first reply (and others). We've mentioned
std::back_inser ter there.
I can pass a normal iterator if I want to overwrite or a
back_insert_ite rator if I want to append...
Yes, of course - read my first example.
May a back_insert_ite rator 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_ite rator 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.c omwrote:
StephQ wrote:
Thanks for the reply.
However I got an idea.... what if I use a back_insert_ite rator?
This way only one version can cover everything!

Did you not read my first reply (and others). We've mentioned
std::back_inser ter 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_ite rator if I want to append...

Yes, of course - read my first example.
May a back_insert_ite rator 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_ite rator
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_ite rator 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
4444
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. The Mersenne Twister is a "random number" generator invented by Makoto Matsumoto and Takuji Nishimura; their website includes numerous implementations of the algorithm.
4
1708
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 different et lib from scratch. Or, maybe I was just ignorant and there is some already? matrix, string, array, vector, whatever, the idea of et is quite similar. We need a leaf node and a binary non-leaf node for expressing
4
9021
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, even the removal, I just don't know how to keep track of the parent, so that I can set its child to the child of the node to be removed. IE - if I had C / \ B D
13
2614
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 all an issue for me, and this is purely a toy, so to speak. I'm quite aware that this is not the quickest way to implement the quicksort algorithm, but I basically just wanted to try to make a "generic function". I tested it with a few arrays of...
23
1766
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(), LCase() and vbCr Whilst not currently able to port to C# I am trying to remove usage of these functions and constants.
8
2450
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 it's not flexible enough anymore and I need something more advanced. I already have a data structure in mind, but I don't know how to implement that nicely in C++. // Main class which holds the lists with // edges and vertices. These lists are...
37
3818
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 is quite importante - it's not a realtime system, but almost - and I concern about std::string performance in terms of speed. No doubt to use std implementation is a lot easier but I can't sacrifice speed.
4
4945
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 complete code example: //----------------------------- using System; using System.Collections.Generic;
7
2040
by: Dave | last post by:
I've got these declarations: public delegate void FormDisplayResultsDelegate<Type>(Type displayResultsValue); public FormDisplayResultsDelegate<stringdisplayMsgDelegate; instantiation: displayMsgDelegate = DisplayStatusMessage; implementation: public void DisplayStatusMessage(string statusMessage)
0
9669
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9517
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5435
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
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 we have to send another system
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.