includes()

What is the right answer in a school test, for the code below:
a. runtime error - Line II
or
b. 1,0
thank you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <deque>
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
class Pocket { 
        int value;
public:
        Pocket(int value):value(value){}
        int getValue() const  { return value; }  
        bool operator < (const Pocket & _Right) const { return value < _Right.value; } };
ostream & operator <<(ostream & stream, const Pocket & pocket) 
{         stream << pocket.getValue();         return stream;	}
int main() {
      Pocket mynumbers1[] = { 3, 9, 0, 2, 1, 4, 5 };
      Pocket mynumbers2[]={Pocket(3),Pocket(2),Pocket(4),Pocket(1)};
      deque<Pocket> d1(mynumbers1, mynumbers1+7);
      set<Pocket> s1(mynumbers1, mynumbers1+7);
      sort(d1.begin(), d1.end());
      sort(mynumbers1, mynumbers1+5);
      cout<<includes(d1.begin(),d1.end(), mynumbers1, mynumbers1+4)<<","//LINE I
      <<includes(s1.begin(),s1.end(), mynumbers2, mynumbers2+4)//LINE II
                <<endl;        return 0;	}
No answer can be provided if no question is asked.
If you compile it, it returns
1,0
. Was that your question?
Anyway, (http://www.cplusplus.com/reference/algorithm/includes/) std::includes throws exceptions if
“...any element comparison (or call to comp) throws or if any of the operations on iterators throws.”

Your element comparison doesn’t throw any exception:
bool operator<(const Pocket & _Right) const { return value < _Right.value; }
and your iterators range - s1.begin(), s1.end() - is, I think, valid.

I'm not sure if I have understood your problem, anyway...
Last edited on
Hi Enoizat,
Although the code is wrong if we run it the output is 1,0 - is this the correct answer or is "runtime error"?
As you can see, at line 22 :includes(s1.begin(), s1.end(), mynumber2, mynumber2+4), I used the unsorted array mynumbers2 (incorrect use!). So you don't get any error message, although I use includes() function in a wrong way.
although I use includes() function in a wrong way.

Did you?
includes(s1.begin(),s1.end(), mynumbers2, mynumbers2+4)
It looks like you used the overloaded version with 4 parameters, which assumes the container being already sorted. Perhaps you intended to use one of the versions with five parameters?
http://en.cppreference.com/w/cpp/algorithm/includes
It will need a flag like
-std=c++17 or -std=gnu++17 or similar, according to your compiler.

Topic archived. No new replies allowed.