array container for loop

Hi;
I need help with array container. More specifically, would like to know if the following for loop works as expected. I want to find all instances of a substring mysub in array container myarr and replace each occurrence of mysub with empty string " ". To do that, I'd like to use for loop with search algorithm.

Code below:

p=array iterator

for ( p=search(myarr.cbegin(),myarr.end(), mysub.begin(),mysub.end();
p!=myarr.end();
p=search(p,myarr.end(),mysub.begin(),mysub.end() );

{
while ( p != mysub.end() *p=" ";

//I am assuming that loop body gets executed upon each finding of substring mysub
//and that p=search(p,myarr.end(),mysub.begin(),mysub.end() finds all values of p
//that has points to the start of mysub. Once p is found, replace the substring with " "


}

thanks;
First, please use the code tags ('<>') for your code - it makes it much easier to read. Also, did you consider std::replace_if? Assuming 'mysub' is a std::string:
 
std::replace_if(myarr.begin(), myarr.end(), [&](const std::string& val) {return val==mysub;}, "");

However, your code (convoluted as it is) looks like it should do what you want it to do. Though, your code for setting the string to be empty is dodgy (infinite loop - you are setting 'p' to be " ", but testing it against being mysub.end, which it never will be).
Last edited on
I'm learning C++ and taking an intro class to STL and I agree that it's poor. My class project requires substituting a string phrase in array with another. I was able to use the above loop with vector and deque and I would like to reuse it with array.

The reason why p will never == mysub.end() is because it will be set to " " when comparing against mysub.end()? Is that correct?

I'll take a look at replace_if. Never looked at replace_if.

thanks
Topic archived. No new replies allowed.