如何设置动态分配的数组的内容?

时间:2014-02-27 04:32:59

标签: c++ arrays initialization declaration

我对如何在main中分配全局指针和赋值感到有点困惑 功能??

例如,这里是我的代码示例

bool *list;
int main()
{
  list=new bool[7];    
  //i want to auto add a value but how, is that below code is correct??
  list={true,false,true,true,true,true};
}

我尝试用流血的c ++ 抱歉我的英语不好。

4 个答案:

答案 0 :(得分:2)

此语法

list={true,false,true,true,true,true};

错了。

相反,你可以写

bool *list;
int main()
{
  list=new bool[7] {true,false,true,true,true,true};    
}

或者您应该使用赋值运算符

bool *list;
int main()
{
  list=new bool[7];
  list[0] = true;
  list[1] = false;
  list[2] = true;
  list[3] = true;
  list[4] = true;
  list[5] = true;     
}

或者您可以使用指向std :: array类型的对象的指针。例如

#include <array>

std::array<bool, 7> *list;

int main()
{
  list=new std::array<bool, 7>;

  *list =  {true,false,true,true,true,true};    
}

最后你可以使用std::vector<bool>代替指针。或std::bitset:)

答案 1 :(得分:0)

list[0] = true;
list[1] = false;
list[2] = true;
list[3] = true;
list[4] = true;
list[5] = true;
list[6] = ???; (whatever you want it to be - true or false)

当你没有数十或数百个元素时,这是最简单的方法。

答案 2 :(得分:0)

您可以使用bitset而不是数组。

#include <bitset>
#include <string>

std::bitset<7>* list;

int main()
{
    list = new std::bitset<7>;

    *list = std::bitset<7>(std::string("111101"));
}

答案 3 :(得分:0)

为什么指针和动态分配?为什么不简单:

bool list[7] = {true,false,true,true,true,true};

int main()
{
    // ... no need to initialize or assign here ...
}

注意:数组大小为7,但您只提供6个初始值。你确定那是你想要的吗?