我並不完全清楚是什麼了(我在0..500)是,但如果這是你需要做的:
#include <map>
#include <iostream>
#include <algorithm>
using std::map;
int main(int argc, const char** argv)
{
map<int /*time*/, int /*client*/> slot_info;
slot_info[123] = 1;
slot_info[125] = 2;
slot_info[480] = 3;
slot_info[481] = 1;
slot_info[482] = 3;
for (int timeKey = 0; timeKey <= 500; ++timeKey) {
auto it = slot_info.find(timeKey);
if (it != slot_info.end()) {
auto nextIt = ++it;
nextIt = std::find_if(nextIt, slot_info.end(), [=] (const std::pair<int, int>& rhs) { return rhs.second == it->second; });
if (nextIt != slot_info.end()) {
std::cout << "found " << it->second << " with " << it->first << " and " << nextIt->first << std::endl;
}
}
}
}
但它也似乎更可能是你可能只想在地圖上迭代檢查每個值。
問題的第二部分「我對地圖.begin()和'.end()的理解是它是字面的 - 即它在這種情況下不會返回20給我,因爲它已經到達結束。」
「begin()」和「end()」是絕對的,與您可能擁有的任何當前迭代器無關。
#include <map>
#include <iostream>
#include <algorithm>
using std::map;
std::ostream& operator<<(std::ostream& os, const std::pair<int, int>& item) {
std::cout << "[" << item.first << "," << item.second << "]";
return os;
}
int main(int argc, const char** argv)
{
map<int /*time*/, int /*client*/> slot_info;
slot_info[123] = 1;
slot_info[125] = 2;
slot_info[480] = 3;
slot_info[481] = 1;
slot_info[482] = 3;
for (auto it = slot_info.begin(); it != slot_info.end(); ++it)
{
std::cout << "*it = " << *it << ", but *begin = " << *(slot_info.begin()) << std::endl;
}
return 0;
}
所以,你有另一種選擇是 - 相當昂貴
for (int timeKey = 0; timeKey <= 500; ++timeKey) {
auto firstIt = slot_info.find(i); // find a slot for this time.
if (firstIt == slot_info.end())
continue;
auto secondIt = std::find(slot_info.begin(), slot_info.end(), [=](const std::pair<int, int>& rhs) { return firstIt->second == rhs.second && firstIt->first != rhs.first; });
if (secondIt != slot_info.end()) {
// we found a match
}
}
你有什麼具體問題? – poolie
@poolie「我在循環回到地圖前端時遇到了問題,當它到達結尾時」,即當我在480號插槽,並且下一個分配插槽是2時,我如何找到它? – sccs
爲什麼需要「循環」:一旦你找到一個值,你繼續通過你的收藏找到第二個實例 - 你知道它不是在第一個之前(或者你已經找到它)。不確定你要求的是什麼... – John3136