i have made a queue using STL. the queue contains strings only. how to check for a particular string if it present in queue or not?

Dani AI

Generated

Brief summary and the key point from the thread: originally tried strcmp and then switched to queue<char*>. correctly noted that std::string supports value comparison. The important difference to understand is what queue<char*> actually stores and the practical consequences of that choice.

queue<char*> holds pointers to characters (C-style strings). The queue copies pointer values, not the string data. That means you must manage the memory those pointers name yourself. Pushing a pointer to a temporary or to a local buffer will leave a dangling pointer when that object goes out of scope. Also, comparing two char* with == compares addresses, not string contents; strcmp compares contents but expects C strings (use someStdString.c_str() if you must pass a std::string to a C function). For safety and simplicity, prefer std::string unless you have a compelling reason to use raw pointers.

Two practical ways to check whether a string is present in a std::queue<std::string>:

bool contains(std::queue<std::string> q, const std::string& value) {
    while (!q.empty()) {
        if (q.front() == value) return true;
        q.pop();
    }
    return false;
}

Or use the underlying container (the default is std::deque) and std::find if you need iterators without copying:

std::deque<std::string> d = /* ... */;
if (std::find(d.begin(), d.end(), value) != d.end()) {
    // found
}

If membership checks are frequent and performance matters, keep a separate std::unordered_set<std::string> for O(1) lookups. For reference on container adaptor behavior and std::string::c_str(), see std::queue — cppreference and std::string::c_str() — cppreference.

Recommended Answers

All 5 Replies

what STL container did you use?

actually i m using strcmp function for ccomparing which is giving type mismatch error.
so i did this : queue<char*> myqueue .
earlier it was: queue<string> myqueue

now the error has gone and code works fine but i didnot understand what does queue<char*> myqueue means?
what type value the queue have?

and sorry for the late reply.

You don't use strcmp with std::string, instead std::string has == operator that returns true if the two strings are equal, false otherwise. for example

std::string s = "Hello";
if( s == "HELLO" )
{

}

ok..it works.
but what does queue<char*> myqueue means?

The contents of the queue are char*, you can't mix it with std::string

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.