Please code in c++, please just code the template and the printVector function,
ID: 3733475 • Letter: P
Question
Please code in c++, please just code the template and the printVector function, please keep the code simple
------------------------------
Assume all other coding, include, etc....use the following pieces of code and write the function printVector that will display the vector by using a function template, and using a const_iterator for outputting vector elements. (Consider using auto in your iterator's declaration)
// prototype for function template printVector
template <tyename T> void printVector(const vector <T>& integers2);
.....
vecctor <int> integers;
//function push_back is in vectors
integers.push_back(2);
integers.push_back(3);
integers.push_back(4);
cout << " Output vector using iterator notation: ";
printVector(integers);
// YOUR CODE HERE......
Explanation / Answer
Have inserted comments in the code for explaination.
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void printVector(const vector <T>& integers2) {
// defined a constant iterator for type of vector passed in the template.
typename vector<T>::const_iterator pos = integers2.begin();
//iteration over vector of integers
for(;pos!= integers2.end(); pos++) {
cout<<*pos<<" ";
}
cout<<endl;
}
int main() {
vector<int> integers;
integers.push_back(2);
integers.push_back(3);
integers.push_back(4);
cout << " Output vector using iterator notation: ";
printVector(integers);
}
Copy paste the code and store it in file. Then run g++ <filename.cpp> to generate a.out.
using command ./a.out will generate the below output.
Output:
Output vector using iterator notation: 2 3 4