在 C++ 中,迭代器的比較操作通常用于檢查兩個迭代器是否指向同一個元素或者檢查迭代器是否已經到達容器的末尾。這些比較操作包括等于(==)、不等于(!=)、小于(<)、大于(>)、小于等于(<=)和大于等于(>=)。
對于迭代器的比較操作,需要注意以下幾點:
std::vector
的迭代器與一個 std::list
的迭代器進行比較。std::vector
、std::array
或 std::deque
的迭代器),可以使用所有比較操作。而對于雙向迭代器(如 std::list
或 std::set
的迭代器),只能使用等于(==)和不等于(!=)操作。std::forward_iterator
),只能比較相等性。但是,從 C++17 開始,單向迭代器也支持不等于(!=)操作。end()
方法返回的迭代器時,需要確保比較的迭代器是有效的。例如,如果你試圖比較一個已經被刪除的元素的迭代器與容器的 end()
迭代器,結果是未定義的。以下是一個簡單的示例,展示了如何在 C++ 中使用迭代器的比較操作:
#include<iostream>
#include<vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int>::iterator it1 = vec.begin();
std::vector<int>::iterator it2 = vec.begin() + 2;
if (it1 == it2) {
std::cout << "it1 and it2 are equal."<< std::endl;
} else {
std::cout << "it1 and it2 are not equal."<< std::endl;
}
if (it1 < it2) {
std::cout << "it1 is less than it2."<< std::endl;
} else {
std::cout << "it1 is not less than it2."<< std::endl;
}
return 0;
}
輸出:
it1 and it2 are not equal.
it1 is less than it2.