c++ - 如何在结构数组中自动初始化最后一项?

标签 c++ windows struct

我将一个数组传递给一个函数,并用一些值对其进行全局初始化。 我在数组末尾使用空字符串来确定数组长度。

现在,有没有什么方法可以自动初始化数组,使其末尾有额外的空项,这样我就没有机会从那里忘记它了?就像 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/

相关文章:

windows - (git bash) 推送到 bitbucket 忽略 SSH key

c++ - while() 不同的输出;相同的变量

c++ - 无法将整数添加到 std::complex<double>

java - 如何处理无法将时间存储在 int 中?

c - 为什么它不起作用? Windows,使用 process.h

sql-server - 这个黑客想做什么?

c - 在 C 中设置 Struct 的字符串成员

c - 结构和位域的奇怪行为

c++ - 编译时指定g++依赖的位置

c++ - 在已发布的结构中添加构造函数(在 memcpy 中使用)是否安全?