簡體   English   中英

如何設置動態分配的數組的內容?

[英]How do you set the contents of a dynamically allocated array?

關於如何在主函數中分配全局指針和賦值,我有點困惑?

例如,這里是我的代碼示例

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={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 :)

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)

當你沒有數十或數百個元素時,這是最簡單的方法。

您可以使用bitset而不是數組。

#include <bitset>
#include <string>

std::bitset<7>* list;

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

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

為什么指針和動態分配? 為什么不簡單:

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

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

注意:數組的大小為7,但您只提供6個初始值。 你確定這是你想要的嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM