1.迭代器
Java 设计模式的迭代器模式,主要是实现通用型遍历方式。C++中所有标准库容器都可以使用迭代器进行访问对象元素
- begin 为迭代器的第一个迭代器,正向迭代器
- end 为迭代器的下一迭代器
- 如果容器相同,则 begin 和 end 返回相同一个迭代器,即同为尾迭代器
/**
* 迭代器
*/
int main() {
string str("hello world");
cout << "Before = " << str << endl;
// 确保 str 非空
if (str.begin() != str.end()) {
// 正向迭代器
string::iterator strItr = str.begin();
while(strItr != str.end()) {
*strItr = toupper(*strItr); // 大写字母转换
cout << *(strItr++) << " ";// 移动内存地址
}
cout << endl;
}
cout << "After = " << str << endl;
return 0;
}
运行结果
Before = hello world
H E L L O W O R L D
After = HELLO WORLD
2.迭代器运算 - (iter + n)
iter + n : 迭代器的新位置比原来向前移动了 n 个位置
string str("hello world");
// 确保 str 非空
if (str.begin() != str.end()) {
string::iterator beginItr = str.begin();
string::iterator endItr = str.end();
/**
* iter + position : 迭代器的新位置比原来向前移动了 position 个位置
*/
int position = (endItr-beginItr) / 2;
string::iterator midItr = beginItr + position;
while(beginItr != str.end()) {
cout << "beginItr = " << *(beginItr++) << endl;
}
while(midItr != str.end()) {
cout << "midItr = " << *(midItr++) << endl;
}
}
运行结果
beginItr = h
beginItr = e
beginItr = l
beginItr = l
beginItr = o
beginItr =
beginItr = w
beginItr = o
beginItr = r
beginItr = l
beginItr = d
midItr =
midItr = w
midItr = o
midItr = r
midItr = l
midItr = d
3.C++ 中的 != 运算符
Java程序的时候大部分都是使用 <= 或 >=为主,很少像c++这么简单粗暴。因为c++ 中遍历大部分是使用带带去而非下标