我是使用矢量的新手,使用它们有点困惑。我写了一些代码,并在评论中添加了一些问题。除了我的评论中的问题,为什么我们需要使用reserve()
进行分配?如果我们分配,我们将使用不会吗?如果我们需要分配,resize()
比reserve()
更有用吗?我真的被卡住了。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a_vector( 10 );
// equal vector<int> a_vector( 10,0 ); ?
cout << "value of vector first " << a_vector.at(0) << endl; //LEGAL
// cout << a_vector.at(10); // ILLEGAL
cout << "vector size " << a_vector.size() << endl;
a_vector.push_back( 100 );
cout << "value of vector at ten " << a_vector.at(10) << endl; //LEGAL
cout << "vector size " << a_vector.size() << endl;
a_vector.pop_back();
cout << "vector size " << a_vector.size() << endl;
a_vector.resize( 12 );
// also does it mean a_vector[10] = 0; and a_vector[11] = 0;?
cout << "vector size " << a_vector.size() << endl;
cout << "value of vector at ten " << a_vector.at(10) << endl; //LEGAL
cout << "value eleventh " << a_vector.at(11) << endl; //LEGAL
a_vector.pop_back();
a_vector.pop_back();
cout << "vector size " << a_vector.size() << endl;
for (int i = 0; i < 2; i++)
{
//doesn't it same as a_vector.resize( 12 ); now ?
//so why do we need resize(); ?
//also do I need reserve() for using push_back() like this ?
a_vector.push_back(0);
}
cout << "vector size " << a_vector.size() << endl;
a_vector.pop_back();
a_vector.pop_back();
cout << "vector size " << a_vector.size() << endl;
return 0;
}
答案 0 :(得分:2)
vector<int> a_vector( 10 ); // equal vector<int> a_vector( 10,0 ); ?
是的,它隐含vector<int> a_vector(10, int());
。
cout << "value of vector first " << a_vector.at(0) << endl; //LEGAL // cout << a_vector.at(10); // ILLEGAL
不违法,只会抛出异常。
a_vector.resize( 12 ); // also does it mean a_vector[10] = 0; and a_vector[11] = 0;?
是。新元素是默认构造的。
for (int i = 0; i < 2; i++) { //doesn't it same as a_vector.resize( 12 ); now ? //so why do we need resize(); ? //also do I need reserve() for using push_back() like this ? a_vector.push_back(0); }
是的,在这种情况下它是一样的。致电resize
的时间更短。
总结:
resize
删除或添加默认构造值,以便使容器的大小为一个reserve
更多地与容器的容量有关,这是动态分配的数组的内部大小