2012-01-17 46 views
1
static int sum = 0; 
static int loop = 0; 

void put_into_vector(ifstream& ifs, vector<int>& v) 
{ 

    // String to store our file input string 
    string s; 

    // Extracts characters from the input sequence until a delimited is found 
    getline(ifs, s); 

    // Input string stream class to modify the strings 
    istringstream iss(s); 

    // Skip all the white spaces. 
    iss >> skipws; 

    // Function to check if stream's error flags (eofbit, failbit and badbit) are set. 
    if(iss.good()) 
    { 
     // Copies elements within the specified range to the container specified. 
     copy(istream_iterator<int>(iss), istream_iterator<int>(),back_inserter(v)); 
    } 
} 

void get_value(vector<int>& v, int start, int end) 
{ 
    while(loop < 4) 
    { 
     if(start == end) 
     { 
      sum = sum + v[start]; 
      loop++; 
      get_value(v,start,end+1); 
     } 
     if(v[start] > v[end]) 
     { 
      sum = sum + v[start]; 
      loop++; 
      get_value(v,start,end); 
     } 
     if(v[start] < v[end]) 
     { 
      sum = sum + v[end]; 
      loop++; 
      get_value(v,end,end+1); 
     } 
    } 
} 

int main() 
{  
    vector<int> triangle_array[4]; 
    ifstream ifs("numbers.txt"); 

    for(int i = 0; i < 4; i++) 
    { 
     put_into_vector(ifs, triangle_array[i]); 
    } 

    int row = 0; 
    get_value(triangle_array[row], 0, 0); 
    return 0; 
} 

我試圖讓我的代碼運行。該代碼讀取一個文本文件,該文件如下:傳遞向量作爲函數的參數

5

8 1

4 8 3

0 7 12 4

當我打電話的get_value功能,並通過它指向的參數第一個矢量 這是v [0] = 5.在第一個條件,當start == end時,我更新max的值,但在d對此我想再次調用相同的函數,但傳遞下一個向量即。 v [1] 其中有「8,1」。我不能這樣做,因爲它在寫入v [1]或其中的任何內容時給我一個錯誤。

的錯誤是:error C2664: 'get_value' : cannot convert parameter 1 from 'int' to 'std::vector<_Ty> &'

你知道的一種方法,我可以通過傳遞指向的VEC到下一行,即vec[0]然後vec[1],vec[2]vec[3]遞歸調用它。

+0

我想獲得在給定的文本文件中的相鄰元素的總和...三角形智力玩具歐拉項目問題67. – andybandy12 2012-01-17 19:40:24

回答

0

我有點困惑,你想要做什麼,但我猜這件事情是這樣的:

//you have 
void get_value(vector<int>& v, int start, int end); 

//you want 
void get_value(vector<int>* v, const int curVectorIdx, const int maxVectors, int start, int end) 
{ 
    int nextVectorIdx = curVectorIdx + 1; 
    if(nextVectorIdx < maxVectors) { 
     vector<int>* nextVector = v + nextVectorIdx; 
     get_value(nextVector, nextVectorIdx, maxVectors, nextVector->begin(), nextVector->end()); 
    } 
} 
+0

也許你應該看看他的文字f再來一次。目前尚不清楚由於格式不正確而導致的結果。 (我重新格式化了它,希望我的改革很快就會顯現出來)。 – 2012-01-17 19:23:40

+0

是的,這是正確的文件。感謝格式。我想獲取第一行的值,然後根據條件進行下一行(使用向量)和修改後的開始和結束值。但我仍然無法弄清楚如何去做 – andybandy12 2012-01-17 19:46:12

+0

不知道反對票是什麼。你的get_value函數需要一個向量&。 如果你想得到其他的行,你需要將它改成類似於我寫的東西。 可以通過手動遍歷地址來獲得其他行,但你可能不應該那樣做。 – 2012-01-17 22:07:14

0

我認爲你需要改變

get_value(triangle_array[row], 0, 0); this line 

要這get_value(triangle_array, 0, 0);