Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using vector as class member [duplicate]

Tags:

c++

class

vector

i'm new to C++ and programming in general, plus english isn't my first language so I might have trouble phrasing my question correctly for you to understand.

I wrote the following, working, program :

#include<iostream>
#include<vector>
using namespace std;

class Vector{
    vector<int>numbers;

public:
    Vector(vector<int> const& v) : numbers(v) {}

    void print(){
        for (const auto& elem : numbers){
            cout << elem << " ";
        }
    }
};


int main(){

    Vector p{ vector < int > {15, 16, 25} };
    p.print();
}

Now if I try to create an object writing:

Vector p{ 15, 16, 25 };

it doesn't work. My question is what do I have to do in order for it to work? Help would be much appreciated! Thanks in advance.

like image 671
Johnnylame Avatar asked Dec 05 '25 10:12

Johnnylame


1 Answers

The easiest way to get what you want is to use an additional set of braces to indicate that the arguments provided, together, form the first argument of the constructor. Try :

int main() {

    Vector p{ {15, 16, 25} };
    p.print();
}

Another way, if you are trying to make it work with main as it current is, is to implement an initializer list constructors.

#include <initializer_list>
#include <iostream>
#include <vector>

using std::vector;
using std::cout;

class Vector {
    vector<int>numbers;

public:
    Vector(vector<int> const& v) : numbers(v) {}

    // Implement initializer list constructor
    Vector(std::initializer_list<int> args) : numbers(args.begin(), args.end()) {}

    void print() {
        for (const auto& elem : numbers) {
            cout << elem << " ";
        }
    }
};


int main() {

    Vector p{ 15, 16, 25 };
    p.print();
}

Note that you can pass the initializer list directory to std::vector's constructor (Vector(std::initializer_list<int> args) : numbers(args) {} would work), but this would incur an additional copy of the list.

like image 135
François Andrieux Avatar answered Dec 08 '25 00:12

François Andrieux