Using a vector as a member of a class

I'm new to C ++ and programming in general, plus English is not my first language, so I might have trouble phrasing my question correctly for you.

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 record:

Vector p{ 15, 16, 25 };

      

he does not work. My question is what should I do to make it work? Help would be greatly appreciated! Thanks in advance.

+3


source to share


2 answers


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

int main() {

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

      

Another way, if you are trying to get it to work with main

since it is current, is to implement a constructor initializer list .



#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 the constructor std::vector

( Vector(std::initializer_list<int> args) : numbers(args) {}

will work), but that will result in an extra copy of the list.

+3


source


You need to add a constructor that takes a std :: initializer_list like this:

Vector(std::initializer_list<int> v) : numbers(v){}

      



add that along with your other constructor and it should work.

0


source







All Articles