How to check if a vector contains a given value?
Use find() and find_if() on a vector of strings.
The contains() method of Java Vector class is used to check the vector which is in use contains the specified element or not. It returns true if this vector contains the specified element, otherwise returns false.
Approach 1: Return index of the element using std::find() std::find() searches for an element equal to the value that is passed as a parameter and returns an iterator pointing to that element in the vector. The parameter passed here is key k, the function call will return an iterator pointing to key k in the vector.
Both the match()
(returns the first appearance) and %in%
(returns a Boolean) functions are designed for this.
v <- c('a','b','c','e') 'b' %in% v ## returns TRUE match('b',v) ## returns the first location of 'b', in this case: 2
is.element()
makes for more readable code, and is identical to %in%
v <- c('a','b','c','e') is.element('b', v) 'b' %in% v ## both return TRUE is.element('f', v) 'f' %in% v ## both return FALSE subv <- c('a', 'f') subv %in% v ## returns a vector TRUE FALSE is.element(subv, v) ## returns a vector TRUE FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With