473,597 Members | 2,146 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cannot compile the following example code (person-pointer)

Hi,

I don't understand these errors I get:

g++ Persort.cpp
Persort.cpp: In function 'int main()':
Persort.cpp:43: error: name lookup of 'j' changed for new ISO 'for' scoping
Persort.cpp:37: error: using obsolete binding at 'j'
- - - - -
#include <iostream>
#include <string> //for string class
using namespace std;
////////////////////////////////////////////////////////////////
class person //class of persons
{
protected:
string name; //person's name
public:
void setName() //set the name
{ cout << "Enter name: "; cin >> name; }
void printName() //display the name
{ cout << endl << name; }
string getName() //return the name
{ return name; }
};
////////////////////////////////////////////////////////////////
int main()
{
void bsort(person**, int); //prototype
person* persPtr[100]; //array of pointers to persons
int n = 0; //number of persons in array
char choice; //input char

do { //put persons in array
persPtr[n] = new person; //make new object
persPtr[n]->setName(); //set person's name
n++; //count new person
cout << "Enter another (y/n)? "; //enter another
cin >> choice; // person?
}
while( choice=='y' ); //quit on 'n'

cout << "\nUnsorted list:";
for(int j=0; j<n; j++) //print unsorted list
{ persPtr[j]->printName(); }

bsort(persPtr, n); //sort pointers

cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
{ persPtr[j]->printName(); }
cout << endl;
return 0;
} //end main()
//--------------------------------------------------------------
void bsort(person** pp, int n) //sort pointers to persons
{
void order(person**, person**); //prototype
int j, k; //indexes to array

for(j=0; j<n-1; j++) //outer loop
for(k=j+1; k<n; k++) //inner loop starts at outer
order(pp+j, pp+k); //order the pointer contents
}
//--------------------------------------------------------------
void order(person** pp1, person** pp2) //orders two pointers
{ //if 1st larger than 2nd,
if( (*pp1)->getName() > (*pp2)->getName() )
{
person* tempptr = *pp1; //swap the pointers
*pp1 = *pp2;
*pp2 = tempptr;
}
}

- - - - -

How to fix them?

With visual studio, I could go to msdn.com and look up all kinds of
different errors. Is there something like that for g++?
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 25 '06 #1
26 2871
Martin Jørgensen wrote:
Persort.cpp: In function 'int main()':
Persort.cpp:43: error: name lookup of 'j' changed for new ISO 'for'
scoping
Persort.cpp:37: error: using obsolete binding at 'j'
Next time copy parts of the error message into Google - it should easily
find this one.
for(int j=0; j<n; j++) //print unsorted list .... for(j=0; j<n; j++) //print sorted list


The ISO C++ Standard changed the scope of 'j'. It formerly lived in the
block around the first for loop. Now it lives only in this for-loop and its
controlled statement or block.

The second for loop now sees no 'j'. Instead of just barfing "unknown
identifier" or something, the g++ maintainers intercepted this particular
situation and gave you a complete error message describing the difference
between the old and new compiler behavior.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 25 '06 #2
On Sat, 25 Mar 2006 17:37:20 +0100, Martin Jørgensen
<un*********@sp am.jay.net> wrote:
Hi,

I don't understand these errors I get:

g++ Persort.cpp
Persort.cpp: In function 'int main()':
Persort.cpp:43 : error: name lookup of 'j' changed for new ISO 'for' scoping
Persort.cpp:37 : error: using obsolete binding at 'j'
j is only in the scope of the first "for" loop. Declare it outside of
the loop or redeclare it within the second loop.

[snip] for(int j=0; j<n; j++) //print unsorted list
{ persPtr[j]->printName(); }
j is now out of scope.

bsort(persPtr, n); //sort pointers

cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
for (int j=0; // etc.
{ persPtr[j]->printName(); }
cout << endl;
return 0;
} //end main()
//--------------------------------------------------------------
void bsort(person** pp, int n) //sort pointers to persons
{
void order(person**, person**); //prototype
int j, k; //indexes to array
These work OK because both counters are visible outside the loop
scopes.
for(j=0; j<n-1; j++) //outer loop
for(k=j+1; k<n; k++) //inner loop starts at outer
order(pp+j, pp+k); //order the pointer contents
}
//--------------------------------------------------------------
void order(person** pp1, person** pp2) //orders two pointers
{ //if 1st larger than 2nd,
if( (*pp1)->getName() > (*pp2)->getName() )
{
person* tempptr = *pp1; //swap the pointers
*pp1 = *pp2;
*pp2 = tempptr;
}
}

- - - - -

How to fix them?

With visual studio, I could go to msdn.com and look up all kinds of
different errors. Is there something like that for g++?


Have you tried:
man gcc

or:
man g++

?

--
Bob Hairgrove
No**********@Ho me.com
Mar 25 '06 #3
* Martin Jørgensen:

I don't understand these errors I get:

g++ Persort.cpp
Persort.cpp: In function 'int main()':
Persort.cpp:43: error: name lookup of 'j' changed for new ISO 'for' scoping
Persort.cpp:37: error: using obsolete binding at 'j'
- - - - -
int main()
{
for(int j=0; j<n; j++) //print unsorted list
{ persPtr[j]->printName(); }

bsort(persPtr, n); //sort pointers

cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
{ persPtr[j]->printName(); }
Here you need to write 'for( int j=0; ...', the scope of the previous
declaration of j ended at the end of that for-loop.

How to fix them?


Why not implement the program in C++ instead of C? <g>

E.g., preserving the program logic exactly (or as best I could see),
#include <algorithm> // std::sort
#include <iostream> // std::cin, std::cout
#include <istream> // operator>>
#include <ostream> // operator<<, std::endl
#include <string> // std::string
#include <vector> // std::vector

class Person
{
protected:
std::string myName;
public:
Person( std::string const& name ): myName( name ) {}
std::string name() const { return myName; }
};

std::string lineFrom( std::istream& stream )
{
std::string line;
std::getline( stream, line );
return line;
}

std::string nameFromUser()
{
std::cout << "Enter name: "; return lineFrom( std::cin );
}

bool userAffirms( std::string const& question )
{
char choice;

std::cout << question;
std::cin >> choice;
std::cin.ignore ( INT_MAX, '\n' );
return (choice != 'n'); // Can be Really Improved.
}

void printNameOf( Person const& person )
{
// Original code's newline at front preserved, but why choose that?
std::cout << std::endl << person.name();
}

void printList( std::vector<Per son> const& persons )
{
for( std::size_t i=0; i < persons.size(); ++i )
{
printNameOf( persons[i] );
}
}

bool order( Person const& a, Person const& b )
{
return a.name() < b.name();
}

int main()
{
std::vector<Per son> persons;

do
{
persons.push_ba ck( nameFromUser() );
}
while( userAffirms( "Enter another (y/n)? " ) );

std::cout << "\nUnsorted list:"; printList( persons );
std::sort( persons.begin() , persons.end(), order );
std::cout << "\nSorted list:"; printList( persons );
std::cout << std::endl;
}

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 25 '06 #4
Alf P. Steinbach wrote:
* Martin Jørgensen: -snip-
cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
{ persPtr[j]->printName(); }

Here you need to write 'for( int j=0; ...', the scope of the previous
declaration of j ended at the end of that for-loop.


Thanks.
How to fix them?

Why not implement the program in C++ instead of C? <g>

E.g., preserving the program logic exactly (or as best I could see),
#include <algorithm> // std::sort
#include <iostream> // std::cin, std::cout
#include <istream> // operator>>
#include <ostream> // operator<<, std::endl
#include <string> // std::string
#include <vector> // std::vector


This is perhaps a newbie question, but why do you like to write std:: in
front of many of the commands?
class Person
{
protected:
std::string myName;
Why not private here?
public:
Person( std::string const& name ): myName( name ) {}
std::string name() const { return myName; }
};

std::string lineFrom( std::istream& stream )
{
std::string line;
std::getline( stream, line );
return line;
}

std::string nameFromUser()
{
std::cout << "Enter name: "; return lineFrom( std::cin );
}
What is this istream all about? You're saying something like:
std::getline ( (type istream), (type string) )?
bool userAffirms( std::string const& question )
{
char choice;

std::cout << question;
std::cin >> choice;
std::cin.ignore ( INT_MAX, '\n' );
return (choice != 'n'); // Can be Really Improved.
}
What's that INT_MAX-thing doing? It's not defined anywhere here... Still
the program works.
void printNameOf( Person const& person )
{
// Original code's newline at front preserved, but why choose that?
std::cout << std::endl << person.name();
}

void printList( std::vector<Per son> const& persons )
{
for( std::size_t i=0; i < persons.size(); ++i )
{
printNameOf( persons[i] );
}
}
I haven't learned about vector's but will soon learn about it, so this
is an excellent tutorial code for me, in just 2-3 weeks :-)
bool order( Person const& a, Person const& b )
{
return a.name() < b.name();
}

int main()
{
std::vector<Per son> persons;

do
{
persons.push_ba ck( nameFromUser() );
}
while( userAffirms( "Enter another (y/n)? " ) );

std::cout << "\nUnsorted list:"; printList( persons );
std::sort( persons.begin() , persons.end(), order );
std::cout << "\nSorted list:"; printList( persons );
std::cout << std::endl;
}


Looks very nice - thanks for posting it...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 25 '06 #5
Bob Hairgrove wrote:
On Sat, 25 Mar 2006 17:37:20 +0100, Martin Jørgensen
<un*********@sp am.jay.net> wrote:

-snip-
With visual studio, I could go to msdn.com and look up all kinds of
different errors. Is there something like that for g++?

Have you tried:
man gcc

or:
man g++

?


Come on. It looks like shit, with that formatting and the search
capabilites are poor. So much information and so hard to find what is
relevant.
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 25 '06 #6
In article <17************ @news.tdc.dk>,
Martin Jørgensen <un*********@sp am.jay.net> wrote:
Hi,

I don't understand these errors I get:

g++ Persort.cpp
Persort.cpp: In function 'int main()':
Persort.cpp:43: error: name lookup of 'j' changed for new ISO 'for' scoping
Persort.cpp:37: error: using obsolete binding at 'j'
Everyone else told you what would fix the error. I'm going to critique
your program. :-)

In general, you have done an excellent job. The impression I get is that
your assignment was to write a bubble sort routine, and test it by
allowing the user to input some names, then sort and output them. If
this was not your assignment, then you probably still have some work to
do.

#include <iostream>
#include <string> //for string class
using namespace std;
////////////////////////////////////////////////////////////////
class person //class of persons
{
protected:
string name; //person's name
public:
void setName() //set the name
{ cout << "Enter name: "; cin >> name; }
void printName() //display the name
{ cout << endl << name; }
string getName() //return the name
{ return name; }
};
The invariant that a concrete class is supposed to maintain is the
single most important aspect of it.

You see, for a concrete class to be useful it must either (a) contain
more than one member-variable and maintain some sort of invariant
(guaranteed relationship) between them or (b) contain only one
member-variable and restrict its allowed values in some way (the
invariant would be that the member-variable will never be certain
values.)

Do you know what the invariant you created for this class is? If so,
express it in a comment.
////////////////////////////////////////////////////////////////
int main()
{
void bsort(person**, int); //prototype
Prototypes inside functions isn't a great idea IMO. Every module that
wants to use this bsort function should have a single place to go to get
the prototype, usually a header file. In this case, the prototype should
be outside of, and above main, but below class person.
person* persPtr[100]; //array of pointers to persons
int n = 0; //number of persons in array
Here is a perfect example for a class. There is an invariant between 'n'
and 'persPtr' such that n defines how many of the values in persPtr are
valid. Both of these variables should be in a class that has the job of
maintaining that invariant.

What if the user enters over 100 names? Whenever you use an array, you
have to insure that it's kept within bounds. Another job for the class
mentioned above?

Of course, if a class already exists that can do the job with minimal
effort, use it rather than writing your own. Consider using std::vector
char choice; //input char

do { //put persons in array
persPtr[n] = new person; //make new object
You create new objects here, but never delete them. Although the system
will clean them up upon exit, get in the habit of deleting every object
you new when you are done with it. In this case, you should go through
the array and delete all the persons before returning from main.
persPtr[n]->setName(); //set person's name
n++; //count new person
cout << "Enter another (y/n)? "; //enter another
cin >> choice; // person?
}
while( choice=='y' ); //quit on 'n'
The 'choice' variable is only used in the two lines above, yet its scope
is all of main. It's good practice to limit the scope of variables to
only the part of the program where they are actually used. This helps
insure that they don't accidentally get used incorrectly. In this case,
a function that gets the users choice and returns true if that choice is
'y' would be ideal. Then you can simply call that function inside the
while condition.
cout << "\nUnsorted list:";
for(int j=0; j<n; j++) //print unsorted list
{ persPtr[j]->printName(); }

bsort(persPtr, n); //sort pointers

cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
{ persPtr[j]->printName(); }
cout << endl;
return 0;
} //end main()
I want to talk for a second about code comments... Anyone who has
bothered to look at the definition of "bsort" will know that it sorts
pointers (after all you have a comment to that effect. :-) So the "sort
pointers" comment above is superfluous. The other two, however are
somewhat handy because they explain what several lines of code are
doing. Note however the duplication between "print unsorted list" and
"print sorted list". Ideally when you have two blocks of code alike, you
should make a function that contains the block just once, and call it
twice. On top of that, if you call this function "print_list ", it will
render these comments superfluous as well. You see, comments aren't bad,
but code that requires comments to be understood often is.
//--------------------------------------------------------------
void bsort(person** pp, int n) //sort pointers to persons
{
void order(person**, person**); //prototype
int j, k; //indexes to array

for(j=0; j<n-1; j++) //outer loop
for(k=j+1; k<n; k++) //inner loop starts at outer
order(pp+j, pp+k); //order the pointer contents
}
//--------------------------------------------------------------
void order(person** pp1, person** pp2) //orders two pointers
{ //if 1st larger than 2nd,
if( (*pp1)->getName() > (*pp2)->getName() )
{
person* tempptr = *pp1; //swap the pointers
*pp1 = *pp2;
*pp2 = tempptr;
}
}


Much like the comment I made about classes above, if a function already
exists that can do what you want, then consider using it rather than
writing your own.

In both cases (with functions and classes,) there is often something
that *almost* does what you want but not quite. You are then left with
the decision as to wether you should write something that does exactly
what you want, or write something that adapts your problem to fit its
solution. Your choice should be guided by several factors including ease
of understanding, amount of code required, as well as the performance of
the solution.

In this particular case, there are a couple general-purpose sort
routines already available in the standard library. Unless your
assignment was to write a bubble sort routine, your code would probably
be better served if you adapted one of the standard sort routines to
your purposes rather than writing your own. (a) The code needed to adapt
their solution to your purposes would be less than the code required to
create a new solution. (b) Less code (if written clearly) tends to be
easer to understand, (c) the general solution would likely still fall
within what performance requirements your program has and may even be
better. (After all the library implementors have spent much more time
perfecting their sort routines than you have.)

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 25 '06 #7
Daniel T. wrote:
In article <17************ @news.tdc.dk>,
Martin Jørgensen <un*********@sp am.jay.net> wrote: -snip-
Do you know what the invariant you created for this class is? If so,
express it in a comment.
I don't know what you mean by the word "invariant" .

////////////////////////////////////////////////////////////////
int main()
{
void bsort(person**, int); //prototype

Prototypes inside functions isn't a great idea IMO. Every module that
wants to use this bsort function should have a single place to go to get
the prototype, usually a header file. In this case, the prototype should
be outside of, and above main, but below class person.


Why below class person?

person* persPtr[100]; //array of pointers to persons
int n = 0; //number of persons in array

Here is a perfect example for a class. There is an invariant between 'n'
and 'persPtr' such that n defines how many of the values in persPtr are
valid. Both of these variables should be in a class that has the job of
maintaining that invariant.

What if the user enters over 100 names? Whenever you use an array, you
have to insure that it's kept within bounds. Another job for the class
mentioned above?


I know, but it's not that important here... Besides that, I'm a c++
beginner so I wouldn't know how to do it better (in C however I think I
could do it now, although I'm not a C-expert).
Of course, if a class already exists that can do the job with minimal
effort, use it rather than writing your own. Consider using std::vector

char choice; //input char

do { //put persons in array
persPtr[n] = new person; //make new object

You create new objects here, but never delete them. Although the system
will clean them up upon exit, get in the habit of deleting every object
you new when you are done with it. In this case, you should go through
the array and delete all the persons before returning from main.


Ok.
persPtr[n]->setName(); //set person's name
n++; //count new person
cout << "Enter another (y/n)? "; //enter another
cin >> choice; // person?
}
while( choice=='y' ); //quit on 'n'

The 'choice' variable is only used in the two lines above, yet its scope
is all of main. It's good practice to limit the scope of variables to
only the part of the program where they are actually used. This helps
insure that they don't accidentally get used incorrectly. In this case,
a function that gets the users choice and returns true if that choice is
'y' would be ideal. Then you can simply call that function inside the
while condition.


Good idea.
cout << "\nUnsorted list:";
for(int j=0; j<n; j++) //print unsorted list
{ persPtr[j]->printName(); }

bsort(persPtr, n); //sort pointers

cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
{ persPtr[j]->printName(); }
cout << endl;
return 0;
} //end main()

I want to talk for a second about code comments... Anyone who has
bothered to look at the definition of "bsort" will know that it sorts
pointers (after all you have a comment to that effect. :-) So the "sort
pointers" comment above is superfluous. The other two, however are
somewhat handy because they explain what several lines of code are
doing. Note however the duplication between "print unsorted list" and
"print sorted list". Ideally when you have two blocks of code alike, you
should make a function that contains the block just once, and call it
twice. On top of that, if you call this function "print_list ", it will
render these comments superfluous as well. You see, comments aren't bad,
but code that requires comments to be understood often is.


Ok, good point. I understand what you mean, but I wouldn't know how to
change it now, since I'm a c++ beginner...
//--------------------------------------------------------------
void bsort(person** pp, int n) //sort pointers to persons
{
void order(person**, person**); //prototype
int j, k; //indexes to array

for(j=0; j<n-1; j++) //outer loop
for(k=j+1; k<n; k++) //inner loop starts at outer
order(pp+j, pp+k); //order the pointer contents
}
//--------------------------------------------------------------
void order(person** pp1, person** pp2) //orders two pointers
{ //if 1st larger than 2nd,
if( (*pp1)->getName() > (*pp2)->getName() )
{
person* tempptr = *pp1; //swap the pointers
*pp1 = *pp2;
*pp2 = tempptr;
}
}

Much like the comment I made about classes above, if a function already
exists that can do what you want, then consider using it rather than
writing your own.

In both cases (with functions and classes,) there is often something
that *almost* does what you want but not quite. You are then left with
the decision as to wether you should write something that does exactly
what you want, or write something that adapts your problem to fit its
solution. Your choice should be guided by several factors including ease
of understanding, amount of code required, as well as the performance of
the solution.

In this particular case, there are a couple general-purpose sort
routines already available in the standard library. Unless your
assignment was to write a bubble sort routine, your code would probably
be better served if you adapted one of the standard sort routines to
your purposes rather than writing your own. (a) The code needed to adapt
their solution to your purposes would be less than the code required to
create a new solution. (b) Less code (if written clearly) tends to be
easer to understand, (c) the general solution would likely still fall
within what performance requirements your program has and may even be
better. (After all the library implementors have spent much more time
perfecting their sort routines than you have.)


Actually it was part of this code example not to use any standard
library functions... But nice comments...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 25 '06 #8
In article <th************ @news.tdc.dk>,
Martin Jørgensen <un*********@sp am.jay.net> wrote:
Daniel T. wrote:
In article <17************ @news.tdc.dk>,
Martin Jørgensen <un*********@sp am.jay.net> wrote: -snip-
Do you know what the invariant you created for this class is? If so,
express it in a comment.


