Trouble with index - c++

Write the find function, which takes a fixed integer vector reference and a single value integer and returns the index of the first occurrence of this value in the vector or the length of the vector if no value in it. The function should be adapted for use in the sample program
below. The function uses only the vector header file.
This is what I've done so far:
#include <vector>
#include <iostream>
using namespace std;
int find(const vector<int> &r ,int number)
{
int i=0;
int x;
for(i;i<r.size();++i)
{
if(r[i]==number)
{
break;
}
}
return 0;
}
int main()
{
int result = find(vector<int> {3, -1, 7, 12, -5, 7, 10}, 7);
cout << result << endl;
}
And, I'm stuck, I don't know how to return the index.

You should add return i; instead of breaking out of the loop
and maybe return -1 instead of 0 if the number is not found.

Return index i when found otherwise return 0 after the loop like this:
int find( const std::vector<int>& r, const int number )
{
for ( int i = 0; i < r.size(); ++i )
{
if ( r[i] == number )
{
return i;
}
}
return 0;
}
The x is unused in find function.

You should return i from your function

Related

How to check if a number is in a vector, and if not, then to return -1?

This is pretty easy if I can import <algorithm> or any other things at the top, but I just started using C++ and my professor asked us to use only loops and conditionals for this problem.
The problem itself is to give a vector v and an int seek to a function. A loop runs through the vector to find the index of the first location of the number. If it can be found, then return the index of where the number is, if not then return -1.
I got the first part down, but now I am having an issue with the second part.
#include <iostream>
#include "vectorutils.h"
#include <vector>
using namespace std;
//endl = new line
int main() {
cout << find({1, 2, 3, 4, 5, 6, 7, 8}, 28) << endl;
}
int find(const std::vector<int>& v, int seek) {
int ind = 1;
for (int i = 0; i < v.size(); i++) {
if (seek == v[i]) {
return i;
}
else {
return -1;
}
}
You have the return -1; statement in the wrong place. It needs to be after the loop exits, not inside the loop. For example:
int find(const std::vector<int>& v, int seek) {
for (int i = 0; i < v.size(); i++) {
if (seek == v[i]) {
return i;
}
// else {
// return -1;
// }
}
return -1; // <-- moved down here!
}
In your original code (if it could compile, which it doesn't), the logic is wrong. If the vector is empty then you return nothing at all (which is undefined behavior), and if the 1st element does not match the number then you return -1 immediately without checking the remaining elements at all.
The above change fixes both of those issues.

How do I linear search two arrays in c++?

I have two arrays of data type double - called array1[10] and array2[8]. I am required to search for array2 inside array1 at each element using a linear search function. The function declaration is
string linSearch (double array1[10], double array2[8]);
If array2 is found inside array1 then I need to print out the index of where it is found in array1. If its not found I need the output to be "NA". This output must be a delimited-comma- string.
eg.
//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}
//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:
2,NA,5,6,0,NA,NA,7
So far I have the code that follows. Its my first time working with arrays and I am still having difficulties grasping the concept- like once I define the function how do I even call it in the main program?! anyway..the function definition I have (excluding the main program) is:
string linSearch (double array1[10], double array2[8])
{
int index1 = 0;
int index2 =0;
int position =-1;
bool found = false;
while (index1<10 && !found && index2<8)
{
if array1[index1] == array2[index2])
{
found = true;
position = index1;
}
index1++;
index2++;
}
return position;
}
I am EXTREMELY confused about searching for one array in the other and how to output the delimited list as well as how to connect it to my main program. Any help would be GREATLY appreciated. Thanks!
#include <iostream>
using namespace std;
string linSearch(double array1[10], double array2[8])
{
string result = "";
bool found;
for (int j = 0; j < 8; j++)
{
if(j > 0)
result.append(", ");
found = false;
for (int i = 0; i < 10; i++){
if (array1[i] == array2[j]) {
result.append(to_string(i));
found = true;
}
}
if(!found)
result.append("NA");
}
return result;
}
int main(){
double a1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double a2[8] = {11, 25, 3, 41, 5, 6, 7, 8};
cout << linSearch(a1, a2) << endl;
return 0;
}
You are not searching one array inside the other. You are searching for elements from one array in a second array. If you are using a linear search and if you do not want to sort the array, you need 2 nested loops to do that. One for each element in the second array, and one to find that element in the first array.
Keep things simple and start with finding the position of a single element in one array. Because you are comparing doubles, you should not compare them with ==. Next you just need a function that calls the first for each element in the second array:
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
void index_to_string(const std::vector<double>& v,double e,std::ostream& out){
auto it = std::find_if(v.begin(),
v.end(),
[e](const double& x) {
return std::abs(e-x) < 1e-8;
}
);
if (it == v.end()) {
out << "NA";
} else {
out << (it - v.begin());
}
}
void all_indices_to_string(const std::vector<double>& v1,const std::vector<double>& v2,std::ostream& out){
if (v1.size() == 0 || v2.size()==0) return;
index_to_string(v1,v2[0],out);
for (size_t i=1;i<v2.size();++i){
out << ",";
index_to_string(v1,v2[i],out);
}
}
int main() {
double array1[] ={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4};
double array2[] ={6,45,2,7,1.1,5,4,8.8};
all_indices_to_string(
std::vector<double>(std::begin(array1),std::end(array1)),
std::vector<double>(std::begin(array2),std::end(array2)),
std::cout
);
}
Output:
2,NA,5,3,0,NA,NA,7
In your example of arrays and the expected output
//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}
and
2,NA,5,6,0,NA,NA,7
^
there is a typo. The output should be
2,NA,5,3,0,NA,NA,7
^
because the number 7 is found in the third position of the array array1.
Here you are.
#include <iostream>
#include <string>
#include <sstream>
std::string linearSearch( const double a1[], size_t n1, const double a2[], size_t n2 )
{
std::ostringstream os;
for ( size_t i = 0; i < n2; i++ )
{
if ( i != 0 ) os << ',';
size_t j = 0;
while ( j < n1 && a2[i] != a1[j] ) ++j;
if ( j == n1 ) os << "NA";
else os << j;
}
return os.str();
}
int main()
{
double a1[] = { 1.1, 1.2, 6, 7, 3.5, 2, 7, 8.8, 9, 23.4 };
const size_t N1 = sizeof( a1 ) / sizeof( *a1 );
double a2[] = { 6, 45, 2, 7, 1.1, 5, 4, 8.8 };
const size_t N2 = sizeof( a2 ) / sizeof( *a2 );
std::cout << linearSearch( a1, N1, a2, N2 ) << '\n';
return 0;
}
The program output is
2,NA,5,3,0,NA,NA,7

Comparing elements in the array by use of pointers (C++)

I am creating the function, compare_arrays to check if elements inside the pre-defined arrays are similar. I want to use pointer and pass the arrays by reference into the function. This is the function I coded so far but pylint is giving me an error for my second if loop stating that *arry1 and *arry2 are not defined. Can someone help me understand this error better.
Also, how do I call the function and pass in arr_one, arr_two, etc.....
#include <iostream>
using namespace std;
int size1 = 3, size2 = 3;
int arr_one[] = {1, 2, 3};
int arr_two[] = {1, 2, 3};
int main(){
bool compare_arrays( int *arry1, int size1, int *arry2, int size2);{
if (size1 != size2){
return false;
}
for(int i=0; i < size1; i++);{
if (*arry1 != *arry2);{
return false;
}
}
*arry1++;
*arry2++;
return true;
}
}
The biggest and main problem in your code is the inclusion of the ; at the end of compare_arrays. What you're actually doing is declaring a function, compare_arrays, then creating a separate scope, which is why arry1 is not defined. If you remove this semi-colon, your error will start to make more sense:
bool compare_arrays( int *arry1, int size1, int *arry2, int size2) {
Now the compiler will tell you you cannot define an function within a function, which is easy to solve. Move compare_arrays outside of main:
bool compare_arrays( int *arry1, int size1, int *arry2, int size2){
if (size1 != size2){
return false;
}
for(int i=0; i < size1; i++);{
if (*arry1 != *arry2);{
return false;
}
}
*arry1++;
*arry2++;
return true;
}
int main() {
}
This will now compile, but probably not run as you expect, because you have an extra erroneous semi-colon at the end of your second if statement. What this means is the semi-colon is treated as the expression from the if, then you'll always return false;. Fix this by removing the semi-colon:
for (int i = 0; i < size1; i++) {
And now you can simply call your code in main like so:
int main() {
if (compare_arrays(arr_one, size1, arr_two, size2)) {
std::cout << "arrays are equal\n";
}
}
However, you can trivialise the whole thing by using std::vector:
#include <vector>
#include <iostream>
int main() {
std::vector<int> v1 = { 1, 2, 3 };
std::vector<int> v2 = { 1, 2, 3 };
if (v1 == v2)
std::cout << "arrays are equal\n";
}
You put compare_arrays function body inside the main function. remove the body of the function out the main and just call it from inside the main function. Also, you put the semi-colon after if statement and function header and that's wrong. your code should be like this
#include <iostream>
using namespace std;
int size1 = 3, size2 = 3;
int arr_one[] = { 1, 2, 3 };
int arr_two[] = { 1, 2, 3 };
bool compare_arrays(int *arry1, int size1, int *arry2, int size2) {
if (size1 != size2) {
return false;
}
for (int i = 0; i < size1; i++) {
if (*arry1 != *arry2) {
return false;
}
}
*arry1++;
*arry2++;
return true;
}
int main() {
cout << compare_arrays(arr_one, size1, arr_two, size2) << endl;
}

Storing values of individual components of arrays in functions using static

I had a quick question with regard to arrays in c++.
Let's say that for the program I wanted to store a specific value for each of the individual subscript components of the array. I wanted to create a function to do it and the problem here is I want a way of storing the individual values and remembering it. Since a local variable in a function will get its memory erased, I know we need to employ a static variable but I don't know how to do it.
Thanks
Varun G.
Let's say I have the function
int calculate(int array[], int size)
{
int i;
for(i=0; i<10; i++)
{
array[i]=0;
}
if(size >= 0 && size <=9)
{
array[size] = array[size]+1;
}
}
Here I want to basically create the array with the 10 numbers all being 0 and then if it falls in the range between 0 and 9 I want to add 1 to the specific position I want to also remember the position and the value so I can repeat it next time
For example if I enter 9 2 times I will get the array[size] to be 1 when I want it to be 2
Do you mean like this?
#include <iostream>
int f(int i) {
static const int data[8] = { 1, 1, 2, 3, 5, 8, 13, 21 };
return data[i];
}
int main() {
std::cout << f(4) << std::endl;
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
void init( int a[], size_t n )
{
std::srand( ( unsigned int )std::time( 0 ) );
for ( size_t i = 0; i < n; i++ ) a[i] = std::rand() % n;
}
int main()
{
const size_t N = 10;
int a[N];
init( a, N );
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
}
Another way
#include <iostream>
#include <array>
void init( std::array<int, 10> &a )
{
a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
}
int main()
{
std::array<int, 10> a;
init( a );
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
}
If the size of the array has to be changed inside the function then it is better to use class std::vector instead of the array
I think you are looking for something along these lines:
int calculate( int size )
{
static int a[10] = { 0 };
if ( size >= 0 && size < 10 )
{
++a[size];
return a[size];
}
return -1;
}
The array will only be initialized once and will preserve its values between calls.

How do I find a particular value in an array and return its index?

Pseudo Code:
int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x;
x = find(3).arr ;
x would then return 2.
The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?).
To find the index, use std::distance and std::find from the <algorithm> header.
int x = std::distance(arr, std::find(arr, arr + 5, 3));
Or you can make it into a more generic function:
template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
size_t i = 0;
while (first != last && *first != x)
++first, ++i;
return i;
}
Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.
In your case, you would use it like so:
size_t x = index_of(arr, arr + 5, 3);
Here is a very simple way to do it by hand. You could also use the <algorithm>, as Peter suggests.
#include <iostream>
int find(int arr[], int len, int seek)
{
for (int i = 0; i < len; ++i)
{
if (arr[i] == seek) return i;
}
return -1;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int x = find(arr,5,3);
std::cout << x << std::endl;
}
The fancy answer:
Use std::vector and search with std::find
The simple answer
Use a for loop
If the array is unsorted, you will need to use linear search.
#include <vector>
#include <algorithm>
int main()
{
int arr[5] = {4, 1, 3, 2, 6};
int x = -1;
std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );
std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
if (it != testVector.end())
{
x = it - testVector.begin();
}
return 0;
}
Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.
int arr[5] = {4, 1, 3, 2, 6};
vector<int> vec;
int i =0;
int no_to_be_found;
cin >> no_to_be_found;
while(i != 4)
{
vec.push_back(arr[i]);
i++;
}
cout << find(vec.begin(),vec.end(),no_to_be_found) - vec.begin();
We here use simply linear search. At first initialize the index equal to -1 . Then search the array , if found the assign the index value in index variable and break. Otherwise, index = -1.
int find(int arr[], int n, int key)
{
int index = -1;
for(int i=0; i<n; i++)
{
if(arr[i]==key)
{
index=i;
break;
}
}
return index;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
int x = find(arr ,n, 3);
cout<<x<<endl;
return 0;
}
You could use the STL algorithm library's find function provided
#include <iostream>
#include <algorithm>
using std::iostream;
using std::find;
int main() {
int length = 10;
int arr[length] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int* found_pos = find(arr, arr + length, 5);
if(found_pos != (arr + length)) {
// found
cout << "Found: " << *found_pos << endl;
}
else {
// not found
cout << "Not Found." << endl;
}
return 0;
}
There is a find(...) function to find an element in an array which returns an iterator to that element. If the element is not found, the iterator point to the end of array.
In case the element is found, we can simply calculate the distance of the iterator from the beginning of the array to get the index of that element.
#include <iterator>
using namespace std;
int arr[ 5 ] = { 4, 1, 3, 2, 6 }
auto it = arr.find(begin(arr), end(arr), 3)
if(it != end(arr))
cerr << "Found at index: " << (it-begin(arr)) << endl;
else
cerr << "Not found\n";