2009-03-06 113 views
-1

初学者问题在这里:矢量范围与结构

即时读取文件,存储到结构成员的feilds,然后将结构的名称存储到一个向量。

我输出我的向量的大小,并进行调试,看看它是否工作,我有文件中的领域隔离。

即时通讯在一个向量* ptrFunc()函数中执行此操作。

和我返回& vectorObject所以我不需要使用向量类型ptr obj声明。

即使使用我的返回类型,从一个函数移动到另一个函数,是否需要重新解析文件?

继承人一些代码,即时通讯不认为我是在非常明确:

//Varaible Declartions/Intializations 
    //Open File 

    vector<myStruct> *firstFunc() 
    { 

    while (!inFile->eof()) 
    { 
    // Isolating each feild delimited by commas 
    getline(*inFile, str1, ','); 
    myStruct.f1 = str1; 

    getline(*inFile, str2, ','); 
    myStruct.f2 = str2; 

    getline(*inFile, str3, ','); 
    myStruct.f3 = atof(str3.c_str() ); 

    getline(*inFile, str4); 
    myStruct.f4 = atof(str4.c_str()); 

    v.push_back(myStruct); 
     // We have the isolated feilds in the vector... 
     // so we dance 
     } 
    return &v; 
     } 
    // Now do i still have to do the getlines and push_back with the vector again in another function? 

    vector<myStruct> *otherFunc() 
    { 
     sStruct myStruct; 
     vector<myStruct> *v = firstFunc(), 
     vInit; 
     v = &vInit 
     vInit.push_back(myStruct); 
     ... 

因此多数民众赞成在那里我调试它,我的结构成员已经失去了所有的数据!

我应该在第一个函数中做些什么,以便我的结构成员不会丢失他们的数据?

我的猜测是创建一个void函数或其他东西。但是,然后将其存入矢量将成为问题。

我只是有范围问题。 :p

+0

请您使用的语言添加至少一个标签。 – tehvan 2009-03-06 06:40:30

回答

1

是否可能使您从firstFunc()返回的向量'v'被分配到堆栈上?如果是这样,那么这可能是你的问题,因为你返回一个超出范围的对象的地址,因为函数退出。

因此修复这个问题,通过值返回向量,或使用new在堆上创建它。

2

声明你的功能是这样的:

void firstFunc(vector<myStruct> &v) 
{ 
... 
} 

void otherFunc(vector<myStruct> &v) 
{ 
... 
} 

,并利用它们这样

void foo() 
{ 
vector<myStruct> v; 
firstFunc(v); 
otherFunc(v); 
}