C++ 迭代器::next() 函数



C++ iterator::next() 函数返回一个迭代器,该迭代器指向您在从当前元素递增迭代器指针后获得的元素。它返回已根据指定数量提前的实参的副本,而不会更改原始实参。

如果该函数是随机访问迭代器,则它仅使用一次 operator+ 或 operator-。否则,在前进 n 个元素之前,该函数会重复将递增或递减运算符 (operator++ 或 operator—) 应用于复制的迭代器。

语法

以下是 C++ iterator::next() 函数的语法 -

ForwardIterator next (ForwardIterator it, typename iterator_traits<ForwardIterator>::difference_type n = 1);

参数

  • it − 它指示当前位置。
  • n − 它指示必须迭代的次数。

示例 1

让我们考虑以下示例,我们将使用 next() 函数并检索输出。

#include <iostream>
#include <iterator>
#include <vector>
int main() {
   std::vector<int> tutorial{ 11,22,33,44 };
   auto it = tutorial.begin();
   auto nx = std::next(it,1);
   std::cout << *it << ' ' << *nx << '\n';
}

输出

当我们编译并运行上述程序时,这将产生以下结果 -

11 22

示例 2

在以下示例中,我们将声明两个数组并对第二个数组应用 next() 函数,该函数返回完整的第二个数组以及第一个数组的四个元素。

#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
using namespace std;
int main() {
   list<int> t1 = {123,234,345,456,567,678};
   list<int> t2 = { 11,22,33,44};
   list<int>::iterator i1;
   i1 = t1.begin();
   list<int>::iterator i2;
   i2 = std::next(i1, 4);
   std::copy(i1, i2, std::back_inserter(t2));
   cout << "\nResult = ";
   for (i1 = t2.begin(); i1 != t2.end(); ++i1) {
      cout << *i1 << " ";
   }
   return 0;
}

输出

运行上述程序后,它将产生以下结果 -

Result = 11 22 33 44 123 234 345 456 

示例 3

考虑以下示例,我们将运行循环并应用 next() 函数来检索输出。

#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
int main () {
   std::list<int> mylist;
   for (int i = 0; i < 10; i++) mylist.push_back (i*1);
   std::cout << "mylist:";
   std::for_each (mylist.begin(),
      std::next(mylist.begin(),4),
   [](int x) {
      std::cout << ' ' << x;
   } );
   std::cout << '\n';
   return 0;
}

输出

运行上述程序后,它将产生以下结果 -

mylist: 0 1 2 3
广告

© . All rights reserved.