【问题标题】:libc++abi.dylib: terminating with uncaught exception of type std::length_error: vectorlibc++abi.dylib:以 std::length_error:vector 类型的未捕获异常终止
【发布时间】:2015-10-04 20:27:57
【问题描述】:

我真的是 C++ 新手。我知道这可能是由于错误的内存分配造成的,但我尝试仅运行指示错误的行,并没有发现任何错误......

函数有错误部分(t 为 1211200*7 数组):

vector<double>tmp;
vector<size_t>tmpsort;
long ctmp=1000000,c=570404,l=1211200,indt=0;
double** m = new double*[ctmp];
for(int i = 0; i < ctmp; ++i)
    m[i] = new double[7];
    double** mt = new double*[c];
    for(int i = 0; i < c; ++i)
        mt[i] = new double[7];
for (int i=0; i<l; i++) {
    if (t[i][0]!=0&&t[i][1]!=0) {
        mt[indt][0]=t[i][0];
        mt[indt][1]=t[i][1];
        mt[indt][2]=t[i][2];
        mt[indt][3]=t[i][3];
        mt[indt][4]=t[i][4];
        mt[indt][5]=t[i][5];
        mt[indt][6]=t[i][6];
        indt++;
    }
}
for (int i=0; i<c; i++) {
    tmp.push_back(pow(pow(distanceEarth(mt[i][1], mt[i][0], d[1], d[0]),2)+pow(mt[i][2]-d[2],2),0.5));
}
    tmpsort.assign(ordered(tmp).begin(), ordered(tmp).end());//signal SIGABRT
    for (int i=0; i<1000; i++) {
        m[i][0]=mt[tmpsort[i]][0];
        m[i][1]=mt[tmpsort[i]][1];
        m[i][2]=mt[tmpsort[i]][2];
        m[i][3]=mt[tmpsort[i]][3];
        m[i][4]=mt[tmpsort[i]][4];
        m[i][5]=mt[tmpsort[i]][5];
        m[i][6]=mt[tmpsort[i]][6];
    }
    c=1000;

对于已订购(来自c++ sort keeping track of indices):

template <typename T>
vector<size_t> ordered(vector<T> const& values) {
vector<size_t> indices(values.size());
iota(begin(indices), end(indices), static_cast<size_t>(0));

sort(begin(indices), end(indices),[&](size_t a, size_t b) { return values[a] < values[b];});
return indices;
}

对于distanceEarth(一个可以返回两点之间距离的函数):

double deg2rad(double deg) {
return (deg * M_PI / 180);}
double rad2deg(double rad) {
return (rad * 180 / M_PI);}
double distanceEarth(double lat1d, double lon1d, double lat2d, double lon2d) {
double lat1r, lon1r, lat2r, lon2r, u, v;
lat1r = deg2rad(lat1d);
lon1r = deg2rad(lon1d);
lat2r = deg2rad(lat2d);
lon2r = deg2rad(lon2d);
u = sin((lat2r - lat1r)/2);
v = sin((lon2r - lon1r)/2);
return 2.0 * earthRadiusKm * asin(sqrt(u * u + cos(lat1r) * cos(lat2r) * v * v));}

终端将错误消息显示为标题。谁能建议我接下来要检查什么?谢谢!

【问题讨论】:

    标签: c++ xcode vector


    【解决方案1】:

    你这里有问题:

    tmpsort.assign(ordered(tmp).begin(), ordered(tmp).end());//signal SIGABRT
    

    函数ordered 按值返回。这意味着 begin()end() 被调用用于不同的临时向量。

    【讨论】:

    • 谢谢。请问如何将ordered(tmp) 分配给tmpsort?该功能不是主要功能,所以我不能在这里使用“=”...
    • 他们似乎都是vector&lt;size_t&gt;,所以简单的分配应该可以工作。
    • Xcode 建议“没有可行的重载 '='”。我改用 push_back 并成功运行。
    • 更新:更改为以下行后仍然崩溃: for (auto i:ordered(tmp)) { tmpsort.push_back(i);//signal SIGABRT }
    • 更新:上述错误仅发生在从 i 推回第一个元素时。不知何故,用范围初始化 tmpsort 解决了它。
    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2014-10-04
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多