0

How can I use c++ assert to check if a value is found in an array? I know I could use a simple for loop but I am supposed to use assert for my project.

Function signature:

template <class K, class V>
K& Map<K, V>::operator[](const V &value) const //Assert the argument is found 
//in the Values array and then return the key with the given value 
{
}

Update:

Is this code correct? I am not sure since it does not use assert to check if the value is found in an array.

template <class K, class V>
K& Map<K, V>::operator [] (const V &value) const
{
    for (int i = 0; i < size; i++) 
    {
        if (A2[i] == value)
            return A1[i];
    }

    assert(false);
}
11
  • We need to know what Map is. Commented Nov 29, 2020 at 18:17
  • Also, operator[] cannot be const if the Map works anything like std::map. Commented Nov 29, 2020 at 18:20
  • @PaulMcKenzie This operator[] will assert the key already exists, it is a precondition that the argument will be found. So it will not insert new elements and is not intended to behave like std::map. Commented Nov 29, 2020 at 18:22
  • using assert is no alternative to using a loop. You can do it with or without assert and with or without a (explicit) loop Commented Nov 29, 2020 at 18:23
  • "I know I could use a simple for loop but I am supposed to use assert for my project." assert is not a replacement for for here. You have to some how determine if value is in your map, then you can assert that condition. Commented Nov 29, 2020 at 18:24

1 Answer 1

1

Is this code correct?

assert is "disabled" when NDEBUG is set. else std::abort would be called (after a diagnostic).

So, if code reaches that assert,

if NDEBUG is defined, your program reaches end of function returning non-void type, so it is undefined behavior.

If set, program is well defined and abort.

throwing exception might be more appropriated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.