2011-08-23 54 views
1

問題在標題中。需要幫助弄清楚爲什麼我的代碼編譯但沒有按預期工作。謝謝!如何設置一個函數將字符串矢量轉換爲VC++中的整數向量?

//This example demonstrates how to do vector<string> to vectro<int> conversion using a function. 
#include <iostream> 
#include <string> 
#include <vector> 
#include <sstream> 

using namespace std; 

vector<int>* convertStringVectorToIntVector (vector<string> *vectorOfStrings) 
{ 
    vector<int> *vectorOfIntegers = new vector<int>; 
    int x; 
    for (int i=0; i<vectorOfStrings->size(); i++) 
    { 
     stringstream str(vectorOfStrings->at(i)); 
     str >> x; 
     vectorOfIntegers->push_back(x); 
    } 
    return vectorOfIntegers; 
} 


int main(int argc, char* argv[]) { 

    //Initialize test vector to use for conversion 
    vector<string> *vectorOfStringTypes = new vector<string>(); 
    vectorOfStringTypes->push_back("1"); 
    vectorOfStringTypes->push_back("10"); 
    vectorOfStringTypes->push_back("100"); 
    delete vectorOfStringTypes; 

    //Initialize target vector to store conversion result 
    vector<int> *vectorOfIntTypes; 
    vectorOfIntTypes = convertStringVectorToIntVector(vectorOfStringTypes); 

    //Test if conversion is successful and the new vector is open for manipulation 
    int sum = 0; 
    for (int i=0; i<vectorOfIntTypes->size(); i++) 
    { 
     sum+=vectorOfIntTypes->at(i); 
     cout<<sum<<endl; 
    } 
    delete vectorOfIntTypes; 
    cin.get(); 
    return 0; 
} 

回答

2

上面的代碼只有一個問題:您要刪除vectorOfStringTypes你把它傳遞給你的轉換函數之前。

將行delete vectorOfStringTypes;移動到調用convert函數後,程序按預期工作。

+0

謝謝!它現在有效。 – nebulus

相關問題