首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

嵌套种引发vector容器元素为空

2013-10-17 
嵌套类引发vector容器元素为空TCHAR* pstr NULLwhile (...){CString strName GetData()ASSERT(!strN

嵌套类引发vector容器元素为空
TCHAR* pstr = NULL;

while (...)
{
CString strName = GetData();
ASSERT(!strName.IsEmpty());
pstr = new TCHAR[MAX_PATH]; 
lstrcpy(pstr, strName);
obj.m_vec.push_back(pstr);
}


循环后,结果容器发现为空,,一个元素都没有,非常奇怪。

上完整的code:

class Example
{
struct  test
{
vector<TCHAR*> m_vec;
public:
~test()
{
for(vector<TCHAR*>::iterator iter = m_vec.begin();  iter != m_vec.end(); iter ++)
{
 if( *iter != NULL)
 {
delete *iter;
*iter = NULL;
 }
}
}
}obj;


//其他成员函数省去

};

调用代码:

TCHAR* pstr = NULL;

while (...)
{
CString strName = GetData();
ASSERT(!strName.IsEmpty());
pstr = new TCHAR[MAX_PATH];   //肯定有值的
lstrcpy(pstr, strName);
obj.m_vec.push_back(pstr);
}

是不是嵌套类的导致的vector为空,一个元素都没有

[解决办法]
你的问题跟嵌套类没关系。
[解决办法]
嵌套类,一点也没有问题:
这里有一个VC MFC 控制台例子,如下:

#include "stdafx.h"
#include "CStingTest.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;


using namespace std;

void main_func()
{
class Example
{
public:
struct test{
public:
vector<TCHAR *> m_vec;
~ test(){
if(m_vec.size() ==0 )return ;

for(vector<TCHAR *> ::iterator it =m_vec.begin();it!=m_vec.end();it++)
{

   
   _tprintf(_T("%s \n"),*it);
   delete *it;
   *it=NULL;

}


}
}test;

}obj;


int i=0;
while(i<10)
{
CString strName = _T("Abcd");//GetData();
ASSERT(!strName.IsEmpty());
CString s;
s.Format (_T(" %d") , i);
strName+= s;
TCHAR* pstr = new TCHAR[MAX_PATH]; 
//lstrcpy(pstr, (LPCTSTR)strName);//
_tcscpy(pstr, (LPCTSTR)strName);//_tcscpy 可能更好。
obj.test.m_vec.push_back(pstr);
i++;
}
}


int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;

// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CString strHello;
strHello.LoadString(IDS_HELLO);
cout << (LPCTSTR)strHello << endl;

main_func();
}

return nRetCode;
}

输出:
Hello from MFC!
Abcd 0
Abcd 1
Abcd 2
Abcd 3
Abcd 4
Abcd 5
Abcd 6
Abcd 7
Abcd 8
Abcd 9

热点排行