debug c++之 vector or list
时间:2011-03-23 来源:范晨鹏
为什么 vector::front()的值在 push_back 之后不再正确?
class CMyClass
{
public:
int m_first;
CMyClass( )
{
m_first = 3;
}
};
int vector_or_List()
{
CMyClass temp;
vector<CMyClass> vecInt;
cout << "temp:" << temp.m_first << endl;
vecInt.push_back( temp );
const CMyClass& shadow_vec_front= vecInt.front();
cout << "shadow_vec_front:" << shadow_vec_front.m_first << endl;
vecInt.push_back( temp);
cout << "shadow_vec_front:" << shadow_vec_front.m_first << endl;
list<CMyClass> listInt;
cout << "temp" << temp.m_first << endl;
listInt.push_back( temp );
const CMyClass& shadow_list_front = listInt.front();
cout << "shadow_list_front:" << shadow_list_front.m_first << endl;
listInt.push_back( temp);
cout << "shadow_list_front:" << shadow_list_front.m_first << endl;
return 0;
}
int main()
{
vector_or_List();
system( "pause" );
return 0;
}
{
public:
int m_first;
CMyClass( )
{
m_first = 3;
}
};
int vector_or_List()
{
CMyClass temp;
vector<CMyClass> vecInt;
cout << "temp:" << temp.m_first << endl;
vecInt.push_back( temp );
const CMyClass& shadow_vec_front= vecInt.front();
cout << "shadow_vec_front:" << shadow_vec_front.m_first << endl;
vecInt.push_back( temp);
cout << "shadow_vec_front:" << shadow_vec_front.m_first << endl;
list<CMyClass> listInt;
cout << "temp" << temp.m_first << endl;
listInt.push_back( temp );
const CMyClass& shadow_list_front = listInt.front();
cout << "shadow_list_front:" << shadow_list_front.m_first << endl;
listInt.push_back( temp);
cout << "shadow_list_front:" << shadow_list_front.m_first << endl;
return 0;
}
int main()
{
vector_or_List();
system( "pause" );
return 0;
}
如何改进?
1、vector中存储指针而不是存储变量
2、用 resize 预先分配足够大小的空间
3、多线程环境下,用 list而不用 vector。
扩大地来讲,直接对容器中的对象进行操作,经常是一个比较危险的动作。
相关阅读 更多 +