在C++ 11中,有两个版本std::vector::resize():
void resize( size_type count );
void resize( size_type count, const value_type& value);
Run Code Online (Sandbox Code Playgroud)
我理解(正如对该问题的答案之一的评论之一所建议的),第一个要求value_type是默认可构造的,而第二个要求它是可复制构造的.但是,(gcc 4.7.0)
using namespace std;
typedef int block[4];
vector<block> A;
static_assert(is_default_constructible<block>::value,";-("); // does not fire
A.resize(100); // compiler error
Run Code Online (Sandbox Code Playgroud)
所以要么我的理解是错误的,要么gcc是错误的.哪一个?
在调整向量大小时,它将调用构造函数然后销毁它.
struct CAT
{
CAT(){cout<<"CAT()"<<endl;}
CAT(const CAT& c){cout<<"CAT(const CAT& c)"<<endl;};
~CAT(){cout<<"~CAT()"<<endl;};
};
int main()
{
vector<CAT> vc(6);
cout<<"-----------------"<<endl;
vc.resize(3);
cout<<"-----------------"<<endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
$./m
CAT()
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
~CAT()
-----------------
CAT() //why resize will call constructor?
~CAT()
~CAT()
~CAT()
~CAT()
-----------------
~CAT()
~CAT()
~CAT()
Run Code Online (Sandbox Code Playgroud)
我使用的是ubuntu 13.10和gcc4.8
哪个操作在C++中成本最高?
1.调整向量的大小(将大小减小1)
2.删除向量中的最后一个元素