Reputation: 18441
I have the following code (found at this link here):
// Example program
#include <iostream>
#include <vector>
#include <chrono>
#include <string>
#include <sstream>
struct ControlStruct {
std::string port;
bool timeoutOn;
int detectionTimeout;
bool state;
};
struct DeviceStruct {
std::string name;
std::vector<ControlStruct> deviceControls;
};
std::vector<DeviceStruct> devices;
int main()
{
for (int i = 0; i < 10; i++)
{
ControlStruct cs;
DeviceStruct device;
std::stringstream ss;
ss << "Device" << i;
device.name = ss.str();
for(int k = 0; k < 5; k++)
{
ControlStruct cs;
ss.clear();
ss << "Port" << i;
cs.port = ss.str();
cs.state = false;
cs.timeoutOn = false;
cs.detectionTimeout = (k * 2) + 1;
device.deviceControls.push_back(cs);
}
devices.push_back(device);
}
//
// Start devices
//
for (auto device : devices)
{
for (auto control : device.deviceControls)
{
control.timeoutOn = true;
control.state = true;
std::cout << "Starting device " << device.name << " with timeout of " << control.detectionTimeout << " sec." << std::endl;
}
}
while (1)
{
for (auto device : devices)
{
for (auto control : device.deviceControls)
{
if (!control.state)
continue;
std::cout << "I NEVER GET HERE!!!!!!!!!!!!" << std::endl;
control.detectionTimeout--;
if (control.detectionTimeout == 0)
{
control.state = false;
std::cout << "Device " << device.name << " timed-out." << std::endl;
}
else
std::cout << "Device " << device.name << " count = " << control.detectionTimeout << std::endl;
}
}
}
}
For some reason, I never get into the I NEVER GET HERE!!!
code...
Is there a special way to set values of structs inside an vector inside a struct that is inside a vector ? Am I missing something here ?
I´m using C++11, gcc linux.
Thanks for helping.
Upvotes: 1
Views: 4018
Reputation: 1613
When you have something like this:
std::vector<DeviceStruct> devices;
for (auto device : devices) { ... }
This iterates through all the DeviceStruct values in the devices vector. However, "auto device" means "give me a copy of the item".
Once you do that, any modifications you make are made to that copy - which is then thrown away when you get to the end of your loop body.
In your case you want to say:
for (auto& device : devices) { ... }
The '&' here means "give me a reference to the device". Now 'device' refers to the actual element inside the vector (rather than a copy of it) so any changes you make to it are made to the original device.
Upvotes: 8