Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program must be written in C++; The purpose of this lab is to practice working w

ID: 3840065 • Letter: P

Question

       Program must be written in C++;  The purpose of this lab is to practice working with vectors.  ______________________________________________________________________________     Some notes about vectors:  A vector is an object that contains a sequence of other objects inside it. The objects inside are all of the same type. They are numbered starting with 0. If the whole vector is called v then the items in it are written v[0], v[1], v[2], ... The last item is v[v.size()-1] NOT v[v.size()]. New items can be "pushed" onto the end of the vector. The last item can be "popped" off of a vector. Vectors can therefore change size. We can find out the current size of a vector: v.size() Vectors can be empty. If so v.empty() is true. If a vector is empty then v[i] and v.pop.... crash. Vectors are empty. by default, when created. Vectors should be passed by reference whenever possible. ______________________________________________________________________________   Write a program that reads an unknown number of integers from a data file called data.txt into a vector of integers named V. V is initially empty and grows as the user reads data from file.     Once done copying data into vector V, you need to print the contents of V and perform some other tasks on the vector as described below.     Your program should do the following:    Create an empty vector of integers V.  Read the integers from data.txt into V.  You may assume data.txt contains the following numbers:   5   6   12   87   100   28   35   66   77   29 Ask the user to input a key. Then search for the key in vector V and inform the user about the existence (true / false) of the key in V. Print the contents of V. 

Explanation / Answer

#include<iostream>
#include<fstream>
#include<vector>
using namespace std;

int main() {

ifstream inputFile;
vector<int> v;
int x;
inputFile.open("data.txt");

if (inputFile.is_open()) {
while (!inputFile.eof()) {


inputFile >> x;
v.push_back(x);


}
}
int key;
bool found = false;
cout<<"Enter the key: ";
cin >> key;
for(int i=0;i<v.size(); i++){
if(v[i]==key){
cout<<"Key found"<<endl;
found = true;

break;
}
}
if(!found){
cout<<"Key not found"<<endl;
}
cout<<"Vector elements are: "<<endl;
for(int i=0;i<v.size(); i++){
cout<<v[i]<<" ";
}
cout<<endl;
inputFile.close();
return 0;
}

Output: