我不完全清楚 for(i in 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
}
}