C++STL中resize()和reserve()的区别

C++STL中resize()和reserve()的区别

简而言之,resize()会构造出新的元素,而reserve()只是为元素预留出空间而已。

resize()

#include<iostream>
#include<vector>
using namespace std;

class A
{
public:
    int val;
};

int main(){
    vector<A> vec;
    vec.resize(10);
    return 0;
}

上述代码中,resize()函数调用的是默认构造函数。

#include<iostream>
#include<vector>
using namespace std;

class A
{
public:
    int val;
    A(int n){
        val = n;
    }
};

int main(){
    vector<A> vec;
    vec.resize(10);
    return 0;
}

上述代码会编译报错,原因是有了显式提供的有参构造函数,编译器就不会再提供默认构造函数了。这时可以为类添加一个无参构造函数即可。

#include<iostream>
#include<vector>
using namespace std;

class A
{
public:
    int val;
    A(){}
    A(int n){
        val = n;
    }
};

int main(){
    vector<A> vec;
    vec.resize(10);
    for(int i=0;i<vec.size();i++){
        cout<<vec[i].val<<endl;
    }
    return 0;
}

输出结果为:

0
0
0
0
0
0
0
0
0
0

reserve()

#include<iostream>
#include<vector>
using namespace std;

class A
{
public:
    int val;
    A(){}
    A(int n){
        val = n;
    }
};

int main(){
    vector<A> vec;
    vec.reserve(10);
    for(int i=0;i<vec.size();i++){
        cout<<vec[i].val<<endl;
    }
    return 0;
}

注意,reserve()只是预留空间,而不会构造新的元素出来,所以上述代码的运行是不会有输出的。

猜你喜欢

转载自blog.csdn.net/qq_38600065/article/details/109079523
今日推荐