我不明白这一点:在抛出"std::length_error"实例后终止调用

I dont understand this: terminate called after throwing an instance of 'std::length_error'

本文关键字:error 实例 调用 终止 length std 这一点 明白      更新时间:2023-10-16

首先,我不是英国人,所以我会尽我所能解释清楚。我抛出了这条线,其中saludo表示问候,retardo表示延迟,numero表示数量,我还创建了一些提示,表示这种情况会发生很多次。所以我要做的是创建10个线程,这将在屏幕上显示从5到15次,从100到300的延迟,他们是一个数字("Soy"数字),但我有这个错误,我无法解决。它工作2-3个线程,然后停止。谢谢顺便说一句。

#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <time.h>
using namespace std;
void saludo(string m, int retardo, int numero) {
    string tabs(numero - 1, 't');
    cout << tabs << m << numero << +"n";
    this_thread::sleep_for(chrono::milliseconds(retardo));
}
int main() {
    int nthread = 10;
    srand(time(NULL));
    thread P[nthread];
    int i = 0;
    while(i<nthread){
        int retardo = rand() % 201 + 100;
        int veces = rand() % 11 + 5;
        for (int x = 0; x<veces; ++x){
            int numero = rand() % 10;
            P[i] = thread(&saludo, "Soy  ", retardo, numero);
            P[i].join();
        }
    }
    cout << "Finn"; 
    return 0;
}

此错误是因为您可能将负数传递给std::string构造函数。rand() % 10可能是0。你在做string tabs(numero - 1, 't');如果numero是0就有问题了