473,700 Members | 2,781 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is wrong with reference into std::map?

Expected output of program:
Key is: 0 String is: Hello
Key is: 1 String is: Goodbye
Key is: 2 String is: The end

Actual output:
Key is: 0 String is: The End
Key is: 1 String is:
Key is: 2 String is:

What am I doing wrong?

If I declare my reference fresh each time, such as putting { } around the
places I insert and doing
std::string& MyString = (*it).second;
each time it will come out right.

Why can't I reuse the references?

It took a long time to find out what was causing this in my program. This
is just a test program showing the issue.

#include <iostream>
#include <string>
#include <map>

std::map<unsign ed int, std::string> MyMap;

int main ()
{
unsigned int ID = 0;
std::map< unsigned int, std::string>::i terator it = MyMap.insert(
MyMap.end(), std::make_pair< unsigned int, std::string >( ID,
std::string() ) );
std::string& MyString = (*it).second;
MyString = "Hello";

ID = 1;
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );
std::string& MyString2 = (*it).second;
MyString = "Goodbye";

ID = 2;
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );
MyString = (*it).second;
MyString = "The End";

for ( std::map< unsigned int, std::string >::iterator i = MyMap.begin();
i != MyMap.end(); ++i )
{
std::cout << "Key is: " << (*i).first << " String is: " <<
(*i).second << std::endl;
}

std::string wait;
std::cin >> wait;
}


May 14 '06 #1
10 2464

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:TB******** *****@fe04.lga. ..
Expected output of program:
Key is: 0 String is: Hello
Key is: 1 String is: Goodbye
Key is: 2 String is: The end

Actual output:
Key is: 0 String is: The End
Key is: 1 String is:
Key is: 2 String is:

What am I doing wrong?

If I declare my reference fresh each time, such as putting { } around the
places I insert and doing
std::string& MyString = (*it).second;
each time it will come out right.

Why can't I reuse the references?

It took a long time to find out what was causing this in my program. This
is just a test program showing the issue.

#include <iostream>
#include <string>
#include <map>

std::map<unsign ed int, std::string> MyMap;

int main ()
{
unsigned int ID = 0;
std::map< unsigned int, std::string>::i terator it = MyMap.insert(
MyMap.end(), std::make_pair< unsigned int, std::string >( ID,
std::string() ) );
std::string& MyString = (*it).second;
MyString = "Hello";

ID = 1;
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );
std::string& MyString2 = (*it).second;
This was a broken attempt to diagnose. Even with this line changed to:
std::string& MyString2 = (*it).second

the output is the same.
MyString = "Goodbye";

ID = 2;
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );
MyString = (*it).second;
MyString = "The End";

for ( std::map< unsigned int, std::string >::iterator i =
MyMap.begin(); i != MyMap.end(); ++i )
{
std::cout << "Key is: " << (*i).first << " String is: " <<
(*i).second << std::endl;
}

std::string wait;
std::cin >> wait;

May 14 '06 #2
Jim Langston wrote:
std::string& MyString2 = (*it).second;
MyString = "Goodbye";
You're going to kick yourself, but you want MyString2 in
the above line. You're righting into the first inserted
string here.
ID = 2;
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );
MyString = (*it).second;
This doesn't initialize a reference, it assigns the value of second
into where MyString was initialized (your first insertion).
MyString = "The End";
And this does another such assignment


May 14 '06 #3

"Ron Natalie" <ro*@spamcop.ne t> wrote in message
news:44******** ******@spamcop. net...
Jim Langston wrote:
std::string& MyString2 = (*it).second;
MyString = "Goodbye";
You're going to kick yourself, but you want MyString2 in
the above line. You're righting into the first inserted
string here.

ID = 2;
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );
MyString = (*it).second;


This doesn't initialize a reference, it assigns the value of second
into where MyString was initialized (your first insertion).


Oh, well, shoot. You're right. That totally excaped me. If the reference
is declared on the same line, then it initializes it.

Hmm.. so how do you assign a reference that has already been initialized?
I.E.
int int1;
int int2;
int& MyRef = int1;
Who do I do to get MyRef to point to int2 now? Or can I?
MyString = "The End";


And this does another such assignment


May 14 '06 #4
Jim Langston wrote:
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );

Could you break up all these long lines, pleeeeze? Start with

typedef std::make_pair< unsigned int, std::string > mapType;

then use that everywhere you copied in that whole gizmo.
Hmm.. so how do you assign a reference that has already been initialized? int& MyRef = int1;
Who do I do to get MyRef to point to int2 now? Or can I?


You can't reseat a reference. That's a feature. You said "point to", which
betrays you think of a reference as a kind of pointer. It's really another
name for something; an alias.

Will a map let you use iterators? Some containers invalidate their iterators
after an insert, but I can't think of a technical reason for a binary tree
to do that, and maps generally implement as binary trees.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 14 '06 #5

"Phlip" <ph******@yahoo .com> wrote in message
news:yT******** *********@newss vr27.news.prodi gy.net...
Jim Langston wrote:
it = MyMap.insert( MyMap.end(), std::make_pair< unsigned int,
std::string >( ID, std::string() ) );
Could you break up all these long lines, pleeeeze? Start with

typedef std::make_pair< unsigned int, std::string > mapType;

then use that everywhere you copied in that whole gizmo.
Yeah, well, the problem is I'm using a number of maps, 4, and I would have
to do that for every map since they're different pair types. By the time I
typedefed the maps, the iterators and the make pairs that's 12 different
things I have to remember what is what.

It's just easier for me to type them in so I don't have to keep going back
and seeing what they are.
Hmm.. so how do you assign a reference that has already been initialized?

int& MyRef = int1;
Who do I do to get MyRef to point to int2 now? Or can I?


You can't reseat a reference. That's a feature. You said "point to", which
betrays you think of a reference as a kind of pointer. It's really another
name for something; an alias.

Will a map let you use iterators? Some containers invalidate their
iterators after an insert, but I can't think of a technical reason for a
binary tree to do that, and maps generally implement as binary trees.


Well, I'm only using the reference after the insert to set the data, then I
don't use it anymore. The reference may be invalidated after another
insert, I'm not sure.

Well, I came across this problem and figured out that by putting brackets
around the whole thing the problem went away, I just wanted to know what the
problem was before I converted it into a function.

I'm goign to have to remember that you can't reset a reference. Dang, I
hope they add that to the language. Even if it takes another keyword.

std::reseat MyRef = int2;
MyRef<std::rese at> = int2;
std::reseat<int &>( MyRef ) = int2;

any format

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!

May 14 '06 #6

Jim Langston wrote:
Well, I came across this problem and figured out that by putting brackets
around the whole thing the problem went away, I just wanted to know what the
problem was before I converted it into a function. You're not reseting the reference in this case, you're just creating a
new one with new initialization
I'm goign to have to remember that you can't reset a reference. Dang, I
hope they add that to the language. Even if it takes another keyword. The language already has this, it's called a pointer :)
std::reseat MyRef = int2;
MyRef<std::rese at> = int2;
std::reseat<int &>( MyRef ) = int2;


int *pPointer = &int2;
*pPointer = 5;
pPointer = int3; // Reseting the pointer

Abdo Haji-Ali
Programmer
In|Framez

May 14 '06 #7

"Abdo Haji-Ali" <ah***@inframez .com> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.com.. .

Jim Langston wrote:
Well, I came across this problem and figured out that by putting brackets
around the whole thing the problem went away, I just wanted to know what
the
problem was before I converted it into a function.

You're not reseting the reference in this case, you're just creating a
new one with new initialization
I'm goign to have to remember that you can't reset a reference. Dang, I
hope they add that to the language. Even if it takes another keyword.

The language already has this, it's called a pointer :)
std::reseat MyRef = int2;
MyRef<std::rese at> = int2;
std::reseat<int &>( MyRef ) = int2;


int *pPointer = &int2;
*pPointer = 5;
pPointer = int3; // Reseting the pointer


Well, yes, I know how to reset pointers. I've been using pointers from my C
days. But I now prefer references.
May 14 '06 #8
Jim Langston wrote:
Could you break up all these long lines, pleeeeze? Start with

