[英]C++ Looping over a map - disappearing objects
所以,我在代碼中發現了一個相當奇怪的錯誤,我很難理解。 我有一個 std::map 用於存儲一些信息。 當我第一次循環時,一切看起來都很好,但是第二次,數據丟失了。
首先,我使用一個結構體和一個類,如下所示:
struct Eng::Pixel{
unsigned int x;
unsigned int y;
};
class Eng::Edge{
public:
enum EdgeType { INTER, INTRA};
EdgeType type;
}
class Eng::Cluster{
public:
std::map<Pixel, std::vector<Edge>> trans;
}
基本上,一個簇包含一張像素圖。 該地圖中的每個像素都包含稱為邊緣的過渡點。 每個像素可以有多個邊緣 - 邊緣可以是 inter(0) 或 intra (1) 類型。 請注意,某些命名空間可能會丟失,因為我試圖盡可能地簡化我的問題。
當我循環代碼時:
std::vector<Cluster> resClusters = this->GenerateClusters();
for(Cluster cluster : resClusters) //For a given cluster in clusters
{
this->CreateIntraEdges(cluster); //Create our intra edges. Succeeds.
std::cout << "Cluster: " << cluster << std::endl; //Prints the bounds of the cluster.
std::cout << "Cluster has " << cluster.trans.size() << " transition pixels." << std::endl; //Prints the keys of the map jsut fine.
for (const auto& p : cluster.trans ) //For each member of the map
{
for(Edge ed : p.second) //For each edge from std::vector<Edge>
{
std::cout << ed.type << " Start: " << ed.s << " End: "<< ed.e << std::endl;
}
}
}
這打印得很好:
Cluster has 6 transition pixels.
0 Start: {2,14} End: {2,15}
1 Start: {2,14} End: {5,14}
1 Start: {2,14} End: {14,0}
1 Start: {2,14} End: {14,6}
1 Start: {2,14} End: {14,8}
1 Start: {2,14} End: {14,14}
0 Start: {5,14} End: {5,15}
...
然而,在沒有 this->CreateIntraEdges 的情況下再次運行循環,我們得到:
Second run!
Cluster: Min: {0,0} Max: {14,14}
Cluster has 6 transition pixels.
0 Start: {2,14} End: {2,15}
0 Start: {5,14} End: {5,15}
0 Start: {14,0} End: {15,0}
0 Start: {14,6} End: {15,6}
0 Start: {14,8} End: {15,8}
0 Start: {14,14} End: {15,14}
0 Start: {14,14} End: {14,15}
...
現在,如果您還想查看 CreateIntraEdge,請執行以下操作:
void CreateIntraEdges(Cluster& c)
{
for (const auto& p1 : c.trans ) //For each object in the map.
{
for (const auto& p2 : c.trans ) //For each object in the map
{
if(p1.first == p2.first)
{
continue;
}
auto [path, weight] = this->GetPath(c, p1.first, p2.first); //See if the two edges can connect.
if(path.size() > 0)
{
Edge newedge;
newedge.Set(p1.first, p2.first, weight, Edge::INTRA);
c.trans[p1.first].push_back(newedge); //Push it back onto the std::vector<Edge> for the pixel p1.first
}
}
}
}
為什么循環看不到類型為 1 的邊? 是因為汽車嗎?
由於地圖使用自定義結構,我還沒有實現迭代器。 這可能是問題的根源嗎?
您創建了許多對象的副本...
std::vector<Cluster> resClusters = this->GenerateClusters();
這里resCluster
是一個副本,對它的更改不會存儲在this
(如果那里有一個向量)。
同
for(Cluster cluster : resClusters)
這里cluster
是向量中元素的副本。 一旦循環迭代或結束,對cluster
更改將丟失。
您可能需要引用,至少對於循環:
for(Cluster& cluster : resClusters)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.