gpt4 book ai didi

c++ - Vector::at 与 vector::operator[]——不同的行为

转载 作者:行者123 更新时间:2023-11-28 06:25:31 25 4
gpt4 key购买 nike

<分区>

#include <iostream>
#include <vector>
#include <stdexcept>

using namespace std;

class sample
{
public:
sample()
{
cout << "consructor called" << endl;

}
void test()
{
cout << "Test function" << endl;
}
};

int main()
{
vector<sample> v;
sample s;
v.push_back(s);

try
{
v.at(1).test(); // throws out of range exception.
v[1000].test(); // prints test function
}
catch (const out_of_range& oor)
{
std::cerr << "Out of Range error: " << oor.what() << '\n';
}
return 0;
}

为什么 v[1000].test(); 在屏幕上打印测试函数。我在 vector 中只添加了一个对象。我同意我可以访问 v[1000] 因为它是顺序的。但是为什么它给出了完全正确的结果呢?提前致谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com