473,585 Members | 2,556 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert a Java iterator loop to C++ STL?


Hi,

I am trying to convert a Java iterator loop to C++ STL? the loop looks
like this:

public static boolean func (List aList) {
int minX = 0
for (Iterator iter = aList.listItera tor(1); iter.hasNext(); ) {
A a = (A) iter.next();

if (! closeEnough(min X, a.x) ) {
return true;
} else {
minX = a.x;
}
}
return false;
}

I am reading the "Effecitive STL" book, it said i should use STL
algorithm instead of writing my loop if possible. I was thinking of
using for_each(). But in this case, i need to update a local variable
'minX' and stop the iteration if certain condition is met. Should I
use for_each()? or I write my own iterator loop?

Thank you for any idea.

Jan 11 '06 #1
6 2816
sa************* **@gmail.com wrote:
Hi,

I am trying to convert a Java iterator loop to C++ STL? the loop looks
like this:

public static boolean func (List aList) {
int minX = 0
for (Iterator iter = aList.listItera tor(1); iter.hasNext(); ) {
A a = (A) iter.next();

if (! closeEnough(min X, a.x) ) {
return true;
} else {
minX = a.x;
}
}
return false;
}

I am reading the "Effecitive STL" book, it said i should use STL
algorithm instead of writing my loop if possible. I was thinking of
using for_each(). But in this case, i need to update a local variable
'minX' and stop the iteration if certain condition is met. Should I
use for_each()? or I write my own iterator loop?

Thank you for any idea.


I think the algorithm you want is "find_if". You can then write your
own predicate. For example, you might have a class named "closeEnoug h"
to act as your predicate:

#include <functional>

class closeEnough : public std::unary_func tion<bool, int>
{
private :
int minX ;
public :
closeEnough() : minX(0) {}

bool operator()(int x)
{
// Your logic for the "closeEnoug h" function goes here.
// Note your ability to change minX as you like.
return true ;
}
} ;
Then your function above would reduce to something like the following
(forgive me if I got some of the logic backwards, but this is the
general idea):

#include <algorithm>
#include <list>

bool func(std::list< int> aList)
{
std::list<int>: :iterator i ;
closeEnough cefunc ;

i = std::find_if(aL ist.begin(), aList.end(), cefunc) ;
return (i == aList.end()) ;
}
Jan 11 '06 #2
Thanks. This is helpful.

Jan 11 '06 #3
> // Note your ability to change minX as you like.
return true ;


Not necessarily. Changing state in a predicate is a dangerous business, see

http://www.informit.com/articles/art...&seqNum=4&rl=1

(Here the order of find_if is guaranteed, so you are more likely to get
away with it. But it's a dodgy practice at best, and likely to teach bad
habits.)
Jan 11 '06 #4
Do you have a better solution to my problem?
Thanks.

Jan 11 '06 #5
sa************* **@gmail.com wrote:
Do you have a better solution to my problem?
Thanks.


Just write a plain old loop.
Jan 12 '06 #6
sa************* **@gmail.com wrote:
Do you have a better solution to my problem?
Thanks.


Depending on just what CloseEnough does, you may just be able to use
min_element as show below. I'm not sure by your example as to whether the
min value is really needed.

#include <algorithm>
#include <list>

bool func( const std::list<int>& aList )
{
typedef std::list<int>: :const_iterator tCItr;

int lMinValue = 0;

tCItr i = std::min_elemen t( aList.begin(), aList.end(), cefunc );

if( i != aList.end() )
{
lMinValue = *i;

return false;
}
else
{
return true;
}
}

Jeff
Jan 12 '06 #7

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

Similar topics

4
2497
by: Scott Smedley | last post by:
Hi all, I'm trying to write a special adaptor iterator for my program. I have *almost* succeeded, though it fails under some circumstances. See the for-loop in main(). Any pointers/help would be muchly appreciated. Apologies for the long post - I couldn't find a shorter way to
3
18263
by: James | last post by:
Has anyone written a utility to convert a C# form to C++.net? i.e. to convert "using System.Data" to "using namespace System::Data" etc
17
4334
by: Allerdyce.John | last post by:
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 calculateAreaPerCent(List rectList, float containerArea) {
5
2615
by: Mark Stijnman | last post by:
I have a question about forward iterators and what one should do or not do with them. I'm planning on writing a container that, when all boils down to it, stores a sequence of strings. I want threads to be able to read this sequence from start to end, and when they reach the end, wait until new data is added to the end. If so, it should pick...
18
7720
by: jacksu | last post by:
I have a simple program to run xpath with xerces 1_2_7 XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); XPathExpression xp = xPath.compile(strXpr); System.out.println(xp.evaluate(new InputSource(new FileInputStream("a.xml"))));
1
1926
by: priyakollu | last post by:
i have developed code in jsp but the problem is i need to convert this to asp.........pleasehelp me regarding this im sending code which i've developed....with file names.......... code.jsp <%@ page import = "java.util.*" %> <%@ page import = "java.io.*" %> <%@ page import = "java.lang.*" %> <%@ page import =...
27
5303
by: Steven D'Aprano | last post by:
I thought that an iterator was any object that follows the iterator protocol, that is, it has a next() method and an __iter__() method. But I'm having problems writing a class that acts as an iterator. I have: class Parrot(object): def __iter__(self): return self def __init__(self): self.next = self._next()
9
7600
by: xxplod | last post by:
I am suppose to modify the Inventory Program so the application can handle multiple items. Use an array to store the items. The output should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory of that product. In...
2
3743
by: yeshello54 | last post by:
so here is my problem...in a contact manager i am trying to complete i have ran into an error..we have lots of code because we have some from class which we can use...anyways i keep getting an error when i do the following. if you add a contact with up to 13 fields it will be stored in a data structure. i have a tabbed pane that will show six of...
0
7836
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...
0
8199
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
8336
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
7950
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
8212
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
5389
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...
0
3835
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
2343
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
0
1175
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...

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.