+ 1
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?
7 ответов
+ 3
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.
https://code.sololearn.com/cz5Sj3h7IKL4/#cpp
+ 3
By this way you can do so
https://code.sololearn.com/ck0Jk9ZK5SOU/?ref=app
+ 3
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;
}
https://www.sololearn.com/learn/261/?ref=app
+ 2
https://code.sololearn.com/ciKOrx92mi23/?ref=app
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.
+ 2
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
+ 1
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!
0
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