c++ - 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;
}
解决方案
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...
}
}
推荐阅读
- r - R中的列/行
- r - 在估计不同类别的平均值时获得相同的值
- visual-studio - Visual Studio 2019:关闭浏览器窗口时停止调试器,但在调试停止时不关闭浏览器
- javascript - '${}' 不能按 javascript 的意图工作
- julia - Julia 在执行函数或其每一行时没有返回相同的值
- javascript - 如何解决“未捕获的类型错误:无法读取未定义的属性'参数'”reactjs + django
- sql-server - 连接数据库表:在一个表中为第二个表中的每个组重复值
- html - 我希望轮播的文本停止移动。我该怎么做?
- azure - 为什么我无法访问模板输出中 publicIpAddress 的某些字段?
- c++ - 为什么它没有按正确的顺序打印?