在类中初始化向量

Initializing vector in class

本文关键字:向量 初始化      更新时间:2023-10-16

这段代码在类外运行良好 -

const char* list[] = {"Author: ", "Label: ", "Price: ", "Date: "};
vector<string> vlist(list, list+4);

但是当我把它放到类中时,它的行为就像一个函数 - 编译器给我错误"列表"不是一种类型,错误:预期的","或"..."。在"+"令牌等之前??

常见模式如下:

class MyClass {
public:
   template<class It>
   MyClass(It beg, It end) : vec(beg,end) { }
private:
   std::vector<std::string> vec;
 };
int main() {
   std::string s[] = { "abc", "bcd" };
   MyClass c(s, s+2);
};

您收到错误,因为类定义无法调用函数,只能声明它们。您可以使用类构造函数中的初始值设定项列表来解决此问题:

const char* list[] = { "Author: ", "Label: ", "Price: ", "Date: " };
class c
{
    vector<string> vlist;
    c() : vlist(list, list + 4) {}
}

数组大小不能在类内初始值设定项中自动推导。相反,您需要指定大小:

const char* list[4] = {"Author: ", "Label: ", "Price: ", "Date: "};

您的vlist成员可以从临时成员初始化:

vector<string> vlist = vector<string>(list, list + 4);

但这可能效率低下。最好在构造函数中初始化它,以避免临时性。

但是,您确定需要纯list阵列吗?因为如果没有,这样做要容易得多:

vector<string> list = {"Author: ", "Label: ", "Price: ", "Date: "};

此外,您需要确保已在编译器中启用了 C++11 模式。使用GCC或Clang,这将是-std=c++11-std=g++11(对于GNU扩展)编译器标志。

如果您使用的是 C++11,则可以通过初始值设定项列表直接初始化向量:

vector<string> vlist {"Author: ", "Label: ", "Price: ", "Date: "};

如果没有,您必须在构造函数中执行此操作,最有可能通过push_back

Class::Class() {
    vlist.push_back("Author :");
    vlist.push_back("Label :");
    vlist.push_back("Price :");
    vlist.push_back("Date :");
}

无论如何,如果最终要使用vector,创建中间 C 样式表是没有意义的。