Reputation: 3
I am trying to iterate over this vector to figure out if a function I have that checks for names in a vector is working.
typedef struct device_t
{
string id;
vector<string> capabilities;
} Device;
vector<Device> devices = {
{ .id = "Television", .capabilities = { "audio", "channel" } },
{ .id = "Smart thermostat", .capabilities = { "temperature" } },
{ .id = "Stereo system", .capabilities = { "audio", "music" } },
{ .id = "Kitchen sink", .capabilities = { } },
{ .id = "Paper shredder", .capabilities = { "shredding" } }
};
vector<Device>::iterator it;
for (it = devicecheck.begin(); it != devicecheck.end(); it++) {
std::cout<< *it;
}
However I have no idea as to reach the {.id}
part inside of the vector devices
. any tips?
Upvotes: 0
Views: 56
Reputation: 4288
it->capabilities
is the std::vector<std::string> capabilities
of the Device
pointed to by the current iterator it
. To iterate over capabilities
you'd do:
for (it = devicecheck.begin(); it != devicecheck.end(); it++) {
for (auto it2 = it->capabilities.begin(); it2 != it->capabilities.end(); it2++)
{
std::cout << *it2 << " ";
}
}
If you don't necessarily need access to the iterators themselves (but just the underlying object) consider the range-based for loop syntax:
for (auto& device : devicecheck)
{
for (auto& capability : device.capabilities)
{
std::cout << capability << " ";
}
}
Upvotes: 2