c++ - 将数组存储在单独的类文件中

标签 c++ arrays function class

我现在正在为 Ludum Dare 编写代码,我试图创建一个单独的类,它会给我一个数组作为函数的返回类型。我设置了一个数组,但我不知道如何使返回类型成为一个数组,以便我可以在 main 函数中使用它。我将如何返回一个数组并将 main.cpp 中的变量设置为该数组?

最佳答案

这里有几个例子,每个都有自己的优点:

#include <iostream>
// C++11 #include <array>
#include <vector>

void myVectorFunc1(std::vector<int>& data)
{
    for (unsigned i = 0; i < data.size(); ++i)
        data[i] = 9;

    data.push_back(1);
    data.push_back(2);
    data.push_back(3);
}

std::vector<int> myVectorFunc2(void)
{
    std::vector<int> data;
    data.push_back(1);
    data.push_back(2);
    data.push_back(3);
    return data;
}

/* C++ 11

template<std::size_t S>
void myArrayFunc1(std::array<int, S>& arr)
{
    for (auto it = arr.begin(); it != arr.end(); ++it)
        *it = 9;
}

std::array<int,5> myArrayFunc2(void)
{
    std::array<int,5> myArray = { 0, 1, 2, 3, 4 };
    return myArray;
}

*/

int main(int argc, char** argv)
{
    // Method 1: Pass a vector by reference
    std::vector<int> myVector1(10, 2);
    myVectorFunc1(myVector1);

    std::cout << "myVector1: ";
    for (unsigned i = 0; i < myVector1.size(); ++i)
        std::cout << myVector1[i];
    std::cout << std::endl;

    // Method 2: Return a vector
    std::vector<int> myVector2 = myVectorFunc2();

    std::cout << "myVector2: ";
    for (unsigned i = 0; i < myVector2.size(); ++i)
        std::cout << myVector2[i];
    std::cout << std::endl;

    /* C++11

    // Method 3: Pass array by reference
    std::array<int, 3> myArray1;
    std::cout << "myArray1: ";
    myArrayFunc1(myArray1);
    for (auto it = myArray1.begin(); it != myArray1.end(); ++it)
        std::cout << *it;
    std::cout << std::endl;

    // Method 4: Return an array
    std::cout << "myArray2: ";
    std::array<int,5> myArray2 = myArrayFunc2();
    for (auto it = myArray2.begin(); it != myArray2.end(); ++it)
        std::cout << *it;
    std::cout << std::endl;

    */

    return 0;
}

关于c++ - 将数组存储在单独的类文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414564/

相关文章:

c++ - 编写一个程序,提示用户输入五个十进制数

C - 不使用 realloc 的动态大小的结构指针数组?

javascript - 将对象数组转换为基元数组(从对象属性中提取)

PHP:使用来自 php 的参数调用 javascript 函数

mysql - 递归函数,保存DynamicPreparedStatement

c++ - 用三个相同的姓氏(C++)按姓氏组织名字?

c++ - vcpkg 是发布开源和跨平台 C++ 库的宝贵选择吗

c++ - 关于 Windows 和 posix 中的 1 个刻度

java - 如何在java中创建由二维int数组组成的二维数组?

c - int *(*(x[3])())[5]; 行是什么意思?用C 做?