1

I need to create a large array(1000) of histograms where each histogram is slightly different. I am new to C++ and my first thought on how to do this was using a for loop which will create the histogram and add it to the array in the loop, but ive run into the issue of variable names (which i expected). How can i make the variable name of each histogram different while adding them in the loop?

sorry if that was poorly worded.

4
  • 1
    C++ has built-in arrays; only one name needed. Better yet, use std::vector. Commented Jun 15, 2012 at 19:46
  • We can help you better if you show us the relevant parts of your code ;) Commented Jun 15, 2012 at 19:47
  • 1
    Welcome to SO. Try to include code, even if it's clunky or not working, otherwise it's hard to understand your point of view. Also, you can use Histogram myHistograms[1000] or std::vector<Histrogram> myHistograms. But the actual implementation depends on your Histogram, especially its constructor and assignment methods. Commented Jun 15, 2012 at 19:51
  • You may have to use dynamic memory as most compilers have smaller limit for static memory allocations. Commented Jun 15, 2012 at 20:16

1 Answer 1

4

It sounds like what you want is a histogram class where each instance is a little different.

class Histogram {
    unsigned m_count;
    std::string m_label;
public:
    Histogram(std::string label) : m_count(0), m_label(label) {}
    std::string & label () { return m_label; }
    std::string label () const { return m_label; }
    unsigned & count () { return m_count; }
    unsigned count () const { return m_count; }
};

It might be easier to manage these within a map rather than a vector (unless you can actually classify the input into a number), but each histogram will need a unique label.

std::map<std::string, std::unique_ptr<Histogram> > histograms;

while (more_input()) {
    input = get_input();
    std::string classification = classify_input(input);
    if (histograms[classification] == 0)
        histograms[classification]
            = std::unique_ptr<Histogram>(new Histogram(classification));
    histograms[classification]->count() += 1;
}
Sign up to request clarification or add additional context in comments.

1 Comment

as it turns out i am an idiot and i was doing the wrong thing all along. Thank you all so much for your help though.

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.