Sring vector iterator
P75-101
标准库类型 string
String 表示可变长的字符序列,使用string类型必须首先包含string头文件,它输入时是以空格结束输入的,要使能够输入一整行,可以使用getline函数,例如:
string line;
while (getline(cin, line))
cout << line << endl;
return 0;
像这样的程序结束输入按CTRL+Z即可。它与数组的最大不同在于它是“内置”的可变长的字符串,它可以任意相加(必须有一个是string类型);可以将它类比为数组,因此,下标的范围是0--n-1 。
同时,在有一种基于范围的for语句可以进行对string 类型字符串的输出,例如:
string s("hello,world!");
for (auto &ss : s)
ss = toupper(ss);
cout << s << endl;
注意:string与字符串字面值不是同一种类型,只是string兼容里C中的字符串。
在上述的例子中,触发getline函数返回的那个换行符实际上被丢弃了,得到的string对象中并不包含该换行符。
标准库类型 vector
标准库类型vector表示对象的集合,其中所有对象的类型都相同。集合中的每个对象都有一个与之对应的索引,索引用于访问对象。在列表初始化时用{}。vector可以在CPP程序运行时进行高效能的增长。在向vector对象中添加元素时,使用push_back()函数较为方便,例如:
string text;
vector<string> ss;
while (cin >> text)
{
ss.push_back(text);
}
return 0;
注意:vector对象可以高效增长,范围for语句体内不应该有改变其所遍历序列的大小。
Vector对象和string对象可以使用下表运算访问已经存在的元素,而不能够添加元素。
迭代器的使用 iterator
我们可以使用string对象和vector对象通过下表运算来访问元素,同样地,迭代器也可以。同时,跟指针类型一样,迭代器可以对对象进行间接的访问。有效的迭代器或者指向某个元素,或者指向容器中的尾元素的下一个位置,而其他的情况均属于无效。
如果容器为空,那么,begin和end返回的是同一个迭代器,都是尾后迭代器。
泛型编程的概念:在C++中多使用 != 而不是 < 或者 <= 等之类的运算符,这是因为这种编程风格在标准库提供的所有容器上都是有效的。
cbegin()和cend()函数是专门得到const_iterator类型的返回值的函数。
为了简化表达式和提供通用性,C++语言定义里箭头运算符 -> 。箭头运算符吧解引用和成员访问两个操作结合在一起,也就是说,it->men 和(*it).men是同样的意思。
注意:凡是使用里迭代器的循环体,都不要向迭代器所属的容器内添加元素。
同时,迭代器也有简单的算术运算和关系运算。
例如:注意一下for输出循环和迭代器中常用的for语句输出的区别 :
string ss;
vector<string> text;
while (cin >> ss)
{
text.push_back(ss);
}
for (auto it : text)
cout << it << " ";
cout << endl;
for (auto ite = text.cbegin(); ite != text.cend() && !ite->empty(); ++ite)
cout << *ite << " ";
cout << endl;
return 0;
附录:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> Vint;
int vint;
while (cin >> vint)
Vint.push_back(vint);
if (Vint.empty())
{
cout << "Ther is no element in Vint." << endl;
return -1;
}
cout << "the adding element side by sideis : " << endl;
for (auto it = Vint.begin(); it != Vint.end() - 1; it++)
{
cout << *it + *(++it) << " ";
if ((it-Vint.begin()+1)% 10 == 0)
cout << endl;
}
if (Vint.size() % 2 != 0)
cout << *(Vint.end() - 1) << endl;
return 0;
}
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<int> Vint;
int vint;
while (cin >> vint)
Vint.push_back(vint);
if (Vint.cbegin() == Vint.cend())
{
cout << "There is no element in thevector! " << endl;
return -1;
}
auto beg = Vint.begin();
auto end = Vint.end();
for (auto it = Vint.begin(); it != beg + (end - beg) / 2; it++)
{
cout << *it + *(beg+(end-it)-1) << " ";
if ((it - beg + 1) % 5 == 0)
cout << endl;
}
if (Vint.size()% 2 != 0)
cout << *(beg+(end-beg)/2) << endl;
return 0;
}