Checking for existence of item in array [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there a code that will check if a certain string is inside an array?
For example I have a string "John" then I need to check if "John" is already in the array names[10].

std::find does exactly that:
auto i = std::find(std::begin(a), std::end(a), "John");
if (i != std::end(a)) … // item found!
However, beware that this does a linear pass over the elements. That’s not a problem for 10 items but it becomes inefficient quickly with larger number. For very large sets, use std::unordered_set instead of an array, to attain (theoretically) constant runtime. Alternatively, if you know that the array is sorted you may employ std::binary_search to attain logarithmic runtime.
Here’s the same code, wrapped inside a convenience function:
template <typename It, typename T>
bool contains(It begin, It end, T const& value) {
return std::find(begin, end, value) != end;
}
And here’s a convenience overload for C arrays:
template <typename T, typename U, std::size_t N>
bool contains(T (&arr)[N], U const& value) {
return std::find(arr, arr + N, value) != arr + N;
}
(The syntax for passing arrays to functions is a bit weird.)

If you want to go archaic:
function in_array(String my_array[], String findthis){
len=sizeof my_array;
for(int i=0;i<len;i++){
if(my_array[i]==findthis){
return true;
}
}
return false;
}
then
in_array(array_of_strings, "john");
I wrote this hastily and I'm very tired, but hopefully it can be of some use.

Related

remove duplicate from a vector of pointers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
I have a vector of custom objects and am required to sort it under various criteria(i.e. cannot use set). I also have a comparator to do the sorting, which forces me to use a vector of pointers. This way, the code compiles but it is now failing to remove duplicates.
vector<customObj*> vec;
//code to remove duplicate
vector<customObj*>::iterator it;
it = unique(vec.begin(), vec.end());
vec.resize(distance(vec.begin(), it));
//code to sort a vector
bool Comp(customObj *a, customObj *b) {
if (condition) {
return (a->getValue() < b->getX=Value());
}
}
It seems there is a typo in the comparison function
//code to sort a vector
bool Comp(customObj *a, customObj *b) {
if (condition) {
return (a->getValue() < b->getX=Value());
^^^^^^^^^^^^^^^^
}
}
Also the comparison function returns nothing if the condition does not evaluate to true.
I think you mean
//code to sort a vector
bool Comp(customObj *a, customObj *b) {
return condition && (a->getValue() < b->getValue());
}
In the call of std::unique you need to use a binary predicate like
//code to sort a vector
bool Equal(customObj *a, customObj *b) {
return consdition && (a->getValue() == b->getValue());
}
vector<customObj*>::iterator it;
it = unique(vec.begin(), vec.end(), Equal);
vec.resize(distance(vec.begin(), it));
Pay attention to that if objects in the vector were dynamically allocated then you need to free them. Otherwise you will have memory leaks.
Instead of raw pointers you should use smart pointer std::unique_ptr.

No matching function for call to "..." Compiler errors involving templated functions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am working on a project where I make various algorithms such as counting and sorting for integers and then I am turning them into template functions so they can be used with things such as vectors and lists.
For example, one templated function looks like this:
template<typename Iter>
int count(Iter* first, Iter* limit, int value)
{
int counter = 0;
while(first != limit)
{
if(*first == value)
++counter;
++first;
}
return counter;
}
When I run some code in my main.cpp such as:
std::vector<int> a = {0, 0, 2, 4, 2, 0};
//I expect count to return 3 for this call...
cout << count(a.begin(), a.end(), 0) << "\n";
It gives me a compiler error:
error: no matching function for call to ‘count(std::vector<int>::iterator, std::vector<int>::iterator, int)’
cout << count(a.begin(), a.end(), 0) << "\n";
I really have tried to figure this out on my own, but it doesn't make sense to me. I have another algorithm called print that prints a vector from vec.begin() to vec.end() that works perfectly fine. I've tried making connections between the one that works and those that don't, but nothing makes logical sense to me.
FOLLOW UP: Could it be that the * in my function definitions are the problem?? Perhaps it is because I have (Iter *first, Iter *last) instead of (Iter first, Iter last)?
Yes, the * in your parameters is the problem. An iterator is not a pointer, but is designed to mimic a pointer (on the other hand, a pointer can be an valid iterator). Do not pass around iterators by pointer, pass them around by value instead, eg:
template<typename Iter>
int count(Iter first, Iter limit, int value)
{
int counter = 0;
while (first != limit)
{
if (*first == value)
++counter;
++first;
}
return counter;
}
On a side note, the standard C++ library already has a std::count() algorithm that does the same thing your count() function does:
#include <vector>
#include <algorithm>
std::vector<int> a = {0, 0, 2, 4, 2, 0};
cout << std::count(a.begin(), a.end(), 0) << "\n";

Binary search template for finding a double nearest to the key [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Is there template in C++ , which allows to find in a sorted vector the value nearest to the key, and returns its index (iterator). What I found, returns only a boolean.
Edited: The question was motivated by the fact that the binary search returns a boolean. I conclude that at the time returning the boolean, also the iterator is known. Returning it, I could find out which element is found. What is the reason that no such binary search is provided?.
I don't know if you want to avoid sorting yourc container / array, so I'm going to post most universal way. And the answer is – no. If you don't want to sort container, there's no ready template, but you can simply write your own function, like this:
template<typename iterator_t, typename value_t, typename comparator_t>
iterator_t nearest_element(iterator_t begin, iterator_t end, value_t value, comparator_t comparator) {
return std::min_element(begin, end, [value, &comparator](double lhs, double rhs) {
return comparator(std::abs(lhs - value), std::abs(rhs - value));
});
}
template<typename iterator_t, typename value_t>
iterator_t nearest_element(iterator_t begin, iterator_t end, value_t value) {
return nearest_element(begin, end, value, std::less<value_t>());
}
It's just simple math, nearest element is one with smallest absolute value of subtracting it from searched value. Code above still lets you change comparator (but hides subtraction / std::fabs) so it can be also used to find farthest value.
Usage (without specified comparator) is simple, like any other standard function:
std::vector<double> vec {2., 5., -4.};
auto it = nearest_element(vec.begin(), vec.end(), -10.);
std::cout << *it << std::endl;

Linear and Binary search using iterator position [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am writing two functions, the first one does a linear search and is supposed to return the position of the first found value if it is in the vector. The second method is a binary search that is done using equal_range and it is supposed to return the same thing as the linear search. Currently they are checking every value as a match. Any help is appreciated.
int linearSearch( const vector<int>& vec, int z)
{
vector<int>::iterator iter = find(vec.begin(), vec.end(), z);
if (iter != vec.end())
return (iter-vec.begin());
else
return -1;
}
int binarySearch( const vector<int>& vec, int z)
{
pair<vector<int>::const_iterator, vector<int>::const_iterator> bounds;
bounds = equal_range(vec.begin(),vec.end(), z);
if (bounds.first != vec.end())
return (bounds.first -vec.begin());
else
return -1;
}
Your description is unclear, but I'll point out some concerns with the code.
In binarySearch() search, there is
bounds = equal_range(vec.begin(),vec.end(), z);
if (bounds.first != v.end())
return (bounds.first -v.begin());
v is not declared anywhere. If the code compiles then, presumably, it is declared somewhere in code you haven't shown. But it may have no relationship to vec. The behaviour of the code (particularly the return) will be undefined.
A rather fundamental difference between the functions is because std::equal_range() assumes a sorted (or partitioned) range, and std::find() does not.

Trying to create a function that will join words together from two unevenly sized vectors of strings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
If I have these two vectors:
vec1: "hello", "world"
vec2: "it", "is", "sunny", "today"
resultvector: "helloit", "worldis"
I need to use stl for this, and a functor. So far what I have throws a stackdump error:
My functor:
reads in two std strings, and "+" them together, returns result of operation.
My function:
Creates a std::list list, and uses std::transform(vec1.begin(), vec1.end(), vec2.begin(), list.begin(), functor()); return list;
My suspicion is that I don't know how to make it iterate only till the end of smaller container, and also maybe I am doing something funky with list.begin() and need something else for it.
Any ideas on how I might accomplish this?
Note: the two vectors are std::vector<string> and result is std::list<string>
Thank you in advance for your help!
In your transform call, use back_inserter(list) in place of list.begin(). back_inserter produces an iterator that translates assignments into push_back calls on underlying container.
std::transform(
vec1.begin(),
vec1.begin()+std::min(vec1.size(),vec2.size()),
vec2.begin(),
std::back_inserter(list),
functor()
);
#include<iostream>
#include<algorithm>
using namespace std;
struct ff
{
string operator ()(const string& x, const string& y ){
return x+y; }
};
int main ()
{
vector <string> vec1{"hello", "world"};
vector <string> vec2{ "it", "is", "sunny", "today"};
vector <string> resultvector;
std::transform(
vec1.begin(), vec1.begin()+min(vec1.size(),vec2.size()),
vec2.begin(),
back_inserter(resultvector),
ff()
);
for(auto i:resultvector)
cout<<i<<endl;
}