简体   繁体   English

C++ - 前两个元素之间的差异

[英]C++ - difference between first two elements

I've recently began to work with C++ std::sets , so there is a question I did not find answer to in Google.我最近开始使用C++ std::sets ,所以有一个问题我没有在谷歌中找到答案。

I have a std::set of some int values (eg, let it be 1, 2, 3, 4, 5 ).我有一个std::set一些int值(例如,让它是1, 2, 3, 4, 5 )。 The task is to calculate difference between two first elements.任务是计算两个第一个元素之间的差异。 Is it possible to do with C++?可以用 C++ 做吗?

I'm using data structure std::set ;我正在使用数据结构std::set And I know that first element can be got like that:我知道第一个元素可以这样得到:

int diff = *arSeq.begin(); int diff = *arSeq.begin();

Where arSeq is mentioned set .其中arSeq被提及set

Is there any way to get the second element?有没有办法获得第二个元素?

Yes it is possible.对的,这是可能的。 Access the first element via the std::set::begin iterator and the next one using the std::next function.通过std::set::begin迭代器访问第一个元素,使用std::next函数访问下一个元素。

#include <iostream>
#include <set>

int main() {
    std::set<int> s = { 1, 2, 3, 4, 5 };
    auto result = *s.begin() - *std::next(s.begin());
    std::cout << result;
}

Please note that you will again get the same result of -1 even if you defined your set as:请注意,你将再次得到相同的结果-1即使你定义你的设置为:

std::set<int> s = { 5, 3, 1, 4, 2 }; 

because the std::set is a container that:因为std::set是一个容器:

contains a sorted set of unique objects...包含一组排序的独特对象...

You can do it the following way您可以通过以下方式进行

#include <iostream>
#include <set>
#include <iterator>

int main()
{
    std::set<int> s({ 1, 2, 3, 4, 5 });

    long long int diff = 0;

    if (not (s.size() < 2))
    {
        auto first = s.begin();
        auto second = std::next(first);

        diff = *first < *second ? ( long long int )*second - *first : ( long long int )*first - *second;
    }

    std::cout << "difference = " << diff << std::endl;

    return 0;
}

What did you mean by first two elements.你说的前两个元素是什么意思。 First two element inserted?插入的前两个元素? then its not possible.那么它是不可能的。 Set elements are sorted with given comparator.集合元素使用给定的比较器进行排序。 By default primitive elements are sorted in ascending order.默认情况下,原始元素按升序排序。 See the output of following program.请参阅以下程序的输出。

// set::begin/end
#include <iostream>
#include <set>
#include<functional>

int main ()
{
  int myints[] = {75,23,65,42,13};
  std::set<int, std::greater<int>> myset (myints,myints+5);

  auto first = myset.begin();
  auto second = std::next(first);

  std::cout <<*first<< ", " <<*second<<"\n";

  return 0;
}`enter code here`

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

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