簡體   English   中英

C++中物體的區分方法

[英]Way to distinguish objects in C++

有一個結構,object 屬於。 沒有定義結構的功能。 列出我使用過的對象

for (auto object:objects)

但現在我需要區分對象以對每 3 個 object 執行不同的操作。 我怎樣才能列出它們,以便我知道哪個 object 是第三個?

您可以使用 for 循環或 while 循環。 這樣,您將能夠使用索引來了解哪個 object 是每三分之一或第 n 個。

for(int i = 0; i < N; ++i) {
    if(i % 3 == 0)
    {   
        objects[i] // do something with this object here
    }
}

或者如果 [] 無法訪問它的對象:

int i = 0;
// remove the & if you need to use a copy of the object
for(auto& object: objects) {
    if(i % 3 == 0)
    {   
        // do something with this object here
    }
    ++i;
}

for (auto object: objects)語句表示包含objects的數據結構是可迭代的,即表示objects數據結構實現了begin()end()函數。 現在據我了解,您需要每 3 個元素執行一次特定操作。 最簡單的方法是:

  • 通過使用額外的計數器:
size_t counter = 0;
for (auto object: objects) {
    if (counter % 3 == 0) {
        // modify object
    }
    counter ++;
}

請注意,在調用for (auto object: objects)時,根據類型對象數據結構,您實際上可能會進行復制。 (不通過引用傳遞 object)。 這是因為 auto 采用存儲在objects數據結構中的元素的偏角類型。 為確保您確實修改了 object,需要指定您傳遞引用:例如for (auto & object: objects)

  • 通過使用迭代器更改 for 循環語句
for (auto it = objects.begin(); it != object.end(); it ++) {
    size_t element_position = std::distance(objects.begin(), it);
    if (element_position % 3 == 0) {
        // do something with * it which stores the object
    }
}

如果數據結構的迭代器不是隨機訪問迭代器,請注意std::distance方法可能是線性的。 更多詳情請查看: https://www.cplusplus.com/reference/iterator/distance/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM