BorlandTalk.com Forum Index BorlandTalk.com
Borland discussion newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

vector weirdness?
Goto page 1, 2  Next
 
Post new topic   Reply to topic    BorlandTalk.com Forum Index -> C++ Builder (Language C++)
View previous topic :: View next topic  
Author Message
Jeff Kish
Guest





PostPosted: Thu Jun 23, 2005 10:09 am    Post subject: vector weirdness? Reply with quote



Greetings.

I am using borland cbuilder 6 with patches.
I had a program that worked fine on xp and 2003 server.
on Windows 2000, much to my chagrin this code repeated a loop many
times more than the number of entries in the vector.. note that
vAsOldPhrases is a vector of AnsiString:



for (int nIndex = 0; nIndex < vAsOldPhrases.size(); nIndex++)
{
//do stuff
}



This code which I replace it did not exhibet the psychotic symptoms.

int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)
{
//do stuff
}


Is what I did a known problem, incorrect use of the language, or just
something that should not of happened, and maybe I just "moved" the
problem by changing the code?


Thanks
Jeff

Jeff Kish
Back to top
Andrue Cope [TeamB]
Guest





PostPosted: Thu Jun 23, 2005 10:22 am    Post subject: Re: vector weirdness? Reply with quote



Jeff Kish wrote:

Quote:
Is what I did a known problem, incorrect use of the language, or just
something that should not of happened, and maybe I just "moved" the
problem by changing the code?

That depends on what 'Do stuff' did. Please post a compilable code
snippet.

Quote:
int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)

I always do this when I'm not using iterators. I've found that there is
a significant (and surprising) penalty in calling .size() at least with
the old Rogue Wave library.
--
Andrue Cope [TeamB]
[Bicester, Uk]
http://info.borland.com/newsgroups/guide.html

Back to top
Hendrik Schober
Guest





PostPosted: Thu Jun 23, 2005 10:22 am    Post subject: Re: vector weirdness? Reply with quote



Jeff Kish <jeff.kish (AT) mro (DOT) com> wrote:
Quote:
[...]
for (int nIndex = 0; nIndex < vAsOldPhrases.size(); nIndex++)
{
//do stuff
}

Note: The correct index type for 'std::evctor is 'std::evctor<T>::size_type', not 'int'.

Quote:
This code which I replace it did not exhibet the psychotic symptoms.

int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)
{
//do stuff
}


Is what I did a known problem, incorrect use of the language, or just
something that should not of happened, and maybe I just "moved" the
problem by changing the code?

What's '// do stuff'? Does it, by any chance,
modify the vector's size

Quote:
Jeff

Jeff Kish

Schobi

--
[email]SpamTrap (AT) gmx (DOT) de[/email] is never read
I'm Schobi at suespammers dot org

"Coming back to where you started is not the same as never leaving"
Terry Pratchett



Back to top
Ed Mulroy
Guest





PostPosted: Thu Jun 23, 2005 10:30 am    Post subject: Re: vector weirdness? Reply with quote

Yes, maybe you did move the problem with the change in the code. I suspect
something in the part you identify as '//do stuff', including what is in any
functions called in '//do stuff'.

There are a couple of other things worth mentioning about that code.

Code 1
Quote:
for (int nIndex = 0; nIndex < vAsOldPhrases.size(); nIndex++)
{
//do stuff
}

Code 2
Quote:
int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)
{
//do stuff
}

Code 1 is inefficient as it calls a class member function each time through
the loop to learn a value which is fixed for the duration of the loop.

Both Code 1 and Code 2 use post-increment when pre-increment is needed.
While the compiler's optimizer is well aware of that bad habit and optimizes
it for integers such as are used here, that habit can greatly hurt
efficiency and code size in any code where the incremented type is an item
with an overloaded post-increment operator.

So Code 1 should change from this:
for (int nIndex = 0; nIndex < vAsOldPhrases.size(); nIndex++)

to something like this:
for (int nIndex = 0, endit = vAsOldPhrases.size(); nIndex < endigl;
++nIndex)

And Code 2 from this:
int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)

to something like this:
int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; ++nIndex)

Yes, these things may seem trivial here, but in a program they have the
potential of greatly slowing the execution of a program and making the code
larger. Also, because of the access of the size() member function in each
loop an error in the code which alters the number of members in the vector
will be more difficult to detect and debug.

.. Ed

Quote:
Jeff Kish wrote in message
news:592lb1tsdrhllsjscjm4n6b94pebk2bfjp (AT) 4ax (DOT) com...
Greetings.

I am using borland cbuilder 6 with patches.
I had a program that worked fine on xp and 2003 server.
on Windows 2000, much to my chagrin this code repeated
a loop many times more than the number of entries in the
vector.. note that vAsOldPhrases is a vector of AnsiString:



for (int nIndex = 0; nIndex < vAsOldPhrases.size(); nIndex++)
{
//do stuff
}



This code which I replace it did not exhibet the psychotic symptoms.

int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)
{
//do stuff
}


Is what I did a known problem, incorrect use of the language, or just
something that should not of happened, and maybe I just "moved" the
problem by changing the code?



Back to top
Duane Hebert
Guest





PostPosted: Thu Jun 23, 2005 11:06 am    Post subject: Re: vector weirdness? Reply with quote


"Ed Mulroy" <dont_email_me (AT) bitbuc (DOT) ket> wrote

Quote:
Code 1 is inefficient as it calls a class member function each time through
the loop to learn a value which is fixed for the duration of the loop.

Well the OP's problem is probably that the value "size" is
not fixed through the loop as he's likely altering it <g> though
you're point is well taken. Why not get the size once as you
suggest?


Quote:
Both Code 1 and Code 2 use post-increment when pre-increment is needed.
While the compiler's optimizer is well aware of that bad habit and optimizes
it for integers such as are used here, that habit can greatly hurt
efficiency and code size in any code where the incremented type is an item
with an overloaded post-increment operator.

So Code 1 should change from this:
for (int nIndex = 0; nIndex < vAsOldPhrases.size(); nIndex++)

to something like this:
for (int nIndex = 0, endit = vAsOldPhrases.size(); nIndex < endigl;
++nIndex)

This would be my preferred format as well, except that
nIndex should by size_t or size_type. In most situations,
comparing an int to a size_t would emit a warning about
comparing signed and unsigned types. I don't believe
Borland emits this warning but GCC and MSVC do.

Quote:
Yes, these things may seem trivial here, but in a program they have the
potential of greatly slowing the execution of a program and making the code
larger. Also, because of the access of the size() member function in each
loop an error in the code which alters the number of members in the vector
will be more difficult to detect and debug.

Agreed.



Back to top
Duane Hebert
Guest





PostPosted: Thu Jun 23, 2005 11:07 am    Post subject: Re: vector weirdness? Reply with quote


"Hendrik Schober" <SpamTrap (AT) gmx (DOT) de> wrote


Quote:
Note: The correct index type for 'std::evctor<T>'
is 'std::evctor<T>::size_type', not 'int'.

Hello Schobi. Do you know of any reason that
size_t shouldn't be used instead of size_type?

Just curious.



Back to top
Hendrik Schober
Guest





PostPosted: Thu Jun 23, 2005 11:15 am    Post subject: Re: vector weirdness? Reply with quote

Duane Hebert <spoo (AT) flarn2 (DOT) com> wrote:
Quote:
"Hendrik Schober" <SpamTrap (AT) gmx (DOT) de> wrote


Note: The correct index type for 'std::evctor<T>'
is 'std::evctor<T>::size_type', not 'int'.

Hello Schobi. Do you know of any reason that
size_t shouldn't be used instead of size_type?

Just curious.

I don't know. I suppose they will be the same
in all implementations, even if the standard
allows them to be different types. (Which I
don't know.)
However, why should use one instead of the
other?

Schobi

--
[email]SpamTrap (AT) gmx (DOT) de[/email] is never read
I'm Schobi at suespammers dot org

"Coming back to where you started is not the same as never leaving"
Terry Pratchett



Back to top
Duane Hebert
Guest





PostPosted: Thu Jun 23, 2005 11:34 am    Post subject: Re: vector weirdness? Reply with quote


"Hendrik Schober" <SpamTrap (AT) gmx (DOT) de> wrote


Quote:
I don't know. I suppose they will be the same
in all implementations, even if the standard
allows them to be different types. (Which I
don't know.)
However, why should use one instead of the
other?

No real reason. Just that size_t is shorter
to write than std::vector<whatever>::size_type.

Porting from Borland to MSVC we had zillions
of warnings from some of the team using int.
I had the lovely task of changing this so I just
replaced all with size_t. I could do a bunch with
search and replace in files. (Borland should
have this feature in their IDE BTW)

Seeing your post, I wanted to make sure that I
didn't waste my time by replacing something
incorrect with something that may also be
incorrect <g>



Back to top
Jeff Kish
Guest





PostPosted: Thu Jun 23, 2005 12:05 pm    Post subject: Re: vector weirdness? Reply with quote

On Thu, 23 Jun 2005 11:22:47 +0100, "Andrue Cope [TeamB]"
<no.spam (AT) not (DOT) a.valid.address> wrote:

Quote:
Jeff Kish wrote:

Is what I did a known problem, incorrect use of the language, or just
something that should not of happened, and maybe I just "moved" the
problem by changing the code?

That depends on what 'Do stuff' did. Please post a compilable code
snippet.

int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)

I always do this when I'm not using iterators. I've found that there is
a significant (and surprising) penalty in calling .size() at least with
the old Rogue Wave library.
Well this is embarassing. Well, I included the text from the unit1.h

and unit1.cpp.
There is a statusbar, richedit and a pushbutton on the form.

I pull out as much code as I can, and now it never stops reading the
input file (endless loop).

Is there some known issues with fstreams, or perhaps just with fools
that don't know what they are doing?

sigh.. I don't know what's wrong.. thanks for any patience or insight.

Note.. the three input files are (where is normal in windows.. these are just 4 line text files from notepad):

one.txt = one<cr> one<cr> one<cr> one<cr>
two.txt = one two<cr>one two<cr>one two<cr>one two<cr>
three.txt = one two three four<cr>one two three four<cr>one two three
four<cr>one two three four<cr>
four.txt = one two three four<cr>one two three four<cr>one two three
four<cr>one two three four<cr>


HEADER

//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <vcl.h>
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ComCtrls.hpp>
//---------------------------------------------------------------------------
#include <string>
#include <vector>

using namespace std;

typedef vector<AnsiString> vAnsiString;
typedef vector<AnsiString>::iterator vAnsiStringIterator;
typedef vector<string> vString;
typedef vector<string>::iterator vStringIterator;
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
TStatusBar *StatusBar1;
TRichEdit *RichEdit1;
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
void testCall(vAnsiString involdphrases, vAnsiString
invnewphrases);
void SearchAndReplaceFileText(AnsiString asInputFileSpec,
AnsiString asOldPhrase, AnsiString asNewPhrase,
vAnsiString & inVErrors);
void SearchAndReplaceFileTextWildCard( AnsiString asFileWildCard,
vAnsiString vAsOldPhrases, vAnsiString vAsNewPhrases,
vAnsiString & inVErrors,
char * useWildCardSpec );

};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


BODY

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <fstream.h>
#include <iostream.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------


__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
//do something here
vAnsiString vAsOldPhrases;
vAnsiString vAsNewPhrases;

vAsOldPhrases.push_back("one");
vAsOldPhrases.push_back("two");
vAsOldPhrases.push_back("three");
vAsOldPhrases.push_back("four");
vAsNewPhrases.push_back("ONE TWO THREE FOUR FIVE");
vAsNewPhrases.push_back("TWO THREE FOUR FIVE");
vAsNewPhrases.push_back("THREE FOUR FIVE");
vAsNewPhrases.push_back("FOUR FIVE");
testCall(vAsOldPhrases, vAsNewPhrases);
}
//---------------------------------------------------------------------------


void TForm1::testCall(vAnsiString vAsOldPhrases, vAnsiString
vAsNewPhrases)
{
AnsiString AsOldString;
AnsiString AsNewString;
vAnsiString inVErrors;

SearchAndReplaceFileTextWildCard( "c:\temp\TEST\",
vAsOldPhrases, vAsNewPhrases,
inVErrors,
"*.txt" );
}

void TForm1::SearchAndReplaceFileText(AnsiString asInputFileSpec,
AnsiString asOldPhrase, AnsiString asNewPhrase,
vAnsiString & inVErrors)
//throw (AnsiString)
{
AnsiString AsDebugString = "In search and replace for file: " +
asInputFileSpec;
//DebugOut(asInputFileSpec.c_str());
//CursorSaver myCursor;

try
{
// Do some lengthy operation

AnsiString asSearchPhrase = asOldPhrase.Trim();
AnsiString asReplacePhrase = asNewPhrase.Trim();
// replace the text..
// first open the files
ifstream infile;
infile.open(asInputFileSpec.c_str());
if (infile.fail())
{
MessageBeep(0);
AnsiString asErr = "Error opening input file " +
asInputFileSpec;
inVErrors.push_back(asErr);
StatusBar1->SimpleText = asErr;
throw asErr;
}
// now input is open.. lets process them
char buff[1024];
AnsiString asToken;
vString vInputStrings;
while (!infile.eof())
{
infile.getline(buff,sizeof(buff));
// do something to the line
AnsiString asTemp = buff;
AnsiString asTemp2;
asTemp2 = StringReplace(asTemp,asSearchPhrase,
asReplacePhrase,
TReplaceFlags() << rfReplaceAll <<
rfIgnoreCase);
string strTemp = asTemp2.c_str();
vInputStrings.push_back(strTemp);

// outfile << asTemp2.c_str() << endl;
}
infile.close();
DeleteFile(asInputFileSpec);
ofstream outfile(asInputFileSpec.c_str(), ios::trunc);
if (outfile.fail())
{
MessageBeep(0);
AnsiString asErr = "Error opening input file " +
asInputFileSpec;
inVErrors.push_back(asErr);
StatusBar1->SimpleText = asErr;
infile.close();
throw asErr;
}
outfile.flush();
vStringIterator Iter;
for (Iter = vInputStrings.begin();
Iter != vInputStrings.end();
Iter++)
{
string asLine = *Iter;
outfile << asLine.c_str() << endl;
{
//AnsiString AsTemp = asLine.c_str();
//DebugOut(AsTemp.c_str());
} }
outfile.close();
outfile.flush();
}
catch (AnsiString asEx)
{
throw asEx;
}
catch (...)
{
throw (AnsiString) "There was an unexpected failure. Please
exit the application";
}
}
void TForm1::SearchAndReplaceFileTextWildCard( AnsiString
asFileWildCard,
vAnsiString vAsOldPhrases, vAnsiString vAsNewPhrases,
vAnsiString & inVErrors,
char * useWildCardSpec ) //throw (AnsiString)
{
//CursorSaver myCursor;

AnsiString AsTargetFile;
AnsiString AsOldString;
AnsiString AsNewString;

AnsiString asThePath = ExtractFilePath(asFileWildCard);
TSearchRec sr;
if ((useWildCardSpec != NULL) && (strlen(useWildCardSpec) > 0))
{
asFileWildCard = asThePath + useWildCardSpec;
}
int iAttributes = faAnyFile & ~faDirectory;
try
{
if (vAsOldPhrases.size() != vAsNewPhrases.size())
{
AnsiString asErr = " Error replacing text in sql script file:
" + asFileWildCard +
" number of old strings to replace does not match number
of new strings to replace ";
throw asErr;
}
if (FindFirst(asFileWildCard.c_str(), iAttributes, sr) == 0)
{
do
{
AsTargetFile = asThePath + (AnsiString) sr.Name;
Form1->RichEdit1->Lines->
Add("Processing " + AsTargetFile );
Application->ProcessMessages();

/* TODO : SIZE HERE SEEMS TO BE PROBLEMATIC */
int nElementCount = vAsOldPhrases.size();
for (int nIndex = 0; nIndex < nElementCount; nIndex++)
{
AsOldString = vAsOldPhrases[nIndex];
AsNewString = vAsNewPhrases[nIndex];
Application->ProcessMessages();

SearchAndReplaceFileText(AsTargetFile,
AsOldString,
AsNewString,
inVErrors);
}
} while (FindNext(sr) == 0);
FindClose(sr);
}
}
catch (AnsiString asEx)
{
AnsiString asErr = asEx + " " +
" Error replacing text in sql script file: " + AsTargetFile +
(AnsiString) ".. attempted to replace " + AsOldString +
(AnsiString)" with " + AsNewString;
inVErrors.push_back(asErr);
throw asEx;
}
}
Jeff Kish

Back to top
Jeff Kish
Guest





PostPosted: Thu Jun 23, 2005 12:33 pm    Post subject: Re: vector weirdness? Reply with quote

On Thu, 23 Jun 2005 07:06:02 -0400, "Duane Hebert" <spoo (AT) flarn2 (DOT) com>
wrote:

Quote:

"Ed Mulroy" <dont_email_me (AT) bitbuc (DOT) ket> wrote

Code 1 is inefficient as it calls a class member function each time through
the loop to learn a value which is fixed for the duration of the loop.

Well the OP's problem is probably that the value "size" is
not fixed through the loop as he's likely altering it <g> though
you're point is well taken. Why not get the size once as you
suggest?


Both Code 1 and Code 2 use post-increment when pre-increment is needed.
While the compiler's optimizer is well aware of that bad habit and optimizes
it for integers such as are used here, that habit can greatly hurt
efficiency and code size in any code where the incremented type is an item
with an overloaded post-increment operator.

So Code 1 should change from this:
for (int nIndex = 0; nIndex < vAsOldPhrases.size(); nIndex++)

to something like this:
for (int nIndex = 0, endit = vAsOldPhrases.size(); nIndex < endigl;
++nIndex)

This would be my preferred format as well, except that
nIndex should by size_t or size_type. In most situations,
comparing an int to a size_t would emit a warning about
comparing signed and unsigned types. I don't believe
Borland emits this warning but GCC and MSVC do.

Yes, these things may seem trivial here, but in a program they have the
potential of greatly slowing the execution of a program and making the code
larger. Also, because of the access of the size() member function in each
loop an error in the code which alters the number of members in the vector
will be more difficult to detect and debug.

Agreed.

Thanks.

.... what is endigl, i.e. how do you compute it in this:
Quote:
to something like this:
for (int nIndex = 0, endit = vAsOldPhrases.size(); nIndex < endigl;
++nIndex)
sigh.. appreciate the feedback.

I'm taking this back from the discussion:

1 - there is a much better way to use the for statement, especially
with regards to preincrement (why again is it better?)
2 - something else in the code is probably altering some size since it
should work anyway.

Any other goofs or analysis.. well I appreciate it.

Jeff Kish

Back to top
Gillmer J. Derge [TeamB]
Guest





PostPosted: Thu Jun 23, 2005 12:40 pm    Post subject: Re: vector weirdness? Reply with quote

Duane Hebert wrote:
Quote:
Seeing your post, I wanted to make sure that I
didn't waste my time by replacing something
incorrect with something that may also be
incorrect

The standard defines a container's size_type as being some
implementation defined unsigned integral type that's large enough to
hold any non-negative value of difference_type. In practice, that's
probably size_t, but it doesn't need to be. However ...

The default allocator class, std::allocator, does explicitly define its
size_type to be size_t. Furthermore, the standard containers are
allowed (but not required) to assume that any allocator defines its
size_type to be size_t.

In practice, this means that if you write an allocator that you want to
work with standard containers, you better use size_t. And unless the
container is doing some weird back and forth type translation, there's
almost no way a container could use any type other than size_t as its
size_type.

Still, having said all that, I don't think it's "illegal" or impossible
to use a different type. Just stupid.

--
Gillmer J. Derge [TeamB]

Back to top
Gillmer J. Derge [TeamB]
Guest





PostPosted: Thu Jun 23, 2005 12:48 pm    Post subject: Re: vector weirdness? Reply with quote

Jeff Kish wrote:
Quote:
1 - there is a much better way to use the for statement, especially
with regards to preincrement (why again is it better?)

In your case, using it on an integer, there's probably not really any
difference, but there could be. The assumption that there's no
difference is based on the assumption that the compiler is smart enough
to optimize your use into a pre-increment. The difference is more
obvious when you think about pre-increment and post-increment as applied
to some user-defined type like an iterator.

Pre-increment increases the value by 1 and returns the new value.
Post-increment, on the other hand, increases the value by 1 and returns
the *old* value. This means that the old value needs to be kept around
in a copy of the original object. A typical implementation would be
something like this:

T& operator++() { // pre-increment
next();
return *this;
}

T operator++(int) { // post-increment
T tmp = *this;
next();
return tmp;
}

It's that extra copy that introduces the inefficiency. If you need
post-increment then by all means use it, but if you're just doing
shorthand for "x = x + 1" then pre-increment might be faster and will
almost certainly be no slower.

--
Gillmer J. Derge [TeamB]

Back to top
Jeff Kish
Guest





PostPosted: Thu Jun 23, 2005 1:33 pm    Post subject: Re: vector weirdness? Reply with quote

On Thu, 23 Jun 2005 08:48:00 -0400, "Gillmer J. Derge [TeamB]"
<spam (AT) gillmerderge (DOT) com> wrote:

Quote:
Jeff Kish wrote:
1 - there is a much better way to use the for statement, especially
with regards to preincrement (why again is it better?)

