当应用于向量时,我在理解 C++ clear 函数的行为时遇到了一些困难。
我尝试编译并运行以下函数:
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
unsigned int i;
vector<int> myvector;
myvector.push_back (1);
myvector.push_back (2);
myvector.push_back (3);
cout << "myvector contains:";
for (i=0; i<myvector.size(); i++) cout << " " << myvector[i];
myvector.clear();
myvector.push_back (11);
myvector.push_back (12);
cout << "\nmyvector contains:";
for (i=0; i<myvector.size(); i++) cout << " " << myvector[i];
cout << endl;
cout << " entry3 = " << myvector[2]<<endl;
return 0;
}
这是输出:
myvector contains: 1 2 3
myvector contains: 11 12
entry3 = 3
怎么可能在清空vector的时候,vector的第三个entry的信息还没有被擦除呢?