473,543 Members | 2,259 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

STL algorithm VS Java loop

Hi,

I am trying to compare the amount of work between using STL algorithm
VS a plain Java loop.

Let's say the class Rect has 2 attributes: area, and areaPerCent.

In Java, I just write a plain for loop with a list:
public static void calculateAreaPe rCent(List rectList, float
containerArea) {
for (Iterator iter = rectList.iterat or(); iter.hasNext(); ) {
Rect r = (Rect) iter.next();
r.areaPerCent = r.area / containerArea;
}
}

And in C++, it is recommded to use STL algorithm instead of a plain
loop, we need to do this:
class doloop : public unary_function< Rect*, void>
{
public:
loopthru(float containerArea) : _containerArea( containerArea) { }

void operator() (Rect* r) {

r->areaPerCent = r->area /_containerArea;
}
private:
_containerArea;

};

void calculateAreaPe rCent(vector<Re ct*>& rl, float containerArea) {
for_each (rl.begin(), rl.end(), doloop(containe rArea));
}

It seems to me the C++ STL algorithm way needs more work. Is that a
fair comparision? Is there a simpler way? Or I should use a plain C++
for loop ?

Thank you.

Jan 17 '06 #1
17 4326
Al************@ gmail.com wrote:
Hi,

I am trying to compare the amount of work between using STL algorithm
VS a plain Java loop.

Let's say the class Rect has 2 attributes: area, and areaPerCent.

In Java, I just write a plain for loop with a list:
public static void calculateAreaPe rCent(List rectList, float
containerArea) {
for (Iterator iter = rectList.iterat or(); iter.hasNext(); ) {
Rect r = (Rect) iter.next();
r.areaPerCent = r.area / containerArea;
}
}

And in C++, it is recommded to use STL algorithm instead of a plain
loop, we need to do this:
class doloop : public unary_function< Rect*, void>
{
public:
loopthru(float containerArea) : _containerArea( containerArea) { }

void operator() (Rect* r) {

r->areaPerCent = r->area /_containerArea;
}
private:
_containerArea;

};

void calculateAreaPe rCent(vector<Re ct*>& rl, float containerArea) {
for_each (rl.begin(), rl.end(), doloop(containe rArea));
}
You don't need to use a for_each in C++, and you can use the common
for() loop method.
Use the fore_each method when you have a generic function, that can be
used with multiple types.
Java doesn't have this option, so it's harder to reuse code in Java.
In C++ we have more options, and therefore can do it in a manner that
is best for a paticular application.

It seems to me the C++ STL algorithm way needs more work. Is that a
fair comparision?
No. Since you're comparring apples and oranges. You can use nearly
the same syntax used in Java, and you have more efficient code.

Is there a simpler way? Or I should use a plain C++ for loop ?

You should be using the plain C++ loop, unless you have a generic
function.

Moreover, you should avoid using pointers unless you're sure you have
to.
In Java, everything is basically a pointer.
In C++, you don't need to use pointers, unless you're using abstract
types.

If Rect is not an abstract type, than there's no need to use a vector
of pointers.
vector<Rect> vRect;

If Rect is an abstract type, than you should use a smart pointer,
instead of a raw dummy pointer.
vector<boost::s hared_ptr<Rect> > vRect;
or
vector<cow_ptr< Rect> > vRect;

See following link for cow pointer:
http://code.axter.com/cow_ptr.h
http://code.axter.com/copy_ptr.h

And check out the boost library for shared_ptr.

Jan 17 '06 #2
Hi

Axter wrote:
You don't need to use a for_each in C++, and you can use the common
for() loop method.
Use the fore_each method when you have a generic function, that can be
used with multiple types.
Why?
I don't see any relation...
Java doesn't have this option, so it's harder to reuse code in Java.


Java 5 knows generics, btw...
It seems to me the C++ STL algorithm way needs more work. Is that a
fair comparision?


No. Since you're comparring apples and oranges. You can use nearly
the same syntax used in Java, and you have more efficient code.


