473,395 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

divide all elements in a vector by a number

Dear all,

I was wondering if I could divide all elements of a vector by the max
element of that vector.

I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions, namely
max_element. I wondered if this is possible or not through the
standard.

BOOST_FOREACH seemed the best option to me. But I wondered :)

Rgds,

Nov 15 '07 #1
22 18020
utab wrote:
Dear all,

I was wondering if I could divide all elements of a vector by the max
element of that vector.

I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions, namely
max_element. I wondered if this is possible or not through the
standard.

BOOST_FOREACH seemed the best option to me. But I wondered :)
Everybody is supposed to do their own homework.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 15 '07 #2
utab wrote:
I was wondering if I could divide all elements of a vector by the max
element of that vector.
Is it really that hard to write a simple for-loop? It will probably be
easier to read than the STL acrobatics needed to do the same thing.
Probably shorter too.
Nov 15 '07 #3
On Thu, 15 Nov 2007 08:35:52 -0800 (PST) in comp.lang.c++, utab
<um********@gmail.comwrote,
>Dear all,

I was wondering if I could divide all elements of a vector by the max
element of that vector.

I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions,
You are halfway there, now check the "bind" family, for example
std::bind2nd or the powerful boost::bind versions.

Something along the lines of (unchecked!)

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::divides<double>,
std::max_element(v.begin(), v.end()));
Nov 15 '07 #4
utab <um********@gmail.comwrote:
I was wondering if I could divide all elements of a vector by the max
element of that vector.

I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions, namely
max_element. I wondered if this is possible or not through the
standard.
First find the max element of the vector (hint: there is an algorithm
for that.) Then transform each element by dividing it by that number.

For extra credit: With the proper use of functors, the whole thing can
be done in one line of code.

Make a stab at it and post it with this same subject. I'd love to see if
you can come up with it, and will help you out if you can at least get
close. :-)
Nov 15 '07 #5
On Nov 15, 6:01 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
utab wrote:
Dear all,
I was wondering if I could divide all elements of a vector by the max
element of that vector.
I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions, namely
max_element. I wondered if this is possible or not through the
standard.
BOOST_FOREACH seemed the best option to me. But I wondered :)

Everybody is supposed to do their own homework.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oops, you are not right since I did not paste any code :)

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(double d)
{
cout << " " << d << endl;
}

int main()
{
vector<doublex;
for(double i=0;i!=10;++i)
x.push_back(i);

double max=*max_element(x.begin(),x.end());

cout << max << endl;

vector<double>::iterator iterx=x.begin();
for(;iterx!=x.end();++iterx)
{
if(fabs(max)>1e-6){ // just a pre-caution for divide by 0.
*iterx=*iterx/max;
}
}
for_each(x.begin(),x.end(),print);

return 0;
}

That was the question, without a loop, is this possible?
I could not find the answer in my references,
I made the example quickly, hope it is error free!
Rgds,
Nov 15 '07 #6
On Nov 15, 7:43 pm, David Harmon <sou...@netcom.comwrote:
On Thu, 15 Nov 2007 08:35:52 -0800 (PST) in comp.lang.c++, utab
<umut.ta...@gmail.comwrote,
Dear all,
I was wondering if I could divide all elements of a vector by the max
element of that vector.
I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions,

You are halfway there, now check the "bind" family, for example
std::bind2nd or the powerful boost::bind versions.

Something along the lines of (unchecked!)

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::divides<double>,
std::max_element(v.begin(), v.end()));
bind,
thank you for the input.
Nov 15 '07 #7
On Nov 15, 7:42 pm, Juha Nieminen <nos...@thanks.invalidwrote:
utab wrote:
I was wondering if I could divide all elements of a vector by the max
element of that vector.

Is it really that hard to write a simple for-loop? It will probably be
easier to read than the STL acrobatics needed to do the same thing.
Probably shorter too.
Just curious, you are right in your reasoning,
Rgds.
Nov 15 '07 #8
For extra credit: With the proper use of functors, the whole thing can
be done in one line of code.

Make a stab at it and post it with this same subject. I'd love to see if
you can come up with it, and will help you out if you can at least get
close. :-)
One line of code, I am really interested and will certainly give that
a try, thanks for the guidance

Rgds
Nov 15 '07 #9
utab wrote:
On Nov 15, 6:01 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
>utab wrote:
>>Dear all,
>>I was wondering if I could divide all elements of a vector by the
max element of that vector.
>>I checked the STL references and found transform, for_each and
lately BOOST_FOREACH, but transform and for_each algorithms are not
suited since I have another argument to supply to the functions,
namely max_element. I wondered if this is possible or not through
the standard.
>>BOOST_FOREACH seemed the best option to me. But I wondered :)

