|
-
August 14th, 2011, 01:16 PM
#1
Why would vector::size() give a garbage value ?
Hello to anyone who reads this, and a very good day to you.
OS: Windows 7
IDE: Code::Blocks
Status: novice C++ programmer
My problem is that myClass.size() is giving a garbage value
when it should be giving the value 2.
My problem is demonstrated below, but I don't know how to replicate the problem exactly. The program below pretty much demonstrates what I'm doing in my actual program. Also note that I checked myClass.empty() immediately after delete, and even though in my original program myClass.size() is giving a garbage value myClass.empty() returns false... So I geuss myClass - isn't - empty, and neither should it be.
And lastly my program crashes once I call myClass.erase()
My questions are:
1)What is wrong with my program?
2) I am expecting to delete the contents that the second pointer element points to. Am I doing my pointer arithmetic wrong?
Code:
#include <iostream>
#include "CMyClass.h"
#include <vector>
using namespace std;
int main()
{
vector<CMyClass*> myClass;
myClass.push_back(new CMyClass());
myClass.push_back(new CMyClass());
cout << "1) myClass.size() " << myClass.size() << "\n"; //This myClass.size() is cool, it gives 2
vector<CMyClass*>::iterator it = myClass.begin() + 1;// I - think - this equals the second element
delete *it;
if (myClass.empty()) std::cout << "myClass is empty ya'll\n";
cout << "2) myClass.size() " << myClass.size() << "\n"; //In my original program myClass.size() gives a garbage value
myClass.erase(it);
cout << "3) myClass.size() " << myClass.size();
return 0;
}
As always, thank you so much to anyone who helps, and the best of wishes to all the gurus, and the members on CodeGuru.
Last edited by kmkkra; August 14th, 2011 at 05:03 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|