如何在struct数组中自动初始化最后一项?

New*_*bie 1 c++ windows struct

我正在将一个数组传递给一个函数,我正在使用一些值全局初始化它.我在数组的末尾使用空字符串来确定数组长度.

现在,有没有办法自动初始化数组以在其末尾有额外的空项目,所以我没有机会从那里忘记它?就像char []的工作方式一样,它会为最终的IIRC增加额外的空值.

这是我现在使用的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*ipp 6

在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);
}
Run Code Online (Sandbox Code Playgroud)