My Array only goes up to 3 values and my second Array repeats whatever the user entered into the 2nd array

54 Views Asked by At

I have changed up my code to be vectors. Now I am trying to find the Union, Intersection, and A-B. My code for both Union and Intersection now is working. I can not figure out how to do my difference. I figured I could take A and if it == to B then not insert it but it still puts them in none the less.

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>

using namespace std;

void Union();
void Intersection();
void Difference();

int main()
{
    Union();
    Intersection();
    Difference();


    return 0;
}

void SetVectors()
{

}


void Union()
{
        int temp = 0;
vector<int> U{};
vector<int> A{3, 4, 9, 12, 13, 15, 16, 17};

vector<int> B{1, 3, 5, 7, 9};

for(int i = 0; i < A.size(); i++)
{
    for (int j = 0; j < B.size(); j++)
    {

        if (A[i] != B[j])
        {
            int temp = A[i];
            U.push_back(temp);
            temp = B[j];
            U.push_back(temp);
        }


              //Used To Sort The Vector So There Is No Duplicates And Its In Order!
              sort( U.begin(), U.end() );
              U.erase( unique( U.begin(), U.end() ), U.end() );
    }

}
cout << "Union: ";
for(int z = 0; z < U.size(); z++)
{
    cout << U[z] << " ";
}
}

void Intersection()
{
        int temp = 0;
vector<int> U{};
vector<int> A{3, 4, 9, 12, 13, 15};
//Used To Sort The Vector So There Is No Duplicates And Its In Order!
sort( A.begin(), A.end() );
A.erase( unique( A.begin(), A.end() ), A.end() );

vector<int> B{1, 3, 5, 7, 9};
//Used To Sort The Vector So There Is No Duplicates And Its In Order!
sort( B.begin(), B.end() );
B.erase( unique( B.begin(), B.end() ), B.end() );



for(int i = 0; i < A.size(); i++)
{
    for (int j = 0; j < B.size(); j++)
    {

        if (A[i] == B[j])
        {
            int temp = A[i];
            U.push_back(temp);
            temp = B[j];
            U.push_back(temp);
        }


              //Used To Sort The Vector So There Is No Duplicates And Its In Order!
              sort( U.begin(), U.end() );
              U.erase( unique( U.begin(), U.end() ), U.end() );
    }

}
cout << "Intersection: ";
for(int z = 0; z < U.size(); z++)
{
    cout << U[z] << " ";
}
}

void Difference()
{
    int temp = 0;
    vector<int> D{};
    vector<int> A{3, 4, 9, 12, 13, 15};

    vector<int> B{1, 3, 5, 7, 9};

    for(int i = 0; i < A.size(); i++)
    {
        for (int j = 0; j < B.size(); j++)
        {

            if (A[i] == B[j])
            {
                cout << A[i];
            }
            else
            {
                int temp = A[i];
                D.push_back(temp);
            }


                  //Used To Sort The Vector So There Is No Duplicates And Its In Order!
                  sort( D.begin(), D.end() );
                  D.erase( unique( D.begin(), D.end() ), D.end() );
        }

    }
    cout << "Difference: ";
    for(int z = 0; z < D.size(); z++)
    {
        cout << D[z] << " ";
    }
}
1

There are 1 best solutions below

0
On

The best help we can provide is to say "Don't do it that way..." Continuing from the comment int A [MaxSizeA]; is declared while MaxSizeA is zero attempting to declare an non-standard Variable Length Array (VLA) with zero elements. That won't work. For starters VLAs are not part of C++, and are only provided as non-standard compiler extensions by some compilers.

Bewilderingly, you #include <vector>, which is great -- that is what you want to use to store an unknown number of objects - but, you fail to make use of std::vector in your code.

Before looking at how you can use std::vector to accomplish what you are trying to do, take a quick look at Why is “using namespace std;” considered bad practice?. Learning good habits early is a lot easier than breaking bad ones later.

std::vector

std::vector allows you to add as many objects to your collection as you like and the memory management is handled automatically. In your case you can ask for MaxSizeA and MaxSizeB and then loop until the user has provided that many valid elements for each. Take A for example, you could do:

#include <limits>
...
    std::vector<int> A{}, B{};
    size_t MaxSizeA, MaxSizeB;
    int val;
    
    std::cout << "How Many Values Do You Wish To Enter For A: ";
    if (!(std::cin >> MaxSizeA)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }

    while (A.size() < MaxSizeA) {
        std::cout << "Enter Values For A[" << A.size() << "]: ";
        if (std::cin >> val)
            A.push_back(val);
        else {
            std::cerr << "  error: invalid integer input.\n";
            std::cin.clear();
            std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

Where you declare your vectors and variables local to main(), there is no reason to use global variables here (and in fact they should be avoided unless absolutely necessary). You prompt for MaxSizeA and then validate the stream-state after your call to std::cin to ensure you have a valid integer value in MaxSizeA. Then you simply loop until A.size() == MaxSizeA ensuring your user provided MaxSizeA valid integer inputs. You handle a failed input by resetting the stream state and then clearing to the end of input with std::cin.ignore(). No counter is needed, you can simple use A.size() and B.size() to determine the current number of elements stored in each vector.

(you can also check std::cin.eof() and std::cin.bad() to catch a user manually generating EOF or catch an unrecoverable stream error -- that is left to you.)

You can use a Range-based for loop (since C++11) to output the contents of each vector, e.g.

    std::cout << "\narray A:\n";
    for (auto& v : A)
        std::cout << v << '\n';

Putting it altogether into an example similar to what your are attempting you would have:

#include <iostream>
#include <vector>
#include <limits>

int main() {
    
    std::vector<int> A{}, B{};
    size_t MaxSizeA, MaxSizeB;
    int val;
    
    std::cout << "How Many Values Do You Wish To Enter For A: ";
    if (!(std::cin >> MaxSizeA)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }

    while (A.size() < MaxSizeA) {
        std::cout << "Enter Values For A[" << A.size() << "]: ";
        if (std::cin >> val)
            A.push_back(val);
        else {
            std::cerr << "  error: invalid integer input.\n";
            std::cin.clear();
            std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    std::cout << "\nHow Many Values Do You Wish To Enter For B: ";
    if (!(std::cin >> MaxSizeB)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }
    
    while (B.size() < MaxSizeB) {
        std::cout << "Enter Values For B[" << B.size() << "]: ";
        if (std::cin >> val)
            B.push_back(val);
        else {
            std::cerr << "  error: invalid integer input.\n";
            std::cin.clear();
            std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    
    std::cout << "\narray A:\n";
    for (auto& v : A)
        std::cout << v << '\n';
    
    std::cout << "\narray B:\n";
    for (auto& v : B)
        std::cout << v << '\n';

}

Example Use/Output

Running the program and intentionally providing bad input to exercise the error handling you could do:

$ ./bin/arrayVLAtoVector
How Many Values Do You Wish To Enter For A: 4
Enter Values For A[0]: 10
Enter Values For A[1]: 20
Enter Values For A[2]: thirty
  error: invalid integer input.
Enter Values For A[2]: 30
Enter Values For A[3]: 40

How Many Values Do You Wish To Enter For B: 3
Enter Values For B[0]: 1
Enter Values For B[1]: 2
Enter Values For B[2]: buckle my shoe
  error: invalid integer input.
Enter Values For B[2]: 3

array A:
10
20
30
40

array B:
1
2
3

Look things over and let me know if you have further questions.