sort 2D string vector by selected column

Hi all, I am trying to sort my 2D vector by a selected column.
My 2D string vector:
a	Wed Feb 13 07:59:50 SGT 2019	2	0	nil
b	Wed Feb 13 07:59:04 SGT 2019	5	0	nil
c	Wed Feb 13 07:59:02 SGT 2019	3	2	nil
d	Wed Feb 13 07:58:49 SGT 2019	7	2	nil
e	Wed Feb 13 07:58:40 SGT 2019	9	111	nil
f	Wed Feb 13 07:58:32 SGT 2019	5	3	nil
g	Wed Feb 13 07:58:24 SGT 2019	6	111	nil
h	Wed Feb 13 07:58:21 SGT 2019	8	0	nil
i	Wed Feb 13 07:59:33 SGT 2019	14	9	nil


My code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	int m = parsedCsv.size();
	int n = parsedCsv[0].size();

	const int columnId = 3;
	std::sort(parsedCsv.begin(), parsedCsv.end(), [&columnId](const std::vector<std::string> &item1, const std::vector<std::string> &item2)
	{
		return item1[columnId] < item2[columnId];
	});

	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++)
			cout << parsedCsv[i][j] << ",";
		cout << endl;
	}


Current output:
a,Wed Feb 13 07:59:50 SGT 2019,2,0,nil,
b,Wed Feb 13 07:59:04 SGT 2019,5,0,nil,
h,Wed Feb 13 07:58:21 SGT 2019,8,0,nil,
e,Wed Feb 13 07:58:40 SGT 2019,9,111,nil,
g,Wed Feb 13 07:58:24 SGT 2019,6,111,nil,
c,Wed Feb 13 07:59:02 SGT 2019,3,2,nil,
d,Wed Feb 13 07:58:49 SGT 2019,7,2,nil,
f,Wed Feb 13 07:58:32 SGT 2019,5,3,nil,
i,Wed Feb 13 07:59:33 SGT 2019,14,9,nil,


As you can see, the third column is not sorting as intended. Whats the issue here? Any response is appreicated

Last edited on
It's sorting fine!

You are comparing strings, not integers. On that basis, "111" < "2".
Use std::stoi if you genuinely want to convert them to integers before comparing.
Thanks for your reply! How may I go about doing that by just converting one column?
1
2
3
4
5
6
7
8
9
10
11
const auto cmp_int = [] ( const std::string& a, const std::string& b )
{
    if( a.size() < b.size() ) return true ;
    else if( a.size() > b.size() ) return false ;
    else return a < b ;
};

std::sort( parsedCsv.begin(), parsedCsv.end(), [=]( const auto& item1, const auto& item2 )
{
    return cmp_int( item1[columnId], item2[columnId] ) ;
});

It worked. Thank you very much!
Last edited on
Topic archived. No new replies allowed.