我将一个数组传递给一个函数,并用一些值对其进行全局初始化。 我在数组末尾使用空字符串来确定数组长度。
现在,有没有什么方法可以自动初始化数组,使其末尾有额外的空项,这样我就没有机会从那里忘记它了?就像 char[] 的工作原理一样,它会向末尾的 IIRC 添加额外的 null。
这是我现在使用的代码:
struct twostrings {
string s1, s2;
};
twostrings options[] = {
{"text1", "more text1"},
{"text2", "more text2"},
{"text3", "more text3"},
{""}, // tells that the array ends here
}
int get_len(twostrings opt[]){
int p = 0;
while(1){
if(opt[p].s1 == ""){
return p;
}
p++;
// now here is a possibility to go in infinite loop if i forgot the empty string.
// currently i have a code here that checks if p > 10000 and gives error message to me if i manage to forget that empty string in accident.
}
return p;
}
void dosomething(twostrings options[]){
int len = get_len(options);
for(int p = 0; p < len; p++){
// do stuff
}
}
int main(){ // yes its not valid written main function. dont bother about it.
dosomething(options);
}
最佳答案
传递 C 数组在 C++ 中不是很惯用。尝试使用 std::vector
代替:
#include <vector>
#include <string>
struct twostrings {
std::string s1, s2;
};
typedef std::vector<twostrings> option_type;
twostrings options[] = {
{"text1", "more text1"},
{"text2", "more text2"},
{"text3", "more text3"}
};
int get_len(const option_type& options){
return options.size();
}
void dosomething(const option_type& options){
int len = get_len(options);
for(int p = 0; p < len; p++){
// do stuff
}
}
int main() { // This main function is perfectly fine!
option_type opt_vector(options, options + (sizeof options / sizeof options[0]));
dosomething(opt_vector);
}
关于c++ - 如何在结构数组中自动初始化最后一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3228527/