C
cppaddict
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:air<POINT, int> pair1(pnt1,123);
testPoints.insert(pair1);
POINT pnt2 = {1,2};
std:air<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
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:air<POINT, int> pair1(pnt1,123);
testPoints.insert(pair1);
POINT pnt2 = {1,2};
std:air<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