0

This is the code I am using:

#include <iostream>
#include <vector>
#include <algorithm>  

using namespace std;

class   Vector
{
 // Use user defined template class for vector handling
    template <class V,class D>
    void vec_add(V &vec, D data)
    {
            vec.push_back(data);
    }
};

int main ()
{
        vector<int> v;  // v is vecor of int elements

        Vector.vec_add(&v,222);
}

Goal: Define a generic add of item to any kind of vector.
Problem: I am getting a compilation error.

Idos
  • 15,053
  • 14
  • 60
  • 75
user3879626
  • 127
  • 6

3 Answers3

1

There are many issues:

First, make the member functions public:

class Vector  
{
public: 

Second,

Vector.vec_add(&v,222);

should be something like

 Vector foo;
 foo.vec_add(v,222);

as you are passing a reference, not a pointer, and you must invoke the member function on an instance, in this case foo, as the member function is not static (think whether you want to make it static, in which case you invoke it as Vector::vec_add). Full working code below:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Vector
{
public:
// Use user defined template class for vector handling
    template <class V, class D>
    void vec_add(V &vec, D data)
    {
        vec.push_back(data);
    }
};

int main ()
{
    vector<int> v;  // v is vecor of int elements

    Vector foo;
    foo.vec_add(v, 222);
    std::cout << v.front(); // test it
}

Live on Coliru

A good advice is to pick up a book from here and learn the basic features of the language.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
0

Why bother making a class? It would have to be static member function, because you didn't make any Vector objects. Better use normal functions, if you don't have any plans with the class alone:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


template <class V,class D>
void vec_add(V &vec, D data)
{
    vec.push_back(data);
}


int main ()
{
        vector<int> v;  // v is vecor of int elements

        vec_add(v,222);
}
xinaiz
  • 7,744
  • 6
  • 34
  • 78
0

You have a several problems with your code: your vec_add is private, it is non static, also you call it with pointer to std::vector - while your method accepts a reference. Below is an example with fixed errors, hopefully this is what you want:

#include <iostream>
#include <vector>
#include <algorithm>  

using namespace std;


class   Vector
{
 // Use user defined template class for vector handling
 public:
    template <class V,class D>
    static void vec_add(V &vec, D data)
    {
            vec.push_back(data);
    }
};

int main ()
{
        vector<int> v;  // v is vecor of int elements

        Vector::vec_add(v,222);
}
marcinj
  • 48,511
  • 9
  • 79
  • 100