David David - 18 days ago 5
C++ Question

C++ - Is it possible to sort 2D string vector by single column?

I have two-dimensional vector

std::vector< std::vector< std::string > > stockVector;


Which looks like:

{
{ 1, "Title 1", 1, 2.20 },
{ 2, "Title 2", 2, 3.30 },
// ...
}


Now I need to sort it by single column at same time - how can I do this?

Answer

Assuming your data looks actually like this:

std::vector< std::vector< std::string > > stockVector
{
   { "1", "Title 1", "1", "2.20" },
   { "3", "Title 3", "3", "4.30" },
   { "2", "Title 2", "2", "3.30" },
};

You can simply use the std::sort with a custom coparator:

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

Which sorts the collection according to the first column.