Return string array in C++ function

前端 未结 3 1239
名媛妹妹
名媛妹妹 2021-01-31 19:12

I am new to C++. For a school project I need to make a function which will be able to return a string array.

Currently I have this in my header:

Config.h

3条回答
  •  后悔当初
    2021-01-31 19:54

    In C++ you don't use an array, but a std::vector instance. Arrays in C++ must have a compile-time fixed length while std::vector instances can change their length at runtime.

    std::vector Config::getVehicles()
    {
        std::vector test(5);
        test[0] = "test0";
        test[1] = "test1";
        test[2] = "test2";
        test[3] = "test3";
        test[4] = "test4";
        return test;
    }
    

    std::vector can also grow dynamically, so in a C++ program you will find more often something like

    std::vector Config::getVehicles()
    {
        std::vector test; // Empty on creation
        test.push_back("test0"); // Adds an element
        test.push_back("test1");
        test.push_back("test2");
        test.push_back("test3");
        test.push_back("test4");
        return test;
    }
    

    Allocating dynamically an array of std::string is technically possible but a terrible idea in C++ (for example C++ doesn't provide the garbage collector that Java has).

    If you want to program in C++ then grab a good C++ book and read it cover to cover first... writing Java code in C++ is a recipe for a disaster because the languages, despite the superficial braces similarity, are very very different in many fundamental ways.

提交回复
热议问题