在c++中按字母顺序对对象向量进行排序

Sorting a vector of objects alphabetically in c++

本文关键字:向量 对象 排序 顺序 c++      更新时间:2023-10-16

所以我创建了一个包含产品对象的向量。该产品有一个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,我可以对productname进行排序,但在那之后,我不知道如何继续,因为我不知道怎样按productname的字母顺序打印整个对象。

现在,我想按产品名称的字母顺序对这3种产品进行排序/打印。我该怎么做(排序部分)?样本输出:

按字母顺序排列的产品

产品ID1:1235

产品制造商:Lays

产品名称:薯片//名称以A开头,因此它是第一个输出

产品ID2:123

产品制造商:索尼

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

产品ID3:1234

产品制造商:LG

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

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

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

最简单的方法是使用标准库中的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 的更多详细信息

使用STL容器进行排序的方法是定义比较器函数,该函数"告诉"std::sort算法如何比较元素以按顺序放置它们。因此,我们需要定义一个小于的关系,我们可以通过为Product类创建一个小于运算符来实现,如下所示:

struct Product
{
    int ID = 0;
    std::string manuf;
    std::string name;
    Product(int ID, const std::string& manuf, const std::string& name)
    : ID(ID), manuf(manuf), name(name) // initialize members here
    {
    }
    // overloading the < operator enables functions
    // like std::sort to compare Product objects to
    // order them accordingly
    bool operator<(const Product& p) const
    {
        return name < p.name; // order by name
    }
};

现在,如果我们向std::sort发送一个装满Product对象的容器,它们将根据名称进行排序。

但是,我们需要通过指针对Product对象进行排序,因此我们需要另一个小于运算符的函数来传递给std::sort函数,该函数在使用比较器函数进行比较之前取消引用指针。

// Function object to sort pointers
struct SortProductPointers
{
    // overload the function call operator
    bool operator()(const Product* lhs, const Product* rhs) const
    {
        // dereference the pointers to compare their targets
        // using the Product class's operator<(...) function
        return *lhs < *rhs;
    }
};

现在我们有了这两个我们可以称之为std::sort算法:

int main()
{
    std::vector<Product*> products;
    products.push_back(new Product(1, "Lays", "A potato chips"));
    products.push_back(new Product(3, "LG", "D 54 inch TV"));
    products.push_back(new Product(2, "Sony", "C vaio laptop"));
    // std::sort takes a third parameter which is the 
    // comparator function object    
    std::sort(products.begin(), products.end(), SortProductPointers());
    for(const auto* p: products)
        std::cout << p->ID << ": " << p->manuf << ", " << p->name << 'n';
    // Don't forget to delete all your Products
    for(auto* p: products)
        delete p;
}

您也可以使用lambda实现

    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(), [](const std::string & a, const std::string & b) -> bool
    {
        return a < b;
    });
    
    std::cout << "Sorted vector:";
  for (std::vector<std::string>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;