Create an object/Native demonstration: Difference between revisions

C++ update
(Clarification?)
(C++ update)
Line 21:
{
// Two standard maps are used to implement FixedMap. One as a private
// base class thatwhich will allow the values (but not the keys) to be modified.
// Members of a private base class are not exposed to the derived class which will
// prevent keys from being added or deleted. Another map will hold copies of
Line 31:
: T(map), m_defaultValues(move(map)){}
// Expose members of the base class that aredo not ablemodify to add or remove keys sothe map.
// that FixedMap will behave like a standard container.
using T::begin;
using T::cbegin;
using T::end;
using T::cend;
using T::at;
using T::empty;
using T::find;
using T::size;
 
// Also expose members that can modify values but not add or remove keys.
using T::at;
using T::begin;
using T::end;
// The [] operator will normally add a new key if the key is not already in the
// map. Instead, throw an error if the key is missing.
auto& operator[](typename T::key_type&& key)
{
auto// iteratorMake =it this->findbehave like at(key);
if(iterator ==return this->endat())forward<typename throw out_of_rangeT::key_type>("key not found"));
return iterator->second;
}
// ResetInstead theof valueremoving ofa key, tochange itsthe initialsematics value.of erase() Throws anto errorrestore
// if the keyoriginal isvalue missingof the key.
void reseterase(typename T::key_type&& key)
{
T::operator[](key) = m_defaultValues.at(key);
}
 
// Also change the sematics of clear() to restore all keys
void clear()
{
// Reset the base class using the defaults
T::operator=(m_defaultValues);
}
};
 
Line 66 ⟶ 74:
cout << "{" << key << " : " << value << "} ";
}
cout << "\n\n";
};
 
Line 72 ⟶ 80:
{
// Create a fixed map based on the standard map
cout << "Map intialized with values\n";
FixedMap<map<const char *string, int>> fixedMap ({
{"a", 1},
{"b", 2}});
PrintMap(fixedMap);
//cout << "Change the values of the keys\n";
fixedMap["a"] = 55;
fixedMap["b"] = 56;
PrintMap(fixedMap);
//cout << "Reset the 'a' key\n";
fixedMap.reseterase("a");
PrintMap(fixedMap);
cout << "Change the values the again\n";
fixedMap["a"] = 88;
fixedMap["b"] = 99;
PrintMap(fixedMap);
cout << "Reset all keys\n";
fixedMap.clear();
PrintMap(fixedMap);
try
{
// Adding or retrieving a missing key is a run time error
cout << "Try to add a new key\n";
fixedMap["newKey"] = 99;
}
Line 94 ⟶ 113:
{
cout << "error: " << ex.what();
}
}
</lang>
{{out}}
<pre>{aMap :intialized 1} {b : 2}with values
{a : 1} {b : 2}
 
Change the values of the keys
{a : 55} {b : 56}
 
Reset the 'a' key
{a : 1} {b : 56}
 
error: key not found</pre>
Change the values the again
{a : 88} {b : 99}
 
Reset all keys
{a : 1} {b : 2}
 
Try to add a new key
error: key not foundmap::at</pre>
 
=={{header|D}}==
125

edits