C++教程-C++输入迭代器

C++ 输入迭代器
- 输入迭代器(Input Iterator)是用于从容器读取值的迭代器。
- 解引用输入迭代器允许我们从容器中检索值。
- 输入迭代器不会修改容器的值。
- 它是单向迭代器,只能向前遍历。
- 它可以递增,但不能递减。
- 输入迭代器可用的运算符有递增运算符(++)、递减运算符(--)、解引用运算符(*)、不等运算符(!=)和等号运算符(==)。
- 输入迭代器由Istream产生。
- 前向迭代器、双向迭代器和随机访问迭代器都是有效的输入迭代器。
属性 | 有效表达式 |
---|---|
输入迭代器是可复制构造、可复制赋值和可销毁的。 | X b(a); b=a; |
可以使用相等或不等运算符进行比较。 | a==b; a!=b; |
可以解引用。 | *a; |
可以递增。 | ++a; |
其中'X'是输入迭代器类型,而'a'和'b'是迭代器类型的对象。
输入迭代器的特性
- 相等/不相等运算符:输入迭代器可以使用相等或不等运算符进行比较。当两个迭代器指向相同位置时,它们相等,否则不相等。假设'A'和'B'是两个迭代器:
A ==B; // 相等运算符
A!=B; // 不相等运算符
让我们看一个简单的例子:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> v{1, 2, 3, 4, 5};
vector<int>::iterator itr, itr1;
itr = v.begin();
itr1 = v.begin() + 1;
if (itr == itr1)
std::cout << "Both the iterators are equal" << std::endl;
if (itr != itr1)
std::cout << "Both the iterators are not equal" << std::endl;
return 0;
}
输出:
Both the iterators are not equal
在上面的例子中,itr和itr1是两个迭代器。这两个迭代器都是vector类型的。'itr'是指向vector的第一个位置的迭代器对象,而'itr1'是指向vector的第二个位置的迭代器对象。因此,这两个迭代器指向相同的位置,所以条件itr1!=itr返回true值并打印“Both the iterators are not equal”。
- 解引用迭代器:我们可以通过解引用运算符(*)来解引用迭代器。假设'A'是一个迭代器:
- A // 通过解引用'A'迭代器。
让我们看一个简单的例子:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> v{11, 22, 33, 44};
vector<int>::iterator it;
it = v.begin();
cout << *it;
return 0;
}
输出:
11
在上面的例子中,'it'是一个迭代器对象,指向vector 'v'的第一个元素。通过解引用迭代器*it返回迭代器指向的值。
- 可交换:指向两个不同位置的两个迭代器可以进行交换。
让我们看一个简单的例子:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector<int> v{11, 22, 33, 44};
vector<int>::iterator it, it1, temp;
it = v.begin();
it1 = v.begin() + 1;
temp = it;
it = it1;
it1 = temp;
cout << *it << " ";
cout << *it1;
return 0;
}
输出:
22 11
在上面的例子中,通过使用第三个迭代器的对象temp,交换了'it'和'it1'两个迭代器。