473,698 Members | 2,250 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Use != rather than < in for loops ?

In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.

The following small snippet erases punctuations in a string. It works
well with < used in the for loop but it breaks when != is used instead.

#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";//s: i18n
//for (string::size_t ype sz = 0; sz < s.size(); ++sz){
/*works with < */
for (string::size_t ype sz = 0; sz != s.size(); ++sz){
/*doesn't work with != */
try{
if (ispunct(s.at(s z))){
s.erase(sz, 1);
}
}catch(exceptio n &e){
cout << e.what() << endl;
}
}
cout << s << endl;
}

Jan 9 '07 #1
32 2100
lovecreatesbea. ..@gmail.com wrote:
In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.

The following small snippet erases punctuations in a string. It works
well with < used in the for loop but it breaks when != is used instead.

#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";//s: i18n
//for (string::size_t ype sz = 0; sz < s.size(); ++sz){
/*works with < */
for (string::size_t ype sz = 0; sz != s.size(); ++sz){
/*doesn't work with != */
try{
if (ispunct(s.at(s z))){
s.erase(sz, 1);
}
}catch(exceptio n &e){
cout << e.what() << endl;
}
}
cout << s << endl;
}
I don't have that book so I can only comment on what you've typed above.
The problem with the != version is that every time you call s.erase,
s.size() decreases by 1. Because s ends in a punctuation character you
erase the '!', thereby decrementing s.size() (12 to 11). Immediately
thereafter you increment sz (11 to 12), and the two values "pass
through" each other without ever being equal. Then you end up going out
of bounds with sz, throwing an out_of_range exception. In general I'd
prefer < to != for loop continuation conditions.
Jan 9 '07 #2
lovecreatesbea. ..@gmail.com wrote:
In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.
They do? Well, I do that when using iterators, but for a loop using an
integer loop counter, I use <.
The following small snippet erases punctuations in a string. It works
well with < used in the for loop but it breaks when != is used instead.

#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";//s: i18n
//for (string::size_t ype sz = 0; sz < s.size(); ++sz){
/*works with < */
for (string::size_t ype sz = 0; sz != s.size(); ++sz){
/*doesn't work with != */
try{
if (ispunct(s.at(s z))){
s.erase(sz, 1);
}
}catch(exceptio n &e){
cout << e.what() << endl;
}
}
cout << s << endl;
}
The problem is that s.size() will be reduced by 1 when you erase a
character. When the last character in your string is removed, your
index "jumps" over the end of the string, so sz will be greater than
s.size(). Therefore the version with < works, but not the one with !=.

Here is a table that shows what it looks like at the beginning of each loop
iteration:

index size character
0 13 h
1 13 e
2 13 l
3 13 l
4 13 o
5 13 , -erased
6 12 w -space is jumped over
7 12 o
8 12 r
9 12 l
10 12 d
11 12 ! -erased
12 11 <none -index is past string end

Jan 9 '07 #3

lovecreatesbea. ..@gmail.com wrote:
In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.

The following small snippet erases punctuations in a string. It works
well with < used in the for loop but it breaks when != is used instead.

#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";//s: i18n
//for (string::size_t ype sz = 0; sz < s.size(); ++sz){
/*works with < */
for (string::size_t ype sz = 0; sz != s.size(); ++sz){
/*doesn't work with != */
try{
if (ispunct(s.at(s z))){
s.erase(sz, 1);
}
}catch(exceptio n &e){
cout << e.what() << endl;
}
}
cout << s << endl;
}
Hi
The use of != is good practice when using iterators since the only type
of iterator that < will be meaningful to it is random access iterator
(the one used in vector and string but not in list, map ..). In this
case since you are not using iterators but comparing ints it is better
using < from the reasons the others pointed out. By the way I will
steer clean from this book. And anther by the way, its better to use
STL algorithms in this case and not to write this kind of explicit
loops so those type of troubles will not arise in the first place

Jan 9 '07 #4

Rolf Magnus wrote:
lovecreatesbea. ..@gmail.com wrote:
In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.

They do? Well, I do that when using iterators, but for a loop using an
integer loop counter, I use <.
The following small snippet erases punctuations in a string. It works
well with < used in the for loop but it breaks when != is used instead.

#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";//s: i18n
//for (string::size_t ype sz = 0; sz < s.size(); ++sz){
/*works with < */
for (string::size_t ype sz = 0; sz != s.size(); ++sz){
/*doesn't work with != */
try{
if (ispunct(s.at(s z))){
s.erase(sz, 1);
}
}catch(exceptio n &e){
cout << e.what() << endl;
}
}
cout << s << endl;
}

The problem is that s.size() will be reduced by 1 when you erase a
character. When the last character in your string is removed, your
index "jumps" over the end of the string, so sz will be greater than
s.size(). Therefore the version with < works, but not the one with !=.

Here is a table that shows what it looks like at the beginning of each loop
iteration:

index size character
0 13 h
1 13 e
2 13 l
3 13 l
4 13 o
5 13 , -erased
6 12 w -space is jumped over
7 12 o
8 12 r
9 12 l
10 12 d
11 12 ! -erased
12 11 <none -index is past string end
Thank you, and thank you all.

Yes, the problem in my last code snippet is not because of those two
operators.
I write a new one. I hope this one doesn't have so many errors like the
last one.

#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";
string::size_ty pe sz = s.size();

cout << s << endl;
for(string::siz e_type idx=0; idx!=sz; ++idx){
//...; idx<sz; ... works
try{
if(ispunct(s.at (idx))){
s.erase(idx, 1);
idx--;
sz--;
}
}catch(exceptio n &e){
cout << e.what() << endl;
}
}
cout << s << endl;

return 0;
}

Jan 9 '07 #5
Mark P <us****@fall200 5REMOVE.fastmai lCAPS.fmwrote in news:UAJoh.3029 8
$h*****@newssvr 11.news.prodigy .net:
lovecreatesbea. ..@gmail.com wrote:
>In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.
You may want to look at the context in which that's used. That "rule"
applies to using iterators in a loop.
[snip]
of bounds with sz, throwing an out_of_range exception. In general I'd
prefer < to != for loop continuation conditions.
I'd amend that statement to clarify about what your using as a loop
continuation condition. Using < when working with iterators may not work.

Jan 9 '07 #6
In article <11************ **********@v33g 2000cwv.googleg roups.com>,
"lovecreatesbea ...@gmail.com" <lo************ ***@gmail.comwr ote:
In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.

The following small snippet erases punctuations in a string. It works
well with < used in the for loop but it breaks when != is used instead.

#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";//s: i18n
//for (string::size_t ype sz = 0; sz < s.size(); ++sz){
/*works with < */
for (string::size_t ype sz = 0; sz != s.size(); ++sz){
/*doesn't work with != */
try{
if (ispunct(s.at(s z))){
s.erase(sz, 1);
}
}catch(exceptio n &e){
cout << e.what() << endl;
}
}
cout << s << endl;
}
I think the above could be done in a better way:

int main() {
string s = "hello, world!";
// first skip through the string to the first punct
string::size_ty pe pos = 0;
while ( pos != s.size() && !ispunct(s[pos]) )
++pos;
// if a punct was found...
if ( pos != s.size() )
{
// start shifting characters to the left,
// overwriting any puncts found along the way
string::size_ty pe index = pos++;
while ( pos != s.size() ) {
if ( !ispunct(s[pos]) ) {
s[index++] = s[pos];
}
++pos;
}
s.resize( index );
}
cout << s << '\n';
}

Of course this simplest and most idiomatic way would be:

bool is_punct( char c ) {
return ispunct( c );
}

int main() {
string s = "hello, world!";
s.erase( remove_if( s.begin(), s.end(), &is_punct ), s.end() );
cout << s << '\n';
}
Jan 9 '07 #7
Daniel T. wrote:
In article <11************ **********@v33g 2000cwv.googleg roups.com>,
"lovecreatesbea ...@gmail.com" <lo************ ***@gmail.comwr ote:
Of course this simplest and most idiomatic way would be:

bool is_punct( char c ) {
return ispunct( c );
}

int main() {
string s = "hello, world!";
s.erase( remove_if( s.begin(), s.end(), &is_punct ), s.end() );
cout << s << '\n';
}
I don't understand why do you need the is_punct() wrapper, cannot ispunct()
work directly as in:
s.erase( remove_if( s.begin(), s.end(), &ispunct ), s.end() );

--
Dizzy
http://dizzy.roedu.net

Jan 9 '07 #8
Dizzy wrote:
I don't understand why do you need the is_punct() wrapper, cannot
ispunct() work directly as in:
s.erase( remove_if( s.begin(), s.end(), &ispunct ), s.end() );
There is a problem with the direct use of functions of the ispunct family,
his siganture and return type can give problems to choose the appropriate
template parameters. And there can be other problems if the implemenation
use signed char in the plain char type. The less problematic solution will
be a wrapper that calls ispunct (static_cast <unsigned char(c) )

--
Salu2
Jan 9 '07 #9
lovecreatesbea. ..@gmail.com wrote:
In C++ Primer 4th, sec 3.3.2, it states that C++ programmers use !=
rather than < in a for loop.
Not smart programmers, who understand what it means for a loop guard
test to check for the correct precondition.

Fact is, if there is some loop variable i, and a limiting value N, and
if it is incorrect to execute the loop body if i is equal to N, or if i
is greater than N, then the proper guard for executing that loop body
is (i < N).

The test (i != N) only works when other logic has already ensured that
(i <= N) is true. That other logic is usually the fact N is
nonnegative, and that i starts at value 0 (and so i <= N) is initially
true, and that i increments by one in each loop iteration toward the
limiting value, and that N does not change.

The correct test (i < N) doesn't rely on any such assumptions. It
doesn't matter what happens to the value of i in each iteration.
The following small snippet erases punctuations in a string. It works
well with < used in the for loop but it breaks when != is used instead.
That's because the body of the loop changes N. If N is a moving target,
then the invariant (i <= N) does not hold from one iteration to the
next. On one iteration, it could be that i == N - 1. But then, i
increments, and N decrements, so that i is suddenly N + 1.
#include <string>
#include <iostream>
#include <exception>
#include <cctype>
using namespace std;

int main(){
string s = "hello, world!";//s: i18n
//for (string::size_t ype sz = 0; sz < s.size(); ++sz){
/*works with < */
for (string::size_t ype sz = 0; sz != s.size(); ++sz){
/*doesn't work with != */
try{
if (ispunct(s.at(s z))){
s.erase(sz, 1);
}
You have another bug here anyway, because if you erase an element of
the string, then you must not increment the sz index. By doing that,
you skip a character, which could be a punctuation character.

Imagine that the action of erase is like that of the Del key on your
keyboard in a typical text editor. When you use Del, the character
under the cursor is eaten, and everything after it moves one position
to the left. If you wanted to delete several punctuation characters in
a row, you'd type Del several times without having to move the cursor.

Similarly, the zs ``cursor'' must not move while characters are being
deleted; after each erasure, the next character to be processed shifts
into the current position, and so that position of the string must be
reevaluated.

If that logic is corrected, then the != test will work, since in any
given iteration, only the s.size() value or the sz value will change,
not both at the same time. Either the size decrements by one, bringing
it closer to sz, or sz increments by one closer to s.size().

Jan 10 '07 #10

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

Similar topics

10
10976
by: george | last post by:
Can anyone help? I query a database and return a result on the column "reference". There might be 7 listings. Each row is displayed in a table, with links through to a detail page. I am working on having a "previous" record and a "next" record link on the detail page. This code below works, for the "next" record, by searching the values in the array $myarray for the variable $ref. It then returns the key value and the key value, as a...
6
2509
by: Some Clown | last post by:
Greetings, I'm trying to figure out how to loop through a vector of strings, searching each item as I go for either a boolean condition or a "contains" test. So if my vector is called 'v' I need to test v.0 for a boolean condition, then test v.1 and put the results in a new string, etc. I've tried several methods, none of which have worked. I've also been looking through my shiny "The C++ Programming Language" guide, but that's not...
7
2999
by: Jose Cuthberto | last post by:
WRAPPER CODE FOR A SET OF HTML FILES, AND BUTTON BAR LOOKS LIKE BELOW: |< < <> > >| => <= O' (magnifying glass for small gif text) I have a number of isolated html files for a 1000 page html document. The .htm files have associated gifs, anchors, using NAME and HREF attributes. The htmls are all flat, ie in the same directory but they are named like chapsec_subsec_page.htm, specifically, a1_1_page_20.htm. The gifs are in a separate...
7
2602
by: John Smith | last post by:
Why in the printout of the following code s, t, and u only go up to 9 but w and x 10? I would think they would at least go up to the same number, be it 9 or 10. The last line of the printout is: column 9 row 9 u 9 v 0 w 10 x 10 y 1 z 48652 ----------------------------------------- for(s = 0; s < 9; s++) for(t = 0; t < 9; t++)
5
2203
by: zaemin | last post by:
From a web-site that teaches optimization for c, I saw bellow optimization rule. int fact1_func (int n) { int i, fact = 1; for (i = 1; i <= n; i++) fact *= i; return (fact);
4
2544
by: Jim Bancroft | last post by:
Hi everyone, I've been working with ASP.Net for about a month, and in all the samples I've seen the authors know ahead of time how many DropDownLists or Labels they're going to need. My problem is that I don't always know at design time how many (for instance) DropDownLists I'll need. As an example, one of my old asp pages queries a table and loops through the resulting recordset, adding one DropDownList per entry and populating it...
6
2259
by: Gonzalo Monzón | last post by:
Hi all! I have been translating some Python custom C extension code into Python, as I need these modules to be portable and run on a PocketPC without the need of compile (for the purpose its a must 2.4 as it is the last PythonCE release with great improvements). But I've been stuck with a script wich does not work as expected once translated to python, 2.4
32
4014
by: T. Crane | last post by:
Hi, I'm struggling with how to initialize a vector<vector<double>> object. I'm pulling data out of a file and storing it in the vector<vector<double>object. Because any given file will have a large amount of data, that I read off using an ifstream object, I don't want to use the push_back method because this grows the vector<vector<double>dynamically, and that will kill my execution time. So, I want to reserve space first, using, of...
4
11934
by: mark4asp | last post by:
I have an element, report which contains tags which have been transformed. E.g. <pis &lt;p&gt <myXml> <report>This text has html tags in it.&lt;p&gt which but <has been changed to &lt;&gt</report> </myXml> I there a way that the XSLT transformation can render the content as html rather than text?
0
8604
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,...
1
8897
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8862
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7729
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
6521
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
5860
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
4370
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...
1
3050
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
2002
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.