ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Hi, majority of examples of the containers such as std::map are based on a key value pair. Say for example if I want to have something similar to an array, how do I do this? An example would be like the following.
Key 1, Value 1a, Value 1b
Key 2, Value 2a, Value 2b
Key 3, Value 3a, Value 3c
An example application would be using the keys to store product codes, value <x>a to store the price, and value <x>b to store availability (true or false as a boolean). How do I declare the variable in this case?
Hi, majority of examples of the containers such as std::map are based on a key value pair. Say for example if I want to have something similar to an array, how do I do this? An example would be like the following.
Key 1, Value 1a, Value 1b
Key 2, Value 2a, Value 2b
Key 3, Value 3a, Value 3c
An example application would be using the keys to store product codes, value <x>a to store the price, and value <x>b to store availability (true or false as a boolean). How do I declare the variable in this case?
Define a structure to contain the values; then use this type as the value-type for the std::map. Here's a simple example:
Code:
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
struct Values
{
Values(const int v1 = 0, const int v2 = 0) : val1(v1), val2(v2) {}
int val1;
int val2;
friend std::ostream& operator<<(std::ostream& os, const Values& v)
{
os << v.val1 << ", " << v.val2;
return os;
}
};
void displayEntry(const std::pair<int, Values>& entry)
{
std::cout << "Entry " << entry.first << " has these values: " << entry.second << std::endl;
}
int main()
{
typedef std::map<int, Values> MyMap;
MyMap mm;
mm[20] = Values(20, 200); // note: copy-constructor called here! This may not be desirable.
mm[10] = Values(10, 100); // same here
mm[30] = Values(30, 300); // same here
std::for_each(mm.begin(), mm.end(), displayEntry);
}
Last edited by dwhitney67; 02-07-2012 at 12:29 PM.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.