473,809 Members | 2,819 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding Map Entries

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,PointCompar e> testPoints;

//THIS CODE IS HERE IS THE PROBLEM
POINT pnt1 = {1,1};
std::pair<POINT , int> pair1(pnt1,123) ;
testPoints.inse rt(pair1);

POINT pnt2 = {1,2};
std::pair<POINT , int> pair2(pnt2,456) ;
testPoints.inse rt(pair2);

std::cout << "direct access {1,1} -> " << testPoints[pnt1] <<
std::endl;

std::map<POINT, int, PointCompare>:: iterator iter;
for (iter = testPoints.begi n(); 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
Jul 22 '05 #1
5 2701
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.inse rt( 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_disclaimer s.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,PointCompar e> testPoints;

POINT pnt2(1,2);

testPoints.inse rt( 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.begi n(); 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.co m> wrote in message
news:m7******** *************** *********@4ax.c om...
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,PointCompar e> testPoints;

//THIS CODE IS HERE IS THE PROBLEM
POINT pnt1 = {1,1};
std::pair<POINT , int> pair1(pnt1,123) ;
testPoints.inse rt(pair1);

POINT pnt2 = {1,2};
std::pair<POINT , int> pair2(pnt2,456) ;
testPoints.inse rt(pair2);

std::cout << "direct access {1,1} -> " << testPoints[pnt1] <<
std::endl;

std::map<POINT, int, PointCompare>:: iterator iter;
for (iter = testPoints.begi n(); 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

Jul 22 '05 #2
On Fri, 23 Jul 2004 16:53:58 -0700, cppaddict wrote:
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;
You don't need the typedef trick for struct declarations in C++:

struct tagPOINT { /* ... */ };
or
struct POINT { /* ... */ };

It is convenient to define a constructor even for a simple struct so
that the code will be more readable (see below):

struct POINT
{
long x;
long y;

POINT(long x_arg, long y_arg)
:
x(x_arg),
y(y_arg)
{}
};

[...]
int main() {
std::map<POINT, int,PointCompar e> testPoints;
You can use typedefs to simplify the code:

typedef std::map<POINT, int,PointCompar e> Points;
typedef Points::iterato r PointIter;

Points testPoints;

//THIS CODE IS HERE IS THE PROBLEM
POINT pnt1 = {1,1};
std::pair<POINT , int> pair1(pnt1,123) ;
testPoints.inse rt(pair1);
Now you can replace the above three lines with

testPoints.inse rt(std::make_pa ir(POINT(1, 1), 123));

Alternatively:

testPoints[POINT(1, 1)] = 123;

[...]
std::map<POINT, int, PointCompare>:: iterator iter;
for (iter = testPoints.begi n(); iter != testPoints.end( ); ++iter)


The typedef defined above will make this simpler too:

for (PointIter iter = /* ... */)

Ali
Jul 22 '05 #3
On Fri, 23 Jul 2004 17:20:29 -0700, Dave Townsend wrote:
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,


Argument deduction works only for function templates; not class
templates.

Some template classes have a corresponding function template to do the
argument deduction. For example:

template <class A>
class Foo
{
public:
Foo(A const & a);
/* ... */
};

template <class A>
Foo<A> MakeFoo(A const & a)
{
return Foo<A>(a);
}

The convenience function for std::pair is std::make_pair.

Ali
Jul 22 '05 #4
Dave and Ali,

Thanks for the tips.

cpp
Jul 22 '05 #5
cppaddict <he***@hello.co m> 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:


There is. Some other parts can be a bit neater as well:

#include <map>
#include <iostream>
#include <iterator>
#include <algorithm>

class POINT {
long x;
long y;

friend std::ostream &operator<<(std ::ostream &os, POINT const &p) {
return os << "{" << p.x << "," << p.y << "}";
}
public:
bool operator<(POINT const &p2) const {
if (x == p2.x)
return y < p2.y;
else
return x < p2.x;
}

POINT(long x_init, long y_init) : x(x_init), y(y_init) {}
};

typedef std::pair<POINT , int> pp;

std::ostream &operator<<(std ::ostream &os, pp const &p) {
return os << "point " << p.first << " -> " << p.second;
}

int main() {
std::map<POINT, int> testPoints;

testPoints[POINT(1,1)] = 123;
testPoints[POINT(1,2)] = 456;

std::cout << "point {1,1} -> " << testPoints[POINT(1,1)]
<< " (direct access)\n";
std::copy(testP oints.begin(), testPoints.end( ),
std::ostream_it erator<pp>(std: :cout, " (algorithm)\n") );

return 0;
}
Jul 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3115
by: Gary Lundquest | last post by:
I have an application with MS Access 2000 as the front end and MySQL as the back end. All was well until I upgraded the MySQL (Linux) server. The Problem: I insert data into a cumulative table. Before when I did this, and there were duplicate entries, the duplicate entries were rejected and I got a return code with the number of affected rows (number added). Now, I get a MyODBC error and the application stops when trying to add...
20
6680
by: Ash Phillips | last post by:
Hi Everyone, I have this program I wrote in VB6 for family use. It's a DVD Database just for me to keep track of them cause I have so many lol. In VB6, I could add items to the ListView in 'frmMain' from 'frmAdd' with the following code: Private Function AddEntry(Title As String, Rating As String, Genre As String, OnLoan As Boolean, ToWho As String)
9
7337
suzee_q00
by: suzee_q00 | last post by:
I will admit that lots of times the obvious eludes me and this is most likely one of those times but if anyone has any ideas on what I can do to make this code work, I would greatly appreciate it. Here's the code: while ( ( fgets ( buf, BUFLEN, fin ) ) != NULL ) /* pulls a line from "fin" up to the length of BUFLEN and stores it in "buf" */ { rmNl ( buf ); /* remove new line */ if ( !lineWithBlanks ( buf ) ) { for (i = 0; buf !=...
5
2204
by: JJ | last post by:
I want to have two lists (may have to be listboxes) on a page that are populated from a database. I then need to be able to click on an entry in one box and add it to the other, _preferably_ without refreshing the page. Is this possible? Am I coming across another reason to venture into AJAX I wonder.... What controls should I use for the lists to allow selection, sorting, etc
0
1435
by: vljones | last post by:
Hoping to find a way of entering new data into a combo box which contains a list of items contained in a table. In addition I want to allocate an ID number to entries that are not currently in the list. I have Form with a subform - frmQuotation!frmSubLimits On the subform I have the following fields: txtSubLimit and numSubLimitID
8
1632
by: =?Utf-8?B?UGF1bA==?= | last post by:
Hi just wondering if anyone had any ideas on how to do this in C#. I am trying to get the total time of several start and stop time data entries. For example the input data looks like starttime endtime 3:00pm 4:00pm 6:00pm 7:00pm. 6:30pm 7:00pm 3:00pm 3:30pm It would be easy but I do not want to count any overlapped times. For
1
1575
by: jeff8676 | last post by:
I'm very new at Access, so if this is a lame question I'm sorry. Anyways, I'm trying to make a query that returns unique entries from a table, but when it finds two entries where everything matches except for in this case the feild "Ammount" it returns the entry unique but adds the differing ammount entries. Bassically I'm trying to get the sum of ammounts for entries that are otherwise duplicates.
9
175
by: =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= | last post by:
``odict.byindex(index)`` For this API, I think it's important to make some performance guarantees. It seems fairly difficult to make byindex O(1), and simultaneously also make insertion/deletion better than O(n). IOW, the PEP should somehow specify which operations are efficient, and which ones aren't. Regards,
4
10336
by: Mikey C | last post by:
Hi Everyone, I understand in many cases, adding to history when updating window.location.hash is a GOOD thing. In my case, I want to update bookmarkability from javascript (post-load), but can't get it to do so without adding a record to history. (Firefox 3.0.3) I know it's possible to do, because Google is doing it. See this URL:...
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9601
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10635
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3013
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.