LearnFrenzy
Sign in Take a free test

STL Algorithms and Iterators · Find the Error · Question 2

Error: iterators of different types as one range Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <algorithm>
#include <iostream>
#include <list>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3};
    std::list<int> l{4, 5, 6};
    auto it = std::find(v.begin(), l.end(), 5);
    std::cout << (it != v.end()) << '\n';
    return 0;
}
  • A 5 is not in v
  • B first and last must have the same iterator type and belong to the same range; v.begin() and l.end() are a vector and a list iterator Correct
  • C find needs a predicate
  • D lists cannot be searched
Correct Answer: Option B

Here it fails to compile; with two vectors of the same type, mixing their iterators would compile and be undefined behaviour.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links