-2

I got the following error. How can I fix it?

Error message

Vector.cpp:9:49: error: expected ';' after expression
if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"};
                                            ^
                                            ;
Vector.cpp:9:37: error: use of undeclared identifier 'out_of_range'
if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"};
                                ^
Vector.cpp:9:70: error: expected ';' after expression
if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"};

user.cpp

#include <iostream>
#include <cmath>

#include "Vector.h"

using namespace std;

double sqrt_sum(Vector& v)
{
    double sum = 0;
    for (int i = 0; i != v.size(); ++i)
        sum += sqrt(v[i]);
    return sum;
}

int main() {
    Vector v(1);
    int sum = sqrt_sum(v);
    cout << sum << endl;
}

Vector.h

class Vector
{
    public:
        Vector(int s);
        double& operator[](int i);
        int size();
    private:
        double* elem;
        int sz;
};

Vector.cpp

#include "Vector.h"

Vector::Vector(int s):elem {new double[s]}, sz{s} 
{
}

double& Vector::operator[](int i)
{
    if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"}; // it works when this line is commented out
    return elem[i];
}

int Vector::size()
{
    return sz;
}

tasks.json

{
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    "args": ["-std=c++11", "-O2", "-g", "user.cpp", "Vector.cpp"],
    "showOutput": "always"
}

Update 1

I added the below two lines, then it works.

#include <iostream>
#include "Vector.h"
using namespace std;
zono
  • 8,366
  • 21
  • 75
  • 113

1 Answers1

2

Try including the exception's header:

#include <stdexcept>

as shown in this example.

And don't forget to use namespace std, or resolve the scope with std::.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Still not sure if ```#include ``` is required or not. Both with and without the line, it works on my case. But thank you share about that and the reference link is quite useful. – zono May 26 '17 at 11:32
  • 1
    @zono it will be probably be included in some other standard header! You are welcome. – gsamaras May 26 '17 at 11:37