在 set 和 multiset 中搜尋值
有幾種方法可以在 std::set 或 std::multiset 中搜尋給定值:
要獲取第一次出現的鍵的迭代器,可以使用 find() 函式。如果金鑰不存在,則返回 end()。
std::set<int> sut;
sut.insert(10);
sut.insert(15);
sut.insert(22);
sut.insert(3); // contains 3, 10, 15, 22
auto itS = sut.find(10); // the value is found, so *itS == 10
itS = sut.find(555); // the value is not found, so itS == sut.end()
std::multiset<int> msut;
sut.insert(10);
sut.insert(15);
sut.insert(22);
sut.insert(15);
sut.insert(3); // contains 3, 10, 15, 15, 22
auto itMS = msut.find(10);
另一種方法是使用 count() 函式,它計算在 set / multiset 中找到了多少相應的值(在 set 的情況下,返回值只能是 0 或 1)。使用與上面相同的值,我們將:
int result = sut.count(10); // result == 1
result = sut.count(555); // result == 0
result = msut.count(10); // result == 1
result = msut.count(15); // result == 2
在 std::multiset 的情況下,可能有幾個元素具有相同的值。要獲得此範圍,可以使用 equal_range() 功能。它返回具有迭代器下限(包括)和上限(不包括)的 std::pair。如果金鑰不存在,則兩個迭代器都將指向最接近的上級值(基於用於對給定 multiset 進行排序的比較方法)。
auto eqr = msut.equal_range(15);
auto st = eqr.first; // point to first element '15'
auto en = eqr.second; // point to element '22'
eqr = msut.equal_range(9); // both eqr.first and eqr.second point to element '10'