I created the following structure

struct Datas { std::string DataName; std::vector<boost::variant<std::string, int, double>> Data; }; struct Topic { std::string TopicName; std::vector<Datas> DataList; }; struct Group { std::string NodeName; std::vector<Topic> TopicList; }; .... std::vector<Group> test; 

Is it possible to search for any data through std :: find?

  • Can. If you add a comparison of elements. Or use find_if with the corresponding predicate. - Harry
  • @Harry - DR.zarigan
  • What kind of "data" are you going to look for? You have drawn a four-level hierarchical structure. What exactly and where exactly are you going to look? Try to more specifically formulate the question. - AnT

1 answer 1

A search in a vector with elements of a custom type is possible - via find using the equality operator, or find_if with the provision of a search predicate.

An example is below.

 struct Test { string name; vector<int> data; bool operator==(const Test& t) { return name == t.name; } }; int main(int argc, const char * argv[]) { vector<Test> v{ {"a",{1,2,3}}, {"b",{4,5,6}}, {"c",{7,8,9}} }; // Поиск с использованием оператора равенства (ищем с name=="b") if (auto t = find(v.begin(),v.end(),Test{"b",{}}); t != v.end()) { for(auto i: t->data) cout << i << " "; cout << endl; } // Поиск с использованием предиката - тот, где первый элемент data - 7 if (auto t = find_if(v.begin(),v.end(), [](const Test& q){ return q.data.size()>0 && q.data[0] == 7; }); t != v.end()) { for(auto i: t->data) cout << i << " "; cout << endl; } }