您的位置:首页 > 编程语言 > C语言/C++

C++ Primer 学习笔记——顺序容器的string操作

2016-02-27 15:08 761 查看
vector对象的增长

分配比新的空间更大的内存空间,容器预留这些空间作为备用,直到备用也用完时(大小超过当前的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: