1

How can I create a array with dinamic size like this:

int sentLen = sentences.size();

double a[sentLen][sentLen];

for (int i = 0; i < sentLen; i++) 
{
    for (int j = 0; j < sentLen; j++)
    {
        a[i][j] = somefunction(i, j);
    }
}

My research led me to malloc which isn't recommended or other too complicated methods. After I realised that size must be constant, I tried using unordered_map, and I have tried the following:

std::unordered_map <int, int, double> a;


for (int i = 0; i < sentLen; i++) 
{
    for (int j = 0; j < sentLen; j++)
    {
        a.insert({ i, j, somefunc(i, j) });
    }
}

but still unsuccessful.

3
  • It depends on what you mean "dynamic size". Also there is nothing wrong with your first code block. Commented Apr 27, 2014 at 2:42
  • @Daniel I'm getting Expressions must have a constant value with the first code. Commented Apr 27, 2014 at 2:45
  • 1
    What compiler and version are you using? Older compilers do not support variable length arrays. If your compiler doesn't support it, minimal research is required to find the answer. Commented Apr 27, 2014 at 2:48

2 Answers 2

1

You don't really want to use arrays.

std::vector<std::vector<double>> a{
   sentLen, std::vector<double>{ sentLen, 0.0 } };

for (int i = 0; i < sentLen; ++i)
{
    for (int j = 0; j < sentLen; ++j)
    {
        a[i][j] = somefunc(i, j);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the idea. Tho seems there is syntax error, because I got it running like std::vector<std::vector<double>> a(sentLen, std::vector<double>(sentLen, 0.0));
Based on his first example, I don't believe the OP really needs any of the functionality of a vector, other than being able to declare it of variable length. He should use array pointers and new the memory himself. Using a vector of vectors is overkill.
@Deepsy Put a space between the end brackets > >.
Using the new operator is generally a bad idea.
The {} initialization is a C++11 feature. Your post looked like you were attempting to use it. If you use g++ or clang++, try the -std=c++11 switch.
1

You're getting an error because you can't use variables as static array sizes. They must be known at compile time. You have to allocate dynamically or use a vector instead.

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.