1

Say I have a class that contains a map with a pointer-type key:

class Base;
class App
{
  private:
    size_t n;
    map<string, Base*> m;
};

What I want is that, when I refer to a map key for the first time, I need the "Base*" pointer already allocated for "n" elements. I can't do this allocation in the constructor, because the map key value will only be known at run-time. Not sure what is the best solution for this.

1
  • Firstly, you mean "value", not "key", right? Secondly, how and when is n determined? Is it a compile-time constant? Commented Nov 10, 2013 at 2:23

1 Answer 1

1

"Not sure what is the best solution for this"

I would say that avoiding dynamically allocated C-style array would be a good start. Maybe instead of

map<string, Base*> m;

you could use:

map<string, std::vector<Base> > m;

"when I refer to a map key for the first time, I need the "Base*" pointer already allocated for "n" elements"

You could do something like this:

std::vector<Base>& getVal(const std::string& key) {
    if (m.count(key) > 0 && m[key].size() > 0)
        return m[key];
    m[key] = std::vector<Base>(10); // n
    return m[key];
}
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.