为什么我得到一个"向量下标超出范围"我的代码错误?

时间:2015-12-03 10:42:13

标签: c++ vector subscript

为什么我的"矢量下标超出范围"我的代码有错误吗?

class CSVRow
{
public:
    string const& operator[](size_t index) const
    {
        return m_data[index];
    }
    size_t size() const
    {
        return m_data.size();
    }
    void readNextRow(istream& str)
    {
        string line;
        getline(str, line);

        stringstream lineStream(line);
        string cell;

        m_data.clear();
        while (getline(lineStream, cell, ','))
        {
            m_data.push_back(cell);
        }
    }
private:
    vector<string> m_data;
}
;

istream& operator>>(istream& str, CSVRow& data)
{
    data.readNextRow(str);
    return str;

}
int main()
{
    ifstream file("full_training_dataset.csv");

    CSVRow row;
    while (file >> row)
        cout << row[1] << endl;


    return 0;
}

1 个答案:

答案 0 :(得分:1)

while (file >> row)
    cout << row[1] << endl;

First time element would be inserted ar row[0] not at row[1].