C++11 是否可以使用大括号初始值设定项删除结构数组?
我想知道:我有一个包含一些数据的结构数组。如果我想删除所有数据并将所有值保留在结构数组中作为默认值,是否可以使用C++11括号初始值设定项C++11 是否可以使用大括号初始值设定项删除结构数组?,c++11,C++11,我想知道:我有一个包含一些数据的结构数组。如果我想删除所有数据并将所有值保留在结构数组中作为默认值,是否可以使用C++11括号初始值设定项 #include <iostream> using namespace std; typedef struct{ int i; char a; }mystruct; int main() { mystruct structure[2]; structure{}; structure[0].i = 69;
#include <iostream>
using namespace std;
typedef struct{
int i;
char a;
}mystruct;
int main()
{
mystruct structure[2];
structure{};
structure[0].i = 69;
cout << structure[0].i << endl; // Should print 69
structure{};
cout << structure[0].i << endl; //Should print 0
return 0;
}
#包括
使用名称空间std;
类型定义结构{
int i;
字符a;
}我的结构;
int main()
{
mystruct结构[2];
结构{};
结构[0],i=69;
cout行结构{};
无效。如果要擦除数组中的所有结构,我不知道如何使用单个赋值。但是可以对单个数组元素使用此类赋值,例如
structure[0] = {};
可能的解决方案(如果可以包括算法
):
#包括
#包括
使用名称空间std;
类型定义结构{
int i;
字符a;
void erase(){i=0;a=0;}
}我的结构;
int main()
{
mystruct结构[2];
//结构{};
结构[0],i=69;
cout您的结构应该有一个默认构造函数,以便为其字段定义值
例如:
struct mystruct {
int a = 1;
char c = 'a';
};
mystruct s1;
assert(s1.a == 1);
然后,您可以通过指定默认构造值来“擦除”:
s1.a = 2;
s1 = mystruct();
assert(s1.a == 1);
对数组执行此操作是不可能的
编辑:
我应该提到,当equal分配非静态成员时,结构将不再是聚合。也就是说,聚合初始化不再可能:
mystruct x{1,2}; // fails to compile
虽然这会调用隐式默认构造函数:
mystruct x{};
原始数组在C++中不可复制:
#include,.尝试编译并运行吗?我现在无法编译它。这就是为什么我要问结构[0]。int
??我的意思是结构[0]。它没有“重新初始化”(看起来像你正在尝试的那样)。随着统一初始化的出现,你可以使用={…}进行分配
为赋值运算符的参数构造临时数组的语法。数组不能赋值给,std::array
s可以,因为它们有一个隐式赋值运算符。
mystruct x{};
#include <array>
#include <iostream>
using namespace std;
struct mystruct {
int i;
char a;
};
int main()
{
std::array<mystruct, 2> structure = {};
structure[0].i = 69;
cout << structure[0].i << endl; // Should print 69
structure = {};
cout << structure[0].i << endl; //Should print 0
}