In your case, using it on an integer, there's probably not really any
difference, but there could be. The assumption that there's no
difference is based on the assumption that the compiler is smart enough
to optimize your use into a pre-increment. The difference is more
obvious when you think about pre-increment and post-increment as applied
to some user-defined type like an iterator.

Pre-increment increases the value by 1 and returns the new value.
Post-increment, on the other hand, increases the value by 1 and returns
the *old* value. This means that the old value needs to be kept around
in a copy of the original object. A typical implementation would be
something like this:

T& operator++() { // pre-increment
next();
return *this;
}

T operator++(int) { // post-increment
T tmp = *this;
next();
return tmp;
}

It's that extra copy that introduces the inefficiency. If you need
post-increment then by all means use it, but if you're just doing
shorthand for "x = x + 1" then pre-increment might be faster and will
almost certainly be no slower.
Thanks.

And.. I should use something besides an integer? i.e. size_t or
whatever?


Regards
Jeff Kish

Back to top
Jeff Kish
Guest





PostPosted: Thu Jun 23, 2005 1:39 pm    Post subject: Re: vector weirdness? Reply with quote

On Thu, 23 Jun 2005 09:33:32 -0400, Jeff Kish <jeff.kish (AT) mro (DOT) com>
wrote:

Quote:
On Thu, 23 Jun 2005 08:48:00 -0400, "Gillmer J. Derge [TeamB]"
[email]spam (AT) gillmerderge (DOT) com[/email]> wrote:

Jeff Kish wrote:
1 - there is a much better way to use the for statement, especially
with regards to preincrement (why again is it better?)

In your case, using it on an integer, there's probably not really any
difference, but there could be. The assumption that there's no
difference is based on the assumption that the compiler is smart enough
to optimize your use into a pre-increment. The difference is more
obvious when you think about pre-increment and post-increment as applied
to some user-defined type like an iterator.

Pre-increment increases the value by 1 and returns the new value.
Post-increment, on the other hand, increases the value by 1 and returns
the *old* value. This means that the old value needs to be kept around
in a copy of the original object. A typical implementation would be
something like this:

T& operator++() { // pre-increment
next();
return *this;
}

T operator++(int) { // post-increment
T tmp = *this;
next();
return tmp;
}

It's that extra copy that introduces the inefficiency. If you need
post-increment then by all means use it, but if you're just doing
shorthand for "x = x + 1" then pre-increment might be faster and will
almost certainly be no slower.
Thanks.
And.. I should use something besides an integer? i.e. size_t or
whatever?


Regards
Jeff Kish
As a closing thanks..

vector<AnsiString>::size_type nElementcount = vAsOldPhrases.size();
for (vector<AnsiString>::size_type nIndex = 0;
nIndex < nElementCount;
++nIndex)
{
//do stuff
}

note;I'm sure the //do stuff did not modify the size, but maybe some
other bugs inadvertently did in the original problem post.
Jeff Kish

Back to top
Gillmer J. Derge [TeamB]
Guest





PostPosted: Thu Jun 23, 2005 1:48 pm    Post subject: Re: vector weirdness? Reply with quote

Jeff Kish wrote:
Quote:
And.. I should use something besides an integer? i.e. size_t or
whatever?

Right, but for different reasons. Pre/post-increment will be the same
for a size_t as for any other integral type.

The issue with int is that v.size() actually returns
vector<T>::size_type which is probably size_t which is probably
something like unsigned long. This poses two problems.

1. If your vector is really, really big you could actually get back a
value that's too big to fit in an int. At that point your int size
might have a negative value or some other incorrect value, and your loop
wouldn't work. This probably isn't a realistic problem for most
applications, but there's no reason to tempt fate.

2. The compiler ought to warn you about trying to convert an unsigned
long to an int because of the potential for problem #1. Using size_t is
a simple way to avoid that warning.

Quote:
vector<AnsiString>::size_type nElementcount = vAsOldPhrases.size();
for (vector<AnsiString>::size_type nIndex = 0;
nIndex < nElementCount;
++nIndex)
{
//do stuff
}

Yep. I like to put both the index and the size variables inside the loop.

for (vector nElementCount = vAsOldPhrases.size();
nIndex < nElementCount;
++nIndex)
{
//do stuff
}

--
Gillmer J. Derge [TeamB]

Back to top
Display posts from previous:   
Post new topic   Reply to topic    BorlandTalk.com Forum Index -> C++ Builder (Language C++) All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.