【问题标题】:Trouble initialising array in G++ [duplicate]在G ++中初始化数组时遇到问题[重复]
【发布时间】:2015-05-15 23:25:24
【问题描述】:

我尝试将我的int cate[catNum] 数组初始化为所有1s,当cout<<cate[1] 时,它输出0?不知道是什么问题,理论上应该是1?

int main ()
{
    int const catNum = 13;    
    int cate[catNum]= {1};
    cout<<cate[1]<<endl;
}

【问题讨论】:

标签: c++ arrays g++


【解决方案1】:
int cate[catNum]= {1};

此语法将第一个元素初始化为 1,其余元素初始化为 0。(从技术上讲,它值初始化其余元素。)

试试,

std::fill( std::begin( cate ), std::end( cate ), 1 );

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

您将 cate 定义为 13 个整数的数组,但初始化器 {1} 只有一个整数,因此您只将第一个元素初始化为 1。要全部设置它们,您可以执行类似的操作

for (int i = 0; i < catNum; i++) { cate[i] = 1; }

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多