双向量隐藏变量

时间:2017-10-31 21:25:01

标签: c++ vector double

当我访问双向量时,我遇到了一个有趣的问题。我的想法是在访问向量之前删除了所有信息。 for循环尝试访问向量并成功说向量为空,但是当我直接访问向量点时,它表明向量中仍然存在变量。

此外,矢量设置如下:

vector<vector<string>> proTable;

这是试图访问向量的循环。

    for(int a = 0; a < proTable.size(); a++)
    {
            for(int b = 0; b < proTable[a].size(); b++)
            {
                    cout << proTable[a][b] << "\t";
            }
    }

但如果我以这种方式编辑for循环,它会返回变量。

        for(int a = 0; a < proTable.size(); a++)
    {
            for(int b = 0; b < proTable[a].size(); b++)
            {
                    cout << proTable[a][b] << "\t";
            }
            cout << proTable[0][0];
    }

第一个没有打印出来。第二个打印之前在矢量中的X.此外,向量不显示它是空的。

如果重要的话,这就是我删除它的方式。

void MRelation::RemoveColumn(vector<int> rem)
{
    while(!rem.empty())
    {
            int z = rem[rem.size() - 1];
            for(int a = 0; a < proTable.size(); a++)
            {
                    for(int b = z; b < proTable[a].size() - 1; b++)
                    {
                            proTable[a][b] = proTable[a][b+1];
                    }
                    proTable[a].pop_back();
            }
            rem.pop_back();
    }
}

vector rem保存需要从表中删除的列。

2 个答案:

答案 0 :(得分:1)

  

我在访问矢量之前删除了所有信息。

访问超出范围的向量具有未定义的行为。由于向量为空,proTable[0]超出范围。在cout << proTable[0][0];行中,您可以访问proTable[0]。因此,程序的行为是未定义的。

  

它表明向量中仍然存在变量。

你不能从观察未定义的行为中得出这样的结论。

&#34;向量中仍然存在变量&#34;不一定是你看到输出的原因。您看到了输出,因为行为未定义。

答案 1 :(得分:0)

我发现它是什么。我删除内部向量的内容但不删除向量本身,然后向量会认为它包含某些内容,并将提取不再存在的信息。这是我遇到问题的代码。它已使用if语句进行编辑以纠正它。

void MRelation::FinalPrint()
{
    if(curTable.size() < 2)
    {
            ss << "? No\n";
    }       
    else
    {
            ss << "? Yes(" << curTable.size() - 1 << ")\n";
    }       
    if(!proTable[0].empty()) //This was added in after to correct the problem
    {
            for(int c = 1; c < proTable.size(); c++)
            {
                    ss << "  " << proTable[0][0] << "=" << proTable[c][0];
                    for(int d = 1; d < proTable[0].size(); d++)
                    {
                            ss << ", ";
                            ss << proTable[0][d] << "=" << proTable[c][d];
                    }
                    ss << "\n";
            }
    }
}

很抱歉没有将所有内容放在上下文中。我试图输入尽可能多的相关信息而不需要输入300行代码。