How to pass template vector as function argument C++

3 Answers

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

template <class T>
void print_vector(const std::vector<T>& v) {
     for (T n : v) {
          std::cout << n << "\n";
    }
}
 
int main() {
    std::vector<int> v = {3, 8, 12, 98};
     
    print_vector(v);
 
}
 
 
/*
 
3
8
12
98
 
*/

 

 



answered Dec 2, 2019 by avibootz
edited Dec 27, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>

template <class T>
T sum_vector(const std::vector<T>& v) {
    T sum = 0.0;
    for (T n : v) {
         sum += n;
    }
     
    return sum;
}
 
int main() {
    std::vector<int> v = {3, 8, 12, 98};
 
    std::cout << sum_vector(v);
}
 
 
 
/*
 
121
 
*/

 



answered Dec 2, 2019 by avibootz
edited Dec 27, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>
 
template <class T>
T sum_vector(const std::vector<T>& v) {
    T sum = 0.0;
    for (T n : v) {
         sum += n;
    }
     
    return sum;
}
 
int main() {
    std::vector<double> v = {3.1, 8.5, 12.4, 98.7};
     
    std::cout << sum_vector(v);
 
}
 
 
/*
 
122.7
 
*/

 



answered Dec 2, 2019 by avibootz
edited Dec 27, 2024 by avibootz

Related questions

...