我試圖在 cost[x][y] 處添加一些值,并且串列必須是指標型別。我這樣宣告串列:
list<int>* cost = new list<int>[V]; // V being user input
在這里,我試圖在 cost[x][y] 的位置添加值“c”。我應該如何添加它。當我嘗試使用下面的迭代器時,它說
“除錯斷言失敗”
“無法增加端點迭代器”
代碼:
void addCost(int x, int y, int c) // adds cost in cost[x][y] and cost[y][x] indicies
{
auto it = cost[x].begin();
advance(it, y);
*it = c;
}
uj5u.com熱心網友回復:
問題是串列最初是空的。所以,有0個元素。
因此,您可以撰寫cost[x]并且可以獲得迭代器。那沒問題。但是,如前所述,串列是空的。因此,如果您嘗試推進迭代器,它將失敗。
因為,it將等于end()一開始。這是無法推進的。
否則,它會起作用。. .
一些演示示例:
#include <iostream>
#include <list>
constexpr size_t SIZE = 10;
int main() {
size_t numberOfElementsX{ SIZE };
size_t numberOfElementsY{ SIZE };
std::list<int>* cost = new std::list<int>[numberOfElementsX];
for (size_t i = 0; i < numberOfElementsX; i)
cost[i].resize(numberOfElementsY);
auto it = cost[3].begin();
std::advance(it, 5);
*it = 42;
for (auto i : cost[3])
std::cout << i << ' ';
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448846.html
上一篇:C 中的從屬名稱是什么?
