I have a custom vector class that encapsulates the std::vector
. I'm using it in a while loop to read through a CSV file line by line and store the columns into a Vector
called columns
and perform a bunch of operations on these values. Everything works fine, but after looping through some amount of lines it throws the error:
terminate called after throwing an instance of
std::out_of_range
I'm assuming my Vector
stops resizing for some reason, but it reads every line the way I want it to for a good amount of lines before it throws this error and stops. I use the std::cerr
statements to see whether a couple of my column values are read correctly and using that, I can see that it stops before the end of the file. Why is this the case?
while(getline(datafile, line))
{
string token;
Vector<string> columns;
WindLogType windlog2;
stringstream ss(line);
columns.add(string());
while(getline(ss, token, ','))
{
columns.add(token);
}
stringstream date(columns[1]);
string windspeed = columns[11];
string solar1 = columns[12];
cerr << solar1 << endl;
string temperature1 = columns[18];
cerr << temperature1 << endl;
}
My Vector class:
#ifndef VECTOR2_H
#define VECTOR2_H
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
template <class T>
class Vector
{
public:
Vector(){};
~Vector();
void add(const T &obj);
int vecsize() const{return data.size();}
T& operator[](const int index);
const T& operator[](const int index) const;
private:
vector<T> data;
};
template <class T>
T& Vector<T>::operator[](int index){
if(index < 0 || index > data.size()){
throw("Out of bounds");
}
return data.at(index);
}
template <class T>
const T& Vector<T>::operator[](int index) const{
if(index < 0 || index > data.size()){
throw("Out of bounds");
}
return data.at(index);
}
template <class T>
Vector<T>::~Vector(){
data.clear();
}
template <class T>
void Vector<T>::add(const T &obj){
data.push_back(obj);
}
#endif // VECTOR_H