代码之家  ›  专栏  ›  技术社区  ›  Saurav Sahu

为什么vector::clear不在foreach循环内工作?

  •  0
  • Saurav Sahu  · 技术社区  · 7 年前

    我的代码:

    vector<int> v[10];
    const int x = 3;
    void clearBySimpleLoop(){
        for (int i = 0; i < x; i++){
            v[i].clear();
        }
    }
    int main()
    {
        for (int i = 0; i < x; i++){
            v[i].push_back(11+i);
            v[i].push_back(11+i+1);
            v[i].push_back(11+i+2);
        }
        for (auto vec : v) vec.clear(); //#01. Contents are not cleared. Size of the contained vectors remains same.
        clearBySimpleLoop(); //#02. Contents are cleared. Size of the contained vectors becomes zero. 
        return 0;
    }
    

    问题是为什么代码在 前额 循环(01)无法清除数组中的向量,而简单的 对于 循环(02)成功吗?

    演示: https://onlinegdb.com/B1m8-2jG4

    1 回复  |  直到 7 年前
        1
  •  6
  •   463035818_is_not_an_ai    7 年前

    当你写作时

    for (auto vec : v) vec.clear(); //
    

    然后 auto 被欺骗为 std::vector<int> 因此 vec 是元素的副本 v . 清除副本,但保持实际元素不变。如果要对元素本身进行操作,则必须使用引用:

    for (auto& vec : v) vec.clear();
    

    我个人的经验法则是在使用时总是明确地提到指向性、常量和引用性。 汽车 . 我想它的用途是 汽车 更具可读性,但这只是我的观点。注意这里你别无选择,但是如果你遵守规则,你就可以更容易地意识到这一点。 VEC 是值,而不是引用。