Everybody is supposed to do their own homework.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Oops, you are not right since I did not paste any code :)

[..code..]

That was the question, without a loop, is this possible?
Yes, but you'd have to use recursion. As to whether it's possible
using 'transform', 'bind', 'divides', etc., you have your reply, but
keep in mind there is always a loop whether *you* write it or it is
written *for you* in the library routine.
I could not find the answer in my references,
I made the example quickly, hope it is error free!
I didn't check it. But I'd probably moved the 'if(fabs(max)))' out
of the loop and changed the 'max' to something else (since there
are functions named 'max' in 'std').

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 15 '07 #10
Daniel T. wrote:
utab <um********@gmail.comwrote:
>I was wondering if I could divide all elements of a vector by the max
element of that vector.

I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions, namely
max_element. I wondered if this is possible or not through the
standard.

First find the max element of the vector (hint: there is an algorithm
for that.) Then transform each element by dividing it by that number.

For extra credit: With the proper use of functors, the whole thing can
be done in one line of code.

Make a stab at it and post it with this same subject. I'd love to see if
you can come up with it, and will help you out if you can at least get
close. :-)
Although there are mulitple ways of doing this in one line as an
academic exercise, I think performance and readiability wise, a 2 liner
is better for practical purposes. I don't doubt your intention but let's
not send out the wrong signal. :)

To the OP, do look up boost::lambda, suppose you already have the
maximum value in max_r, there is a succinct way to express your
algorithm through transform:

std::transform(from.begin(), from.end(), to.begin(), _1/max_r);

You can do in place transformation:
std::transform(from.begin(), from.end(), from.begin(), _1/max_r);

Fei
Nov 15 '07 #11
On Nov 15, 8:10 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
utab wrote:
On Nov 15, 6:01 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
utab wrote:
Dear all,
>I was wondering if I could divide all elements of a vector by the
max element of that vector.
>I checked the STL references and found transform, for_each and
lately BOOST_FOREACH, but transform and for_each algorithms are not
suited since I have another argument to supply to the functions,
namely max_element. I wondered if this is possible or not through
the standard.
>BOOST_FOREACH seemed the best option to me. But I wondered :)
Everybody is supposed to do their own homework.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oops, you are not right since I did not paste any code :)
[..code..]
That was the question, without a loop, is this possible?

Yes, but you'd have to use recursion. As to whether it's possible
using 'transform', 'bind', 'divides', etc., you have your reply, but
keep in mind there is always a loop whether *you* write it or it is
written *for you* in the library routine.
I could not find the answer in my references,
I made the example quickly, hope it is error free!

I didn't check it. But I'd probably moved the 'if(fabs(max)))' out
of the loop and changed the 'max' to something else (since there
are functions named 'max' in 'std').

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Thank you all for the replies and guidance
Nov 15 '07 #12
On Nov 15, 7:43 pm, David Harmon <sou...@netcom.comwrote:
On Thu, 15 Nov 2007 08:35:52 -0800 (PST) in comp.lang.c++, utab
<umut.ta...@gmail.comwrote,
Dear all,
I was wondering if I could divide all elements of a vector by the max
element of that vector.
I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions,

You are halfway there, now check the "bind" family, for example
std::bind2nd or the powerful boost::bind versions.

Something along the lines of (unchecked!)

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::divides<double>,
std::max_element(v.begin(), v.end()));
The correct form should be, after some reading in the directions you
provided,

transform(x.begin(), x.end(), x.begin(),
std::bind2nd(std::divides<double>(),*max_element(x .begin(),
x.end())));

I have once more appreciated the full power of STL.

These tricks are very nice :), thank you

Best regards,
Nov 15 '07 #13
On Thu, 15 Nov 2007 08:35:52 -0800 (PST), utab wrote:
Dear all,

I was wondering if I could divide all elements of a vector by the max
element of that vector.
In addition to the answers you have already received, you could
consider using std::valarray. It is specifically designed for
doing mathematical operations to a mass of items at the same
time. Who knows, maybe it has also parallel or vectorization
optimizations in it for modern platforms.

--
Joel Yliluoma - http://bisqwit.iki.fi/
: comprehension = 1 / (2 ^ precision)
Nov 16 '07 #14
On Thu, 15 Nov 2007 08:35:52 -0800 (PST), utab wrote:
Dear all,

I was wondering if I could divide all elements of a vector by the max
element of that vector.
In addition to the answers you have already received, you could
consider using std::valarray. It is specifically designed for
doing mathematical operations to a mass of items at the same
time. Who knows, maybe it has also parallel or vectorization
optimizations in it for modern platforms.

Example:
std::valarray<inttmp;
...
tmp /= tmp.max();

--
Joel Yliluoma - http://bisqwit.iki.fi/
: comprehension = 1 / (2 ^ precision)
Nov 16 '07 #15
On Nov 15, 8:18 pm, Fei Liu <fei....@gmail.comwrote:
Daniel T. wrote:
utab <umut.ta...@gmail.comwrote:
I was wondering if I could divide all elements of a vector by the max
element of that vector.
[...]
Although there are mulitple ways of doing this in one line as an
academic exercise, I think performance and readiability wise, a 2 liner
is better for practical purposes. I don't doubt your intention but let's
not send out the wrong signal. :)
I think by "one line", he really meant one C++ statement. I've
never managed to get even the simplest call to std::transform on
a single line, while still keeping a reasonable line length.
(If humans are to read the code, something about 60 characters,
not counting indentation, is about the limit. You can exceed it
occassionally, but 80 characters is a good absolute limit.)

David Harmon's suggestion is only one C++ statement, is very
readable, and probably results in the best performance you're
likely to get.

--
James Kanze (GABI Software) email:ja*********@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
Nov 16 '07 #16
On Nov 16, 10:45 am, Joel Yliluoma <bisq...@iki.fiwrote:
On Thu, 15 Nov 2007 08:35:52 -0800 (PST), utab wrote:
Dear all,
I was wondering if I could divide all elements of a vector by the max
element of that vector.

In addition to the answers you have already received, you could
consider using std::valarray. It is specifically designed for
doing mathematical operations to a mass of items at the same
time. Who knows, maybe it has also parallel or vectorization
optimizations in it for modern platforms.

Example:
std::valarray<inttmp;
...
tmp /= tmp.max();

--
Joel Yliluoma -http://bisqwit.iki.fi/
: comprehension = 1 / (2 ^ precision)
I see this is also a nice suggestion since my concern for using C++ is
mainly on number crunching.

Rgds,
Nov 16 '07 #17
James Kanze wrote:
On Nov 15, 8:18 pm, Fei Liu <fei....@gmail.comwrote:
>Daniel T. wrote:
utab <umut.ta...@gmail.comwrote:
>I was wondering if I could divide all elements of a vector by the max
element of that vector.

[...]
>Although there are mulitple ways of doing this in one line as an
academic exercise, I think performance and readiability wise, a 2 liner
is better for practical purposes. I don't doubt your intention but let's
not send out the wrong signal. :)

I think by "one line", he really meant one C++ statement. I've
never managed to get even the simplest call to std::transform on
a single line, while still keeping a reasonable line length.
(If humans are to read the code, something about 60 characters,
not counting indentation, is about the limit. You can exceed it
occassionally, but 80 characters is a good absolute limit.)

David Harmon's suggestion is only one C++ statement, is very
readable, and probably results in the best performance you're
likely to get.
I must be missing something here. The one-command versions (and also the
2-command ones) that I can see are either not readable or not correct (at
least they have undefined behavior when the vector is empty or when the
maximum element is 0).
Best

Kai-Uwe Bux
Nov 16 '07 #18
Kai-Uwe Bux <jk********@gmx.netwrote:
I must be missing something here. The one-command versions (and also the
2-command ones) that I can see are either not readable or not correct (at
least they have undefined behavior when the vector is empty or when the
maximum element is 0).
Well, the one David harman posted was what I was thinking about. I grant
that it would have undefined behavior if the maximum element is 0
(however, isn't 0/0 well defined?) but it would work fine if the array
is empty.

I would probably preface it with an assert to make sure that such isn't
the case.
Nov 16 '07 #19
Daniel T. wrote:
[..] isn't 0/0 well defined?[..]
Most definitely not. Is it 1 (since the numerator and the denominator
are the same)? Is it 0 (since the numerator is 0)? Is it division by
zero (since the denominator is 0)?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 16 '07 #20
Daniel T. wrote:
Kai-Uwe Bux <jk********@gmx.netwrote:
>I must be missing something here. The one-command versions (and also the
2-command ones) that I can see are either not readable or not correct (at
least they have undefined behavior when the vector is empty or when the
maximum element is 0).

Well, the one David harman posted was what I was thinking about.
That would be this:

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::divides<double>,
std::max_element(v.begin(), v.end()));
I grant
that it would have undefined behavior if the maximum element is 0
(however, isn't 0/0 well defined?)
a) 0/0 is not well-defined, neither in math nor in C++.

b) The maximum in the vector can be 0 while other elements are not: they
could be all negative.

but it would work fine if the array is empty.
Nope. The posted version seems to be missing the dereferencing of
max_element, which returns an iterator. If dereferencing is done, it will
have UB for empty vectors:

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::divides<double>,
* std::max_element(v.begin(), v.end()));

The point is that the dereferencing is done _before_ std::transform has a
chance to tell that nothing needs to be done.

I would probably preface it with an assert to make sure that such isn't
the case.

Best

Kai-Uwe Bux
Nov 16 '07 #21
On Nov 16, 11:14 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
James Kanze wrote:
On Nov 15, 8:18 pm, Fei Liu <fei....@gmail.comwrote:
Daniel T. wrote:
utab <umut.ta...@gmail.comwrote:
I was wondering if I could divide all elements of a
vector by the max element of that vector.
[...]
Although there are mulitple ways of doing this in one line
as an academic exercise, I think performance and
readiability wise, a 2 liner is better for practical
purposes. I don't doubt your intention but let's not send
out the wrong signal. :)
I think by "one line", he really meant one C++ statement.
I've never managed to get even the simplest call to
std::transform on a single line, while still keeping a
reasonable line length. (If humans are to read the code,
something about 60 characters, not counting indentation, is
about the limit. You can exceed it occassionally, but 80
characters is a good absolute limit.)
David Harmon's suggestion is only one C++ statement, is very
readable, and probably results in the best performance
you're likely to get.
I must be missing something here. The one-command versions
(and also the 2-command ones) that I can see are either not
readable or not correct (at least they have undefined behavior
when the vector is empty or when the maximum element is 0).
Touche. You can handle the empty array case in a single
statement, using ?:, of course, but an if would be more natural
(since there's nothing to do in once case, and (void)0 is not
really very "natural"). For the case where the maximum element
is 0, you really have to define what is wanted---maybe a simple
pre-condition (all elements 0.0) is all that is wanted. But
you're right that unless the code has considered the case, it's
not correct.

--
James Kanze (GABI Software) email:ja*********@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
Nov 17 '07 #22
On Nov 16, 6:30 pm, utab <umut.ta...@gmail.comwrote:
On Nov 16, 10:45 am, Joel Yliluoma <bisq...@iki.fiwrote:


On Thu, 15 Nov 2007 08:35:52 -0800 (PST), utab wrote:
Dear all,
I was wondering if I could divide all elements of a vector by the max
element of that vector.
In addition to the answers you have already received, you could
consider using std::valarray. It is specifically designed for
doing mathematical operations to a mass of items at the same
time. Who knows, maybe it has also parallel or vectorization
optimizations in it for modern platforms.
Example:
std::valarray<inttmp;
...
tmp /= tmp.max();
--
Joel Yliluoma -http://bisqwit.iki.fi/
: comprehension = 1 / (2 ^ precision)

I see this is also a nice suggestion since my concern for using C++ is
mainly on number crunching.
all the above are based on loops ,so you cantry recursion yourself.

regards,
FM.
Nov 23 '07 #23

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

Similar topics

8
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in...
1
by: Tino | last post by:
I have a std::vector<int> which, after some initialization, has a fixed number of elements...after initialization I must do the following repeatedly: I remove an element which could be anywhere in...
6
by: Jason Heyes | last post by:
What is a good way of removing elements from std::vector so that the elements removed satisfy a predicate and end up stored in another std::vector. It seems as though the algorithm std::remove_if...
34
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and...
8
by: cayblood | last post by:
Hello, I have been interested in something kind of like the next_permutation from the STL algorithm library, except that I want it to find possible combinations of vector elements. Here is a more...
7
by: linq936 | last post by:
Hi, The following is a psudo code to describe my question: vector<int> ints; vector<int>::iterator itr; while (itr != ints.end()){ int j = some_function(*i); if (j>0){ ints.push_back(j); }
4
by: Ole Nielsby | last post by:
I need to build a small array of pointers to a type MyType. The array size can be from 1 upwards, is not known beforehand, typically < 10 but I don't want a small fixed limit. Elements will be...
2
by: Angus | last post by:
Hello I have a vector<int(aRemovecoll) which is a list of the indexes to be removed from another vector. The other vecotr contains an object - I will call it SomeObject. So the other vecotr is...
11
by: C C++ C++ | last post by:
Hi all, got this interview question please respond. How can you quickly find the number of elements stored in a a) static array b) dynamic array ? Rgrds MA
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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
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,...

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.