问题描述
问题来自C ++ Primer 5th Edition上的练习:
The problem comes from an exercise on C++ Primer 5th Edition:
---------- ------原始问题----------
----------------Oringinal Question------------
首先,我尝试以下一些直接方法:
First I try the following somewhat direct way:
vector<char *> vec = {"Hello", "World"};
vec[0][0] = 'h';
但是在编译代码时我得到了警告:
But compiling the code I get a warning:
temp.cpp:11:43: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
vector<char *> vec = {"Hello", "World"};
^
运行./a.out我得到
And running the ./a.out I get a
Segmentation fault (core dumped)
我认为这是因为我尝试写入const char。所以我尝试另一种方式:
I think it is because I try to write to a const char. So I try another way:
char s1[] = "Hello", s2[] = "World";
vector<char *> vec = {s1, s2};
vec[0][0] = 'h';
这次可以。但这似乎有些乏味。
It is OK this time. But it seems a little tedious. Is there any other elegant way to initialize a vector with string literal?
推荐答案
这里是一种方法:
template <size_t N>
void append_literal(std::vector<char*>& v, const char (&str)[N]) {
char* p = new char[N];
memcpy(p, str, N);
v.push_back(p);
}
std::vector<char*> v;
append_literal(v, "Hello");
append_literal(v, "World");
只需记住:
void clear(std::vector<char*>& v) {
for (auto p : v) delete[] p;
}
尽管从问题的措辞来看,如果无论如何,它都是 vector< const char *>
,就好像它是 vector< char *>
(您复制时不会修改源,所以可以修改源也没关系),因此我会坚持练习,就像您刚做过一样:
Although from the wording of the question, syntactically it's the same work either way if it was a vector<const char*>
as if it were a vector<char*>
anyway (you're not modifying the source when you're copy, so doesn't matter if you could modify the source), so I would stick to the exercise as if you just did:
std::vector<const char*> v{"Hello", "World!"};
这篇关于如何优雅地初始化vector< char *>与字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!