【问题标题】:Sorting a vector of objects alphabetically in c++在 C++ 中按字母顺序对对象向量进行排序
【发布时间】:2016-01-13 02:34:30
【问题描述】:

所以我创建了一个包含产品对象的向量。 该产品有一个 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

产品制造商:莱士

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

产品 ID2:123

产品制造商:索尼

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

产品 ID3:1234

产品制造商:LG

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

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

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

【问题讨论】:

  • 您是将指针存储在向量中还是实际对象中?
  • 您使用指针是否有原因,或者您可以将Product 对象直接存储在 vector 中吗?
  • 我有一个构造函数 product(int id, string manuf, string productname) 我将产品对象存储到向量中
  • 但是你使用指针有什么原因吗?为什么不只是std::vector&lt;Product&gt; products
  • 我猜它指向我的产品类别?我很抱歉,但我什至不知道它是如何工作的。我参考了我的讲师过去给出的一个例子,他就是这样做的。

标签: c++


【解决方案1】:

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

【讨论】:

  • 我很抱歉,但对象存储在我的向量中而不是字符串中!我已经编辑了我的问题。
  • 然后你必须为对象提供你自己的比较函数。考虑重载运算符
  • 也可以使用 lambda 而不是比较器的单独函数,如下所示:auto compareFunc = [](std::string a, std::string b) {return a&lt;b;};
【解决方案2】:

使用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
    }
};

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

然而,我们需要通过它们的指针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;
}

【讨论】:

  • 它适用于字符串向量,但我的向量包含对象!
  • @J.Will 所以你的问题变了,我的回答也变了:)希望它足够清楚。
【解决方案3】:

你也可以使用 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 2019-06-15
    • 2015-07-06
    • 2011-08-29
    • 2013-05-02
    • 2014-02-08
    相关资源
    最近更新 更多