Can anyone tell me how to find out how many objects are in a given array of objects?
Do you use sizeof()?
I tried to use strlen, but it says that I can't do that unless it's a string of characters.
Can anyone tell me how to find out how many objects are in a given array of objects?
Do you use sizeof()?
I tried to use strlen, but it says that I can't do that unless it's a string of characters.
num objects = sizeof(array)/sizeof(array[0]);
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
That won't work if the array was declared outside of the current scope (i.e. in another function, as only a pointer to the first element in the array will be passed).
So, you have a couple options:
1. Make sure you only use that method in the proper scope.
2. Keep track of this information in another variable.
3. Use a container such as std::vector.
The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.
I tried:
length = sizeof(PArray)/sizeof(PArray[0]);
but it returned 0. Doing each individually, it returned that the sizeof PArray was 4 and the sizeof PArray[0] or PArray[1] was 30. So, does sizeof(PArray) return 4 because it is returning the memory the pointer takes up and not the memory the array takes up?
How can I fix this?
thanks
sarah
>> How can I fix this?
ggOriginally Posted by Zach L.
I'm sorry, I'm really new to this...
What is std::vector and how do I use it?
thanks, Sbook
You can get away with three basic operations using a std::vector. push_back(), size(), and operator[]:
push_back() appends a new item onto the vector, size() tells you how many items are in the vector, and operator[] makes a vector look like an array for subscripting.Code:#include <iostream> #include <vector> int main() { std::vector<int> v; for ( int i = 0; i < 10; i++ ) v.push_back ( i ); for ( int i = 0; i < v.size(); i++ ) std::cout<< v[i] <<'\n'; }
This is all well and good, but the above code will probably give you a warning about a mismatch between signed and unsigned types. That's because size() returns vector<T>::size_type, which is unsigned. You can call that the fourth 'operation':
That should suffice until you get to the point where you need more power. But by then you'll know enough to figure out how to use the other member functions of the std::vector class.Code:#include <iostream> #include <vector> int main() { std::vector<int> v; for ( int i = 0; i < 10; i++ ) v.push_back ( i ); for ( std::vector<int>::size_type i = 0; i < v.size(); i++ ) std::cout<< v[i] <<'\n'; }
My best code is written with the delete key.