关于c++的容器大小的操作

#include<iostream>
#include<vector>
using namespace std;
void main()
{
vector<int>a(10);
cout<<a.max_size()<<endl;
}
为什么输出了1073741823不输出10?

一,容器分为顺序容器和联合容器。其中顺序容器有 vector, list deque头文件分别为
#include<vector>
#include<list>
#include<deque>
要把元素放入容器内。必须该元素要支持复制拷贝操作,因为cin cout等流对象不支持拷贝,同时引用也不支持拷贝,所以这些对象不能放入容器类内。
构造函数如下:
C<type> obj; //空容器
C<type> obj(copyfrom); //拷贝构造
C<type> obj(begin, end); //拷贝begin 和end之间的元素,包括begin不包括end
C<type> obj(n, eletype); //构造容器包含n个元素,每个元素值为eletype
最后一种只能顺序容器专用的
C<type> obj(n); //构造容器对象,为n个已初始化元素

利用容器类嵌套可以模仿多元数组,如
vector< vector<int> > obj; //容器obj里的元素为包含int元素的容器对象.相当于二元数组

二,添加元素到容器类内
把元素加入顺序容器可以使用push_back(ele);方法,如
string word;
while (cin >> word)
container.push_back(word);
除了可以使用push_back之外,list和deque(双端队列)还支持push_front(ele)方法

int i = 0;
list<int> ilist;
for (i = 0; i != 5; i++)
ilist.push_front(i);
其他插入方法有insert,有三种重载形式如下
insert(p, t); //在p(iterator)之前插入元素值为t
insert(p, n, t); //在p之前插入n个元素值为t
insert(p, b, e); //在p之前插入一一列元素由b和e指示

三,map的用法示例
/*
* A program to transform words.
* Takes two arguments: The first is name of the word transformation file
* The second is name of the input to transform
*/
int main(int argc, char **argv)
{
// map to hold the word transformation pairs:
// key is the word to look for in the input; value is word to use in the output
map<string, string> trans_map;
string key, value;
if (argc != 3)
throw runtime_error("wrong number of arguments");
// open transformation file and check that open succeeded
ifstream map_file;
if (!open_file(map_file, argv[1]))
throw runtime_error("no transformation file");
// read the transformation map and build the map
while (map_file >> key >> value)
trans_map.insert(make_pair(key, value));
// ok, now we're ready to do the transformations
// open the input file and check that the open succeeded
ifstream input;
if (!open_file(input, argv[2]))
throw runtime_error("no input file");
string line; // hold each line from the input
// read the text to transform it a line at a time
while (getline(input, line)) {
istringstream stream(line); // read the line a word at a time
string word;
bool firstword = true; // controls whether a space is printed
while (stream >> word) {
// ok: the actual mapwork, this part is the heart of the program
map<string, string>::const_iterator map_it =
trans_map.find(word);
// if this word is in the transformation map
if (map_it != trans_map.end())
// replace it by the transformation value in the map
word = map_it->second;
if (firstword)
firstword = false;
else
cout << " ";// print space between words
cout << word;
}
cout << endl; // done with this line of input
}
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-26
容器大小是size(),不是max_size()
size()是实际存储个数,返回的才是10
max_size()指的是一个vector结构可供储存元素的个数的上线,通常是由于寻址空间决定的。追问

那个最多元素个数是怎么算出来的?

追答

这个不大清楚

本回答被提问者采纳
相似回答