#include <iostream>
#include<vector>
#include<map>
using namespace std;
int main() {
vector<int> v1{1,2,3,4,5};
auto it1 = v1.begin();
auto it2 = v1.end();
if(it1<it2){
cout<<"TRUE"<<endl; // Output: TRUE
}
map<int,int> m;
m.insert(make_pair(1,2));
m.insert(make_pair(5,7));
auto it3 = m.begin();
auto it4 = m.end();
if(it3<it4){
cout<<"TRUE"<<endl;
}
/*
error: no match for 'operator<' (operand types are 'std::_Rb_tree_iterator<std::pair<const int, int> >' and 'std::_Rb_tree_iterator<std::pair<const int, int> >')
18 | if(it3<it4){
| ~~~^~~~
*/
}
Line (it1<it2) 在使用 vector 時作業正常,但 (it3<it4) 在使用 map 時不起作用?請解釋這個概念。
uj5u.com熱心網友回復:
線 (it1<it2) 在使用向量時作業正常,但 (it3<it4)
向量迭代器是隨機訪問迭代器。可以比較隨機訪問迭代器的順序。
但是 (it3<it4) 在使用地圖時不起作用?
映射迭代器不是隨機訪問迭代器。它們不能在順序上進行比較。
但是,如果您知道映射的比較器,那么您可以間接通過兩個迭代器,并將鍵與比較器進行比較。您必須首先檢查結束迭代器,因為您無法從中獲取密鑰(但您確實知道它在所有其他迭代器之后)。這僅適用于有序映射,例如std::map. 它不適用于哈希映射,例如std::unordered_map. 它也不會找出多映射中兩個迭代器與相同元素的相對順序。
一般來說,給定一對前向迭代器和結束迭代器,您可以通過從一個迭代器開始進行線性搜索來找出這對迭代器,直到找到第二個迭代器或容器的末尾。如果你在另一個迭代器之前找到 end,那么 other 是第一個;如果你確實找到了另一個迭代器,那么它就在之后。這當然具有線性最壞情況復雜度。
uj5u.com熱心網友回復:
有關迭代器類別的概述,請參見此處:https : //en.cppreference.com/w/cpp/iterator。
std::map具有雙向迭代器,同時std::vector具有隨機訪問迭代器。后者可以通過 comapred <,第一個不能。
如果您想知道哪個元素首先出現在地圖中,您可以使用 a std::maps 元素根據鍵進行排序的事實:
if (it3->first < it4->first) { ...
一般來說,您需要考慮到地圖可能使用自定義比較器,因此更通用的方法是
if ( m.key_comp()(it3->first,it4->first) ) { ...
但是,當其中一個迭代器等于end映射的時,任何一種方法都會失敗,因為您無法取消參考它來獲取鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368287.html
下一篇:如何將字串轉換為字母字典?
