【问题标题】:Accessing vector at index 0 when it's empty为空时访问索引 0 处的向量
【发布时间】:2020-07-09 22:41:18
【问题描述】:

为什么我仍然可以从vectors[0] 获得价值,即使我在第一步已经pop_back()?
我猜现在我的vectors 是空的并通过调用empty() 来检查它

#include <iostream>
#include <vector>

struct Vector2 {
    int x, y;

    Vector2(int _x, int _y)
        : x(_x)
        , y(_y) {}

    Vector2(const Vector2& vec)
        : x(vec.x)
        , y(vec.y) {
        std::cout << "[Copy] Vector2{" << x << "," << y << "} copied!"
                  << std::endl;
    }

    void Print() {
        std::cout << "[Print] Vector2{" << x << "," << y << "}" << std::endl;
    }
};

void PrintVectors(const std::vector<Vector2>& vectors) {
    std::cout << "---" << std::endl;
    for (auto& vector : vectors) {
        std::cout << "Vector2{" << vector.x << "," << vector.y << "}"
                  << std::endl;
    }
}

int main() {
    std::vector<Vector2> vectors;
    vectors.push_back({21, 78});

    PrintVectors(vectors);

    // First
    vectors.pop_back();
    if (vectors.empty()) {
        std::cout << "Empty condition!" << std::endl;
    }
    vectors[0].Print(); // ---> I thought I'd get an error at this point.
    vectors.insert(vectors.begin(), {vectors[0].x + 1, vectors[0].y});
    PrintVectors(vectors);

    // Second
    vectors.pop_back();
    vectors[0].Print();
    vectors.insert(vectors.begin(), {vectors[0].x + 1, vectors[0].y});
    PrintVectors(vectors);

    // Third + no pop_back needed
    vectors[0].Print();
    vectors.insert(vectors.begin(), {vectors[0].x + 1, vectors[0].y});
    PrintVectors(vectors);

    // 4th
    vectors.pop_back();
    vectors[0].Print();
    vectors.insert(vectors.begin(), {vectors[0].x + 1, vectors[0].y});
    PrintVectors(vectors);
}

然后,这个条件让我通过 gdb 进行调试。我看到_M_ 的值在变化,但我不知道发生了什么(我看不到_M_start 和_M_finish 之间的模式或关系)。

【问题讨论】:

  • 试试.at(0) 而不是[0]。

标签: c++ stl stdvector


【解决方案1】:

使用operator[] 访问索引为 0 的空向量超出范围,因此 undefined behaviour 这样做会使您的整个程序无效。允许编译器生成它想要的任何结果。 任何行为都是可以接受的。 你无法推理包含 UB 的程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 2018-06-15
    • 2015-09-08
    • 2021-12-21
    相关资源
    最近更新 更多