2010-11-24 110 views
50

是否可以初始化一个向量数组的字符串。初始化一个向量数组的字符串

例如:

static std::vector<std::string> v; //声明为类成员

我以前static只是在初始化和字符串填充它。或者我应该只是填充它在构造函数中,如果它不能像我们常规数组那样初始化。

+0

什么初始化它,到底是什么?当然有很多种方法来初始化它。 – 2010-11-24 16:15:03

+0

`静态`不会“填充字符串”。 std :: vector是一个动态数据结构,并且被创建为空。 – Blastfurnace 2010-11-24 16:15:07

+0

在这种情况下,`static`意味着你的班级的多个实例共享相同的`v`,是你真正想要的吗? – birryree 2010-11-24 16:15:47

回答

55

class some_class { 
    static std::vector<std::string> v; // declaration 
}; 

const char *vinit[] = {"one", "two", "three"}; 

std::vector<std::string> some_class::v(vinit, end(vinit)); // definition 

end就是这样我就不必如果长度稍后改变,请写vinit+3并保持最新。其定义为:

template<typename T, size_t N> 
T * end(T (&ra)[N]) { 
    return ra + N; 
} 
14
const char* args[] = {"01", "02", "03", "04"}; 
std::vector<std::string> v(args, args + 4); 

而C++ 0x中,你可以利用std::initializer_list<>

排序的

http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists

+1

+1在C++ 0x提到简单的方法,太糟糕了MSVC 2010不支持这种行为呢:( – rubenvb 2010-11-24 16:45:21

5

一样@武汁:

const char* args[] = {"01", "02", "03", "04"}; 
std::vector<std::string> v(args, args + sizeof(args)/sizeof(args[0])); //get array size 
9

MSVC 2010解决方案,因为它不支持向量std::initializer_list<>,但它支持std::end

const char *args[] = {"hello", "world!"}; 
std::vector<std::string> v(args, std::end(args)); 
22

如果您正在使用cpp11(如需要可在-std=c++0x标志启用),那么你可以简单地初始化这样的载体:

// static std::vector<std::string> v; 
v = {"haha", "hehe"}; 
2

这是2017年,但这个线程是我的搜索引擎顶部今天下面的方法是优选的(初始化列表)

std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" }; 
std::vector<std::string> v({ "xyzzy", "plugh", "abracadabra" }); 
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" }; 

https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists