Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Quick question about typedef XXXXX:size_type, vectors, etc.

Status
Not open for further replies.
Feb 14, 2002
88
0
0
JP
Special thanks to dlkfjdlkfjdlfkd on recommending the Accelerated C++ book. I'm working on it at work in my free time -- have made it Chapter 3 in a few days, so I guess that's good progress.

Couple of questions though:

In one of the examples in the book, the authors want to check if a vector (called vectorname here) has any entries in it. So, they do this:


typedef vector<double>::size_type vec_sz;
vec_sz size = vectorname.size()
if (size == 0 ) {
cout << error_message << endl;
return 1;
}


Just goofing around, trying to figure out &quot;why&quot; as I go along, I tried the following:


//typedef vector<double>::size_type vec_sz;
//vec_sz size = vectorname.size()
if (vectorname.size() == 0 ) {
cout << error_message << endl;
return 1;
}


And it worked just fine. If vectorname.size() all by its lonesome will tell you how many entries is has... why go through the hassle... other than introducing soemthing new?

One other one:
I'm used to pushing and popping arrays in Perl. It seems that C++ will complain if I want to push something too much. Are vectors essentially what you have to use instead of an array if you don't know how many objects it's going to hold?
 
You're right in that you can use vectorname.size() inside the conditional, rather than assign it to a variable and then test the variable in the condition.

I believe in most of the examples the author creates a typedef and uses that typedef in two or more cases throughout the program, so that would explain the typedef.

I suspect it's mostly a case of introducing new concepts: reiterating the fact that the vector (and other containers) has a size_type member and that this type should be used to remember the number of elements in the vector.

In C++ arrays are of a fixed size, so you'll generally have to use a container (such as a vector), which will dynamically resize itself as needed. The alternative is to &quot;do it yourself&quot; using new and delete, but why reinvent the wheel?
 
Also note that probably the best way to tell if a vector has any entries in it is to use empty():

if ( vectorname.empty( ) ) { ... }

This works for other STL containers, too, like list, deque, map, set.
 
Fantastic info guys.

I'm trying to follow the book exactly, as I've heard great things about it, but sometimes I can't help but think, &quot;why&quot;? So far so good.

Also, the empty() seems to be a nice trick.

Much appreciated.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top