【问题标题】:C++ vector reference works funnyC++ 矢量参考作品很有趣
【发布时间】:2015-03-11 15:50:53
【问题描述】:

我编写了一个简单的 c++ 算法来计算向量的排列。如果我改变这 13. 行,下面的代码可以正常工作

vector<int>& pp = p.front();

到这里

vector<int> pp = p.front();

我不明白为什么。我不认为这是由重新分配引起的。有人可以解释一下吗?

#include <vector>

using namespace std;

class Solution {
public:
    void f(vector<vector<int> >& p, vector<int>& num)
    {
        if (p.front().size() == num.size()) return;
        int k = p.size();
        while (k)
        {
            vector<int>& pp = p.front();
            for (int toAdd : num)
            {
                bool found = false;
                for (int i = 0; i < pp.size(); i++)
                {
                    if (pp[i] == toAdd)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    vector<int> newp;
                    for (int i = 0; i < pp.size(); i++)
                    {
                        newp.push_back(pp[i]);
                    }
                    newp.push_back(toAdd);
                    p.push_back(newp);
                }
            }
            p.erase(p.begin());
            k--;
        }
        f(p, num);
    }

    vector<vector<int> > permute(vector<int> &num)
    {
        vector<vector<int>> r;
        r.reserve(2 << num.size());
        for (int i = 0; i < num.size(); i++)
        {
            r.push_back(vector<int>());
            r[i].push_back(num[i]);
        }
        f(r, num);
        return r;
    }
};

int main()
{
    Solution s;
    vector<int> num{ 6, 3, 2, 7, 4, -1 };
    auto a = s.permute(num);
    a.clear();
    return 0;
}

【问题讨论】:

  • 为什么不认为可能是重新分配造成的?
  • 不要持有指向向量中项目的引用或指针,尤其是当您要增加向量中的元素数量时。
  • I have written a simple c++ algorithm to calculate permutations of a vector 这个有std::next_permuation
  • “它有效”是什么意思?
  • 您应该尝试简化代码,看看可能会出现什么问题。例如,更新found 的循环看起来像是对std::find 的调用,if (!found) 内部的循环只是vector&lt;int&gt; newp(pp)...

标签: c++ vector stl pass-by-reference


【解决方案1】:

正是因为这样的说法:

p.push_back(newp)

这会使对向量p 中条目的所有引用无效,因为它可以重新分配内容。

【讨论】:

  • 但是pp在调用push_back()之后没有被使用,那么为什么迭代器失效会导致问题呢?
  • @templateboy 我们怎么知道的?如果循环继续呢?
  • pp 只存在于循环的范围内,所以引用只存在 那个 长。
  • @templateboy 因为 push_back 需要为新元素重新分配内部缓冲区。旧元素不再有效,对它的引用也不再有效。
  • @templateboy push_backfor 循环内,如果循环在push_back 之后继续呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 2014-02-13
  • 1970-01-01
  • 2012-02-19
  • 2017-03-10
  • 2014-11-29
  • 1970-01-01
相关资源
最近更新 更多