|
-
February 12th, 2004, 10:42 AM
#1
vectors and pointers and questions....
Hi all.... I'm trying to practive & learn about STL and pointers and wrote a little dialog app to help me. It complies but gets an unhandled exception error. Here's my data class..
PHP Code:
class MyData
{
public:
MyData();
virtual ~MyData();
void setFirst(int a) { first = a;};
void setName(CString s) { sName = s; };
int getFirst() { return first; };
CString getName() { return sName; };
private:
int first;
CString sName;
}
and instead of the storing MyData objects in a vector in the dialog, I'm trying to store pointers to the MyData objects. So i the MyDialog.h I have this:
PHP Code:
std::vector<MyData*>vPtrs;
int count;// increments number of MyData
Then in the dialog to add a MyData object to the vector when I hit Add Mydata Obj I do this:
PHP Code:
void CMyPointerDlg::OnNewobj()
{
//make a new instance of the obj and add it to the vector
MyData *p = new MyData;
p->setFirst(count);
p->setName("NoName");
vPtrs.push_back(p);
int size = vPtrs.size();
m_sObjCount.Format("%d", size);//format for dialog
UpdateData(false);
count++;
}
and to remove an obj when I press Remove Mydata Obj I do this:
PHP Code:
void CMyPointerDlg::OnRemoveobj()
{
vector<MyData*>::iterator itr;
if(vPtrs.size() > 0)
{
itr = vPtrs.end();
MyData *p;
p= *itr;
int i = p->getFirst();
delete p;//ERROR!
int size = vPtrs.size();
m_sObjCount.Format("%d", size);
UpdateData(false);
}
}
I get the error on the line marked above... am I totally missing the boat here? Thanks......
-
February 12th, 2004, 10:45 AM
#2
vector::end() returns an iterator that's 1 past the end. Try a "--itr" before you dereference it.
-
February 12th, 2004, 10:58 AM
#3
I assume that you are trying to remove the last element ?
STL works with "half-open" ranges.
vPtrs.begin() ... points to the first element
vPtrs.end() ... point to ONE PAST the last element
so the following is incorrect:
Code:
itr = vPtrs.end();
MyData *p;
p= *itr; // de-references Vptr.end()
you can use the back() member function to get the last element
(not tested ...)
Code:
void CMyPointerDlg::OnRemoveobj()
{
if(!vPtrs.empty())
{
MyData *p = vPtrs.back(); // back()
int i = p->getFirst();
delete p;
vPtrs.pop_back();
int size = vPtrs.size();
m_sObjCount.Format("%d", size);
UpdateData(false);
}
}
-
February 12th, 2004, 11:00 AM
#4
Yes, I'm trying to remove the last element. Thanks... I'll give it a try.
-
February 12th, 2004, 11:01 AM
#5
Just as a reference...you might want to take a look at the following introduction to the 'vector' class...
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
|