2014-10-16 56 views
1

我正在編寫一個程序來平衡化學方程式。該程序通過獲取方程字符串,將其拆分爲基於等號的大小爲2的std :: vector,然後將左側separatedEquation[0]和右側separatedEquation[1]解析爲另一組std :: vector的leftHalf和rightHalf分別。指定另一個std :: vector的std :: vector地址

問題

我有一個函數方程:: filterEquation分析給separatedEquation的元素名稱。我想使用一個指向leftHalf或rightHalf地址的臨時向量。我知道這可能是令人困惑的,但這是我的代碼和我正在嘗試做的事情。我認爲我需要使用指針,但是我以前從來沒有必須使用指針,並且對它們沒有效率。

void Equation::filterEquation() 
{ 
    for(int i=0; i<separatedEquation.size(); i++) //i = index of separated equation 
    { 
     int index=0; 
     std::vector<std::string> equationHalf; 
     if(i==0) 
      equationHalf = leftHalf; //set equationHalf to the address of leftHalf 
     if(i==1) 
      equationHalf = rightHalf; //set equationHalf to the address of rightHalf 
     for (std::string::iterator it = separatedEquation[i].begin(); it!=separatedEquation[i].end(); ++it, index++) 
     { 
      //Elements are set up so that He = Helium, while H = Hydrogen. This separates the elements based upon upper and lowercae 
      bool UPPER_LETTER = isupper(separatedEquation[i][index]); //true if character is upperCase 
      bool NEXT_LOWER_LETTER = islower(separatedEquation[i][index+1]); //true if next is lowerCase 
      if (UPPER_LETTER)// if the character is an uppercase letter 
      { 
       if (NEXT_LOWER_LETTER) 
       { 
        std::string temp = separatedEquation[i].substr(index, 2);//add THIS capital and next lowercase 
        equationHalf.push_back(temp); // add temp to vector 
       } 

       else if (UPPER_LETTER && !NEXT_LOWER_LETTER) //used to try and prevent number from getting in 
       { 
        std::string temp = separatedEquation[i].substr(index, i); 
        equationHalf.push_back(temp); 
       } 
      } 
     } 
    } 

} 
+0

在代碼段開始處覆蓋'equationHalf'的兩個'if'語句看起來是錯誤的。 – sircodesalot 2014-10-16 17:50:39

+0

@sircodesalot我知道,但我想不出另一種方式來做到這一點。 (if == i){leftHalf.doSomething()}'和 'if(i == 1){rightHalf.doSomething()}我設置了兩個if語句: 'if 我認爲有可能改寫equationHalf的地址。 – Crysis 2014-10-16 17:53:36

+2

那麼,你寫的東西不可能是你的意思,因爲無論'equationHalf'將*總是*是'rightHalf'('if i == 0'),或者它什麼也不是(如果'i!= 0 ')。 – sircodesalot 2014-10-16 17:57:12

回答

4

在一般意義上,你將取代:

std::vector<std::string> equationHalf; 

... 

equationHalf = leftHalf // same for rightHalf 

std::vector<std::string>* equationHalf; 

... 

equationHalf = &leftHalf // same for rightHalf 

然後用equationHalf->取代equationHalf.任何實例。

雖然,你的情況,我會認真考慮重新考慮你的設計,比如打破了上equationHalf操作到功能,並把它傳遞給了vector參考,以在諸如void doStuff(std::vector<std::string> & equationHalf)操作代碼,然後只需調用doStuff(leftHalf)doStuff(rightHalf)

+1

'std :: vector &equationHalf =((i == 0)?leftHalf:rightHalf);'會工作,假設第二次測試'i == 0'實際上是一個錯字和'i!= 0'是有意的。 – WhozCraig 2014-10-16 18:01:25

+0

@WhozCraig我更正了我的代碼。其實我的意思是'i == 1',但這個矢量永遠不會大於2的大小,所以這個工作。 因爲'std :: vector separateEquation'永遠不會超過2個字符串,是最好的做法,使其成爲一個數組? – Crysis 2014-10-16 18:04:22

+0

@Crysis在你的問題下面看到我的評論。 – WhozCraig 2014-10-16 18:05:28

相關問題