简体   繁体   English

为什么lambda函数用于stl函数,例如C ++中的sort(),max_element()函数将两个参数作为输入?

[英]Why does lambda function used for stl functions such as sort() , max_element() function in C++ take two arguments as input?

I am trying to understand the use of lambda function in sort() operator. 我试图理解在sort()运算符中使用lambda函数。 There is a vector which stores object of type person ; 有存储类型的对象的矢量person ; sort() function is being used to iterate over the vector person and sort it based on class member id . sort()函数用于迭代向量person并基于类成员id对其进行排序。

I do not understand why the lambda function used in the sort function needs two inputs ie. 我不明白为什么sort函数中使用的lambda函数需要两个输入,即。 p1 and p2 ?, why not just input one object p1 ? p1p2 ?,为什么不输入一个对象p1 I always thought stl functions such as sort() and max_element() return iterator to one element. 我一直认为stl函数(如sort()max_element()将迭代器返回给一个元素。

class Person
    {
      private:
        string firstName;
        string lastName;
        int id;

      public:
        Person(const string& fn, const string& ln, int i)
             : firstName(fn), lastName(ln), id(i) { }

        const string& getFirstName() const { return firstName; }
        const string& getLastName() const { return lastName; }
        int getID() const { return id; }
    };

main(){
vector<Person> people;
people.push_back(Person("Davor", "Loayza", 62341));
people.push_back(Person("Eva", "Lopez", 12345));
people.push_back(Person("Julio", "Sanchez", 54321));
people.push_back(Person("Adan", "Ramones", 70000));

sort(people.begin(), people.end(), [](const Person& p1, const Person& p2)
{
  return p1.getID() < p2.getID();
});
return 0;
}

Edit: may be I need to restate my question, my question was how does iterator increment occur in sort() function. 编辑:可能我需要重述我的问题,我的问题是如何在sort()函数中发生迭代器增量。 At the very beginning when iterator = people.begin(), what value is assigned to p1 and what value is assigned to p2 ? 在iterator = people.begin()的最开始,为p1分配了什么值,为p2分配了什么值? Similarly what happens when iterator= people.end()? 类似地,当iterator = people.end()时会发生什么? I am having hard time understanding the logic behind this process? 我很难理解这个过程背后的逻辑吗?

To understand std::sort , you must first understand what sorting is. 要了解std::sort ,您必须首先了解排序是什么。 Here's an exercise for you: 这是给你的练习:

Find yourself a deck of cards. 找到一副纸牌。 I'm going to assume that you know which card has a higher rank compared than another card; 我会假设你知道哪些卡有较高的排名比其他卡相比 ; otherwise this may be confusing. 否则这可能会令人困惑。 It won't mater whether ace is higher rank than king, or lower than two. 无论王牌是高于王还是低于2,都不会影响。 You can ignore suit for now. 你现在可以忽略西装。

Lay the cards in a row (or a fan to save space). 将卡片连续放置(或风扇以节省空间)。 The target is to find out whether any card with higher rank is before a card with lower rank. 目标是找出具有较高等级的任何卡是否在具有较低等级的卡之前。 Think about how you could find that out? 想想你怎么能找到它?

This is how: Start with the first, and the second card. 这是如何:从第一张和第二张卡开始。 Compare their rank. 比较他们的排名。 Does the first card have higher rank than the second? 第一张卡的排名是否高于第二张? If so, we conclude that the answer that we seek is "Yes, there is a card with a higher rank that is before a card of lower rank". 如果是这样的话,我们得出的结论是,我们寻求的答案是“是的,有一张排名较高的牌位于排名较低的牌之前”。 If the first card doesn't have a higher rank than the second, then we cannot answer the question yet. 如果第一张牌的排名不高于第二张牌,那么我们还不能回答这个问题。 We must move on and compare the second card with the third, and repeat the process. 我们必须继续比较第二张卡和第三张卡,然后重复这个过程。

If you reach the end of the deck without finding a card of higher rank that is before a card of lower rank, then the answer we seek is "No". 如果你到达牌组的末尾而没有找到排名较低的牌之前的更高级别的牌,那么我们寻求的答案是“否”。 Let us call such deck sorted (or ordered). 让我们称这样的甲板分类 (或订购)。

Second exercise: If the deck isn't sorted, how could you make it sorted? 第二个练习:如果甲板没有分类,你怎么能把它分类?

This is how: Just like in first exercise, start with the first two cards. 这就是:就像在第一次练习中一样,从前两张牌开始。 This time, if they aren't in the desired order, swap their position so that fist becomes second and second become first. 这一次,如果它们不是所需的顺序,则交换它们的位置,使拳头成为第二个,第二个成为第一个。 Now the two cards are sorted in relation to each other. 现在这两个卡相对于彼此排序。 Then move on to the second and third and repeat the process. 然后转到第二个和第三个并重复该过程。 You'll find that you may need to repeat this process multiple times as one iteration is not necessarily sufficient. 你会发现你可能需要多次重复这个过程,因为一次迭代不一定足够。

Let us call this process sorting (more specifically, this is comparison sorting). 让我们称这个过程为排序 (更具体地说,这是比较排序)。 This is what std::sort does. 这就是std::sort作用。 It compares two elements at a time, and swaps elements until all comparisons between any adjacent pair is true ie until the range is sorted. 它一次比较两个元素,并交换元素,直到任何相邻对之间的所有比较都为真,即直到范围被排序。

The comparison that you did between two cards is analogous with the comparison step that is done by the comparison function object argument of std::sort . 您在两张牌之间进行的比较类似于由std::sort的比较函数对象参数完成的比较步骤。 If you only looked at one card at a time, you wouldn't be able to find out whether it is in its ordered position or not. 如果您一次只查看一张卡,您将无法确定它是否处于其有序位置。


Why does lambda function used for stl functions such as sort() , max_element() function in C++ take two arguments as input? 为什么lambda函数用于stl函数,例如C ++中的sort(),max_element()函数将两个参数作为输入?

Because the comparison function object argument of those functions represents an order relation between two elements of an iterator range. 因为这些函数的比较函数对象参数表示迭代器范围的两个元素之间的顺序关系。 Order relations are binary relations. 订单关系是二元关系。

why not just input one object p1? 为什么不只输入一个对象p1?

Because a unary relation cannot represent an order. 因为一元关系不能代表订单。

I always thought stl functions such as sort() and max_element() return iterator to one element. 我一直认为stl函数(如sort()和max_element())将迭代器返回给一个元素。

how many iterators does sort() function return? sort()函数返回多少个迭代器?

std::sort returns void as per documentation. std::sort根据文档返回void That said, what these functions return, has little relevance with the arity of the comparison function object argument. 也就是说,这些函数返回的内容与比较函数对象参数的arity几乎没有关系。

my question was how does iterator increment occur in sort() function 我的问题是在sort()函数中如何发生迭代器增量

This is not specified. 这没有指定。 The implementer of the algorithm may choose how to increment the iterator. 算法的实现者可以选择如何递增迭代器。 Sorting algorithms often use more than one iterator. 排序算法通常使用多个迭代器。

At the very beginning when iterator = people.begin() , what value is assigned to p1 and what value is assigned to p2 ? iterator = people.begin()的最开始,为p1分配了什么值,为p2分配了什么值?

A sorting algorithm doesn't have to start at the beginning of the range. 排序算法不必从范围的开头开始。 It is unclear what you're referring to with iterator . 目前还不清楚你用iterator指的是什么。

p1 and p2 will be some pair elements in the range of [first, last) . p1p2将是[first, last)范围内的一些对元素。 Exactly which pair is up for the algorithm to decide. 究竟哪一对由算法来决定。

The lambda function is called on elements in the container, to compare if one is greater than the other. 在容器中的元素上调用lambda函数,以比较一个是否大于另一个。 It's not just simply called once for the return of sort : sort returns nothing. 它不仅仅是为了返回sort调用一次: sort返回任何内容。 It takes two parameters so it can compare. 它需要两个参数才能进行比较。 If it only took a single parameter, what would it compare it to? 如果它只采用一个参数,它会与它进行比较?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM