[C ++]按类成员的值对对象进行排序

时间:2016-04-16 00:22:33

标签: c++ sorting object

在下面显示的代码中,在函数void printExpensiveThanT(..)中我应该打印出目的地,距离和价格,这些优惠比功能中的商品T更贵,已排序按距离值按升序排列。 我不知道应该用什么来对它们进行排序,我用矢量进行了实验,但它没有成功,所以我删除了它。 任何帮助将不胜感激。

<!DOCTYPE html>
<html>
<head>
<title> Self Service</title>
</head>
<body>

<h1>Welcome to the Self Service</h1>
<p>Below you can enter your userID .</p>

<form action="ThankYou.html" method="post">
UserID: <input type="text" name="text"><br>
<input type="submit" value="Submit">
</form>


<input type="button" value="Launch Installer" onclick=

</body>
</html>

1 个答案:

答案 0 :(得分:1)

由于您正在处理指针,最简单的方法是使用std::vectorstd::sort

#include <vector>
//...
void printExpensiveThanT(Transport **offers, int n, AutomobileTransport &T) 
{
    std::vector<Transport*> sortedVect;
    for (int i = 0; i < n; i++)
    {
        if (offers[i]->priceTransport() > T.priceTransport())
            sortedVect.push_back(offers[i]);  // add this item to the vector
    }

    // sort the vector based on the dereferenced pointers and their respective 
    // operator <
    std::sort(sortedVect.begin(), sortedVect.end(), 
    [](Transport* left, Transport* right) { return *left < *right; });

    // print out the values
    for (auto it : sortedVect)
        cout << (*it).getDestination() << " " << (*it).getDistance() << " " << (*it).getPrice() << "\n";
}

此外,您的原始代码循环了一次(i <= n错误)。

编辑:

如果您的编译器不支持C ++ 11语法,那么这是另一种解决方案:

#include <vector>
//...
bool Sorter(Transport* left, Transport* right)
{ return *left < *right; }

void printExpensiveThanT(Transport **offers, int n, AutomobileTransport &T) 
{
    std::vector<Transport*> sortedVect;
    for (int i = 0; i < n; i++)
    {
        if (offers[i]->priceTransport() > T.priceTransport())
            sortedVect.push_back(offers[i]);  // add this item to the vector
    }

    // sort the vector based on the dereferenced pointers and their respective 
    // operator <
    std::sort(sortedVect.begin(), sortedVect.end(), Sorter);

    // print out the values
    std::vector<Transport*>::iterator it = sortedVect.begin();
    while (it != sortedVect.end()) 
    {
        cout << (*it).getDestination() << " " << (*it).getDistance() << " " << (*it).getPrice() << "\n";
        ++it;
    }
}