【问题标题】:filling up an array in c++ [closed]在c ++中填充数组[关闭]
【发布时间】:2013-01-21 20:41:09
【问题描述】:

我是 c++ 新手。我试图编写以下代码来用新值填充数组的每个字节,而不会覆盖其他字节。下面的每个字节(r)都应该在数组的新地址处相加。

int _tmain(int argc, _TCHAR* argv[]) {
    char y[80];
    for(int b = 0; b < 10; ++b) {
        strcpy_s(y, "r");
    }
}

如果 c++ 中有任何函数可以做到这一点,请告诉我。在上述情况下,值 'r' 是任意的,它可以有任何新值。 所以生成的字符数组应该包含值 rrrrrr... 10 次。 非常感谢您。

【问题讨论】:

  • 如果你打算使用 C++,当有 C++ 替代品时,尽量避免使用标准 C 函数。 strcpy 是 C 函数,strcpy_s 是专有扩展,不可移植。

标签: c++ visual-c++ c++11


【解决方案1】:

使用 C++11

#include <algorithm>
#include <iostream>

int main() {
    char array[80];
    std::fill(std::begin(array),std::begin(array)+10,'r');
}

或者,如 cmets 中所述,您可以使用 std::fill(array,array+10,'r')

【讨论】:

  • std::begin 的意义何在?你可以简单地使用array
  • @JackAidley 现在不习惯了:(
  • @JackAidley 使用 -O2 编译,ASM 输出为 near identical
  • @Non-Stop:我非常不同意,std::begin 是毫无意义的冗长。最糟糕的是,它表明正在进行的工作并非如此。任何使用 C 样式数组的人都应该明白,这里的 array 指向数组的第一个元素。
  • @JackAidley:不同意当然是你的权利,即使你错了。 :)
【解决方案2】:

您可以使用[] 运算符并分配char 值。

char y[80];
for(int b=0; b<10; ++b)
    y[b] = 'r';

是的,std::fill 是一种更惯用和现代的 C++ 方式来执行此操作,但您也应该了解 [] 运算符!

【讨论】:

    【解决方案3】:
    // ConsoleApp.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int fun(bool x,int y[],int length);
    int funx(char y[]);
    int functionx(bool IsMainProd, int MainProdId, int Addons[],int len);
    int _tmain(int argc, _TCHAR* argv[])
    {
        int AddonCancel[10];
    
        for( int i = 0 ; i<4 ;++i)
        {
            std::fill(std::begin(AddonCancel)+i,std::begin(AddonCancel)+i+1,i*5);
        }
        bool IsMainProduct (false);
        int MainProduct =4 ; 
        functionx(IsMainProduct,MainProduct,AddonCancel,4);
    
    }
    
    int functionx(bool IsMainProd, int MainProdId, int Addons[],int len)
    {
        if(IsMainProd)
            std::cout<< "Is Main Product";
        else
        {
            for(int x = 0 ; x<len;++x)
            {
              std::cout<< Addons[x];
            }
        }
    
        return 0 ; 
    }
    

    【讨论】:

      【解决方案4】:

      选项 1: 定义时初始化数组。便于初始化少量值。优点是数组可以声明为const(此处未显示)。

      char const fc = 'r';   // fill char
      char y[ 80 ] = { fc, fc, fc, fc,
                       fc, fc, fc, fc,
                       fc, fc };
      

      选项 2: 经典C

      memset( y, y+10, 'r' );
      

      选项 3: 经典(C++11 之前)C++

      std::fill( y, y+10, 'r' );
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      相关资源
      最近更新 更多