I don't know what you mean by the word "invariant" .


Something that is guaranteed to always be true. Whatever the invariant
is, the class's principal job is to ensure that it stays true no matter
what member-functions are called, and no matter what parameters are sent
to those functions. For example:

class Range {
// invariant: low() < high()
public:
int low() const;
int high() const;
// other member-functions
};

The class above has the invariant that the value returned by low() will
always be less than the value returned by high(). This means that *every
other member-function* must work to make sure that no matter what
happens, low() < high() will always be true.

////////////////////////////////////////////////////////////////
int main()
{
void bsort(person**, int); //prototype

Prototypes inside functions isn't a great idea IMO. Every module that
wants to use this bsort function should have a single place to go to get
the prototype, usually a header file. In this case, the prototype should
be outside of, and above main, but below class person.


Why below class person?


Because bsort(person**, int) is supposed to work with persons. Declaring
it after person makes sense. In a larger program, both class person and
the bsort algorithm would be in a header file together.
person* persPtr[100]; //array of pointers to persons
int n = 0; //number of persons in array

Here is a perfect example for a class. There is an invariant between 'n'
and 'persPtr' such that n defines how many of the values in persPtr are
valid. Both of these variables should be in a class that has the job of
maintaining that invariant.

What if the user enters over 100 names? Whenever you use an array, you
have to insure that it's kept within bounds. Another job for the class
mentioned above?


I know, but it's not that important here...


It's *always* important to make sure the program can *never* go over the
bounds of its arrays.
Besides that, I'm a c++
beginner so I wouldn't know how to do it better (in C however I think I
could do it now, although I'm not a C-expert).


This is a great time to learn. The most obvious solution is to break out
of the loop that creates person objects if the array is full...

do {
persPtr[n] = new person;
persPtr[n]->setName();
++n;
if ( n < 100 ) {
cout << "Enter another (y/n)? ";
cin >> choice;
}
else {
cout << "Memory full.\n";
choice = 'n';
}
}
while ( choice == 'y' )

The obvious way to test this is to try reducing the size of the array
for a run or two. Of course to do that, you need to change two values (
the two "100"s in the code.) Better would be to create a constant that
is used in both places...

const int max_names = 100;
//...
person* persPtr[max_names];
//...
if ( n < max_names ) {
//...
cout << "\nUnsorted list:";
for(int j=0; j<n; j++) //print unsorted list
{ persPtr[j]->printName(); }

bsort(persPtr, n); //sort pointers

cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
{ persPtr[j]->printName(); }
cout << endl;
return 0;
} //end main()

I want to talk for a second about code comments... Anyone who has
bothered to look at the definition of "bsort" will know that it sorts
pointers (after all you have a comment to that effect. :-) So the "sort
pointers" comment above is superfluous. The other two, however are
somewhat handy because they explain what several lines of code are
doing. Note however the duplication between "print unsorted list" and
"print sorted list". Ideally when you have two blocks of code alike, you
should make a function that contains the block just once, and call it
twice. On top of that, if you call this function "print_list ", it will
render these comments superfluous as well. You see, comments aren't bad,
but code that requires comments to be understood often is.


Ok, good point. I understand what you mean, but I wouldn't know how to
change it now, since I'm a c++ beginner...


Sure you do:

void print_persons( person** persPtr, int n )
{
for ( int j = 0; j < n; ++j )
persPtr[j]->printName();
}

Then your code becomes:

cout << "\nUnsorted list:";
print_persons( persPtr, n );

bsort( persPtr, n );

cout << "\nSorted list:";
print_persons( persPtr, n );

//--------------------------------------------------------------
void bsort(person** pp, int n) //sort pointers to persons
{
void order(person**, person**); //prototype
int j, k; //indexes to array

for(j=0; j<n-1; j++) //outer loop
for(k=j+1; k<n; k++) //inner loop starts at outer
order(pp+j, pp+k); //order the pointer contents
}
//--------------------------------------------------------------
void order(person** pp1, person** pp2) //orders two pointers
{ //if 1st larger than 2nd,
if( (*pp1)->getName() > (*pp2)->getName() )
{
person* tempptr = *pp1; //swap the pointers
*pp1 = *pp2;
*pp2 = tempptr;
}
}

Much like the comment I made about classes above, if a function already
exists that can do what you want, then consider using it rather than
writing your own.

In both cases (with functions and classes,) there is often something
that *almost* does what you want but not quite. You are then left with
the decision as to wether you should write something that does exactly
what you want, or write something that adapts your problem to fit its
solution. Your choice should be guided by several factors including ease
of understanding, amount of code required, as well as the performance of
the solution.

In this particular case, there are a couple general-purpose sort
routines already available in the standard library. Unless your
assignment was to write a bubble sort routine, your code would probably
be better served if you adapted one of the standard sort routines to
your purposes rather than writing your own. (a) The code needed to adapt
their solution to your purposes would be less than the code required to
create a new solution. (b) Less code (if written clearly) tends to be
easer to understand, (c) the general solution would likely still fall
within what performance requirements your program has and may even be
better. (After all the library implementors have spent much more time
perfecting their sort routines than you have.)


Actually it was part of this code example not to use any standard
library functions... But nice comments...


Yet you used operator<< for input, operator>> for output and operator
new to create person objects. Also, of course, several of the functions
defined in class string were used as well.

You see, it's very hard to write anything useful without using any of
the standard library functions. :-)

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 26 '06 #9
Daniel T. wrote:
In article <th************ @news.tdc.dk>,
Martin Jørgensen <un*********@sp am.jay.net> wrote:

