你可以的
class Wine
{
public:
string name;
string vintage;
string price; // Maybe you want to convert to double instead of storing a string
// and so on
}
vector<Wine> myWines;
在您的 while 循环中,您可以添加:
Wine tmp;
tmp.name = row[0];
tmp.vintage = row[1];
// and so on
myWines.push_back(tmp);
现在您可以像这样按名称排序
std::sort(myWines.begin(), myWines.end(),
[] (Wine const& a, Wine const& b) { return a.name < b.name; });
或者像这样的年份
std::sort(myWines.begin(), myWines.end(),
[] (Wine const& a, Wine const& b) { return a.vintage < b.vintage; });
排序可以展示如下:
class Wine
{
public:
string name;
string vintage;
string price; // Maybe you want to convert to double instead of storing a string
// and so on
};
int main()
{
vector<Wine> myWines;
Wine tmp;
tmp.name = "d";
tmp.vintage = "3";
tmp.price = "i";
myWines.push_back(tmp);
tmp.name = "g";
tmp.vintage = "1";
tmp.price = "f";
myWines.push_back(tmp);
tmp.name = "a";
tmp.vintage = "2";
tmp.price = "c";
myWines.push_back(tmp);
cout << "Unsorted" << endl;
// Print the vector
for (auto& v : myWines)
{
cout << v.name << " " << v.vintage << " " << v.price << endl;
}
cout << "Sort by name" << endl;
std::sort(myWines.begin(), myWines.end(),
[] (Wine const& a, Wine const& b) { return a.name < b.name; });
// Print the vector
for (auto& v : myWines)
{
cout << v.name << " " << v.vintage << " " << v.price << endl;
}
cout << "Sort by vintage" << endl;
std::sort(myWines.begin(), myWines.end(),
[] (Wine const& a, Wine const& b) { return a.vintage < b.vintage; });
// Print the vector
for (auto& v : myWines)
{
cout << v.name << " " << v.vintage << " " << v.price << endl;
}
return 0;
}
输出:
Unsorted
d 3 i
g 1 f
a 2 c
Sort by name
a 2 c
d 3 i
g 1 f
Sort by vintage
g 1 f
a 2 c
d 3 i