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

Write a function named problem2 in a header file that accepts two arguments: a t

ID: 656539 • Letter: W

Question

Write a function named problem2 in a header file that accepts two arguments: a two dimensional
vector of a template type and a value of the sample template type as is
stored in the 2D vector. Search for a value in the given two dimensional 2D
vector and return the x,y coordinate of an element with that value or return
std::make_pair(-1, -1) if the element is not present.

This function then should run using the code below.

int main( int argc, char** argv) {

   std::vector< std::vector<int>> matrix(3, std::vector<int>(3, 0));
   matrix.at(2).at(1) = 5;
   std::vector< std::vector<std::string>> matrix2(4, std::vector<std::string>(2, "hello"));
   matrix2.at(0).at(1) = "world";
   if (std::make_pair(2, 1) != problem2(matrix, 5) or
           std::make_pair(-1, -1) != problem2(matrix, 8) or
           std::make_pair(0, 1) != problem2(matrix2, std::string("world"))) {
       std::cerr<<"Test 2 failed. ";
   }
   else {
       std::cerr<<"Test 2 passed. ";
       score += 10;
   }

Explanation / Answer

Program code:

// Matrix vector.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include "Matrix.h"

#include <iostream>

#include <vector>

using namespace std;

int main( int argc, char** argv)

{

    std::vector<std::vector<int>> matrix(3, std::vector<int>(3, 0));

    matrix.at(2).at(1) = 5;

    int score=0;

    std::vector< std::vector<std::string>> matrix2(4, std::vector<std::string>(2, "hello"));

    matrix2.at(0).at(1) = "world";

    if (std::make_pair(2, 1) != problem2(matrix, 5) || std::make_pair(-1, -1) != problem2(matrix, 8) )

    {  

         std::cerr<<"Test 2 failed. ";

    }

    else

    {

         std::cerr<<"Test 2 passed. ";

         score += 10;

    }

    system("pause");

    return 0;

}

//Matrix.h

#ifndef Matrix

#define Matrix

#include <iostream>

#include <vector>

using namespace std;

template <class T1> std::pair<T1, T1> problem2(vector<vector<T1>> mat, T1 value)

{

    for(int i=0;i<mat.size();i++)

    {

         for(int j=0; j<mat.at(i).size();j++)

         {

             if(mat[i][j]==value)

             {               

                 return (std::pair<T1, T1>(i, j));

             }       

         }

    }

    return std::make_pair(-1, -1);

}

#endif

Sample Output:

Test 2 passed.

Press any key to continue . . .

Note: Please the check the code. The required code is highlighted in bold letters. The if condition in the main function has been modified too.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote