I have a set of words (BELLOW, CELLO, HAAF, HABIT, HADAL, HAIR, HELLO, HELP, RABIT) stored in std::set datastructure.
From the above set DS, I want to extract words which starts(0th index) with 'H' and store it other container(say std::setstd::string ctr). Now, ctr will have - HAAF, HABIT, HADAL, HAIR, HELLO, HELP
Now, I want to fetch the words which has the second letter(1st Index) as 'A' from the container ctr. Now, ctr will have - HAAF, HABIT, HADAL, HAIR
I want to fetch the words which has the letter 'A' in any index other than 0th & 1st Indices. Basically, I don't want to check the string 0th and 1st positions.
Now, ctr will have - HAAF, HADAL
I'm not sure how to do the 3rd step.
#include <iostream>
#include <set>
int main()
{
std::set<std::string> words = {"BELLOW", "CELLO", "HAAF",
"HABIT", "HADAL", "HAIR",
"HELLO", "HELP", "RABIT"};
for (const std::string& s : words) {
std::cout << s << std::endl;
}
std::set<std::string> etr;
/* Extract words start with letter 'H' */
for (const std::string& s : words) {
if (s[0] == 'H') {
//std::cout << s << std::endl;
etr.insert(s);
}
}
std::cout << std::endl;
for (const std::string& s : etr) {
std::cout << s << std::endl;
}
std::set<std::string> etr2;
/* Extract words start with letter 'H' &
second letter as 'A' */
for (const std::string& s : etr) {
if (s[1] == 'A') {
//std::cout << s << std::endl;
etr2.insert(s);
}
}
std::cout << std::endl;
for (const std::string& s : etr2) {
std::cout << s << std::endl;
}
/* Extract words start with letter 'H' &
second letter as 'A', and any other letter as 'A'
but not second letter */
// << I'm not sure >>
return 0;
}
Link for running this program
Solution which I expected:
for (const std::string& s : etr2) {
size_t occ = s.find('A');
// Repeat till end is reached
while(occ != std::string::npos) {
if (std::find(pos.begin(), pos.end(), occ) == pos.end()) {
etr.insert(s);
}
// Get the next occurrence from the current position
occ = s.find('A', occ + 1);
}
}
Find the link for this solution
The same way you checked other words: iterate over the set, but this time iterate over each word and check whether there is any
Ain suitable position.But note that previous checks could be done much more efficiently with
std::setas it is sorted, and you need to extract strings between"H"and"I"(IfollowsH). Twoset::lower_boundcalls would return you the range.