Patrick
Patrick

Reputation: 867

Compile Error on vector initialization in return statement

I just want to do some initial checks, and have some quick of {-1, -1} vector return if necessary. Somehow, compiler says: I should change return type into vector *

But the current return type works for my later parts before I do this pre-checks code. So what do I misunderstood?

class SomeClass {
  public:
    static vector<int> solution(vector<int>& numbers, int target) {
      if (numbers.empty() || numbers.size() < 2) {
        return new vector<int> {-1, -1};   // <== Compile Error
      }
      unordered_map<int, int> hash;
      vector<int> result;
      .
      .
      .
      return result;
    }
};

int main() {
  vector<int> testNums = {11, 15, 2, 7};
  vector<int> result = SomeClass::solution(testNums, 9);
  return 0;
}

Upvotes: 1

Views: 2285

Answers (1)

Dean Seo
Dean Seo

Reputation: 5683

Somehow, compiler says: I should change return type into vector *

In C++, you need a pointer (or a pointer-like type) to point dynamically allocated memory.

Thus, replacing:

return new vector<int> {-1, -1};   

with:

return { -1, -1 };

will make it work as you'd expect.

Upvotes: 5

Related Questions