Non*_*714 2 c++ stl vector c++11
我看到了这个问题,并注意到一条评论说:
也许你在其中一个向量上走出界限?
我不要求有关索引与[]哪个是出界,这显然是出界的一个元素.从我所知道的,这不是OP所做的.(我可能完全错了.)我没有听说过任何其他与出境有关的案例std::vector.
我被教导使用时矢量被保护免受越界限制.push_back(/*data*/).由于评论员的声誉很高,我的评论来自于知识的深度.该问题中的OP使用.push_back(),再次,我认为这是一个std::vector成员函数,不受出界限制.
std::vector在这方面我是否应该了解一些比C++更专业的人可以解释的东西?
不,他们不是该受保护的.C++使得它更容易正确:
std::vector<int> v;
for (int i : v) // cannot go out of bounds
Run Code Online (Sandbox Code Playgroud)
但总的来说,不能总是事先证明你是对的:
std::vector<int> v = something();
int i = v[v[0]]; // How would the compiler know if it's legal?
Run Code Online (Sandbox Code Playgroud)
为了使这个安全无关v,你可以写
int i = v.at(v.at(0)); // might throw at runtime
Run Code Online (Sandbox Code Playgroud)
但由于额外的运行时检查,这个速度较慢.