Associative array/Creation: Difference between revisions

added C++
m (Added subsections to Perl. Added Array Operation template)
(added C++)
Line 3:
 
In this task, the goal is to create an [[associative array]].
 
==[[C plus plus|C++]]==
'''Compiler:''' g++ 4.0.2
 
#include <map>
#include <string>
#include <iostream>
#include <ostream>
int main()
{
// This is an associative array which maps strings to ints
typedef std::map<std::string, int> colormap_t;
colormap_t colormap;
// First, populate it with some values
colormap["red"] = 0xff0000;
colormap["green"] = 0x00ff00;
colormap["blue"] = 0x0000ff;
colormap["my favourite color"] = 0x00ffff;
// then, get some values out
int color = colormap["green"]; // color gets 0x00ff00
color = colormap["black"]; // accessing unassigned values assigns them to 0
// get some value out without accidentally inserting new ones
colormap_t::iterator i = colormap.find("green");
if (i == colormap.end())
{
std::cerr << "color not found!\n";
}
else
{
color = i->second;
}
// Now I changed my mind about my favourite color, so change it
colormap["my favourite color"] = 0x337733;
// print out all defined colors
for (colormap_t::iterator i = colormap.begin(); i != colormap.end(); ++i)
std::cerr << "colormap[\"" << i->first << "\"] = 0x" << std::hex << i->second << "\n";
}
 
==[[Perl]]==
Anonymous user