簡體   English   中英

分配另一個std :: vector的std :: vector地址

[英]Assign std::vector address of another std::vector

我正在寫一個平衡化學方程式的程序。 該程序通過取等式字符串,根據等號將其分成大小為2的std :: vector進行工作,然后將左側的splitEquation separatedEquation[0]和右側的separatedEquation[1]解析為另一組std :: vector的leftHalf和rightHalf分別。

問題

我有一個函數方程:: 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);
                }
            }
        }
    }

}

一般而言,您將替換為:

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

...

equationHalf = leftHalf // same for rightHalf

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

...

equationHalf = &leftHalf // same for rightHalf

然后替換equationHalf. Half的任何實例equationHalf. equationHalf->

但是,在您的情況下,我可能會考慮重新考慮您的設計,例如將對equationHalf進行運算的代碼分解為一個函數,並將其傳遞給要對vector進行操作的引用,例如void doStuff(std::vector<std::string> & equationHalf) ,然后只需調用doStuff(leftHalf)doStuff(rightHalf)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM