Home > Software design >  Global int alternative
Global int alternative

Time:05-28

i have an int linked list, and a function called filter which receives a list and a condition function. The filter function goes through the nodes in the list and if the condition is true, it adds it to a new list.

I've created this so that it filters the list through a number i choose to be divided by while the program is running, but it uses a global int, is there an alternative without changing the function filter, I've thought about making it call for a function to be called once to setup the number but didn't succeed,

static int choosenDividedBy = 1;

static bool dividedBy(int n);

int main() {
    Queue<int> q4;
    for (int i = 1; i <= 10; i  ) {
        q4.pushBack(i);
    }
    std::cout << "Choose a number to divide by:" << std::endl;
    std::cin >> choosenDividedBy;
    q4 = filter(q4, dividedBy);
    for (Queue<int>::Iterator i = q4.begin(); i != q4.end();   i) {
        std::cout << *i << std::endl;
    }
    return 0;
}

static bool dividedBy(int n) {
    return (n % choosenDividedBy) == 0;
}

Edit: filter:

template<class T>
Queue<T> filter(const Queue<T>& queue, bool (*condition)(T)) {
    Queue<T> newQueue;
    for(typename Queue<T>::ConstIterator i = queue.begin();i != queue.end();  i) {
        try {
            if(condition(*i)) {
                newQueue.pushBack(*i);
            }
        } catch(typename Queue<T>::ConstIterator::InvalidOperation& exception) {
            throw exception;
        }
    }
    return newQueue;
}

CodePudding user response:

You would create a a filter class that has a normal (non-static) member that stores your int and has the filter method you also have.

  • Related