std::string的resize()与reserve()的区别:
resize():改变的是size()与capacity()的大小
(1)、比原来的变小之后,后面的会被截断
(2)、比原来的变大之后,后面的会被填充新的东西,不同的编译器可能会不同
reserve():改变的只是capacity()的大小
程序如下:
#include <math.h>
#include <stdio.h>
#include <string>
#include<iostream>using namespace std;int main()
{std::string s1("hello");std::cout << "s1=" << s1 << " s1.size=" << s1.size() << " s1.capacity=" << s1.capacity() << endl;std::cout << "after resize to 2" << endl;s1.resize(2); //尺寸由5改变为2,多余字符被截掉了,只剩下hestd::cout << "s1=" << s1 << " s1.size=" << s1.size() << " s1.capacity=" << s1.capacity() << endl;std::cout << "after resize to 100" << endl;s1.resize(100);//尺寸由2改变为100,后面的数据被填充了98个astd::cout << "s1=" << s1 << " s1.size=" << s1.size() << " s1.capacity=" << s1.capacity() << endl;std::cout << "\n";std::cout << "===================================================================" << endl;std::cout << "\n";std::string s2("hello");std::cout << "s2=" << s2 << " s2.size=" << s2.size() << " s2.capacity=" << s2.capacity() << endl;std::cout << "after reserve to 20" << endl;s2.reserve(20); //只改变capacity()的大小,其他的不变std::cout << "s2=" << s2 << " s2.size=" << s2.size() << " s2.capacity=" << s2.capacity() << endl;std::cout << "after reserve to 2" << endl;s2.reserve(2); //只改变capacity()的大小,其他的不变std::cout << "s2=" << s2 << " s2.size=" << s2.size() << " s2.capacity=" << s2.capacity() << endl;return 0;
}
结果: