开发者

Order results by value

I want to loop through a vector to find records with a given ID. The ID is provided by the user. The code below will return all values with the given ID in the order they appear in the vector. How can I order the results by Price, say from lowest to highest?

   for(Seek = List.begin() ; Seek !=List.end() ; Seek++) {
    if(Seek->GetID() == Input)
        cout <<"Price: " &开发者_高级运维lt;< Seek->GetPrice() << endl;


Use the C++ Standard Library sort function with a custom compare should do what you want. I don't know what type Seek is exactly but here is something to get you started.

struct compareSeeks {
  bool operator() (const Seek& lhs, const Seek& rhs) { return (lhs.price < rhs.price);}
} mycompare;

// method code here...
sort(List.begin(); List.end(), mycompare);

You can see more here http://www.cplusplus.com/reference/algorithm/sort/.

[update] I assume that your list is already filtered on the correct ID and so I am focusing on just the sort aspect of the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