I'm working on a project that includes a handmade Set of sorts using a template class with two types and vectors (which I may change to pointers but not at the moment).
Adding and outputting values works fine, and I'm able to access the key and values using eachother as well.
However I'm having problems with removing values. This is the code I have for it:
bool Remove(Tkey key)
{
for (int i = 0; i < size(); i++)
{
if (keyPtr[i] == key)
{
keyPtr.erase(keyPtr.begin() + (i-1));
valuePtr.erase(valuePtr.begin() + (i-1));
return true;
}
}
return false;
}
So that when I want to use it it will look like this:
cout << "Remove Value 6" << endl;
list.Remove(6);
What I expect from vectors is when that calls, the data with the key as 6 would be removed. However I get this as my output:
Key : 0 Value : 0
Key : 1 Value : 3
Key : 2 Value : 6
Key : 3 Value : 9
Key : 4 Value : 12
Key : 5 Value : 15
Key : 6 Value : 18
Key : 7 Value : 21
Key : 8 Value : 24
Key : 9 Value : 27
Find value 5: 15
Remove Value 6
Key : 0 Value : 0
Key : 1 Value : 3
Key : 2 Value : 6
Key : 3 Value : 9
Key : 4 Value : 12
Key : 0 Value : 0
Key : 6 Value : 18
Key : 7 Value : 21
Key : 8 Value : 24
Key : 9 Value : 27
All the class code is in a header because templates classes can't be split between header and cpp without having the main method inside the cpp file. Is there something I should check or is it something to do with the code being inside the header?
EDIT: This is the code I'm using to get the output. It's in a file called "main.cpp"
#include <iostream>
#include <vector>
#include "DictionaryList.h"
using namespace std;
void main()
{
DictionaryList<int,int> list;
for (int i = 0; i < 11; i++)
{
list.Add(i, i*3);
}
for (int i = 0; i < 10; i++)
{
cout << "Key : " << list.Exists(i*3) << " Value : " << list.Get(i) << endl;
}
cout << "Find value 5: " << list.Get(5) << endl;
cout << "Remove Value 6" << endl;
list.Remove(6);
for (int i = 0; i < 10; i++)
{
cout << "Key : " << list.Exists(i*3) << " Value : " << list.Get(i) << endl;
}
system("pause");
}
You get the observed output because:
You are removing element 5 rather than 6. Having found the index i
corresponding to the requested key, you then erase element i-1
. Change the erase
arguments to begin() + i
to remove the expected key/value pair.
Your output loop prints a line for each possible key, whether or not it's there, hence the line saying Key : 0 Value : 0
where the removed element was. I guess List.Exists()
looks up a value, returning a key if it's found and zero if it's not, and List.Get()
returns zero if the key is not found. That behaviour will lead to errors: there's no way to distinguish missing elements from zero-valued elements.
Even if you don't want to use the standard map containers for some reason, I suggest giving your container a similar interface; as well as being familiar to people who use the standard containers, a lot of thought went into making their interfaces difficult to misuse.