简体   繁体   English

我怎样才能返回数组?

[英]How can I return an array?

Is there any way to return an array from a function? 有没有办法从函数返回一个数组? More specifically, I've created this function: 更具体地说,我创建了这个函数:

char bin[8];

for(int i = 7; i >= 0; i--)
{
    int ascii='a';
    if(2^i-ascii >= 0)
    {
        bin[i]='1';
        ascii=2^i-ascii;
    }
    else
    {
        bin[i]='0';
    }
}

and I need a way to return bin[] . 我需要一种方法来返回bin[]

You can't do that but you can: 你不能这样做,但你可以:

  • return a dynamicaly allocated array - best owned by a smart pointer so that the caller does not have to care about deallocating memory for it - you could also return something like an std::vector this way. 返回一个动态分配的数组 - 最好由智能指针拥有,这样调用者不必关心为它释放内存 - 你也可以这样返回类似std :: vector的东西。
  • populate an array/vector passed to you as an argument by pointer (suggested) or a non const reference. 通过指针(建议)或非const引用填充传递给您的数组/向量作为参数。

Your array is a local variable allocated on the stack. 您的数组是在堆栈上分配的本地变量。 You should use new [] to allocate it on the heap. 您应该使用new []在堆上分配它。 Then you can just say: return bin; 然后你可以说: return bin; . Beware that you will have to explicitly free it with delete [] when you are done with it. 请注意,完成后必须使用delete []明确释放它。

You are really asking the wrong question. 你真的在问错误的问题。 If you want to do string processing in C++, use the std::string and/or std::vector classes, not arrays of char. 如果要在C ++中进行字符串处理,请使用std :: string和/或std :: vector类,而不是char数组。 Your code then becomes: 然后你的代码变成:

vector <char> func() {
    vector <char> bin(8);
    for( int i = 7; i >= 0; i-- ) {
       int ascii='a';
       if ( 2 ^ i - ascii >= 0 ) {
          bin[i] = '1';
          ascii = 2^i - ascii;
       }
       else {
        bin[i] ='0';
       }
    }
    return bin;
}

I think your best bet is to use a vector. 我认为你最好的选择是使用矢量。 It can function in many ways like an array and has several upsides (length stored with type, automatic memory management). 它可以在许多方面起作用,如阵列,并有几个上升(长度存储类型,自动内存管理)。

void Calculate( std::vector<char>& bin) {
  for(int i = 7; i >= 0; i--)
  {
    int ascii='a';
    if(2^i-ascii >= 0)
    {
        bin.push_back('1');
        ascii=2^i-ascii;
    }
    else
    {
        bin.push_back('0');
    }
  }
}

If you want to return a copy of the array (might make sense for small arrays) and the array has fixed size, you can enclose it in a struct; 如果要返回数组的副本(可能对小数组有意义)并且数组具有固定大小,则可以将其包含在结构中;

struct ArrayWrapper {
   char _bin[8];
};

ArrayWrapper func()
{
    ArrayWrapper x;

    // Do your stuff here using x._bin instead of plain bin

    return x;
}

Or just use a std::vector as has been already suggested. 或者只是使用已经建议的std :: vector。

Similar implemented to @ari's answer, i want to say there is already a boost solution, boost::array solving your problem: 类似于@ ari的答案,我想说已经有一个提升解决方案, boost::array解决你的问题:

boost::array<char, 8> f() {
    boost::array<char, 8> bin;
    for(int i = 7; i >= 0; i--) {
        int ascii = 'a';
        if(2 ^ i-ascii >= 0) {
            bin[i] = '1';
            ascii = 2 ^ i-ascii;
        } else {
            bin[i] = '0';
        }
    }
}

...
boost::array<char, 8> a(f());

[I'm not sure what you want to do with that algorithm though, but note that i think you want to do 1 << i (bit-wise shift) instead of 2 ^ i which is not exponentiation in C++.] [我不知道你想用这个算法做什么,但请注意,我认为你想做1 << i (逐位移位)而不是2 ^ i ,这不是 C ++中的指数化。

Boost array is a normal array, just wrapped in a struct, so you lose no performance what-so-ever. Boost数组是一个普通的数组,只是包含在一个结构中,所以你不会失去任何性能。 It will also be available in the next C++ version as std::array , and is very easy to do yourself if you don't need the begin() / size() / data() -sugar it adds (to be a container). 它也可以在下一个C ++版本中作为std::array ,如果你不需要它添加的begin() / size() / data() sugar,它就很容易自己做(作为一个容器) )。 Just go with the most basic one: 只需使用最基本的一个:

template<typename T, size_t S>
struct array { 
    T t[S];
    T& operator[](ptrdiff_t i) { return t[i]; }
    T const& operator[](ptrdiff_t i) const { return t[i]; }
};

But as usual, use the tools already written by other people, in this case boost::array . 但像往常一样,使用其他人已经编写的工具,在本例中为boost::array It's also got the advantage of being an aggregate (that's why it has no user declared constructor), so it allows initializing with a brace enclosed list: 它还具有聚合的优点(这就是它没有用户声明构造函数的原因),因此它允许使用括号括起的列表进行初始化:

boost::array<int, 4> a = {{ 1, 2, 3, 4 }};

you need to pass array bin as an argument in your function. 你需要在你的函数中传递数组bin作为参数。 array always pass by address , therefore you dont need to return any value. 数组总是按地址传递 ,因此您不需要返回任何值。 it will automatically show you all changes in your main program 它会自动显示主程序中的所有更改

void FunctionAbc(char bin[], int size);


void FuncationAbc(bin, size)
{
for(int i = 7; i >= 0; i--)
{
    int ascii='a';
    if(2^i-ascii >= 0)
    {
        bin[i]='1';
        ascii=2^i-ascii;
    }
    else
    {
        bin[i]='0';
    }
}

}

You'll want to pass by reference, as follows: 您将要通过引用传递,如下所示:

void modifyBin(char (&bin)[8])
{
    /* your function goes here and modifies bin */
}

int main() 
{
    char bin[8];
    modifyBin(bin);
    /* bin has been updated */
    return 0;
}

I think that everyone else answered this one... use a container instead of an array. 我认为其他人都回答了这个...使用容器而不是数组。 Here's the std::string version: 这是std::string版本:

std::string foo() {
    int ascii = 'a';
    std::string result("00000000");
    for (int i=7; i>=0; --i) {
        if (2^i-ascii >= 0) {
            result[i] = '1';
            ascii = 2^i-ascii;
        }
    }
    return result;
}

I'm not really sure if 2^i-ascii is want you want or not. 我不确定2^i-ascii是否是你想要的。 This will be parsed as (2 ^ (i - ascii)) which is a little strange. 这将被解析为(2 ^ (i - ascii)) ,这有点奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM