newbie question: map<string, int[2]>

H

Hyrum Mortensen

Hi,

If I create a structure like this:
map<string, int[2]> myMap;

How do I access the first element of the array? I get a compiler's
error if I try something like this: myMap["foo"][0]

If the above structure is NOT possible, what is something that's
equivalent?
 
R

Rolf Magnus

Hyrum said:
Hi,

If I create a structure like this:
map<string, int[2]> myMap;

You can't. Arrays are not assignable, and so they cannot be the element
type of any standard container.
How do I access the first element of the array? I get a compiler's
error if I try something like this: myMap["foo"][0]

If the above structure is NOT possible, what is something that's
equivalent?

struct twoInts
{
int data[2];
}

std::map<std::string, twoInts> myMap;

access it like:

myMap["foo"].data[0];
 
V

Victor Bazarov

Hyrum Mortensen said:
If I create a structure like this:
map<string, int[2]> myMap;

You cannot. Arrays cannot be used for values in standard containers.
They do not satisfy the Assignable requirement.
How do I access the first element of the array? I get a compiler's
error if I try something like this: myMap["foo"][0]

Of course.
If the above structure is NOT possible, what is something that's
equivalent?

You need to wrap the array into a class:

struct TwoInts {
int a, b;
int& operator[](int i) {
if (i == 0) return a;
else if (i == 1) return b;
else throw "Out of range";
}
};

then you can use it with a map:

map<string, TwoInts> myMap;

map["foo"][0] = 42;

Victor
 
K

Kapil Khosla

Hi,

If I create a structure like this:
map<string, int[2]> myMap;

How do I access the first element of the array? I get a compiler's
error if I try something like this: myMap["foo"][0]

If the above structure is NOT possible, what is something that's
equivalent?

This code might help.
// This is the main project file for VC++ application project
// generated using an Application Wizard.

#include "stdafx.h"

#using <mscorlib.dll>
#include <map>
#include <string>

using namespace System;

struct twoInts
{
int data[2];
}myStruct;

int main()
{
// Create your data set to be entered into the MAP

myStruct.data[0] = 0;
myStruct.data[1] = 1;

std::map<std::string, twoInts> myMap;
// Insert it into the MAP

myMap["one"] = myStruct;


return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top