Vector function? | Sololearn: Learn to code for FREE!


Vector function?

I want to make a function that would print the contents of a vector. However, I don't want to write a function for each data type. Is there a way I can maybe use templates or something to print the contents of a vector so I don't need a function for each type?

2/2/2019 9:05:29 AM

Daniel Cooper

7 Answers

New Answer


I believe this is what you are looking for. Daniel Cooper This is a simplified version of what code learner has provided you with, given the cons that the function assumes std::cout is overloaded for that datatype you are printing.


By this way you can do so


Daniel Cooper in simple just defined an structure and initialise the vector variables then use according to your need as in this Dot product is method is defined for returning the dot product typedef struct{ float i,j,k; }Vector; Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13}; float dotProduct(Vector a, Vector b) { return a.i*b.i+a.j*b.j+a.k*b.k; }

+2 I have created abstract class Printable with method print. every class whose instance you want to print should implement printable. then i am passing the vector to printVector function which calls print method on every object. I have included two examples.


Daniel Cooper are you talking about mathematical vector? or vector from c++ STL library?, I am assuming its from stl library. And I guess Mohit the coder (M.S.D) is considering mathematical vector


Hatsy Rei That's exactly what I was looking for. I tried that but it didn't work for me. Maybe I spelled something wrong 🤔 I didn't save my code so I can't compare mine to yours. Rip I dunno. Lol. Thanks!


Mohit the coder (M.S.D) Would it be too much to ask you to use a less complex example? Unfortunately I won't have much time to figure out what this code does and would appreciate it if you could narrow your response down to exactly what I need. If not, it's fine. I just barely have an understanding of this code xD