Jackie
Jackie

Reputation: 23477

int does not increment in struct when using ++

I have a struct that contains an int but when I call the following...

typedef std::map<char, MessageLetter> Letters;
...
Letters lList;
...
MessageLetter m = lList[letter];
std::cout << "Before " << m.count << std::endl;
int c = ++m.count;
m.count = c;
std::cout << "After " << m.count << std::endl;

I am new to C++ and I am guessing this is a pointer issue but the output is...

Before 1
After 2
Before 1
After 2

I would expect...

Before 1
After 2
Before 2
After 3

Upvotes: 0

Views: 227

Answers (2)

Joe Z
Joe Z

Reputation: 17936

I'm assuming this statement is part of a body of a loop:

MessageLetter m = lList[letter];

On each iteration of the loop, you're copying alList[letter] into m. Any modifications to m will be lost after the loop iteration completes. You will not modify lList[letter].

If you want to modify lList[letter], you either need to modify it directly, or make m a reference to it:

MessageLetter& m = lList[letter];

If you do not want to modify lList[letter], then you need to move the above assignment outside the loop to someplace above the loop.

Upvotes: 3

Bill Lynch
Bill Lynch

Reputation: 81916

I think you actually want:

MessageLetter & m = lList[letter];

Upvotes: 4

Related Questions