个性化阅读
专注于IT技术分析

C++输入迭代器

  • 输入迭代器是用于从容器读取值的迭代器。
  • 取消引用输入迭代器可以使我们从容器中检索值。
  • 它不会更改容器的值。
  • 它是单向迭代器。
  • 可以增加, 但不能减少。
  • 可以用于输入迭代器的运算符是增量运算符(++), 减量运算符(-), 解引用运算符(*), 不等于运算符(!=)和等于运算符(==)。
  • 输入迭代器由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是两个迭代器。这两个迭代器都是向量类型的。 “ itr”是指向向量的第一位置的迭代器对象, “ itr1”是指向向量的第二位置的迭代器对象。因此, 两个迭代器都指向相同的位置, 因此条件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”是指向向量“ 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”迭代器。

赞(0)
未经允许不得转载:srcmini » C++输入迭代器

评论 抢沙发

评论前必须登录!