ex9.40:程序中读入了256/512/1000/1048 个词,在resize之后容器的capacity可能是多少?
知识点考查:
(1)vector对象是如何增长的:
为了支持快速随机访问,vector对象将元素连续存储;
假定容器中元素连续存储,且容器大小可变,当向vector和String中添加元素,如果没有空间容纳新元素,为了保证元素连续存储,容器必须分配新的内存空间,将旧元素移动到新空间,然后添加新元素,释放旧存储空间。如果每添加一个新元素,vector就执行一次内存分配和内存释放,性能会很慢。因此,vector和string的实现通常会分配比新的空间需求更大的内存空间
(2)容器大小管理操作
c.shrink_to_fit()//将capacity()减少为与size()相同大小,适用于vector string deque
c.size() //已经保存的元素的数目
c.capacity() //不重新分配内存的前提下,c至少可以保存多少元素
/*-----------------capacity和reserve只适用于vector和string----------------*/
c.reserve(n) //预先分配至少能容纳n个元素的内存空间
c.resize() //只改变容器中元素的数量,而不是容器的容量
注意:只要没有操作需求超出vector的capacity,vector就不能重新分配内存空间
代码如下:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void fun(int num)
{
vector<string>svec;
svec.reserve(1024);
string word;
for (int i=0;i<num;i++)
{
svec.push_back("ok");
}
svec.resize(svec.size()+svec.size()/2);
cout << "读入" << num << "个词后容器的 size=" << svec.size() << " capacity=" << svec.capacity() << endl;
cout << endl;
}
int main()
{
fun(256);
fun(512);
fun(1000);
fun(1048);
return 0;
}
ex9.43:编写一个函数,接受三个string参数s,oldVal,newVal,使用迭代器及insert erase函数将s中所有oldVal替换为newVal.测试程序,用它替换通用的简写形式,如将”tho”替换为”though”,将”thru”替换为”through”.
知识点考查:
(1)认识std::distance函数
distance (InputIterator first, InputIterator last);
Return value:The number of elements between first and last.
Parameters
first: Iterator pointing to the initial element.
last: Iterator pointing to the final element. This must be reachable from first.
InputIterator shall be at least an input iterator.
(2)认识std::advance函数
void advance (InputIterator& it, Distance n);//使得迭代器it前进n步
Return value: none
Advance iterator: Advances the iterator it by n element positions.
Parameters:
it
Iterator to be advanced.
InputIterator shall be at least an input iterator.
n
Number of element positions to advance.
This shall only be negative for random-access and bidirectional iterators.
Distance shall be a numerical type able to represent distances between iterators of this type.
(3)
s.erase(pos,len)
//删除从位置pos开始的len个字符,如果len被省略,则删除从pos开始直至s末尾的所有字符
s.insert(pos,args)
//在pos之前插入args指定的字符,pos可以是一个下标或一个迭代器
代码如下:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void find_Replace(string& s, const string& oldVal, const string& newVal)
{
for (auto it = s.begin();
distance(it, s.end()) >=distance(oldVal.begin(), oldVal.end());
)
{
if (string{ it, it + oldVal.size() } == oldVal)//使用迭代器,判断查找字符相同的方法
{
it = s.erase(it, it + oldVal.size());
it = s.insert(it,newVal.cbegin(),newVal.cend());
advance(it, newVal.size());
}
else
++it;
}
}
int main()
{
{
string str{ "To drive straight thru is a foolish, tho courageous act." };
find_Replace(str, "thru", "through");
find_Replace(str, "tho", "though");
std::cout << str << std::endl;
}
{
string str{"To drive straight thruthru is a foolish, thotho courageous act." };
find_Replace(str, "thru", "through");
find_Replace(str, "tho", "though");
std::cout << str << std::endl;
}
{
string str{ "my world is a big world" };
find_Replace(str, "world","worldddddddddddd");
std::cout << str << std::endl;
}
return 0;
}
ex9.44:重写上一题的函数,这次使用一个下标和replace.
**知识点考查:**
s.replace(pos,len,args)
//从下标pos位置开始len长度的字符替换成args,这里args参数是str字符串
s.replace(b,e,args)//将迭代器b,e直接元素替换为args
//具体args可代表什么,参照书本
代码如下:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void find_Replace(string& s, const string& oldVal, const string& newVal)
{
for (string::size_type i = 0; i != s.size(); i++)
//size()这个函数返回的类型,绝对不是整形,而是size_type类型的
{
if (s.substr(i,oldVal.size())==oldVal)//使用for循环判断查找相同字符串方法
{
s.replace(i,oldVal.size(),newVal);
i += newVal.size() - 1;//?
}
}
}
int main()
{
{
string str{ "To drive straight thru is a foolish, tho courageous act." };
find_Replace(str, "thru", "through");
find_Replace(str, "tho", "though");
cout << str << endl;
}
return 0;
}
ex9.45:编写一个函数,接受一个表示名字的string参数和两个分别表示前缀(如”Mr.”,”Ms.”)和后缀(如”Jr”,”III”)的字符串。使用迭代器及Insert和append函数将前缀和后缀添加到指定的名字中,将生成的新string返回。
知识点考查:insert(iter,args), 这里args是一对迭代器,即insert(iter,b2,e2)
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void func(string &name, const string &frontVal, const string &backVal)
{
auto it1 = name.begin();
name.insert(it1, frontVal.begin(), frontVal.end());
name.append(backVal);
}
int main()
{
string str = "Xia ";
func(str,"Ms ","Jr");
cout << str<< endl;
return 0;
}
ex9.46:重写45题,使用位置和长度来管理string,并使用insert.
知识点考查: insert(pos,args),即在位置pos之前插入args指定的字符
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void func(string &name, const string &frontVal, const string &backVal)
{
/*auto it1 = name.begin();
it1=name.insert(it1, frontVal.begin(), frontVal.end());
name.insert(it1+ frontVal.size()+backVal.size()+1, backVal.begin(), backVal.end());
*/
name.insert(0,frontVal);
name.insert(name.size(), backVal);
}
int main()
{
string str = "Xia";
func(str,"Ms.",",Jr");
cout << str<< endl;
return 0;
}
ex9.47:编写程序,首先查找string”ab2c3d7RE6”中的每个字符,然后查找其中每个字母字符。编写两个版本的程序,第一个用find_first_of,第二个用find_first_not_of.
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string str("ab2c3d7R4E6");
string numbers("0123456789");
string alphabet{ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" };
for (string::size_type pos = 0; (pos = str.find_first_of(numbers, pos)) != string::npos;++pos)//循环判断条件:返回值npos
{
cout << "find number at index:" << pos <<", element is"<< str[pos] << endl;
}
cout <<"------------------------------------------------------"<<endl;
for (string::size_type pos = 0; (pos = str.find_first_of(alphabet, pos)) != string::npos; ++pos)
{
cout << "find alphabet at index: " << pos << ", element is " << str[pos] << endl;
}
cout << endl;
for (string::size_type pos = 0; (pos = str.find_first_not_of(numbers, pos)) != string::npos; ++pos)
{
cout << "find not number at index: " << pos << ", element is " << str[pos] << endl;
}
return 0;
}
ex9.49:如果一个字母延伸到中线之上,如d,f,则称其有上出头部分;如果延伸到中线之下,如p,g,则称其有下出头部分;编写实现,读入一个单词文件,输出最长的既不包含上出头也不包含下出头部分的单词。
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main(int argc, char**argv)
{
string s = "acenmorsuvwxz";
ifstream infile("1.txt");//和cpp一个文件下
string str;
infile >> str;//单词文件读入
cout << "读入的字符串为:" << str << endl;
unsigned pos1 = 0;
unsigned pos2 = 0;
unsigned lenMax = 0;
unsigned pos3 = 0;//记录不出头串的首位置
while ((pos1 = str.find_first_of(s, pos1)) != string::npos)//找到第一个不出头字符
{
pos2 = pos1;
if ((pos2 = str.find_first_not_of(s, pos2)) != string::npos)//从第一个不出头字符开始找到第一个出头字符
{
if (pos2 - pos1 >= lenMax)//找出最大长度并记录此区间的首位置
{
lenMax = pos2 - pos1;
pos3 = pos1;
}
}
++pos1;
}
string s2 = str.substr(pos3, lenMax);
cout << "最长的不出头串:" << s2 << endl;
return 0;
}
ex9.50:编写程序,处理一个vector,其元素都表示整型值。计算vector中所有元素之和。修改程序,使之计算表示浮点值的string之和。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int sum_int(vector<string>svec)
{
int sum = 0;
for (auto i : svec)
sum += stoi(i);
return sum;
}
int sum_float(vector<string>svec)
{
int sum = 0;
for (auto i : svec)
sum += stof(i);
return sum;
}
int main()
{
vector<string>svec = {"1","2.2","3.5","6"};
cout << sum_int(svec) << endl;
cout << sum_float(svec) << endl;
return 0;
}
//输出结果 12
// 12
ex9.51:设计一个类,它有三个unsigned成员,分别表示 年月日,为其编写构造函数,接收一个表示日期的string参数。构造函数应处理不同的数据格式,如1/1/1900, Jan 1 1900, January 1, 1900。
代码如下:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class my_Date
{
public:
my_Date(const string&s);
unsigned year;
unsigned month;
unsigned day;
void show()
{
cout << year << "年" << month << "月" << day << "日" << endl;
}
};
my_Date::my_Date(const string&s)
{
unsigned format = 0;
//! 1/1/1900
if (s.find_first_of("/") != string::npos)
format = 0x10;
//! Jan 1, 1900
if (s.find_first_of(",")>=4 && s.find_first_of(",") != string::npos)
format = 0x01;
switch (format)
{
case 0x10:
day = stoi(s.substr(0,s.find_first_of("/")));
month = stoi(s.substr(s.find_first_of("/")+1,
s.find_last_of("/")-s.find_first_of("/")-1
)
);
year = stoi(s.substr(s.find_last_of("/")+1, 4));
break;
//! format = January 1, 1900 or Jan 1, 1900
case 0x01:
day = stoi(s.substr(s.find_first_of("1234567890"),
s.find_first_of(",") - s.find_first_of("1234567890")
)
);
if (s.find("Jan") < s.size()) month = 1;//if (s.find("January") < s.size()) month = 1;
if (s.find("Feb") < s.size()) month = 2;
if (s.find("Mar") < s.size()) month = 3;
if (s.find("Apr") < s.size()) month = 4;
if (s.find("May") < s.size()) month = 5;
if (s.find("Jun") < s.size()) month = 6;
if (s.find("Jul") < s.size()) month = 7;
if (s.find("Aug") < s.size()) month = 8;
if (s.find("Sep") < s.size()) month = 9;
if (s.find("Oct") < s.size()) month = 10;
if (s.find("Nov") < s.size()) month = 11;
if (s.find("Dec") < s.size()) month = 12;
year = stoi(s.substr(s.find_last_of(" ") + 1, 4));
break;
}
}
int main()
{
// my_Date d3("January1,1900");
my_Date d1("Jan 6, 1900");
my_Date d2("02/10/2017");
d1.show();
d2.show();
return 0;
}