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

Using Vector in C++ Write a template function that takes as a parameter a vector

ID: 3783610 • Letter: U

Question

Using Vector in C++

Write a template function that takes as a parameter a vector of objects of some unknown class and two objects obj1 and obj2 of the same class. Modify the input vector to replace every instance of obj1 in the vector with obj2. If no instances of obj1 are found, add a new element at the end of the vector containing obj2. (Recall that you can access vectors like arrays, but they have useful methods like size and push_back. Vector declarations look like this: vector varName; Vectors are also covered further in the book in Section A.6.3 - page 707.)

Explanation / Answer

Hi friend, Please find my implementation of function.

template <class someType>
void replaceObj(vector<someType> list, someType obj1, someType obj2) {

   int isOccur = 0;

   for(int i=0; i<list.size(); i++){
       // replace each occurence of obj1 with obj2
       if(obj1 == list[i]){
           list[i] = obj2;
           isOccur = 1;
       }
   }
   // if obj1 is not present in list, then add obj2 at end
   if(isOccur == 0)
       list.push_back(obj2);

}


Note:
   someType class should override '==' operator

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