Click to See Complete Forum and Search --> : Matching a word in any element of a vector?
vim84
February 26th, 2006, 10:44 AM
hello, i can match up a word in an specific element of a vector and then perform a action if all the elements match the specific word. the vector is called 'tokens'.
The problem is i want to able to go through a vector of any size and be able to match up one word (or more) to any element of the vector, then to perform the action.
for ( int i=0; i<tokens.size();i++)
{
if (tokens[i] == "MY" && tokens[i+1] =="NAME")
{
// then perform a action......
}
cout << myResponse << endl;
fileout << myResponse ;
}
thanks for anyhelp.
V
Siddhartha
February 26th, 2006, 10:58 AM
[ redirected ]
Regards,
Siddhartha
exterminator
February 27th, 2006, 12:00 AM
You can use the std::find algorithm in a loop. It takes the begin and end iterator for the container and find the value passed as the third argument. Returns the iterator position where it first finds the occurence. You can then input that iterator position as the begin and the end one as end and search for that item again.
Using a multimap might prove better where the key would be these strings. You can find the range in one shot using equal_range().
What is the problem you are facing? What you are trying to do will also work? Regards.
Odiee
February 27th, 2006, 02:19 AM
you can't do that on char, you must use string if you want to do '==' operations, and in your code u must use in for loop
for (int c=0;c<tokens.size();c+=2) beacuse you are using it to check the word[c] and word[c+1] (operator &&).
NMTop40
February 27th, 2006, 12:47 PM
You will have an access violation on the last test where you read one past the last element of the vector.
There are many algorithms but there is no for_each_if. You could write one or you can just loop where you need it.
Writing a for_each_if would look something like this:
template < typename FwdIter, typename Op, typename Pred >
Op for_each_if( FwdIter first, FwdIter last, Op op, Pred pred )
{
for ( ; first != last; ++first )
{
if ( pred( *first ) )
{
op( first );
}
}
return op;
}
In your case though your condition seems to be based on consecutive elements so it wouldn't work here.
XZminX
February 28th, 2006, 12:10 PM
for loop should be:
for (unsigned int i=0; i<tokens.size()-1; i+=2)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.