Use iterators to go through a data structure. Use a loop to read in some number
ID: 3574109 • Letter: U
Question
Use iterators to go through a data structure. Use a loop to read in some number of integers into a vector. Once you have populated the vector with integers, use two iterators
to compare the first and last elements, followed by the comparison of the second and second-to-last, and so on. Make sure to use the iterator libary #include <iterator>
bash-4.1 /iterator Enter an integer (-1 to exit) 10 Enter an integer (-1 to exit) 15 Enter an integer (-1 to exit) 20 Enter an integer (-1 to exit) 20 Enter an integer (-1 to exit) 10 Enter an integer (-1 to exit) 10 Enter an integer (-1 to exit) -1 front: 10 back:10 are equal. front:15 back:10 are not equal front: 20 back:20 are equal. -bash-4.1$Explanation / Answer
Your Program :
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
std :: vector<int> myvector ; //vector of intrger
int main() {
int input;
while(input!=-1){
cout << "Enter an integer (-1 to exit) :" << endl;
if(input == -1){break;}
cin >> input; //taking input from user into vector
myvector.push_back(input); //pushing the input to vector
}
vector<int>::iterator it; //initialize iterator
int n = myvector[myvector.size()-2];
int i=0; //counter
for(it=myvector.begin() ; it < myvector.end()-2; it++,i++){
if(*it == n){ //comparision of elements
cout << "front : " << *it << " " << "and back : " << n << " " << "are equal" << endl;
}
else{
cout << "front : " << *it << " " << "and back : " << n << " " << "are not equal" << endl;
}
}
return 0;
}
Output :
Enter an integer (-1 to exit) : 1
Enter an integer (-1 to exit) : 10
Enter an integer (-1 to exit) : 20
Enter an integer (-1 to exit) : 20
Enter an integer (-1 to exit) : 10
Enter an integer (-1 to exit) : 20
Enter an integer (-1 to exit) : -1
front : 1 and back: 20 are not equal
front : 10 and back: 20 are not equal
front : 20 and back: 20 are equal
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.