Daniel T. wrote:
In article <17************ @news.tdc.dk>,
Martin Jørgensen <un*********@sp am.jay.net> wrote:
-snip-

Do you know what the invariant you created for this class is? If so,
express it in a comment.


I don't know what you mean by the word "invariant" .

Something that is guaranteed to always be true. Whatever the invariant
is, the class's principal job is to ensure that it stays true no matter
what member-functions are called, and no matter what parameters are sent
to those functions. For example:

class Range {
// invariant: low() < high()
public:
int low() const;
int high() const;
// other member-functions
};

The class above has the invariant that the value returned by low() will
always be less than the value returned by high(). This means that *every
other member-function* must work to make sure that no matter what
happens, low() < high() will always be true.


Ok.
////////////////////////////////////////////////////////////////
int main()
{
void bsort(person**, int); //prototype
Prototypes inside functions isn't a great idea IMO. Every module that
wants to use this bsort function should have a single place to go to get
the prototype, usually a header file. In this case, the prototype should
be outside of, and above main, but below class person.


Why below class person?

Because bsort(person**, int) is supposed to work with persons. Declaring
it after person makes sense. In a larger program, both class person and
the bsort algorithm would be in a header file together.


Yes, I have something to learn here....
person* persPtr[100]; //array of pointers to persons
int n = 0; //number of persons in array
Here is a perfect example for a class. There is an invariant between 'n'
and 'persPtr' such that n defines how many of the values in persPtr are
valid. Both of these variables should be in a class that has the job of
maintainin g that invariant.

What if the user enters over 100 names? Whenever you use an array, you
have to insure that it's kept within bounds. Another job for the class
mentioned above?


I know, but it's not that important here...

It's *always* important to make sure the program can *never* go over the
bounds of its arrays.

Besides that, I'm a c++
beginner so I wouldn't know how to do it better (in C however I think I
could do it now, although I'm not a C-expert).

This is a great time to learn. The most obvious solution is to break out
of the loop that creates person objects if the array is full...

do {
persPtr[n] = new person;
persPtr[n]->setName();
++n;
if ( n < 100 ) {
cout << "Enter another (y/n)? ";
cin >> choice;
}
else {
cout << "Memory full.\n";
choice = 'n';
}
}
while ( choice == 'y' )

The obvious way to test this is to try reducing the size of the array
for a run or two. Of course to do that, you need to change two values (
the two "100"s in the code.) Better would be to create a constant that
is used in both places...


Oh, yeah. I didn't think of that.... That was easy enough :-)
const int max_names = 100;
//...
person* persPtr[max_names];
//...
if ( n < max_names ) {
//...


Agreed.
cout << "\nUnsorted list:";
for(int j=0; j<n; j++) //print unsorted list
{ persPtr[j]->printName(); }

bsort(persPtr, n); //sort pointers

cout << "\nSorted list:";
for(j=0; j<n; j++) //print sorted list
{ persPtr[j]->printName(); }
cout << endl;
return 0;
} //end main()
I want to talk for a second about code comments... Anyone who has
bothered to look at the definition of "bsort" will know that it sorts
pointers (after all you have a comment to that effect. :-) So the "sort
pointers" comment above is superfluous. The other two, however are
somewhat handy because they explain what several lines of code are
doing. Note however the duplication between "print unsorted list" and
"print sorted list". Ideally when you have two blocks of code alike, you
should make a function that contains the block just once, and call it
twice. On top of that, if you call this function "print_list ", it will
render these comments superfluous as well. You see, comments aren't bad,
but code that requires comments to be understood often is.


Ok, good point. I understand what you mean, but I wouldn't know how to
change it now, since I'm a c++ beginner...

Sure you do:

void print_persons( person** persPtr, int n )
{
for ( int j = 0; j < n; ++j )
persPtr[j]->printName();
}

Then your code becomes:

cout << "\nUnsorted list:";
print_persons( persPtr, n );

bsort( persPtr, n );

cout << "\nSorted list:";
print_persons( persPtr, n );


Oh... This is something with pointers to pointers... Still a bit tricky
for me, so thanks for showing it so I can study the example code... I
think pointers to int/double/whatever is something I can handle easily
but pointers to pointers are a bit tricky yet...
//--------------------------------------------------------------
void bsort(person** pp, int n) //sort pointers to persons
{
void order(person**, person**); //prototype
int j, k; //indexes to array

for(j=0; j<n-1; j++) //outer loop
for(k=j+1; k<n; k++) //inner loop starts at outer
order(pp+j, pp+k); //order the pointer contents
}
//--------------------------------------------------------------
void order(person** pp1, person** pp2) //orders two pointers
{ //if 1st larger than 2nd,
if( (*pp1)->getName() > (*pp2)->getName() )
{
person* tempptr = *pp1; //swap the pointers
*pp1 = *pp2;
*pp2 = tempptr;
}
}
Much like the comment I made about classes above, if a function already
exists that can do what you want, then consider using it rather than
writing your own.

In both cases (with functions and classes,) there is often something
that *almost* does what you want but not quite. You are then left with
the decision as to wether you should write something that does exactly
what you want, or write something that adapts your problem to fit its
solution. Your choice should be guided by several factors including ease
of understanding, amount of code required, as well as the performance of
the solution.

In this particular case, there are a couple general-purpose sort
routines already available in the standard library. Unless your
assignment was to write a bubble sort routine, your code would probably
be better served if you adapted one of the standard sort routines to
your purposes rather than writing your own. (a) The code needed to adapt
their solution to your purposes would be less than the code required to
create a new solution. (b) Less code (if written clearly) tends to be
easer to understand, (c) the general solution would likely still fall
within what performance requirements your program has and may even be
better. (After all the library implementors have spent much more time
perfecting their sort routines than you have.)


Actually it was part of this code example not to use any standard
library functions... But nice comments...

Yet you used operator<< for input, operator>> for output and operator
new to create person objects. Also, of course, several of the functions
defined in class string were used as well.

You see, it's very hard to write anything useful without using any of
the standard library functions. :-)


I meant: this code had to show how to sort without using general-purpose
sort-routines. But you knew that, based on your smiley I think :-)
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 26 '06 #10

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

Similar topics

13
1653
by: Mtk | last post by:
Hi! Why does the following, simple, example produce such errors? I know it has to do with the two header files including each other and (moreover) the usage of the classes One and Two in the "opposite" header file... What do I have to do to make this example work? Thanks for all the help! // * Error messages: One.h(11): error C2146: syntax error : missing ';' before identifier 't'
0
7969
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7886
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,...
0
8272
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8035
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
6688
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
5847
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
3886
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...
0
3927
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1494
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.