1

I have two integer arrays [call one A and one B for simplicity] and a given integer value. I want to do two things with the arrays:

  1. I want to know if the given integer value is contained within the 'A' array dataset. If it is, I want to know the elements position within the 'A' array.
  2. I want to pull the element from array 'B' that corresponds with the position of the element in array 'A'.

Sorry if this isn't very clear, I did my best to explain it. Anyway, I'm very new to arrays and am not very familiar with how to interact with them (it also seems there's a bunch of ways to do it depending on what you include in the program). What are some good references for this?

I'd like to just do this using an if loop to search for the given integer in array 'A', and if that's true, then pull the corresponding value from B based on the position of the array element in A.

I currently have something like this:

#include <iostream>
#include <time.h>   // time
#include <stdlib.h> // srand, rand

using namespace std;
int main ()
{
    srand(time(NULL)); // Initiate seed
    int pointPos = rand() % 6 + 1; // Generate random point

    int velPoint[6] = {1, 2, 3, 4, 5, 6}; // velocity-point array
    int accel[6] = {14, 17, 23, 32, 41, 59}; //

    if (pointPos...) //This is where I want to check velPoint array to see if the random point is within the array
        // Here is where I want to pull the element from accel that is in the same position as the matching element in velPoint
}

2 Answers2

0

It is actually just like you said, although technically an "if loop" does not exist.

const int num = 6;
int velPoint[num] = {1, 2, 3, 4, 5, 6}; // velocity-point array
int accel[num] = {14, 17, 23, 32, 41, 59}; //
srand(time(NULL)); // Initiate seed
int pointPos = rand() % 6 + 1; // Generate random point
int covalue;
for( int i = 0; i < num; i++ ){ // loop through all the elements
  if( velPoint[i] == pointPos ){
    covalue = accel[i];
    break;
  }
}

You could also use the built in function std::find() A nice example can be found here: std::find()

You may think about switching to vectors or updating your datastructure, possibly making pairs or your own structs to group the data.

infinitezero
  • 691
  • 1
  • 6
  • 18
  • Ah right, meant if statement! It's hard to type all that out on a mobile phone. Thank you for the feedback, I'll definitely look into other data structures. –  Sep 15 '16 at 19:01
0

For a simple, easy-to-understand test, we could try something like this:

// This function takes an array of N elements of type T, and a value of type T.
//  (In your case, it will take parameters "const int (&arr)[6]" and "const int& val".)
// Array and value are passed by const reference, as this function doesn't modify either.
template<typename T, size_t N>
size_t checkForValue(const T (&arr)[N], const T& val)
{
    // Iterate over array.
    for (size_t i = 0; i < N; ++i)
    {
        // Compare element to desired value.
        if (arr[i] == val) { return i; }
    }

    // If value isn't found in array, return the array's size to indicate this.
    return N;
}

It can be used like so:

using namespace std;
int main ()
{
    srand(time(NULL)); // Initiate seed
    int pointPos = rand() % 6 + 1; // Generate random point

    int velPoint[6] = {1, 2, 3, 4, 5, 6}; // velocity-point array
    int accel[6] = {14, 17, 23, 32, 41, 59}; //

    size_t accelIndex = checkForValue(velPoint, pointPos);
    int accelValue = 0;

    // If pointPos was found in velPoint, look up element at same index in accel.
    // To determine if it was found, we check if the returned value is equal to the size of
    //  the array.  If it is, then the value wasn't found, and we don't access accel; if it
    //  isn't, the value was found, and we have a valid index.
    if (accelIndex != (sizeof(velPoint)/sizeof(velPoint[0])))
    {
        accelValue = accel[accelIndex];
    }

    // ...
}

Note that the function checkForValue() is very similar to the library function std::find(), in <algorithm>; while it would be better to use std::find() instead of writing your own, I provided this function to illustrate a few things which will be useful to you as you learn to use arrays:

  • How to iterate over an array using a for loop.
  • How to compare a free-standing value to an array element.
  • How to pass an array by reference, to prevent it from decaying into a pointer and losing type and dimension information. [Normally, if you have an array defined as T arr[N], and you pass it as a function parameter (such as func(arr)), that function will take the array as T* arr, a pointer to the first element. Passing by reference prevents this, and using a template to determine T and N instead of hard-coding them into the signature allows the function to accept any array.]
  • How to determine the size of a C array, by using sizeof(array) / sizeof(array[0]). This obtains the number of bytes used by the array, then divides it by the number of bytes used by each element, to obtain the number of elements.

If you would instead prefer to use std::find(), try this:

#include <cstdlib>
#include <ctime>
#include <algorithm> // For std::find.
#include <iterator>  // For std::distance.

using namespace std;
int main ()
{
    srand(time(NULL)); // Initiate seed
    int pointPos = rand() % 6 + 1; // Generate random point

    int velPoint[6] = {1, 2, 3, 4, 5, 6}; // velocity-point array
    int accel[6] = {14, 17, 23, 32, 41, 59}; //

    // Obtain pointer to element containing pointPos, then use pointer arithmetic to
    //  convert it to an index.
    // Included to show what happens behind the scenes.  Use std::distance instead.
    // size_t accelIndex = std::find(std::begin(velPoint), std::end(velPoint), pointPos) -
    //                     std::begin(velPoint);

    // Obtain pointer to element containing pointPos with std::find(), then convert to
    //  index of that element with std::distance().
    // If pointPos isn't found, this will be equal to the array's size.
    size_t accelIndex = std::distance(std::begin(velPoint),
                                      std::find(std::begin(velPoint),
                                                std::end(velPoint),
                                                pointPos));

    int accelValue = 0;

    // If pointPos was found in velPoint, look up related element in accel.
    // If std::find() is unable to find pointPos, it will return an iterator to the end of
    //  the passed range; due to std::distance (or our pointer arithmetic, if you use it
    //  instead), this will be converted into a value equal to the size of the array, as
    //  with checkForValue() above.
    if (accelIndex != (sizeof(velPoint) / sizeof(velPoint[0])))
    {
        accelValue = accel[accelIndex];
    }

    // ...
}

This also illustrates how to:

  • Obtain an iterator to the first element of an array, with std::begin(array); this is element 0. For a C array of type T, this iterator will be a pointer-to-T, or T*.
  • Obtain an iterator to the past-the-end element of the array, with std::end(array); for an array of size N, this is element N. For a C array of type T, this iterator will be a pointer-to-T, or T*. [Note that this is not actually a member of the array, but the next memory address after the array's allocated storage ends. For 6-element arrays, for example, it is where the 7th element would be, if there was one.]
  • Pass an array to a standard library function which takes a range, by passing iterators to the first and past-the-end elements.
  • Convert a pointer to an element of an array into the index number of the pointed-to element using pointer arithmetic, by subtracting a pointer to the first element of the array.
  • Convert a pointer to an element of an array into the index number of the pointed-to element using std::distance(). This is preferred to pointer arithmetic, as it works with any type of range, not just C arrays.
Community
  • 1
  • 1
  • Thank you so much for all of this, it will be very helpful while I work through this! –  Sep 15 '16 at 19:01
  • @CourtneyLeigh You're welcome. I forgot to mention this, but if you need to determine the size of an array, you can also use this C++ idiom: `template size_t size(const T (&arr)[N]) { return N; }`. This takes any array by reference, to prevent pointer decay, and obtains the size as a template parameter. – Justin Time - Reinstate Monica Sep 15 '16 at 19:13