在Vector容器中有以下几个关于大小的函数admin管理员组文章数量:1611902
方法 | 效果 |
size() | 返回容器的大小 |
empty() | 判断容器是否为空 |
max_size() | 返回容器最大的可以存储的元素 |
capacity() | 返回容器当前能够容纳的元素数量 |
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> sentence;
sentence.reserve(5);
//append some elements
sentence.push_back("hello");
sentence.push_back("how");
sentence.push_back("are");
sentence.push_back("you");
sentence.push_back("?");
copy(sentence.begin(), sentence.end(), ostream_iterator<string>(cout, " "));
cout << endl;
//print "technical data"
cout << "max_size():" << sentence.max_size() << endl;
cout << "size():" << sentence.size() << endl;
cout << "capacity():" << sentence.capacity() << endl;
cout << "**************************" << endl;
//swap second and fourth element
swap(sentence[1], sentence[3]);
//insert element "always" before element "?"
sentence.insert(find(sentence.begin(), sentence.end(), "?"), "always");
//assign "!" to the last element
sentence.back() = "!";
copy(sentence.begin(), sentence.end(), ostream_iterator<string>(cout, " "));
cout << endl;
//print "technical data"
// return maximum possible length of sequence
//回容器的最大可以存储的元素个数,这是个极限,当容器扩展到这个最大值时就不能再自动增大
cout << "max_size():" << sentence.max_size() << endl;
// return length of sequence
cout << "size():" << sentence.size() << endl;
// return current length of allocated storage
cout << "capacity():" << sentence.capacity() << endl;
system("Pause");
return 0;
}
本文标签: 区别sizeVectormaxsizeCapacity
版权声明:本文标题:vector的size(),capacity(),max_size()的用法和区别 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728621277a1166388.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论