I have some strange problem I don't really understand. Maybe I'm missing something very stupid, but I can't figure out what I'm doing wrong
So I have this at the beginning of my code:
vector<car*> database;
As I use dynamic memory, I need to clear it at the end.
So I'm doing this (I believe this is correct, please tell me if I'm doing anything wrong here):
1 2 3 4
for (int i = 0; i < database.size(); i++)
{
delete database[i];
}
Pretty easy. It compiles and it doesn't give any problems (ofcourse I can't see if the memory is really deleted - is there any way to check this?) but it gives a warning:
warning C4018: '<' : signed/unsigned mismatch
At this line:
for (int i = 0; i < database.size(); i++)
I don't get it. Am I missing something VERY stupid or why does the compiler gives a warning?
It gives you this warning because vector::size() returns an unsigned integer, and your variable 'i' is a signed integer. Your code will run totally correctly, you won't have any leaks, but if you change int to unsigned, the warning will disappear. Unless database's size is VERY big (depending on your complier) you won't have any problems with this code either.
Yes jsmith that's the right answer, but please don't tell me you write this down every time :)
Although the most generic answer would be to use iterators, but I found iterators slower for vector than this operator[] approach.
vector iterators are pointers; they
should be as fast as indexing.
That's what I used to think, until I implemented a UTF-8 to wchar_t conversion function and string iterators were ten times slower than directly accessing the string with raw pointers.
EDIT: After some testing, here's what I found: Iterators are much slower than pointers without optimization. With optimization, they're take 3.8 times the time for the same algorithm with pointers.
Here are the times for converting a 280 MiB UTF-8 file: Pointers: 2515 ms.
Iterators: 9547 ms.
vector<>::size() returns a vector<>::size_type, not an int. vector<>::size_type happens to be a typedef
for size_t, which happens to be a typedef for unsigned int.
Therefore, the comparison i < database.size() is comparing a [signed] int (i) against an unsigned int
(database.size()). This generates the warning.
You're right, GCC inlines iterators -- furthermore, for a big enough n, iterators are actually faster -- but not all compilers do. If you know your compiler inlines iterators and you'll only be using that compiler, then you don't lose anything by using them. If you're writing cross-platform, however...