我正在用 C++ 编写一个小代码,但我一直收到此错误 [重复]

问题描述 投票:0回答:1
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Tag{
public:
    string name{};
    vector<string> attribute{};
    vector<string> value{};
};

Tag get_tag_and_value(string tag_line){
    Tag tag{};
    for(char c:tag_line){
        cout<<c<<endl;
    }
    
    return tag;
}

int main() {
    string temp;
    vector<Tag> tags{};
    
    int N{}, Q{};
    cin>>N>>Q;
    cout<<N<<" "<<Q<<endl;
    for (auto i{0};i<=N;i++){
        getline(cin, temp);
        tags.at(i) = get_tag_and_value(temp);
        temp.erase();
        cout<<temp;
    }
    return 0;
}

我每次跑步都会得到错误:

在抛出“std::out_of_range”的实例后调用终止 what(): vector::_M_range_check: __n(即 0)>= this->size()(即 0)

Code 在

tags.at(i) = get_tag_and_value(temp);
不存在时工作正常。这里有什么问题?

我希望代码能够读取这些行,我将在

tags.at(i) = get_tag_and_value(temp);
中处理它们。我试图读取 linein
get_tag_and_value()
函数但得到了同样的错误。

c++ getline
1个回答
1
投票

你的向量大小为零,所以

tags.at(i) = get_tag_and_value(temp);

正确抛出错误。

用这个代替

tags.push_back(get_tag_and_value(temp));

将一个项目添加到向量的后面(因此将其大小增加一个)。

当您分配给给定索引时,向量会自动增长,这似乎是对向量的普遍误解。这不是真的。

© www.soinside.com 2019 - 2024. All rights reserved.