0

I have the following code:

class SegmentTree {
public:
    unordered_map<int, int> tree;
    vector<int> nums;

    SegmentTree(vector<int> nums)  {
        this->nums = nums;
        build(0, nums.size() - 1, 1);
    }
};

class NumArray {
public:
    SegmentTree s;
    NumArray(vector<int> nums) {
        s = SegmentTree(nums);
    }
};

I am getting an error saying

note: candidate expects 1 argument, 0 provided

Presumably SegmentTree is being initialized when I do SegmentTree s.

However, I want to initialize it only within the constructor of NumArray.

How do I accomplish this?

sop
  • 3,445
  • 8
  • 41
  • 84
nz_21
  • 6,140
  • 7
  • 34
  • 80
  • 1
    `this->nums = nums;` - don't use the constructor body to *assign* values when you can use the constructors *initialization list* to *initialize* objects: `SegmentTree(vector nums) : nums(nums) {`. And you may consider naming your arguments different than your member variables (personally I always use a `m_` prefix for members) to reduce confusion and avoid problems with shadowing. – Jesper Juhl Apr 14 '20 at 19:40

1 Answers1

1

You need to use an initaliser list

NumArray(vector<int> nums) : s(nums) {
}

Assignment is not the same as initialisation. Your version tried to default initialise s and only then assign to it. But because your SegmentTree class has no default constructor this failed.

john
  • 85,011
  • 4
  • 57
  • 81