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.