[英]How can I access the values of a map as a whole
我在C ++中有一張這樣的地圖:
std::map<int, int> points;
我知道我可以在這樣的for循環中訪問兩個整數
for (auto map_cntr = points.begin(); map_cntr != points.end(); ++map_cntr)
{
int A = map_cntr->first; // key
int B = map_cntr->second; // val
}
但是我想知道我如何才能整體訪問每個點(而不是上面的條目)。
我認為是這樣的:
for (auto map_cntr = points.begin(); map_cntr != points.end(); ++map_cntr)
{
auto whole_point = points.at(map_cntr);
}
實際上,我想對地圖的一個條目(點)的整數進行操作,並與地圖的以下條目(點)的整數進行操作。
我想用地圖的以下項(點)的整數對地圖的項(點)的整數進行操作。
Map
不適合根據您要根據先前元素修改當前元素的元素順序來執行操作的容器。 對於這些事情,您可以使用向量或成對數組。
您可以使用foreach循環
std::map<int, int> points;
for (auto pair : points)
{
// pair - is what you need
pair.second;
pair.first;
auto whole_point = pair;
}
我想使用地圖的以下條目(點)的整數對地圖的條目(點)的整數進行操作
您無法直接修改地圖中[key,value]對的鍵。 如果需要,您必須擦除該對並插入另一對。
如果只需要寫一個對的值,或者只需要讀取對,則可以使用單個迭代器來完成,如下所示:
// assuming the map contains at least 1 element.
auto it = points.begin();
std::pair<const int, int>* currentPoint = &(*it);
it++;
for (; it != points.end(); ++it) {
auto& nextPoint = *it;
// Read-only: currentPoint->first, nextPoint.first
// Read/write: currentPoint->second, nextPoint.second
currentPoint = &nextPoint;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.