Вы можете использовать комбинацию std::find_if
и std::find
.
The std::find_if
проходит через sample
объектов и проверяют каждый элемент с предикатом, который сам использует std::find
, чтобы пройти через все std::string
элементов внутри и сравнивает каждый из них в знак вы хотите найти.
Вот пример, используя функцию лямбда создать предикат:
#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';
}
}
Выход:
two
ли цель, чтобы получить итератор на 'sample' вектор которого содержит строку ? –
написание find_if(), поскольку это легко – murthi