-3

I need a create array in c++ but I need array always with variables name

int Magic(string name_array,int n)
{
string Name = "Something";
Name.append(name_array);
double * Name = new double[n];

}

int main()
{
Magic("a.txt",10);
}

And I have this error:

operator' : 'identifier1' differs in levels of indirection from 'identifier2'

I know it's not a python but maybe a map help me? How I can make this?

  • 3
    I would suggest; since your comment of "but maybe a map help me" - that you search for `c++ map` and see what you find out – UKMonkey Mar 02 '18 at 13:28
  • 4
    Perhaps you could explain what you're actually trying to achieve? "array with variables name" doesn't mean anything. – Useless Mar 02 '18 at 13:29
  • 1
    Possible duplicate of [Convert string to variable name or variable type](https://stackoverflow.com/questions/7143120/convert-string-to-variable-name-or-variable-type) – Arnav Borborah Mar 02 '18 at 13:29
  • You get this error because `Name` is already declared as `string` 2 lines above. Try `double * SomeOtherName = new double[n];`, this will compile. But it's still unclear what you're trying to achieve. The code you show here make so sense at all to me. – Jabberwocky Mar 02 '18 at 13:32
  • 1
    *I know it's not a python* -- First, what is / was your python program supposed to accomplish? That is what you focus on, not the syntax you used in python, and making failed attempts to make C++ look like python syntax. – PaulMcKenzie Mar 02 '18 at 13:33
  • @ArnavBorborah not sure if it is a duplicate. For me it's unclear for the moment. – Jabberwocky Mar 02 '18 at 13:35
  • 1
    The concept of a variable's name is only relevant at compile time. There is no such thing as a variable's run-time name, much less it's dynamic name. – François Andrieux Mar 02 '18 at 13:38

1 Answers1

4

If you want to be able to access different arrays by string names, consider using a std::map<std::string, std::vector<double>>. This maps strings to C++'s better, more dynamic answer to arrays. In this case your code would be something like:

#include <iostream>
#include <map>
#include <vector>



void AddVector(std::map<std::string, std::vector<double>> &io_map,
    const std::string& i_name,
    const std::size_t i_size)
{
    io_map[i_name].resize(i_size);
}

int main()
{
    std::map<std::string, std::vector<double>> vector_map;
    AddVector(vector_map, "Vector1", 3);
    AddVector(vector_map, "Vector2", 10);

    std::cout << "Vector with string key Vector1 has size: " << vector_map["Vector1"].size() << std::endl;
    return 0;
}

In this code I've tried to be as close to the code you've given - resizing the vectors to the size you would have created the array in your "Magic" function. However, vectors can dynamically resize, so you may not even need to create/resize them in your code depending on your use case.

Joris Timmermans
  • 10,814
  • 2
  • 49
  • 75