typedef std::make_pair< unsigned int, std::string > mapType;

then use that everywhere you copied in that whole gizmo.
Yeah, well, the problem is I'm using a number of maps, 4, and I would have
to do that for every map since they're different pair types. By the time
I typedefed the maps, the iterators and the make pairs that's 12 different
things I have to remember what is what.


That sounds like an argument _for_ typedeffing.
It's just easier for me to type them in so I don't have to keep going back
and seeing what they are.
Give them stupid names, like map_int_string. Nobody said the names had to
reveal their logical intent.

(Actually, someone _did_ say that. Skip that rule for now!)
I'm goign to have to remember that you can't reset a reference. Dang, I
hope they add that to the language. Even if it takes another keyword.

std::reseat MyRef = int2;
MyRef<std::rese at> = int2;
std::reseat<int &>( MyRef ) = int2;


What's the point? Just use a pointer if you need the ability to re-seat.

That's why you should prefer references to pointers unless you need
pointers' extra abilities. Adding such abilities to pointers would dilute
their effectiveness as the _weakest_ kind of handle we have.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 14 '06 #9
Jim Langston <ta*******@rock etmail.com> wrote:
Well, yes, I know how to reset pointers. I've been using pointers
from my C days. But I now prefer references.


Better use pointers when they are appropriate and do not
dogmatically
stick to references. If you want to reseat, then pointers _are_
appropriate.

If you need reseating functionality here is a different matter. I
have
not looked closely at the code to advise on that.

(sorry I accidently replied to your email at first)

regards
--
jb

(reply address in rot13, unscramble first)
May 14 '06 #10

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

Similar topics

5
29249
by: Christopher | last post by:
I am having problems iterating through the sequence of objects stored in my std::map I want to call a function from the "value" object in the map. Here is my snippet: typedef std::map<SOCKET, Player> PLAYERMAP_SOCKET; ..... BOOL Player::Send(std::string data) ...... // Send the text to all clients
24
17310
by: Duane Hebert | last post by:
2 questions: Given a map defined as std::map<int,string> stringmap; //How do you access the data_type (string) via an iterator? std::string spoo("doh");
2
2337
by: ash | last post by:
Hi, I'm getting started with STL, and am stuck at creating a map container. I checked one of the texts and found a code in there. To make it simple, i wrote the following: #include <iostream.h> #include <string.h> #include <map>
44
8789
by: jmoy | last post by:
I am a C programmer graduating to C++. As an exercise I wrote a program to count the number of times that different words occur in a text file. Though a hash table might have been a better choice, I chose to use std::map. However, the program runs at less than half the speed of an equivalent program that uses ordinary handcoded binary trees. The result is not changed very much if I replace std::string as the key with a simple string class...
13
9669
by: kamaraj80 | last post by:
Hi I am using the std:: map as following. typedef struct _SeatRowCols { long nSeatRow; unsigned char ucSeatLetter; }SeatRowCols; typedef struct _NetData
4
6247
by: Evyn | last post by:
Hi all, I'm starting to fool around with STL and in particular std::map. How do I iterate through one map and insert every pair in another map? I have the following so far: map<double, doublefset1; map<double, doublefset3;
7
6256
by: DevNull | last post by:
Hi there everyone, I'm creating a very simple immediate mode command interpreter. The final purpose is to provide a pluggable control and command console for a MUD server I have written. The basic theory is we wrap the functions we want exposed to the console in a function with a prototype of int func(State*)
8
4070
by: mveygman | last post by:
Hi, I am writing code that is using std::map and having a bit of an issue with its performance. It appears that the std::map is significantly slower searching for an element then a sequential search in a vector. Has anyone run into this before?
7
10253
by: guido | last post by:
Hi, I'm looking for a container class that can map whole ranges of keys to objects - something like std::map, but not only for individual values for the key, but for whole ranges. Example: I want to be able to tell the container to return object a for every given key between 0 and 10, object c for every key between 11 and 500000 and object c for every key between 500001 and 599999, without having to
0
8641
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
9060
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...
1
8958
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8912
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6557
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5897
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4650
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3082
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
3
2021
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.