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

This is a c++ stl programming question. Please write in regular code and nothing

ID: 3685526 • Letter: T

Question

This is a c++ stl programming question. Please write in regular code and nothing too advanced please. Thanks.

Vector Container:

1a. Write a template function(in header file) to search a value stored in a vector and return the position(index) of the item if found; otherwise, return a negative value. Then write a driver to test it. The driver should at least test two different type of vector. Use vector index to do it.

1b. Write a template function(in header file) to search a value stored in a vector and return the position(index) of the item if found; otherwise, return a negative value. Then write a driver to test it. The driver should at least test two different type of vector. Use iterator to do it.

Explanation / Answer

searchVector.h

#include <vector>
using namespace std;

template<class T>
int searchByIndex(vector<T>& v,T& a) {
for(int i=0;i<v.size();++i)
{
    if(a==v[i])
    {
        return i;
    }
}
return -1;
}

template<class T>
int searchByIterator(vector<T>& v,T& a) {
int index=0;
typedef typename vector<T>::iterator iterator;
for(iterator it=v.begin();it!=v.end();++it)
{
    if(a==*v)
    {
        return index;
    }
    index++;
}
return -1;
}

testIndex.cpp(driver class for index wise searching)

#include <iostream>
#include <vector>
#include "searchVector.h"
using namespace std;

int main()
{
   vector<int> v1;
   for(int i=0;i<5;++i)
   {
       v1.push_back(i);  
   }
   int x=3;
   cout<<searchByIndex(v1,x)<<endl;
   x=9;
   //should print -1 as element is not there in the vector
   cout<<searchByIndex(v1,x)<<endl;

   vector<char> v2;
   v2.push_back('a');
   v2.push_back('c');
   v2.push_back('d');
   v2.push_back('b');

   char c='d';
   cout<<searchByIndex(v2,c)<<endl;
   c='f';
   //should print -1 as element is not there in the vector
   cout<<searchByIndex(v2,c)<<endl;


}

output

3

-1

2

-1

testIterator.cpp

#include <iostream>
#include <vector>
#include "searchVector.h"
using namespace std;

int main()
{
   vector<int> v1;
   for(int i=0;i<5;++i)
   {
       v1.push_back(i);  
   }
   int x=3;
   cout<<searchByIterator(v1,x)<<endl;
   x=9;
   //should print -1 as element is not there in the vector
   cout<<searchByIterator(v1,x)<<endl;

   vector<char> v2;
   v2.push_back('a');
   v2.push_back('c');
   v2.push_back('d');
   v2.push_back('b');

   char c='d';
   cout<<searchByIterator(v2,c)<<endl;
   c='f';
   //should print -1 as element is not there in the vector
   cout<<searchByIterator(v2,c)<<endl;


}

output

3

-1

2

-1

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