【发布时间】:2020-09-03 01:43:44
【问题描述】:
我有一个自定义向量类,它封装了std::vector。我在 while 循环中使用它逐行读取 CSV 文件并将列存储到名为 columns 的 Vector 中,并对这些值执行一系列操作。一切正常,但是在循环了一些行之后,它会抛出错误:
在抛出
std::out_of_range的实例后调用终止
我假设我的 Vector 出于某种原因停止调整大小,但它会按照我想要的方式读取每一行,然后再抛出此错误并停止。我使用std::cerr 语句来查看我的几个列值是否被正确读取并使用它,我可以看到它在文件结束之前停止。为什么会这样?
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;
}
我的向量类:
#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
【问题讨论】:
-
你能告诉我们
Vector的相关代码吗?当您不显示此自定义类时,很难帮助您解决自定义类中的错误;) -
学习使用调试器或者打印明显太小的向量的大小。
-
@churill 很抱歉。我现在已经编辑了显示我的矢量类的帖子
-
最好使用调试器来检查向量中的值。不相关,但
operator[]的条件是差一,应该是 ` if(index = data.size()), sincedata.size()` 已经超出-界限。 -
@thedafferg:运行调试会话并检查这些索引是否存在(1、11、12、18)。访问器正在检查边界,但忽略了
index == size()的情况。应该是index >= 0 && index < size()。但是,您也不需要检查边界,因为std::vector::at()方法已经为您执行此操作,并且它会引发您看到的std::out_of_range异常。顺便说一句,您不需要 ctor 和 dtor,因为编译器为您提供了这些,std::vector有自己的。并且,最好使用std::size_t作为索引。示例:godbolt.org/z/g9d9xr.
标签: c++ string file csv vector