CPP47. 迭代器遍历容器
描述
键盘输入 5 个整数,将这些数据保存到 vector 容器中,采用正向迭代器和反向迭代器分别遍历 vector 中的元素并输出。输入描述
输入 5 个整数输出描述
示例1
输入:
1 2 3 4 5
输出:
1 2 3 4 5 5 4 3 2 1
C++ 解法, 执行用时: 2ms, 内存消耗: 308KB, 提交时间: 2022-02-08
#include <iostream> // write your code here...... #include <vector> #include <bits/stdc++.h> using namespace std; int main() { // write your code here...... vector<int> v; int a; while(cin >> a){ v.push_back(a); } vector<int>::iterator iter = v.begin(); while(iter != v.end()){ cout << *iter << " "; iter++; } cout << endl; while(iter != v.begin()){ iter--; cout << *iter << " "; } cout << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 388KB, 提交时间: 2022-01-24
#include <iostream> // write your code here...... #include <vector> using namespace std; int main() { // write your code here...... vector<int> v; v.resize(5); for (int i = 0; i < 5; i++){ cin >> v[i]; } for (vector<int>::iterator it = v.begin(); it < v.end(); it++){ cout << *it << ' '; } cout << endl; for (vector<int>::reverse_iterator it = v.rbegin(); it != v.rend(); it++){ cout << *it <<' '; } cout << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 388KB, 提交时间: 2021-11-22
#include <iostream> // write your code here...... #include <vector> using namespace std; int main() { // write your code here...... vector<int>v; int num=0; for(int i=1;i<=5;i++) { cin >> num; v.push_back(num); } for(vector<int>::iterator it = v.begin();it != v.end();it++) { cout << *it << " "; } cout << endl; for(vector<int>::iterator it = v.end()-1 ;it != v.begin()-1;it--) { cout << *it << " "; } cout << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 396KB, 提交时间: 2021-10-31
#include <iostream> // write your code here...... #include <vector> using namespace std; int main() { // write your code here...... vector<int> i_vec; for(int i=0,val; i<5; ++i){ cin >> val; i_vec.push_back(val); } for(auto f_it=i_vec.begin(); f_it!=i_vec.end(); ) cout << *f_it++ << ' '; cout << endl; for(auto b_it=i_vec.rbegin(); b_it!=i_vec.rend(); ) cout << *b_it++ << ' '; cout << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 408KB, 提交时间: 2021-11-14
#include <iostream> #include<vector> // write your code here...... using namespace std; int main() { // write your code here...... vector<int> arr; for(int i=1;i<=5;i++){ int a; cin>>a; arr.push_back(a); } vector<int>::iterator it = arr.begin(); for(it;it!=arr.end();it++) cout<<*it<<" "; cout<<endl; it = arr.end()-1; for(int i=1;i<=5;i++){ cout<<*it<<" "; it--; } return 0; }