data structures - Overloading [] operator in C++ -
im trying overload [] operator in c++ can assign / values data structure dictionary used in c#:
array["mystring"] = etc.
is possible in c++?
i attempted overload operator doesnt seem work,
record& mydictionary::operator[] (string& _key) { (int = 0; < used; ++i) { if (records[i].key == _key) { return records[i]; } } }
thanks.
your code on right track - you've got right function signature - logic bit flawed. in particular, suppose go through loop without finding key you're looking for:
for (int = 0; < used; ++i) { if (records[i].key == _key) { return records[i]; } }
if happens, function doesn't return value, leads undefined behavior. since it's returning reference, going cause nasty crash second try using reference.
to fix this, you'll need add behavior ensure don't fall off of end of function. 1 option add key table, return reference new table entry. behavior of stl std::map
class's operator[]
function. throw exception saying key wasn't there, have drawback of being bit counterintuitive.
on totally unrelated note, should point out technically speaking, should not name parameter function _key
. c++ standard says identifier name starts 2 underscores (i.e. __myfunction
), or single underscore followed capital letter (as in _key
example) reserved implementation whatever purposes might deem necessary. #define
identifier nonsensical, or have map compiler intrinsic. potentially cause program stop compiling if move 1 platform another. fix this, either make k
lower-case (_key
), or remove underscore entirely (key
).
hope helps!
Comments
Post a Comment