首页 > 解决方案 > vector::size() 是否可能返回错误值?

问题描述

在一个 c++ 编程课程中,我们做了一个练习,在这种情况下,我决定在 for range 中使用 std::vector 的函数“size”而不是迭代器。然后我的老师告诉我,“有时”函数大小可能会返回错误值,因此 for 循环可能会超出范围或不够。

我在 4 个不同的编译器中用 c++ 编写了将近 2 年,但我不认为这是真的。

vector 的 size() 函数会返回错误的值吗?

编辑:我同意这个问题不需要代码,因为这是一个理论案例,但我会用简短的​​版本来说明你:

#include <iostream>
#include <vector>

using namespace std;

typedef vector<uint64_t> telephone_nums;

int main(int argc, const char * argv[]) {
    vector<telephone_nums> telephone_mat;

    // adding elements to telephone_mat

    for (size_t x = 0; x < telephone_mat.size(); ++x){
        for (size_t y = 0, len = telephone_mat[x].size(); y < len; ++y){
            //modification in the matriz...
        }
    }

    return 0;
}

标签: c++for-loop

解决方案


vector 的 size() 函数会返回错误的值吗?

当然。当您需要的“正确”值不是向量的大小时,它可能会返回“错误”值。

我的老师告诉我的是“size()”“不应该在任何情况下使用”

这是非常愚蠢的夸张。

size()在我看来,尽管在初学者看来是正确的,但在某些情况下,带有索引的循环会出错,这会更正确。在大多数情况下,虽然一个特定的循环是正确的,但有一个更好的替代方案,可以说更具可读性且不易出错。但是仍然有一些循环的索引和size()优越性,尽管这种情况可能并不常见。

一个初学者在不知不觉中编写具有未定义行为的程序的典型示例,即使该程序在初学者眼中看起来是正确的:

for (size_t x = 1; x <= telephone_mat.size(); ++x)

另一个典型的初学者错误:

for (size_t i = 0; i < vec.size(); ++i)
    if (condition)
        vec.erase(vec.begin() + i);

编写循环的一种可能更简单的方法的示例(尽管这是否适用取决于向量的修改方式):

for (auto& nums : telephone_mat){
    for (auto& element : nums){
        //modification in the matriz...
    }
}

推荐阅读