473,725 Members | 2,193 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using accumulate algorithm with a set of pairs

I have a set of pairs defined as follow:

set< pair<UserEquipm ent*, double> > numberOfFreqSlo tsToAdd;

and I need to iterate through all the elements of the set in order
accumulate the second field of the pair (that is double). Is there any
way I can use the algorithm accumulate to accomplish this?
The following line of code

double unit = accumulate( numberOfFreqSlo tsToAdd.begin() ,
numberOfFreqSlo tsToAdd.end(), 0.0);

of course, won't work. Can you suggest anything similar using the
algorithm accumulate?

Thanks
Francesco

Feb 12 '06 #1
5 7786
TB
cesco sade:
I have a set of pairs defined as follow:

set< pair<UserEquipm ent*, double> > numberOfFreqSlo tsToAdd;

and I need to iterate through all the elements of the set in order
accumulate the second field of the pair (that is double). Is there any
way I can use the algorithm accumulate to accomplish this?
The following line of code

double unit = accumulate( numberOfFreqSlo tsToAdd.begin() ,
numberOfFreqSlo tsToAdd.end(), 0.0);

of course, won't work. Can you suggest anything similar using the
algorithm accumulate?


template <class InputIterator, class T, class BinaryOperation >
T accumulate (InputIterator first, InputIterator last, T init,
BinaryOperation binary_op);

Where foreach element:

init = binary_op(init, *first);

--
TB @ SWEDEN
Feb 12 '06 #2
In article <11************ **********@z14g 2000cwz.googleg roups.com>,
"cesco" <fd**********@g mail.com> wrote:
I have a set of pairs defined as follow:

set< pair<UserEquipm ent*, double> > numberOfFreqSlo tsToAdd;

and I need to iterate through all the elements of the set in order
accumulate the second field of the pair (that is double). Is there any
way I can use the algorithm accumulate to accomplish this?
The following line of code

double unit = accumulate( numberOfFreqSlo tsToAdd.begin() ,
numberOfFreqSlo tsToAdd.end(), 0.0);

of course, won't work. Can you suggest anything similar using the
algorithm accumulate?


I gave an answer to this in comp.learn.c-c++. Here I will give several
answers:

class Object { };

int main() {
typedef std::set<std::p air<Object*, double> > MySet;
MySet mySet;

double unit = accumulate(mySe t.begin(), mySet.end(), 0.0,
plus_second<MyS et::value_type> () );
}

The 'plus_second' functor is defined as follows:

template <typename Pair>
struct plus_second :
std::binary_fun ction<typename Pair::second_ty pe, Pair,
typename Pair::second_ty pe>
{
typename Pair::second_ty pe operator()(
const typename Pair::second_ty pe& x, const Pair& y ) const
{
return x + y.second;
}
};

Or something slightly more generic:

class Object { };

int main() {
typedef std::set<std::p air<Object*, double> > MySet;
MySet mySet;

double unit = accumulate(mySe t.begin(), mySet.end(), 0.0,
apply_to_second <std::plus<doub le>, MySet::value_ty pe>());
}

