Tamás Szelei
Tamás Szelei

Reputation: 23921

C++ check if a list contains a sublist

I need a container in which I can check if a sequence of elements are present or not. Same thing as substring matching, just for generic collections. I know it's not hard to write, but if it's implemented in some lib already, I wouldn't bother (maybe Boost has something like this?)

Upvotes: 3

Views: 3106

Answers (3)

Šimon Tóth
Šimon Tóth

Reputation: 36433

The mismatch algorithm from STL is pretty much strcmp for generic containers.

http://www.cplusplus.com/reference/algorithm/mismatch/

Upvotes: 0

Yakov Galka
Yakov Galka

Reputation: 72469

Any sequence container will do. You just need to use std::search algorithm to do the search of the sublist:

vector<int> sequence = ...;
vecter<int> sublist = ...;

vector<int>::iterator pos = std::search(
    sequence.begin(), sequence.end(), 
    sublist.begin(), sublist.end());

if(pos == sequence.end()) 
    // not fount
else 
    // found at pos

Upvotes: 10

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

Do you want std::search?

Upvotes: 2

Related Questions