2

Why will this code cause segmentation fault with this input? If I change >= to > within the lambda function the segfault won't appear.

My code is

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

int NUM=17;

int main()
{
    auto compare = [=](vector<float> &lhs, vector<float> &rhs)
    {
        return lhs[5] >= rhs[5];
    };
    vector<vector<float>> res(NUM);
    freopen("in.txt", "r", stdin);
    for (int i = 0; i < NUM; i++)
    {
        for (int j = 0; j < 6; j++)
        {
            float val;
            cin >> val;
            res[i].push_back(val);
        }
    }
    sort(res.begin(), res.end(), compare);
    for (auto v : res)
    {
        cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << " " << v[5] << endl;
    }

}

my input txt is

882.5 518.5 185 381 23 0.814666
886.5 520.5 205 377 11 0.159534
254 595.5 176 221 19 0.431349
254 595.5 176 221 20 0.29856
254 595.5 176 221 21 0.266644
252.5 594 175 218 23 0.22405
255.5 593.5 173 219 22 0.221642
870 324.5 308 569 23 0.209181
886.5 520.5 205 377 15 0.201386
886.5 520.5 205 377 14 0.190138
848.5 489.5 181 335 23 0.187043
886.5 520.5 205 377 17 0.17942
884.5 520.5 197 381 22 0.173269
886.5 520.5 205 377 1 0.169222
778.5 460.5 421 425 23 0.167407
886.5 520.5 205 377 75 0.159534
886.5 520.5 205 377 33 0.159534
user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 2
    The lambda violates strict ordering. – 273K Feb 03 '23 at 05:57
  • 1
    freopen? Why not just use `std::ifstream file{"input.txt"}; float f; while(file >> float)...` there is usually no need to use reopen. And a bit of advice stop using `using namespace std;` – Pepijn Kramer Feb 03 '23 at 06:25

0 Answers0