Which uses something like (though I can't say I like the name much:)

template < typename Op, typename Pair >
class apply_to_second : std::binary_fun ction<
typename Pair::second_ty pe, Pair, typename Pair::second_ty pe >
{
Op fn;
public:
typename Pair::second_ty pe operator()( const typename
Pair::second_ty pe& x, const Pair& y ) const
{
return fn( x, y.second );
}
};

Whether you use one of the above, the one I gave in the other group, or
the simplest one:

class Object { };

typedef std::set<std::p air<Object*, double> > MySet;

double fn(double x, const MySet::value_ty pe& y)
{
return x + y.second;
}

int main()
{
MySet mySet;

double unit = accumulate(mySe t.begin(), mySet.end(), 0.0,
ptr_fun(&fn));
}

Is up to you. I'll leave you with the XP mantra, "use the simplest thing
that works, refactor mercilessly."

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 13 '06 #3

cesco wrote:
I have a set of pairs defined as follow:

set< pair<UserEquipm ent*, double> > numberOfFreqSlo tsToAdd;

and I need to iterate through all the elements of the set in order
accumulate the second field of the pair (that is double). Is there any
way I can use the algorithm accumulate to accomplish this?
The following line of code

double unit = accumulate( numberOfFreqSlo tsToAdd.begin() ,
numberOfFreqSlo tsToAdd.end(), 0.0);

of course, won't work. Can you suggest anything similar using the
algorithm accumulate?


You can use an iterator that gets a first or second pair's member for
you.
http://groups.google.com/group/comp....b344960588d3ac

Feb 13 '06 #4
I'm facing a similar problem: I need to transform the set of pairs by
scaling the second element (that is a double) by a certain factor.

The following line of code:
// typedef set<pair<UserEq uipment*, double> SetOfFsDouble;
// SetOfFsDouble numberOfFreqSlo tsToAdd
transform(numbe rOfFreqSlotsToA dd.begin(), numberOfFreqSlo tsToAdd.end(),
numberOfFreqSlo tsToAdd.begin() , f_gx(bind2nd(st d::multiplies<d ouble>(),
unit), select2nd<SetOf FsDouble::value _type>()));

reports the following error:

1>c:\program files\microsoft visual studio 8\vc\include\al gorithm(650)
: error C2679: binary '=' : no operator found which takes a right-hand
operand of type 'double' (or there is no acceptable conversion)
1> c:\program files\microsoft visual studio
8\vc\include\ut ility(55): could be 'std::pair<_Ty1 ,_Ty2>
&std::pair<_Ty1 ,_Ty2>::operato r =(const std::pair<_Ty1, _Ty2> &)'
1> with
1> [
1> _Ty1=UserEquipm ent *,
1> _Ty2=double
1> ]
1> while trying to match the argument list
'(std::pair<_Ty 1,_Ty2>, double)'
1> with
1> [
1> _Ty1=UserEquipm ent *,
1> _Ty2=double
1> ]

while the following approach:

transform(numbe rOfFreqSlotsToA dd.begin(), numberOfFreqSlo tsToAdd.end(),
numberOfFreqSlo tsToAdd.begin() ,
::make_pair(sel ect1st<SetOfFsD ouble::value_ty pe>(),
(bind2nd(std::m ultiplies<doubl e>(), unit),
select2nd<SetOf FsDouble::value _type>())) );

where I try to overcome the previous problem by creating a Pair to give
back to the set, reports the following error:

1>c:\program files\microsoft visual studio 8\vc\include\al gorithm(650)
: error C2064: term does not evaluate to a function taking 1 arguments
1> c:\program files\microsoft visual studio
8\vc\include\al gorithm(685) : see reference to function template
instantiation '_OutIt
std::_Transform <std::_Tree<_Tr aits>::iterator ,_OutIt,_Fn1,st d::_Iter_random _helper<_Cat1,_ Cat2>::_Iter_ra ndom_cat>(_InIt ,_InIt,_OutIt,_ Fn1,_InOutItCat ,std::_Range_ch ecked_iterator_ tag)'
being compiled
1> with
1> [
1>
_OutIt=std::_Tr ee<std::_Tset_t raits<std::pair <UserEquipmen t
*,double>,SinrB asedWithoutPowe rScaling::Numbe rOfFrequencySlo tsComparison,st d::allocator<st d::pair<UserEqu ipment
*,double>>,fals e>>::iterator,
1> _Traits=std::_T set_traits<std: :pair<UserEquip ment
*,double>,SinrB asedWithoutPowe rScaling::Numbe rOfFrequencySlo tsComparison,st d::allocator<st d::pair<UserEqu ipment
*,double>>,fals e>,
1> _Fn1=std::pair< select1st<std:: pair<UserEquipm ent
*,double>>,sele ct2nd<std::pair <UserEquipmen t *,double>>>,
1>
_Cat1=std::_Tre e<std::_Tset_tr aits<std::pair< UserEquipment
*,double>,SinrB asedWithoutPowe rScaling::Numbe rOfFrequencySlo tsComparison,st d::allocator<st d::pair<UserEqu ipment
*,double>>,fals e>>::iterator:: iterator_catego ry,
1>
_Cat2=std::_Tre e<std::_Tset_tr aits<std::pair< UserEquipment
*,double>,SinrB asedWithoutPowe rScaling::Numbe rOfFrequencySlo tsComparison,st d::allocator<st d::pair<UserEqu ipment
*,double>>,fals e>>::iterator:: iterator_catego ry,
1>
_InIt=std::_Tre e<std::_Tset_tr aits<std::pair< UserEquipment
*,double>,SinrB asedWithoutPowe rScaling::Numbe rOfFrequencySlo tsComparison,st d::allocator<st d::pair<UserEqu ipment
*,double>>,fals e>>::iterator,
1>
_InOutItCat=std ::_Iter_random_ helper<std::_Tr ee<std::_Tset_t raits<std::pair <UserEquipmen t
*,double>,SinrB asedWithoutPowe rScaling::Numbe rOfFrequencySlo tsComparison,st d::allocator<st d::pair<UserEqu ipment
*,double>>,fals e>>::iterator:: iterator_catego ry,std::_Tree<s td::_Tset_trait s<std::pair<Use rEquipment
*,double>,SinrB asedWithoutPowe rScaling::Numbe rOfFrequencySlo tsComparison,st d::allocator<st d::pair<UserEqu ipment
*,double>>,fals e>>::iterator:: iterator_catego ry>::_Iter_rand om_cat
1> ]

Do you have any suggestion on how to solve this problem?

Feb 13 '06 #5

cesco wrote:
I'm facing a similar problem: I need to transform the set of pairs by
scaling the second element (that is a double) by a certain factor.


Use boost::transfor m_iterator for that.

Feb 13 '06 #6

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

Similar topics

12
1927
by: Christof Krueger | last post by:
Hello, I'm quite new to C++ so maybe there's something I miss. I write a simple board game. It has a board class. This class has a method that returns the count of pieces a player has on the board. Since this function does not change anything in the class I declared it as const. To count all pieces of a given color the functions iterates through a "map" of CNode-pointers. "CNode" is another class that is irrelevant to the problem.
1
2400
by: tuko | last post by:
Hello kind people. I have the classes "point", "curve", "surface", "region" as shown below. Every class has a member function that returns a list of pointers to objects that comprise the *this object. In main function I have implemented an algorithm (some lines of code noted as "My Algorithm") which in the current state works for "surface" and "curve" objects.
1
3606
by: yinglcs | last post by:
I have a function in STL which add the 'area' attribute of a list of Rect. template< class T1, class T2> class add_area_per_cent : public binary_function<T2, T1, T2> { public: add_area_per_cent() { }
6
4520
by: aka_eu | last post by:
I have this problem. I'm trying to get all the valid combination C(N,K) that pass one condition. For example C(5,3) can use in any combination this numbers {1,2,3,4,5} But let's say that I have the limitations that these pair of numbers cannot be part of the same combination {2,3} and {4,5}
7
2693
by: Henrique A. Menarin | last post by:
I want to create a function _and so that I could write vector<boolasserts; //... bool b = _and(asserts); and it "anded" all the elements in the vector. I implemented it like this:
0
1061
by: Drunkard | last post by:
Hallo does anyone have shortest path with forbidden pairs algorithm written in C or C++ or .net or C# ?????? Please help me.
0
1038
by: striker16 | last post by:
Hi there, I'm looking for an algorithm to solve following problem: There is a random list of floating point numbers with two positions after the decimal point (dollar prices). Any two of those numbers can be considered a pair if they are added up and their resulting number of cents is equal to a certain number X. Now, all pairs have to be formed in such a way that, at the end, there will be a maximum number of pairs. Each floating...
15
2444
by: mcjason | last post by:
I saw something interesting about a grid pair puzzle problem that it looks like a machine when you find each that work out the way it does and say with all the others that work out the way they do together overlapping common pieces but say connected each working out as connected, but together as connected it's connected with the others connected. a whole machine where connected together is a condition of the machine together as...
2
4659
by: shashankbs | last post by:
Given a topology and a certain node X, find the shortest path tree with X as the root. * Input: a topology file similar to the following (which is a three-node ring) -------------------------------------------- Nodes: (3) // there are three nodes (node 0, 1 and 2) Edges: (3)
0
8888
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
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
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
8097
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...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
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
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.