Reputation: 17
If I have a table of vectors declared as
vector<int> table[9][9]
and I want to compare and delete the element if it already exists, would the deletion be:
for(int row = 0; row < 9; row++)//erases the current choice from the whole row
{
for(int h = 0; h < (int)table[row][k].size();h++)
{
if(table[row][k][h] == table[i][k][0])
{
table[row][k].erase(table[row][k].begin() + h);
}
}
}
I thought this would work, but I'm not 100% because I tried to delete every element using this technique and it didn't work, for those of you who want to see the code I used to delete all the elements, then it is:
for(int i = 0; i < 9; i++)
for(int k = 0; k < 9; k++)
for(int n = 0; n < table[i][k].size();n++)
table[i][k].erase(table[i][k].begin + n);
this method did not work, so I used clear instead.
Upvotes: 0
Views: 107
Reputation: 279195
I don't know what choice
and k
are, but to erase all values from a vector v
that are equal to a particular value val
use the "erase-remove idiom":
v.erase(
std::remove(v.begin(), v.end(), val),
v.end()
);
Hence, to do this same thing for all vectors in table
:
for (auto &row : table) {
for (auto &v : row) {
v.erase(
std::remove(v.begin(), v.end(), val),
v.end()
);
}
}
If you have a more complicated condition than equality, use remove_if
in place of remove
. But in your case, the extra condition involving puzzle
doesn't use the loop variable h
, so I think you can test that before looking in the vector:
if (puzzle[row][k] == 0) {
// stuff with erase
}
In C++03 you can't use "range-based for loops" for (auto &row : table)
. So if you don't have C++11, or if you need the index for use in the puzzle
test, then stick with for(int i = 0; i < 9; i++)
.
Upvotes: 4