如何在 C++ 中声明一个字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare an array of strings in C++?
提问by naumcho
I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?
我试图以最好的方式遍历静态字符串数组的所有元素。我希望能够在一行中声明它并轻松地从中添加/删除元素,而不必跟踪数字。听起来很简单,不是吗?
Possible non-solutions:
可能的非解决方案:
vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
Problems - no way to create the vector on one line with a list of strings
问题 - 无法使用字符串列表在一行上创建向量
Possible non-solution 2:
可能的非解决方案 2:
string list[] = {"abc", "xyz"};
Problems - no way to get the number of strings automatically (that I know of).
问题 - 无法自动获取字符串的数量(我知道)。
There must be an easy way of doing this.
必须有一个简单的方法来做到这一点。
回答by Anthony Cramp
C++ 11 added initialization lists to allow the following syntax:
C++ 11 添加了初始化列表以允许以下语法:
std::vector<std::string> v = {"Hello", "World"};
Support for this C++ 11 feature was added in at least GCC 4.4and only in Visual Studio 2013.
至少在GCC 4.4 中添加了对此 C++ 11 功能的支持,并且仅在Visual Studio 2013 中添加。
回答by Tyler
You can concisely initialize a vector<string>
from a statically-created char*
array:
您可以vector<string>
从静态创建的char*
数组简洁地初始化 a :
char* strarray[] = {"hey", "sup", "dogg"};
vector<string> strvector(strarray, strarray + 3);
This copies all the strings, by the way, so you use twice the memory. You can use Will Dean's suggestion to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
顺便说一下,这会复制所有字符串,因此您使用了两倍的内存。您可以使用 Will Dean 的建议,用 arraysize(str_array) 替换这里的幻数 3——尽管我记得有一些特殊情况,其中特定版本的 arraysize 可能会做一些坏事(抱歉,我无法立即记住细节) . 但它经常正常工作。
Also, if you're really gung-ho about the one line thingy, you can define a variadic macro so that a single line such as DEFINE_STR_VEC(strvector, "hi", "there", "everyone");
works.
此外,如果您真的很喜欢单行代码,您可以定义一个可变参数宏,以便像这样的单行DEFINE_STR_VEC(strvector, "hi", "there", "everyone");
工作。
回答by Will Dean
Problems - no way to get the number of strings automatically (that i know of).
问题 - 无法自动获取字符串的数量(我知道)。
There is a bog-standard way of doing this, which lots of people (including MS) define macros like arraysize
for:
有一种沼泽标准的方法可以做到这一点,很多人(包括 MS)定义了如下宏arraysize
:
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
回答by Will Dean
Declare an array of strings in C++ like this : char array_of_strings[][]
在 C++ 中声明一个字符串数组,如下所示: char array_of_strings[][]
For example : char array_of_strings[200][8192];
例如 : char array_of_strings[200][8192];
will hold 200 strings, each string having the size 8kb or 8192 bytes.
将保存 200 个字符串,每个字符串的大小为 8kb 或 8192 字节。
use strcpy(line[i],tempBuffer);
to put data in the array of strings.
用于strcpy(line[i],tempBuffer);
将数据放入字符串数组中。
回答by Eclipse
One possiblity is to use a NULL pointer as a flag value:
一种可能性是使用 NULL 指针作为标志值:
const char *list[] = {"dog", "cat", NULL};
for (char **iList = list; *iList != NULL; ++iList)
{
cout << *iList;
}
回答by Ross Smith
You can use the begin
and end
functions from the Boost range library to easily find the ends of a primitive array, and unlike the macro solution, this will give a compile error instead of broken behaviour if you accidentally apply it to a pointer.
您可以使用Boost 范围库中的begin
和end
函数轻松找到原始数组的末尾,并且与宏解决方案不同,如果您不小心将其应用于指针,这将产生编译错误而不是破坏行为。
const char* array[] = { "cat", "dog", "horse" };
vector<string> vec(begin(array), end(array));
回答by Shadow2531
Here's an example:
下面是一个例子:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
int main() {
const char* const list[] = {"zip", "zam", "bam"};
const size_t len = sizeof(list) / sizeof(list[0]);
for (size_t i = 0; i < len; ++i)
std::cout << list[i] << "\n";
const std::vector<string> v(list, list + len);
std::copy(v.begin(), v.end(), std::ostream_iterator<string>(std::cout, "\n"));
}
回答by Matthew Crumley
You can use Will Dean's suggestion [
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
您可以使用 Will Dean 的建议 [
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
] 用 arraysize(str_array) 替换这里的幻数 3——尽管我记得有一些特殊情况,在这种情况下,特定版本的 arraysize 可能会做一些坏事(对不起,我不记得细节了立即地)。但它经常正常工作。
The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[])
is really some_function(string *parameter)
.
它不起作用的情况是“数组”实际上只是一个指针,而不是实际的数组。此外,由于数组传递给函数的方式(转换为指向第一个元素的指针),即使签名看起来像一个数组,它也不能跨函数调用工作——some_function(string parameter[])
实际上是some_function(string *parameter)
.
回答by DrPizza
Instead of that macro, might I suggest this one:
而不是那个宏,我可以建议这个:
template<typename T, int N>
inline size_t array_size(T(&)[N])
{
return N;
}
#define ARRAY_SIZE(X) (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)
1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant.
1) 我们想用一个宏使它成为一个编译时常量;函数调用的结果不是编译时常量。
2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays.
2) 但是,我们不想使用宏,因为宏可能会被意外地用在指针上。该函数只能用于编译时数组。
So, we use the defined-ness of the function to make the macro "safe"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.
因此,我们使用函数的定义性来使宏“安全”;如果函数存在(即它的大小非零),那么我们使用上面的宏。如果函数不存在,我们将返回一个错误的值。
回答by DrPizza
#include <boost/foreach.hpp>
const char* list[] = {"abc", "xyz"};
BOOST_FOREACH(const char* str, list)
{
cout << str << endl;
}