0

Quick question which I fear has a short and disappointing answer but alas I shall ask anyway.. In the C++ Dictionary method TryGetValue() is there any way to change the default value that will be returned for an integer (to -1 instead for example) when the key is not present? The problem is that 0 is the default and this is not suitable because a value of 0 would make sense in the context of my program.

If not, is the ContainsKey() method that much slower? Or is it splitting hairs and nothing to worry about seeing as in all likelihood I have no choice..

Many thanks

PS I don't need to perform any hashing function (though this might be in the implementation for Dictionary anyway!), nor have any particular ordering to my collection, I just want lookup and adding to be as fast as possible. Is Dictionary a sound choice?

Darius
  • 5,180
  • 5
  • 47
  • 62
  • 1
    Do you mean Managed C++? It is not the same as C++ should be tagged as such. – Praetorian Jul 28 '11 at 22:30
  • I'm writing in unmanaged using Dictionary^ dictionary = gcnew Dictionary(); syntax... though with ints instead of string – Darius Jul 28 '11 at 22:33
  • 1
    There is no operator named `gcnew` in C++. You're using [Managed C++, or C++/CLI](https://secure.wikimedia.org/wikipedia/en/wiki/Managed_C%2B%2B_programming_language) as it is known now – Praetorian Jul 28 '11 at 22:36
  • Oh I see. In truth I barely use C++ generally. My apologies for the mix up. – Darius Jul 28 '11 at 22:37
  • you are definitely using managed code : [hint1](http://msdn.microsoft.com/en-us/library/bb347013.aspx) - on this page it says clearly that the function is in .Net Framework 4.0 and [hint2](http://msdn.microsoft.com/en-us/library/te3ecsc8(v=vs.80).aspx) ... you are using gcnew wich is creating a new garbage collected object.. that means it's managed – Ioan Paul Pirau Jul 28 '11 at 22:39
  • The gcnew is a pretty big giveaway... my bad. Thanks for the tips. Any ideas on the question too? – Darius Jul 28 '11 at 22:42

1 Answers1

0

Why don't you create a class that inherits from Dictionary(Of TKey, TValue) and override the TryGetValue function. You could then use your own class and it would behave just as you would want it to...

Ioan Paul Pirau
  • 2,733
  • 2
  • 23
  • 26
  • That's true, perhaps I will resort to that then. Just seems like an oversight that MS don't let you set a default value. Thanks for your help. – Darius Jul 28 '11 at 22:48
  • I have just realised that the bool returned by the method indicates whether the value was present or not. Sorry for not noticing that before, yesterday was a long day and I blame fatigue!! Thanks again – Darius Jul 29 '11 at 09:46