gpt4 book ai didi

c++ - 在 C++ 中按字母顺序对对象 vector 进行排序

转载 作者:太空狗 更新时间:2023-10-29 23:35:33 25 4
gpt4 key购买 nike

所以我创建了一个包含产品对象的 vector 。该产品有一个 int ID、字符串制造商和字符串产品名称。假设我通过这样做存储了一些产品

vector<product*>productlist;
Product*p = new Product(123, "Sony", "C vaio laptop")
Product*p1 = new Product(1234, "LG", "D 54 inch TV")
Product*p2 = new Product(1235, "Lays", "A potato chips")
productlist.push_back(p);
productlist.push_back(p1);
productlist.push_back(p2);

我有一个名为 getproductname(){return productname;} 的方法可用于获取产品名称,我可以对产品名称进行排序,但之后我不知道如何继续,因为我不知道如何按产品名称的字母顺序打印整个对象。

现在我想按 productname 的字母顺序对 3 种产品进行排序/打印。我该怎么做(排序部分)?示例输出:

产品按字母顺序排序

产品 ID1:1235

产品制造商:乐事

Product name:A potato chips//name以A开头所以是第一个输出

产品 ID2:123

产品制造商:索尼

产品名称:C vaio笔记本电脑

产品 ID3:1234

产品制造商:LG

产品名称:D 54英寸电视//名称以D开头所以是最后一个

我试过插入 sort(productlist.begin(), productlist.end());但它只适用于带有字符串而不是对象的 vector 。

一开始问的问​​题太模糊/太简单。已编辑!

最佳答案

最简单的方法是使用标准库中的std::sort() 函数。你可以尝试这样的事情:

#include <iostream>     // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector

bool compareFunction (std::string a, std::string b) {return a<b;}
//compare any way you like, here I am using the default string comparison

int main ()
{
std::string myNames[] = {"Henry","Tom","Jafar","Alice","Bob","Cindy","Clara","Michael"};

std::vector<std::string> myvector (myNames, myNames+8); //create vector from array

std::sort(myvector.begin(),myvector.end(),compareFunction);//sort the vector


std::cout << "Sorted vector:";
for (std::vector<std::string>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}

我建议您查看文档以获取有关 std::sort 的更多详细信息

关于c++ - 在 C++ 中按字母顺序对对象 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34757448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com