-
Another map question
I'm working on a simple data structure and some functions that take various shapes and perform calculations on them. The shapes will be constructed out of real physical materials, and I need a way to count each segment length. The count and lengths are arbitrary, as are the number of lengths.
I know this code isn't complete, I'm just showing an outline of what I'm trying to accomplish.
Code:
#include <map>
#include <vector>
using std::map;
using std::vector;
struct SEG_PROPERTIES
{
int material;
unsigned int thickness;
bool is_coated;
};
struct SEG_COUNTS
{
struct SEG_PROPERTIES segProperties;
// For total length of all segments with same properties
unsigned int totalLength;
// first = length of segment
// second = count of segments with length
map <unsigned int, unsigned int> segment;
};
vector <SEG_COUNTS> segCounts;
void someFunction(void)
{
// Misc code...
// Line in question
segCounts[1].segment.first = 5;
}
When I try to refer to the .first or .second elements of segCounts[].segment I get this compilation error:
Code:
error C2039: 'first' : is not a member of std::map<_Kty,_Ty>
So I thought that maybe for some reason I need to specify using a pair in the declaration of segment...
Code:
#include <utility>
using std::pair;
...
struct SEG_COUNTS
{
...
map <pair<unsigned int, unsigned int> > segment;
};
But that gives me different errors, and I really don't think that's the way I'm supposed to declare a map. It's obvious I'm doing something wrong, maybe the syntax is eluding me. Anyone care to enlighten me?
-
segCounts[1].segment is a std::map, and a std::map does not have a public member named first (or second). What exactly were you trying to do on that line?
-
first is part of std::pair which map::find() returns. You are using the map incorrectly.
-
What I'm really looking to do is retrieve and set the two values in segment. I thought that this was done with the .first and .second members of the map, but I guess I'm mistaken.
-
Perhaps you are looking to use a pair instead of a map?
-
I need a map, I think. For each segCounts there will be an assortment of length/count pairs that need to be stored.
-
hmm... okay, in your original code, you need to understand that segCounts[1].segment is a map. You might write segCounts[1].segment[5], which would then be an unsigned int presumably representing the count of segments with length 5.
-
Okay, I think I've got it. I just needed to get an iterator to the segment in question...
Code:
void someFunction(void)
{
map <unsigned int, unsigned int>::iterator iterCurrent;
unsigned int length = 4;
unsigned int count = 1;
iterCurrent = segCounts[1].segment.find(length);
iterCurrent->second = count;
}
-
...which is what I said in my post.
-
Yes, thank you Bubba. When I first read your post I didn't quite understand, I'd never used the ::find member function before. You definitely got me on track there.