本文主要是介绍About the reverse_iterator,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
reverse_iterator: 反向迭代器
A copy of the original iterator (the base iterator) is kept internally and used to reflect the operations performed on the reverse_iterator: whenever the reverse_iterator is incremented, its base iterator is decreased, and vice versa. A copy of the base iterator with the current state can be obtained at any time by calling member base.
Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the reversed range).
简单说就是,如果用一个正常iterator去初始化reverse_iterator, 结果就是指向base iterator的前一个。或者你也可以直接指定rbegin() 或者rend().
直接使用:
// vector::rbegin/rend
#include <iostream>
#include <vector>int main ()
{std::vector<int> myvector (5); // 5 default-constructed intsint i=0;std::vector<int>::reverse_iterator rit = myvector.rbegin();for (; rit!= myvector.rend(); ++rit)*rit = ++i;std::cout << "myvector contains:";for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';return 0;
}
output是:
myvector contains: 5 4 3 2 1
或者就是更严格的来定义reverse_iterator,for example:
// reverse_iterator example
#include <iostream> // std::cout
#include <iterator> // std::reverse_iterator
#include <vector> // std::vectorint main () {std::vector<int> myvector;for (int i=0; i<10; i++) myvector.push_back(i);typedef std::vector<int>::iterator iter_type;// ? 0 1 2 3 4 5 6 7 8 9 ?iter_type from (myvector.begin()); // ^// ------>iter_type until (myvector.end()); // ^//std::reverse_iterator<iter_type> rev_until (from); // ^// <------std::reverse_iterator<iter_type> rev_from (until); // ^std::cout << "myvector:";while (rev_from != rev_until)std::cout << ' ' << *rev_from++;std::cout << '\n';return 0;
}
output is:
myvector: 9 8 7 6 5 4 3 2 1 0
这篇关于About the reverse_iterator的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!