Reputation:
I have solved quite a few of Euler problems by now and have been thinking of a more clever way to reuse my functions I have written for earlier problems. So I thought of making a header file that will contain all my useful functions. So far I have been able to successfully include this in my header file without any errors.
#include <cmath>
bool isPrime(long int n)
{
if( n<=0 ) return false;
if( n==1 ) return false;
else if( n < 4 ) return true;
else if( n%2 == 0 ) return false;
else if( n<9 ) return true;
else if( n%3 == 0 ) return false;
else{
int r = floor(sqrt(n));
int f = 5;
while( f <= r ){
if(n%f == 0) return false;
if(n%(f+2) == 0) return false;
f += 6;
}
return true;
}
}
Now I would like to add to in a function that prints out the contents of a vector that can hold any type of variables, so I thought of doing something like this in my header file,
#include <iostream>
#include <vector>
template <typename T>
T printVec(vector<T>* a){
for(int i=0; i<a->size(); i++)
cout << a->at(i) << ", ";
cout << endl;
}
This however has a few issues, is doesn't like the template and it complains about a
not being declared?
Could you please let me know on how to get this done?
Thank you
Upvotes: 1
Views: 159
Reputation: 327
Just make sure you are utilizing namespace std by adding namespace std;
just after includes. If utilizing C++11, this solves your problem:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void printVec(vector<T> a){
for(auto vectorElement: a)
cout << vectorElement << ", ";
cout << endl;
}
int main(void){
vector<int> aVec = {1,2,3,4};
printVec(aVec);
}
Try this cpp.sh/8llel just for reference. Keep in mind your printVec doesn't return a thing so it should be declared void.
Upvotes: 0
Reputation: 218098
std::
are missing:
There are also improvement, const reference is better than pointer
template <typename T>
void printVec(const std::vector<T>& a) {
for (std::size_t i = 0; i != a.size(); ++i) {
std::cout << a.at(i) << ", ";
}
std::cout << std::endl;
}
or even (in C++11)
template <typename T>
void printVec(const std::vector<T>& a){
for (const auto& e : a) {
std::cout << e << ", ";
}
std::cout << std::endl;
}
or
void printVec(const std::vector<T>& a){
std::copy(a.begin(), a.end(), std::ostream_iterator<T>(std::cout, ", "));
std::cout << std::endl;
}
Upvotes: 1