std::next在以某些no表示高級後返回指向元素的迭代器。職位。它在頭文件中定義。
它不修改其自變量,並返回由指定數量增加的自變量的副本。如果它是random-access迭代器,則該函數僅使用一次運算符+或運算符-進行前進。否則,該函數在複製的迭代器上重複使用遞增或遞減運算符(運算符++或運算符-),直到已推進n個元素。
用法:
ForwardIterator next (ForwardIterator it, typename iterator_traits::difference_type n = 1); it:Iterator to the base position. difference_type: It is the numerical type that represents distances between iterators of the ForwardIterator type. n:Total no. of positions by which the iterator has to be advanced. In the syntax, n is assigned a default value 1 so it will atleast advance by 1 position. 返回:It returns an iterator to the element n positions away from it.
// C++ program to demonstrate std::next
#include <iostream>
#include <iterator>
#include <deque>
#include <algorithm>
using namespace std;
int main()
{
// Declaring first container
deque<int> v1 = { 1, 2, 3, 4, 5, 6, 7 };
// Declaring another container
deque<int> v2 = { 8, 9, 10 };
// Declaring an iterator
deque<int>::iterator i1;
// i1 points to 1
i1 = v1.begin();
// Declaring another iterator to store return
// value and using std::next
deque<int>::iterator i2;
i2 = std::next(i1, 4);
// Using std::copy
std::copy(i1, i2, std::back_inserter(v2));
// Remember, i1 stills points to 1
// and i2 points to 5
// v2 now contains 8 9 10 1 2 3 4
// Displaying v1 and v2
cout << "v1 = ";
int i;
for (i = 0; i < 7; ++i) {
cout << v1[i] << " ";
}
cout << "\nv2 = ";
for (i = 0; i < 7; ++i) {
cout << v2[i] << " ";
}
return 0;
}
輸出:
v1 = 1 2 3 4 5 6 7 v2 = 8 9 10 1 2 3 4
How can it be helpful ?
- 列表中的前進迭代器:由於list支持雙向迭代器,因此隻能使用++和--運算符進行遞增。因此,如果我們想將迭代器前進一個以上的位置,則使用std::next可能非常有用。
// C++ program to demonstrate std::next #include <iostream> #include <iterator> #include <list> #include <algorithm> using namespace std; int main() { // Declaring first container list<int> v1 = { 1, 2, 3, 7, 8, 9 }; // Declaring second container list<int> v2 = { 4, 5, 6 }; list<int>::iterator i1; i1 = v1.begin(); // i1 points to 1 in v1 list<int>::iterator i2; // i2 = v1.begin() + 3; // This cannot be used with lists // so use std::next for this i2 = std::next(i1, 3); // Using std::copy std::copy(i1, i2, std::back_inserter(v2)); // v2 now contains 4 5 6 1 2 3 // Displaying v1 and v2 cout << "v1 = "; int i; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { cout << *i1 << " "; } cout << "\nv2 = "; for (i1 = v2.begin(); i1 != v2.end(); ++i1) { cout << *i1 << " "; } return 0; }
輸出:
v1 = 1 2 3 7 8 9 v2 = 4 5 6 1 2 3
說明:在這裏,請看一下如何隻複製列表的選定部分,然後才能使用std::next,否則我們不能使用帶有列表支持的雙向迭代器的+ =,-=運算符。因此,我們使用了std::next並將迭代器直接前進了三個位置。
相關用法
注:本文由純淨天空篩選整理自 std::next in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。