Reputation: 153
I have a class EDSobject:
class EDSobject
{
public:
...
int index;
int subindex;
std::string parameter;
std::string dataType;
int value;
};
In my code I write objects of this class to stringstream file:
if (obj.dataType == "0x0002" || obj.dataType == "0x0003" || obj.dataType
== "0x0004") //signed data types
{
file << " 0x" << obj.subindex << " " <<
obj.parameter << " = " << dec << (int16_t)obj.value << endl;
}
else //unsigned data types
{
file << " 0x" << obj.subindex << " " <<
obj.parameter << " = " << dec << obj.value << endl;
}
You can see that if dataType is "2", "3" or "4", I cast value to signed integer (values inside obj.value are unsigned integer). This works ok. For instance, I get -1386 from 64150.
The problem is when I tried to do it with only casting, like so:
void EDScastAllValues()
{
for (EDSobject obj : EDScontainer)
{
if (obj.dataType == "0x0002" || obj.dataType == "0x0003" ||
obj.dataType == "0x0004") //signed data types
{
int16_t newVal = static_cast<int16_t>(obj.value);
//or int16_t newVal = (int16_t)obj.value;
obj.value = newVal;
}
}
}
And then writing all objects the same, without if statement.
file << " 0x" << obj.subindex << " " << obj.parameter << " = " << dec << obj.value << endl;
Here, the obj.value doesn't change - 64150 is still 64150. I don't get negative values like before.
What am I doing wrong here?
EDIT: forgot to add definition of EDSContainer.
set<EDSobject, cmp> EDScontainer;
Upvotes: 0
Views: 85
Reputation: 154
You are copying objects out of your container and modifying the copies. You want:
for(auto& obj: EDSContainer)
Upvotes: 1