Error while passing vector to instance of object in main

You are passing the wrong types to your constructor:
"Jack" is of type const char[5] and the second argument 28.2 is of type double
Your constructor though is expecting a std::vector<string> and a std::vector<double>. So the problem is your constructor is expecting a “list” of strings and doubles, what you are not giving him.
Considering the name of your class the correct solution should be:

class NamePairs
{
private:
    double age;
    std::string name;
public:
    NamePairs(const std::string& name, double Age)
    {
        this->name = name;
        this->age = age;
    }
};

Now you can instantiate it like that:

NamePairs pair("Alfred", 43.4);

Also consider using a std::pair


Considering you want a list of Persons that each have a Name and Age there a some different Solutions:
You could create a class Person that has two attributes:

class Person
{
private:
    double Age;
    std::string Name;
public:
    Person(double age, const std::string& name)
    {
        Age = age;
        Name = name;
    }
};

And use it like that:

std::vector<Person> persons;
persons.push_back(Person(23.4, "Alfons");

Or you also could (more like your try) create a class PersonList like this:

class PersonList
{
private:
    std::vector<double> Ages;
    std::vector<std::string> names;
public:
    void addPerson(double Age, const std::string& Name)
    {
        Ages.push_back(Age);
        Names.push_back(Names);
    }
};

And use it like that:

PersonList list;
list.addPerson(23.5, "Andrea");

I would greatly prefer the first Approach because it is way easier to handle the Persons if they’re are not in the list(e.g. returned by a accessor or passed around to other functions/objects or if you Need to operate upon them). And it Looks way cleaner to me

Leave a Comment