我試圖理解std::find()
。下面是我的代碼。
std::set::find
在容器中搜索等價于的元素val
,如果找到則回傳一個迭代器,否則回傳一個迭代器到set::end
.
但是當我給的時候,我得到find(100)
的是 7 而不是 20。
#include <iostream>
#include <set>
using namespace std;
int main()
{
set <int> s1{20, 7, 2};
s1.insert(10);
s1.insert(5);
s1.insert(15);
s1.insert(1);
cout << "size() : " << s1.size() << endl;
cout << "max_size() : " << s1.max_size() << endl;
cout << "empty() : " << s1.empty() << endl;
for(auto itr = s1.begin(); itr != s1.end(); itr )
cout << *itr << " ";
cout << endl;
cout << endl << "---- find(value) ----" << endl;
auto a1 = s1.find(10);
//cout << "find(10) : " << a1 << " " << *a1 << endl;
cout << "find(10) : " << *a1 << endl;
auto a2 = s1.find(100);
cout << "find(100) : " << *a2 << endl;
cout << endl << "---- count(value) ----" << endl;
cout << "s1.count(10) : " << s1.count(10) << endl;
cout << "s1.count(100) : " << s1.count(100) << endl;
return 0;
}
輸出:
size() : 7
max_size() : 107374182
empty() : 0
1 2 5 7 10 15 20
---- find(value) ----
find(10) : 10
find(100) : 7
---- count(value) ----
s1.count(10) : 1
s1.count(100) : 0
uj5u.com熱心網友回復:
問題是您正在取消參考a2
指向s1.end()
導致未定義行為的迭代器。出現此問題是因為您在取消參考迭代器之前沒有檢查是否找到了元素。
要解決這個問題,您應該在取消參考迭代器之前添加顯式檢查。
//dereference only if the element was found
if(a2!=s1.end())
{
std::cout << "find(100) : " << *a2 << std::endl;
}
//otherwise print a message saying element not found
else
{
std::cout<<"element not found"<<std::endl;
}
uj5u.com熱心網友回復:
auto a2 = s1.find(100); cout << "find(100) : " << *a2 << endl;
在這里,您取消參考 ( *a2
) 結束迭代器。那是未定義的行為 - 請記住,它s1.end()
指向最后一個元素之后的元素,并且不能被取消參考。
你很不幸你從那個取消參考中得到了一個值 - 如果你的程式崩潰或以其他方式報告問題會更方便。但 UB 不必以任何方式被診斷出來。
如果您使用 Valgrind 的記憶體檢查器(或您喜歡的等價物)運行程式,您可能已經發現了問題。但是很有可能無法檢測到它(如果集合過度分配,這很可能)。
uj5u.com熱心網友回復:
集合中不存在值 100。所以這個電話
auto a2 = s1.find(100);
回傳迭代器s1.end()
。您不能取消參考迭代器。這個說法
cout << "find(100) : " << *a2 << endl;
呼叫未定義的行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471192.html
上一篇:不平衡二叉搜索樹中的搜索操作
下一篇:遍歷包含三個鍵值對的物件陣列