jeudi 29 octobre 2015

C++ Change value of structs inside a vector, that is inside a struct, that is inside another vector

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.

Aucun commentaire:

Enregistrer un commentaire