reverseiterators.cpp

来自「C++高级编程这本书所附的源代码」· C++ 代码 · 共 49 行

CPP
49 行
字号
#include <algorithm>#include <vector>#include <iostream>#include <iterator>using namespace std;// Function template to populate a container of ints.// The container must support push_back().template<typename Container>void populateContainer(Container& cont){  int num;  while (true) {    cout << "Enter a number (0 to quit): ";    cin >> num;    if (num == 0) {      break;    }    cont.push_back(num);  }}int main(int argc, char** argv){  vector<int> myVector;  populateContainer(myVector);  int num;  cout << "Enter a number to find: ";  cin >> num;  vector<int>::iterator it1;  vector<int>::reverse_iterator it2;  it1 = find(myVector.begin(), myVector.end(), num);  it2 = find(myVector.rbegin(), myVector.rend(), num);  if (it1 != myVector.end()) {    cout << "Found " << num << " at position " << it1 - myVector.begin()	 << " going forward.\n";    cout << "Found " << num << " at position "	 << it2.base() - 1 - myVector.begin() << " going backward.\n";  } else {    cout << "Failed to find " << num << endl;  }  return (0);}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?