通常,头文件中应该只定义确实必要的东西,应该养成这个好习惯。
string 类型的输入操作符对空白字符的处理:读取并忽略有效字符(非空白字
符)之前所有的空白字符,然后读取字符直至再次遇到空白字符,读取终止(该
空白字符仍留在输入流中)。
getline 函数对空白字符的处理:不忽略行开头的空白字符,读取字符直至遇到
换行符,读取终止并丢弃换行符(换行符从输入流中去掉但并不存储在 string
对象中)。
为了避免溢出,保存一个string对象size的最安全的方法就是使用标准库类型string :: size_type
应采用C标准库头文件的C++版本。
#include<cctype>
#include<ctype.h>
string str1;
string str2("hello world!");
for(string::size_type val=0;val < str2.size();val++)
str1[val] = str2[val] ;
//这样子是错误的,str1默认初始化为空字符串,不能使用下标val.
可以改成这样:
str1 += str2[val];
vector也是一样,必须是已存在的元素才能用下标操作符进行索引。通过下标操作进行赋值时,不会添加任何元素。
任何改变vector长度的操作都会使已存在的迭代器失效。例如,在调用push_back之后,就不能再信赖指向vector的迭代器的值了。
vector<int>::iterator mid = (vi.begin() + vi.end())/2;
将两个迭代器相加的操作是未定义的,因此用这种方法计算 mid 会出现编译错误。
读一组整数到 vector 对象,计算并输出每对相邻元素的和。如果读入元素个数
为奇数,则提示用户最后一个元素没有求和,并输出其值。然后修改程序:头
尾元素两两配对(第一个和最后一个,第二个和倒数第二个,以此类推),计
算每对元素的和,并输出:
相邻球和:
#include<vector>
#include<iostream>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
// 读入数据到 vector 对象
cout << "Enter numbers(Ctrl+D to end):" << endl;
while (cin>>ival)
ivec.push_back(ival);
// 计算相邻元素的和并输出
if (ivec.size() == 0) {
cout << "No element?!" << endl;
return -1;
}
cout << "Sum of each pair of adjacent elements in the vector:"
<< endl;
for (vector<int>::size_type ix = 0; ix < ivec.size()-1;
ix = ix + 2)
{
cout << ivec[ix] + ivec[ix+1] << "\t";
if ( (ix+1) % 6 == 0) // 每行输出 6 个和
cout << endl;
}
if (ivec.size() % 2 != 0) // 提示最后一个元素没有求和
cout << endl
<< "The last element is not been summed "
<< "and its value is "
<< ivec[ivec.size()-1] << endl;
return 0;
}
首尾求和:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
//读入数据到 vector 对象
cout << "Enter numbers:" << endl;
while (cin>>ival)
ivec.push_back(ival);
//计算首尾配对元素的和并输出
if (ivec.size() == 0) {
cout << "No element?!" << endl;
return -1;
cout << "Sum of each pair of counterpart elements in the vector:"
<< endl;
vector<int>::size_type cnt = 0;
for (vector<int>::size_type first = 0, last = ivec.size() - 1;
first < last; ++first, --last) {
cout << ivec[first] + ivec[last] << "\t";
++cnt;
if ( cnt % 6 == 0) //每行输出 6 个和
cout << endl;
}
if (first == last) //提示居中元素没有求和
cout << endl
<< "The center element is not been summed "
<< "and its value is "
<< ivec[first] << endl;
return 0;
}