标准模版库学习之序列式容器
vector[html]/**目的:学习vector容器的使用。*程序输出:hello, how are you ?max_size(): 134217727size(): 5capacity(): 5hello, you are how always !max_size(): 134217727size(): 6capacity(): 7 //书上说容量会扩充一倍,即:10*经过测试当size()达到8时,capacity()才会扩充为10。请教后知道是编译器不同导致。*总结:reserve()可以用来尽量减少内存重新配置的次数,但不能杜绝,因此,即使使用了reserve(),*每次执行安插或移除操作后,一定要考虑迭代器是否有效,一般会重新生成迭代器。*而且reserve元素数量太多会浪费内存,太小或不使用会导致效率低下(会经常发生内存重新配置)。*/#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std;int main(){vector<string> sentence;vector<string>::iterator it = sentence.begin();sentence.reserve(5);sentence.push_back("hello,");sentence.push_back("how");sentence.push_back("are");sentence.push_back("you");sentence.push_back("?");// 创建迭代器时容量为0,后边添加数据时发生了内存重新配置,所以it迭代器失效了,使用vector一定要谨记此条。//it++; //error!!!!!!!!copy(sentence.begin(), sentence.end(), ostream_iterator<string> (cout, " "));cout << endl;cout << "max_size(): " << sentence.max_size() << endl; //return maximum possible length of sequence。可以理解成硬件允许的最大值cout << "size(): " << sentence.size() << endl;cout << "capacity(): " << sentence.capacity() << endl;swap(sentence[1], sentence[3]);sentence.insert(find(sentence.begin(), sentence.end(), "?"), "always"); //?之前加入always//sentence.insert(find(sentence.begin(), sentence.end(), "?"), "always"); //测试用//sentence.insert(find(sentence.begin(), sentence.end(), "?"), "always"); //sentence.back() = "!"; //“!”覆盖最后一个元素即“?”copy(sentence.begin(), sentence.end(), ostream_iterator<string> (cout, " "));cout << endl;cout << "max_size(): " << sentence.max_size() << endl;cout << "size(): " << sentence.size() << endl;cout << "capacity(): " << sentence.capacity() << endl;getchar();}list[html]/*目的:学习List容器的使用及常用操作(splice、merge等)*程序输出:list1: 0 1 2 3 4 5list2: 0 1 2 3 4 5list1:list2: 0 1 2 0 1 2 3 4 5 3 4 5list1:list2: 1 2 0 1 2 3 4 5 3 4 5 0list1: 0 0 1 1 2 2 3 3 4 4 5 5list2: 0 1 2 3 4 5list1: 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5list2:注意:splice()和merge()做的是移动操作,不是复制*/#include <iostream>#include <list>#include <algorithm>using namespace std;void printLists(const list<int> &l1, const list<int> &l2){cout << "list1: ";copy(l1.begin(), l1.end(), ostream_iterator<int>(cout, " "));cout << endl << "list2: ";copy(l2.begin(), l2.end(), ostream_iterator<int>(cout, " "));cout <<endl << endl;}int main(){list<int> list1, list2;for (int i = 0; i < 6; ++i){list1.push_back(i);list2.push_back(i);}printLists(list1, list2);//注意:splice()和merge()做的是移动操作,不是复制list2.splice(find(list2.begin(), list2.end(), 3), list1);printLists(list1, list2);list2.splice(list2.end(), list2, list2.begin());printLists(list1,list2);list2.sort();list1 = list2;list2.unique();printLists(list1, list2);list1.merge(list2);printLists(list1, list2);getchar();}deque[html]/*目的:学习deque容器的使用。*程序输出:first stringstringstringstringlast stringstring //下标0another stringanother string补充:综合编程 , 其他综合 ,
上一个:1-Overview of UML
下一个:标准模版库学习之关联式容器