<分区>
有时,当变量是对象集合(如数组或列表)时,很容易将其命名为复数。这样可以吗,还是我们应该始终坚持变量的单数名称?例如,一组汽车可以称为“汽车”或“汽车”
考虑另一个例子:
vector< string > students; // it is named as students rather singular student
students.push_back("Mark");
students.push_back("Steve");
// lets say we are using index to retrieve it, it does look
// a little clumsy
string current_student = students[0];
或者,我们可以将容器对象定义为单数,如下所示,但它现在看起来像是代表单个对象而不是学生集合吗?不过,它确实使使用索引看起来更好。
vector< string > student;
我个人喜欢的另一个选项是这样的:
vector< string > student_list;
我将“_list”(或者可以是驼峰符号)附加到集合变量名称(不管它是 vector 、列表还是 map )。这样,对象的名称是单数的,但它将自己标识为对象的集合。
哪个是更好的方式或约定,并且以上内容更具可读性?是否应该绝对避免使用复数名称?
还要考虑另一个更简单的例子,假设我们正在进行一项实验,我们以不同的时间间隔记录一天的温度 100 次,因此我们:
float temperatures[100]; // or temperature[100]? or temperature_list[100]?
或者甚至可能不同:
float temperature_data[100]?