-2

Finding an element in a vector of structures

this link showed me, how to look for a value inside a structure.

but i have something like this,

struct sample {
    string name;
    vector<string> values;
};
vector<sample>v1;

and this is a vector of structures. how to search for a particular string in the values vector, that is present inside the structure samples ? which itself, is a vector of structures ?

thanks.

Community
  • 1
  • 1
murthi
  • 175
  • 1
  • 4
  • 18

2 Answers2

1

You can iterate through the vector v1 containing sample structures accessing each vector v1 member as a struct. Then, you can access the struct member vector to search for desired string:

for (const sample &it : v1) {
    for (const string &st : it.values) {
        if (st == ...) {
        }
    } 
}
Kef
  • 410
  • 3
  • 18
0

You can use a combination of std::find_if and std::find.

The std::find_if goes through the sample objects and checks every element with a predicate which itself uses std::find to go through all std::string elements inside and compares each of them to the token you want to find.

Here is an example, using a lambda function to create the predicate:

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>

struct sample
{
    std::string name;
    std::vector<std::string> values;
};

int main()
{
    std::vector<sample> const v1 =
    {
        { "one",   { "a", "b" } },
        { "two",   { "c", "token to find", "d", "e" } },
        { "three", { "f"} }
    };

    using std::begin;
    using std::end;

    auto const token = "token to find";

    // go through all samples
    auto const sample_iter = std::find_if(begin(v1), end(v1), [&token](sample const& s)
    {
        // in each sample, go through all values
        auto const string_iter = std::find(begin(s.values), end(s.values), token);
        return string_iter != end(s.values);
    });

    if (sample_iter == end(v1))
    {
        std::cout << "not found\n";
    }
    else
    {
        std::cout << sample_iter->name << '\n';
    }

}

Output:

two
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62