J
Jim Langston
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;
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;
}
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;
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;
}