Write a C++ program that uses a function to search a 2D vector of floats. The fu
ID: 3588098 • Letter: W
Question
Write a C++ program that uses a function to search a 2D vector of floats.
The function will have 2 parameters:
1. A 2 dimensional vector of floats, v
2. The floating point number that you are searching for, item
The function will return a vector objects. Each object will contain the row and column of each instance where the item is found in the 2D vector.
If the vector does not contain the item that it is searched for, the vector returned will only have 1 object. Within this object, the value -1 will be stored in the row member. Output to the console screen a message indicating that the vector did not contain this item if this is the case.
The main function will:
1. Output the contents of the 2D vector
2. Output the item number that you are searching for
3. Call the function that will search the 2D vector
4. Output the locations of where the item can be found within the 2D vector or output a message indicating that the item is not located within the 2D vector.
Sample Run #1
Sample Run #2
Explanation / Answer
#include<iostream>
#include<vector>
using namespace std;
struct item{
int a,b;
};
int rows,columns;
vector<item> search(float **a, int b){
vector<item> res;
item c;
for (int i = 0; i<rows; i++){
for (int j =0; j<columns; j++){
if (a[i][j] == b){
c.a = i;
c.b = j;
res.push_back(c);
}
}
}
if (res.size() == 0){
c.a = -1;
c.b = 0;
res.push_back(c);
}
return res;
}
int main(){
int n;
vector<item> res;
cout << "Enter number of rows for 2D: ";
cin >> rows;
cout << "Enter number of columns for 2D: ";
cin >> columns;
float **data;
data = new float *[n];
for (int i = 0; i<rows; i++)
data[i] = new float[columns];
cout << "Enter data for 2D : ";
for (int i = 0; i<rows; i++)
for (int j = 0; j<columns; j++)
cin >> data[i][j];
cout << "Enter number to be searched :";
cin >>n;
res = search(data,n);
cout << "The item that you searched for is : " << n << endl;
if (res.size() == 1){
if (res[0].a == -1){
cout << "The vector did not contain the item you searched for." << endl;
}
else {
cout << "The item that you searched for can be found at following location(s) ->" << endl;
cout << res[0].a << " " << res[0].b << endl;
}
}
else {
cout << "The item that you searched for can be found at following location(s) ->" << endl;
for (int i = 0; i<res.size(); i++)
cout << res[i].a << " " << res[i].b << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.