How to print a vector using template in C++

1 Answer

0 votes
#include <vector>
#include <string>
#include <iostream>

template <class T>
void print_vector(const std::vector<T>& v) {
    for (T n : v) {
        std::cout << n << "\n";
    }
    
    std::cout << "\n";
}
 
int main()
{
    std::vector<int> vecint = { 2, 8, 9, 12, 5, 17, 189 };
    std::vector<double> vecdouble = { 2.3, 0.04, 3.8, 12.01, 15.0 };
    std::vector<std::string> vecstring = { "c++", "vector", "template" };

    print_vector(vecint);
    print_vector(vecdouble);
    print_vector(vecstring);
}
  
      
      
/*
run:
      
2
8
9
12
5
17
189

2.3
0.04
3.8
12.01
15

c++
vector
template

*/

 



answered Dec 26, 2024 by avibootz

Related questions

3 answers 236 views
1 answer 157 views
1 answer 136 views
2 answers 183 views
1 answer 179 views
1 answer 171 views
1 answer 167 views
...