More efficient? I doubt that for_each(begin, end,action) boils down to
anything else but for(For i=begin; i!=end; ++i) action(*i);

Markus

Jan 17 '06 #3
Axter wrote:
vector<boost::s hared_ptr<Rect> > vRect;


Boost also has a "pointer container" library that you might find more
suitable than a vector of shared_ptr, depending on how much flexibility
your program needs.

http://www.boost.org/libs/ptr_contai...container.html

-Alan
Jan 17 '06 #4

Markus Moll wrote:
Hi

Axter wrote:
You don't need to use a for_each in C++, and you can use the common
for() loop method.
Use the fore_each method when you have a generic function, that can be
used with multiple types.


Why?
I don't see any relation...
Java doesn't have this option, so it's harder to reuse code in Java.


Java 5 knows generics, btw...


Generic what?
Can you do template coding with Java 5?
It seems to me the C++ STL algorithm way needs more work. Is that a
fair comparision?


No. Since you're comparring apples and oranges. You can use nearly
the same syntax used in Java, and you have more efficient code.


More efficient? I doubt that for_each(begin, end,action) boils down to
anything else but for(For i=begin; i!=end; ++i) action(*i);


Have you tried using a Java IDE?
Every Java IDE I've tried is painfully slow.
IMHO, why should I bother using Java, if a Java developer can't make a
decent efficient IDE for the language?
By evaluating the performance of most Java IDE's, I have to assume
either there are a lot of bad Java programmers developing IDE's, or
the language is inefficient in general.

Jan 17 '06 #5
Hi

Axter wrote:
Generic what?
Can you do template coding with Java 5?


Depends on what your understanding of "template coding" is.
You certainly cannot do everything you could do with templates.
See http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf if you want to
know more.

But we're moving off topic...
More efficient? I doubt that for_each(begin, end,action) boils down to
anything else but for(For i=begin; i!=end; ++i) action(*i);


Have you tried using a Java IDE?


Eclipse runs quite well.

But anyway, it was a misunderstandin g. I thought you were comparing for_each
to a simple for loop, not Java to C++.

Markus

Jan 17 '06 #6
I thought it is better to use for_each than a plain c++ for loop. That
is why I post my original question.
From Effective STL item 43: Prefer algorithm calls to hand-written

loops.

Otherwise, there is no need to have the for_each() algorithm, right? we
can replace all for_each() calls with a plain c++ for loop.

Thank you.

Jan 17 '06 #7
In nearly every second link the guy's in comp.lang.c++ are trying to
dispose the shared pointers!

So my question:

#####some example from boost-hp#####
ptr_vector<X> pvec;
std::vector<X*> vec;
*vec.begin() = new X; // fine, memory leak
*pvec.begin() = new X; // compile time error
( *vec.begin() )->foo(); // call X::foo(), a bit clumsy
pvec.begin()->foo(); // no indirection needed
*vec.front() = X(); // overwrite first element
pvec.front() = X(); // no indirection needed

#####So this is what I first think of that:
ptr_vector<X*> pvec; //for generics!!
std::vector<X*> vec;
*vec.begin() = new X; // just be sure to delete it, where is the
problem?
*pvec.begin() = new X; // now no error!
( *vec.begin() )->foo(); // call X::foo(), a bit clumsy, but correct
pvec.begin()->foo(); // no indirection needed, yes but no generics
*vec.front() = X(); // overwrite first element
pvec.front() = X(); // compile time error

########
Is this possible?

pvec vec
*vec.begin() = new X;
( *vec.begin() )->foo(); // call X::foo(), a bit clumsy, but correct
*vec.front() = X(); // overwrite first element
delete *vec.begin(); // delete first element

does that compile with either
typedef std::vector<X*> pvec
or
typedef ptr_vector<X*> pvec

Regards,
Sascha

Jan 17 '06 #8
Markus Moll wrote:
It seems to me the C++ STL algorithm way needs more work. Is that a
fair comparision?


No. Since you're comparring apples and oranges. You can use nearly
the same syntax used in Java, and you have more efficient code.


More efficient? I doubt that for_each(begin, end,action) boils down to
anything else but for(For i=begin; i!=end; ++i) action(*i);


I think you might be surprised. Ever heard of loop unrolling, for
instance?

Or, better yet, measure it yourself. It's really not hard to get some
basic perf numbers and answer these things empirically. Or go look up
the source of your favorite STL implementation.

Java has all kinds of difficulty competing in terms of performance.
For example, I recently found a case in which javac generates an extra
bytecode if certain parentheses are added for clarity.

Luke

Jan 18 '06 #9
I guess I was trying to find out what are the advantages of using STL
algorithms over a plain C++ for loop. I did not mean it to be a Java
Vs C++ discussion.

In my provided example, it seems to me it requires more code to use STL
algorithms over a plain c++ loop. And yet, in item 43 of Effective STL
, it said 'perfer algorithm calls to hand-written loops'. And this is
what I don't understand...

Thank you.

Jan 18 '06 #10

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

Similar topics

28
3129
by: joshc | last post by:
If I have an array of data that I know to be sorted in increasing order, and the array is less than 50 elements, and I want to find the first element greater than a certain value, is a simple linear search the best here(for loop from beginning to end of array)? It seems like some other search algorithm like binary or whatever would be of no...
113
12199
by: Bonj | last post by:
I was in need of an encryption algorithm to the following requirements: 1) Must be capable of encrypting strings to a byte array, and decyrpting back again to the same string 2) Must have the same algorithm work with strings that may or may not be unicode 3) Number of bytes back must either be <= number of _TCHARs in * sizeof(_TCHAR), or the...
3
1810
by: AMP | last post by:
Hello, I posted this morning and recieved no responces., so I decided to simplify my question. How do I stop an exception from being thrown after the first run through of the while clause: private void InsertionSort_Function(uint IntCard,int length) { for (int j = 1; j <= (length-1); j++) {
4
32052
prometheuzz
by: prometheuzz | last post by:
Hello (Java) enthusiasts, In this article I’d like to tell you a little bit about graphs and how you can search a graph using the BFS (breadth first search) algorithm. I’ll address, and hopefully answer, the following questions: • what is a graph? • how can a graph be represented as an ADT? • how can we search/walk through a graph using...
0
2953
by: aruna | last post by:
hey guys i earlier had very valuable responses from you all for base64 encoding algorithm.so thank for that. so now i need your assistance to do a float encoding algorithm. you may wonder why i'm so interest about this encoding algorithms. because our group is going to do a project under the ITU-T Recommendation X.891. this is named as fast...
6
17822
by: kamsmartx | last post by:
I'm new to programming and need some help figuring out an algorithm. I need to design some kind of algorithm which will help us define capacity for one of our portfolios....here's the problem explained (also see attached example): 1. The graph defines total capacity, y-axis being $, x-axis being date/time. the bars on the graph represent...
20
3048
by: mike3 | last post by:
Hi. (Xposted to both comp.lang.c++ and comp.programming since I've got questions related to both C++ language and general programming) I've got the following C++ code. The first routine runs in like 65% of the time of the second routine. Yet both do the same thing. However, the second one seems better in terms of the way the code is written...
1
3103
by: almurph | last post by:
Hi everyone, Concerning the Needleman-Wunsch algorithm (cf. http://en.wikipedia.org/wiki/Needleman-Wunsch_algorithm) I have noticed a possible loop. Inside the algorithm there is an important decision making mechanism. Its a "if, else if, else if" structure like:
4
5310
by: slapsh0t11 | last post by:
Hello! I need help with a program that I believe I am nearly done with. However, there seems to be a few details that preclude me from success. Here is my assignment: Here is my class file (Sorts.java): import java.util.*; /**
0
7397
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...
0
7582
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. ...
0
7726
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...
1
7329
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7675
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5877
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...
1
5257
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...
0
3384
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...
1
948
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.