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

C++ 如何设置动态分配数组的内容?,c++,arrays,initialization,declaration,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++ 对不起,我的英语不好 list[0] = true; list[1

关于如何分配全局指针和在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++ 对不起,我的英语不好

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)
当您没有数十个或数百个元素时,这是最简单的方法。

此语法

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::数组*列表;
int main()
{
列表=新的std::数组;
*list={true,false,true,true,true,true};
}

最后,您可以使用
std::vector
代替指针。或者
std::bitset
:)

您可以使用位集而不是数组

#include <bitset>
#include <string>

std::bitset<7>* list;

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

    *list = std::bitset<7>(std::string("111101"));
}
#包括
#包括
std::位集*列表;
int main()
{
列表=新标准::位集;
*列表=标准::位集(标准::字符串(“111101”);
}

为什么要使用指针和动态分配?为什么不简单地:

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

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

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

你必须手动操作;为每个索引赋值,同时也不要忘记删除动态分配的内存…因此没有其他方法可以代替逐个赋值??如果C++11可用,甚至更容易:
list=new bool[7]{true,false,…,true}。如果不是,则选项是临时数组和
std::copy\n
。当然,它应该是一个
std::vector
,不过(需要注意的是它接受
v={…};
)。。您提到的在使用linux和gcc编译器时工作正常。。当我把我的操作系统切换到Windows并使用杀戮C++作为编译器时,你知道如何在C++中使用C++版本11来杀戮C++,这是假设你还在使用GCC。只需安装更新版本的GCC,并相应地更新Dev中的设置。或者告诉开发人员使用C++11,如果它可以与当前版本一起使用,而不是。还有,我说了
std::vector
,忘了你有
bool
s。这不是一个特别好的组合。老实说,这可能符合您的目的,而且
std::deque
是一个不错的选择;不会工作。@Sumeet,在C++11中可以。@Sumee这取决于您使用的编译器。新的C++标准是两年多以前采用的:@ VladfromMoscow:我得到了。@ SUMET,据我所知,C++ 2014还没有采用到目前为止。我认为你是正确的,但是在主函数中可以改变一个数组吗?像下面这样:int main(){list[1]=true;}确保这是可能的。你想阻止吗?然后在 BooList[7 ] =…/Cuff>部分之前放一个<代码> const <代码>。在Linux中使用G++是有效的,但是在Windows中,你提到的不起作用,可能是因为C++ 11与我的流血开发程序C++不兼容。无论如何,谢谢你的帮助。我的代码中没有C++11的具体内容。你的代码中一定有一些愚蠢的错误。你能粘贴它并发布链接吗?