菜鸟笔记
提升您的技术认知

C++ 输入迭代器

阅读 : 690

Input Iterator是用于从容器读取值的迭代器。
取消引用输入迭代器使我们能够从容器中检索值。
它不会更改容器的值。
这是一个单向迭代器。
可以递增,但不能递减。
可用于输入迭代器的运算符为增量运算符(++),减量运算符(-),解引用运算符(*),不等于运算符(!=)和等于运算符(==)。
Istream 产生输入迭代器。
正向迭代器,双向迭代器和随机访问迭代器都是有效的输入迭代器。

属性 有效表达式
输入迭代器是可复制构造的,可分配复制的和可破坏的。 X b(a);
b = a;
可以使用相等或不相等运算符进行比较。 a == b;
a!= b;
可以取消引用。 * a;
它可以递增。 ++ a;

其中" X"是输入迭代器类型,而" a"和" b"是迭代器类型的对象。

输入迭代器的特征:

相等/不相等运算符: 可以使用相等或不相等运算符比较输入迭代器。仅当两个迭代器都指向同一位置时,两个迭代器才相等。假设" A"和" B"是两个迭代器:

A ==B;   // equality operator
A!=B;   // inequality operator

让我们看一个简单的示例:

#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并显示" 两个迭代器都不相等"。
取消引用迭代器: 我们可以使用取消引用运算符(*)取消引用迭代器。假设" A"是一个迭代器:

*A     //  Dereferencing 'A' iterator by using *.

让我们看一个简单的示例:

       #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"迭代器。