C++ Primer 学习笔记——顺序容器的string操作
2016-02-27 15:08
761 查看
vector对象的增长
分配比新的空间更大的内存空间,容器预留这些空间作为备用,直到备用也用完时(大小超过当前的capacity时),才重新分配内存空间
构造string
string上的操作
string搜索操作
compare
分配比新的空间更大的内存空间,容器预留这些空间作为备用,直到备用也用完时(大小超过当前的capacity时),才重新分配内存空间
#include<iostream> #include<vector> using namespace std; int main() { vector<int> v; cout << v.size() << endl << v.capacity() << endl; v.reserve(40);//分配至少容纳40个元素的内存空间 for (int index = 0; index < 24; ++index) v.push_back(index); v.shrink_to_fit();//将多余内存退回给系统 cout << v.size() << endl << v.capacity();//最多可以保存多少元素 return 0; }
构造string
//string的构造函数 string s(cp,n);//从cp指向的数组中拷贝前n个元素 string s(s2,pos2);//从s2字符串的pos2坐标开始拷贝,直到遇到\0 string s(s2,pos2,len2);//从s2字符串的pos2坐标开始拷贝,拷贝len2个 //substr成员函数 s.substr(开始位置,计数器);//从原始string中拷贝
//9.41 vector<char> vec; char ch; while (cin >> ch) vec.push_back(ch); string s(vec.begin(), vec.end());
string上的操作
append(...) replace(...) insert(...) erase(...)
//9.43 void f(string &s, string oldVal, string newVal) { int index = 0; string s2(s, index, oldVal.size()); while (s2 != oldVal) index++;//先找到oldval所在坐标 s.erase(index, oldVal.size()); s.insert(index, newVal); } //9.44 void f(string &s, string oldVal, string newVal) { int index = 0; string s2(s, index, oldVal.size()); while (s2 != oldVal) index++; s.replace(index, oldVal.size(), newVal); }
string搜索操作
find(...) rfind(...)//从右开始搜索 find_first_of(...) find_first_not_of(...)
//9.47 string s("ab2c3d7R4E6"); string numbers("123456789"); string str("abcdRE"); int pos=0; while ((pos = s.find_first_of(numbers,pos)) != string::npos) { cout << pos << endl; pos++; } pos = 0; while ((pos = s.find_first_not_of(numbers, pos)) != string::npos) { cout << pos << endl; pos++; } return 0;
compare
相关文章推荐
- 1071. Speech Patterns (25)
- 理解c语言指针很关键的几句话,二维数组与指针类型的分析
- c语言中关于变量作用域问题
- 九度-题目1023:EXCEL排序
- C语言实现选择排序、直接插入排序、冒泡排序的示例
- 1070. Mooncake (25)
- /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found错误的解决
- C语言(按键获取与函数)
- c++ 设计模式9 (Abstract Factory 抽象工厂模式)
- C语言的画图(圆形动画)
- 1069. The Black Hole of Numbers (20)
- 在VS2015中用C++编写可被其它语言调用的动态库DLL
- C++ 线程安全的singleton如何实现
- c++(重载、覆盖、隐藏)
- c语言库函数 qsort(快速排序函数)
- [C++ Calculator 项目] 初试
- C语言(类型转换)
- 关于C++编译时内链接和外链接
- Hello World 引发的思考
- C++11的资源管理:泛化的RAII