I am trying to add some value at cost[x][y] and the list must be a pointer type. I declared the list like this:
list<int>* cost = new list<int>[V]; // V being user input
And here I'm trying to add the value "c" at the place of cost[x][y]. How am I supposed to add that .When I try to use iterator as below it says
"Debug Assertion Failed"
"Unable to increment end point iterator"
The Code:
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;
}
CodePudding user response:
The problem is that the lists will be initially empty. So, having 0 elements.
So, you can write cost[x]
and can get an iterator. That is OK. But, as said, the list is empty. So, if you try to advance the iterator, it will fail.
Because, it
will be equal to end()
in the beginning. And this cannot be advanced.
Else, it would work . . .
Some demo example:
#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 << ' ';
}