c++ - 调试断言失败:表达式 vector 下标超出范围

我不明白为什么当我在 vector 中保留空间时它说下标超出范围。我创建了我的代码的简短形式来解释问题更好:

#include <vector>
#include <string>
#include <thread>
#include <iostream>

using namespace std;

class A {
public:
    vector<vector<string>> foo;
    thread* aThread;

    A() {
        foo.reserve(10); //makes sure we have space...
        aThread = new thread([this]() {
            for (int i = 0; i < 10; i++) {
                foo[i].push_back("Hello"); // Debug assertion failed. :(
            }
        });
    }
};

int main()
{
    A a;
    a.aThread->join();

    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < a.foo.size(); j++) {
            cout << a.foo[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

只要我尝试将元素添加到线程内的 foo vector 中,它就会在此处给出错误。我无法弄清楚出了什么问题。请帮忙。

回答1

foo.reserve(10)

为 foo 中的元素保留空间,但它不会使用空的 std::vector 填充任何元素。

您可以将其更改为:

foo.resize(10);

这将保留空间并创建空的 vector< 字符串 > 元素,以便您可以访问它们。

相似文章

随机推荐

最新文章