C++ Deleting a specfic value in a vector without knowing location

if (find(visitable.begin(), visitable.end(), ourstack.returnTop())) { ... }

I want to determine whether the top character in stack ourstack can be found in the vector visitable . If yes, I want this character to be deleted from visitable .

How would I code that? I know vectors use erase , but that requires the specific location of that character (which I don't know).

This is for my maze-path-finding assignment.

Also, my returnTop is giving me an error: class "std.stack<char..." has no member returnTop . I declared #include in the top of my program. What's happening here?

Thanks in advance!


If you are using find , then you already know the location of the character. find returns an iterator to the position where the character is found, or to the value used as end if it cannot find it.

vector<?>::const_iterator iter =
    find(visitable.begin(), visitable.end(), ourstack.top());
if( iter != visitable.end() )
{
    visitable.erase( iter );
}

As for stack , the function you are looking for is top() . The standard C++ library does not use camelCased identifiers, that looks more like a Java or C# thing.


Just like this:

// Note assume C++0x notation for simplicity since I don't know the type of the template
auto character = ourstack.top();

auto iter = std::find(visitable.begin(), visitable.end(), character);
if (iter != visitable.end())
    visitable.erase(iter);

returnTop does not exist in the stack class, but top does.

Alternatively if you want some generic (and rather flamboyant way) of doing it:

// Assume type of vector and stack are the same
template <class T>
void TryRemoveCharacter(std::vector<T>& visitable, const std::stack<T>& ourStack)
{
    // Note, could have passed a ref to the character directly, which IMHO makes more sense
    const T& ourChar = ourStack.top();

    visitable.erase(std::remove_if(visitable.begin(), visitable.end(), [&ourChar](const T& character)
    {
        // Note, this will not work http://www.cplusplus.com/reference/algorithm/find/
        // says that std::find uses the operator== for comparisons but I doubt that
        // as compilers typically do not generate equal comparison operator.
        // See http://stackoverflow.com/questions/217911/why-dont-c-compilers-define-operator-and-operator
        // It's best to either overload the operator== to do a true comparison or
        // add a comparison method and invoke it here.
        return ourChar == character;
    }));
}

Note: this alternative way may not be a good idea for an assignment as your teacher will probably find suspicious that you introduce advanced C++ features (C++0x) all of a sudden.
However for intellectual curiosity it could work ;)

Here's how you may use it:

TryRemoveCharacter(visitable, ourstack);
链接地址: http://www.djcxy.com/p/73780.html

上一篇: 平等有什么困难?

下一篇: C ++在不知道位置的情况下删除矢量中的特定值