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

时间:2014-10-16 17:48:56

标签: c++ pointers c++11 vector stdvector

我正在编写一个程序来平衡化学方程式。该程序通过获取方程字符串,根据等号将其拆分为大小为2的std :: vector,然后将左侧separatedEquation[0]和右侧separatedEquation[1]解析为另一个std :: vector分别是leftHalf和rightHalf的集合。

问题

我有一个函数Equation :: 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);
                }
            }
        }
    }

}

1 个答案:

答案 0 :(得分: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)