tomtetlaw -1 Posting Pro

I want to be able to find a class with a variable in it:

for(int i=0;i<classes.size();i++)
{
    if(class[i].name == classes[i])
        return class[i];
}

I think class would be a list of classes that are instanced.
where classes is a vector of strings.

Is this possible?

Dani AI

Generated

— the idea is fine but a few practical points will make it correct and robust.

Avoid naming a variable class (reserved word) and decide what you want to return: an iterator, a pointer, or an std::optional/reference. For a small container a linear search with std::find_if is simple and safe; return the iterator or a pointer to the found element, or nullptr / end() when not found. If lookups by name are frequent, keep an index like std::unordered_map<std::string, T> for O(1) lookup instead of repeating linear scans. When storing polymorphic objects, store pointers or smart pointers (unique_ptr/shared_ptr) so the objects’ lifetimes are preserved.

Example patterns (concept only — adjust types and ownership to your code):

// linear search: returns pointer or nullptr
MyClass* find_by_name(std::vector<MyClass>& v, const std::string& name);

// map lookup: fast, direct access
std::unordered_map<std::string, MyClass*> index;

Use std::find_if for the linear case and std::unordered_map for indexed lookups; see and std::unordered_map. Also pay attention to const-correctness and case sensitivity when comparing names.

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.