繁体   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