leetcode报错runtime error: reference binding to null pointer of type ‘std::vector<std::

    科技2022-09-01  109

    leetcode报错:runtime error: reference binding to null pointer of type 'std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >' (stl_vector.h)

    原因:

    使用了不存在的下标,举个例子,假设新建了一个vector:

    vector<string> ans;

    现在将某个字符串ss放入vector中:

    ans[1].push_back(ss);

    此时就会报错,因为实际上ans[1]这一块空间是不存在的。

    解决方法:

    在初始化vector时就指定vector的大小:

    vector<string> ans(n);
    Processed: 0.008, SQL: 9