You can make things a bit simpler by making POINTs real objects
and adding a constructor so you can stamp out POINT objects
like POINT p(1,2) instead of the mechanism you are using.
You dont have to explicitly create variables for POINT and pair,
you can do things like this:
testPoints.insert( std::pair<POINT,int>(POINT(1,2), 456) );
this creates a temporary POINT object with values 1, 2 and a pair
object with that POINT and they int value 456.
The std::pair<POINT,int> is a bit of a mouthful, I thought you
could just do std::pair and the compiler should deduce the template
arguments, however you can just create a typedef to use instead if
you don't want to type that stuff in over and over.
I've tinkered with your original code below
#include <std_disclaimers.h>
#include <map>
#include <iostream>
struct POINT { // pt
long x;
long y;
POINT(long xx, long yy)
:x(xx), y(yy){}
} ;
//map comparison fctn
struct PointCompare {
bool operator() (POINT p1, POINT p2) const {
if (p1.x == p2.x)
return p1.y < p2.y;
else
return p1.x < p2.x;
}
};
int main() {
std::map<POINT, int,PointCompare> testPoints;
POINT pnt2(1,2);
testPoints.insert( std::pair<POINT,int>(POINT(1,2), 456) );
POINT pnt1(1,2);
std::cout << "direct access {1,1} -> " << testPoints[pnt1] <<
std::endl;
std::map<POINT, int, PointCompare>::iterator iter;
for (iter = testPoints.begin(); iter != testPoints.end();
++iter) {
POINT iterPnt = iter->first;
std::cout << "iterator access: iter->first = {" <<
iterPnt.x << "," << iterPnt.y << "}" << std::endl;
std::cout << "iterator access: iter->second = " <<
(iter->second) << std::endl;
}
return 0;
}
"cppaddict" <he***@hello.com> wrote in message
news:m7********************************@4ax.com...
Hi,
I have some code which uses std::map to associate cartesian POINTs
with values. My current syntax for adding new (POINT,value) entries
to the map is clunky -- it takes three lines for each entry. There
must be a way to trim it down:
<code>
#include <map>
#include <iostream>
typedef struct tagPOINT { // pt
long x;
long y;
} POINT;
//map comparison fctn
struct PointCompare {
bool operator() (POINT p1, POINT p2) const {
if (p1.x == p2.x)
return p1.y < p2.y;
else
return p1.x < p2.x;
}
};
int main() {
std::map<POINT, int,PointCompare> testPoints;
//THIS CODE IS HERE IS THE PROBLEM
POINT pnt1 = {1,1};
std::pair<POINT, int> pair1(pnt1,123);
testPoints.insert(pair1);
POINT pnt2 = {1,2};
std::pair<POINT, int> pair2(pnt2,456);
testPoints.insert(pair2);
std::cout << "direct access {1,1} -> " << testPoints[pnt1] <<
std::endl;
std::map<POINT, int, PointCompare>::iterator iter;
for (iter = testPoints.begin(); iter != testPoints.end();
++iter) {
POINT iterPnt = iter->first;
std::cout << "iterator access: iter->first = {" <<
iterPnt.x << "," << iterPnt.y << "}" << std::endl;
std::cout << "iterator access: iter->second = " <<
(iter->second) << std::endl;
}
return 0;
}
</code>
Thanks for any help,
cpp