在 C++ 中查找字符串数组的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14308935/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:12:42  来源:igfitidea点击:

Finding the size of an String array in C++

c++carrays

提问by turnt

So I have an array of strings. Here's an example:

所以我有一个字符串数组。下面是一个例子:

string array[] = {"Example", "Example2", "Example3"};

Is there any way I can find the number of elements in an array like the one above. I can't use this method:

有什么方法可以找到像上面那样的数组中的元素数。我不能使用这种方法:

int numberofelements = sizeof(array)/sizeof(array[0]);

This is because the size of the elements vary. Is there another way?

这是因为元素的大小不同。还有其他方法吗?

回答by

Given your array of strings, you can most certainly use sizeof(array)/sizeof(array[0])to get its size and the following program works just fine:

给定您的字符串数组,您肯定可以使用它sizeof(array)/sizeof(array[0])来获取其大小,并且以下程序运行良好:

int main()
{
    std::string array[] = { "S1", "S2", "S3" };
    std::cout << "A number of elements in array is: "
              << sizeof(array)/sizeof(array[0]) << '\n';
    foo(array);
}

It is not clear what do you mean by saying that size of elements vary. Size of the elements of any array is always known at compiler-time, no exceptions.

不清楚你说元素的大小不同是什么意思。任何数组元素的大小在编译器时总是已知的,没有例外。

There are, however, situations where the above will not work. Consider the following example:

但是,在某些情况下,上述方法不起作用。考虑以下示例:

void foo(std::string array[])
{
    std::cout << "A number of elements in array is: "
              << sizeof(array)/sizeof(array[0]) << '\n';
}

The above code is doomed to fail. It might look a bit weird at first, but the reason for this is actually very simple — this is called array decaying. It means that every time you pass an array to a function, its type is automatically decayed to that of a pointer. So the above function is in fact an equivalent of this:

上面的代码注定要失败。乍一看可能有点奇怪,但其原因其实很简单——这就是所谓的数组衰减。这意味着每次将数组传递给函数时,其类型都会自动衰减为指针的类型。所以上面的函数实际上是等价的:

void foo(std::string *array)
{
}

And if in the first example the sizeofoperator returns the total size of an array, in the second example it returns the size of a pointer to that array, which is a totally different thing.

如果在第一个示例中sizeof运算符返回数组的总大小,在第二个示例中它返回指向该数组的指针的大小,这是完全不同的事情。

There are usually two ways people go about it. The first is to add a special “last” element of the array so that application can traverse the array until it sees the last element and calculate the array's length. String literals are the perfect example of this — every string literal ends with ‘\0' and you can always calculate its length. Here is an example:

人们通常有两种方法。第一个是添加一个特殊的数组的“最后”元素,以便应用程序可以遍历数组直到它看到最后一个元素并计算数组的长度。字符串字面量就是一个完美的例子——每个字符串字面量都以 '\0' 结尾,你总是可以计算出它的长度。下面是一个例子:

static void foo(const std::string *array)
{
    size_t i = 0;
    while (!array[i].empty())
        ++i;
    std::cout << "Array length is: " << i << std::endl;
}

The downside is obviously a need to traverse the array to determine its length. The second way it to always carry array length around, for example:

缺点显然是需要遍历数组以确定其长度。第二种方式始终携带数组长度,例如:

static void foo(const std::string *array, size_t length)
{
    // ...
}

void bar()
{
    std::string array[] = { "S1", "S2", "S3" };
    foo(array, sizeof(array)/sizeof(array[0]));
}

In C++, you can use a template to deduct array's length, for example:

在 C++ 中,您可以使用模板来扣除数组的长度,例如:

template <size_t array_length>
static void foo(const std::string (&array)[array_length])
{
    std::cout << "A number of elements in template array is: "
              << array_length << '\n';
}

All of the above applies to simple arrays that are built-in into the language. C++, on the other hand, provides a rich set of higher-level containers that give you a lot of flexibility. So you might want to consider using one of the containers that are available to you as part of C++ Standard Library. For a list of standard containers, see — http://en.cppreference.com/w/cpp/container

以上所有内容都适用于语言内置的简单数组。另一方面,C++ 提供了一组丰富的高级容器,为您提供了很大的灵活性。因此,您可能需要考虑使用作为 C++ 标准库的一部分提供给您的容器之一。有关标准容器的列表,请参阅 — http://en.cppreference.com/w/cpp/container

Hope it helps. Good Luck!

希望能帮助到你。祝你好运!

回答by Florian Blanchet

You could use a template function to achieved that :

您可以使用模板函数来实现:

#include<cstdlib>

template<class T, std::size_t n>
constexpr std::size_t size(T (&)[n])
{ return n; }

And like Luchian Grigore said, you should use STL containors. std::array if you want equivalent to static C array.

就像 Luchian Grigore 所说,你应该使用 STL 容器。std::array 如果你想等效于静态 C 数组。

回答by vitperov

There is standart function in stdliblibrary:

stdlib库中有标准函数:

#include <stdlib.h>
static const char * const strings[] = {"str1", "str2", "str3"};
const int stringCount = _countof(strings);

回答by deerishi

You can still use

你仍然可以使用

int numberofelements = sizeof(array)/sizeof(array[0]);

This is because sizeof(array)will return the sum of sizes of pointers corresponding to each string. sizeof(array[0])will return the size of the pointer corresponding to the first string. Thus, sizeof(array)/sizeof(array[0])returns the number of strings.

这是因为 sizeof(array)将返回对应于每个字符串的指针大小的总和。sizeof(array[0])将返回对应于第一个字符串的指针的大小。因此,sizeof(array)/sizeof(array[0])返回字符串的数量。

回答by serup

Here is a different example:

这是一个不同的例子:

string array[] = {"Example", "Example2", "Example3"};
int numberofelements = 0; for(auto c: array) { numberofelements++; };
// now numberofelements will contain 3

回答by Arslan Ahmad

We can find the number of elements of an array by simply using the size()function.

只需使用该size()函数,我们就可以找到数组的元素数。

Example Code:

示例代码:

string exampleArray[] = { "Example", "Example2", "Example3" };
    int size_of_array = size(exampleArray);

cout << "Number of elements in array = " << size_of_array << endl;

Output:

输出:

>>> Number of elements in array = 3

Hope it helps you.

希望对你有帮助。

回答by Pygirl

string s[] = {"apple","banana","cherry","berry","kiwi"};
int size = *(&s+1)-s;  
// OR
int size = sizeof(s)/sizeof(s[0]);

for more info regarding the first one: https://aticleworld.com/how-to-find-sizeof-array-in-cc-without-using-sizeof/

有关第一个的更多信息:https: //aticleworld.com/how-to-find-sizeof-array-in-cc-without-using-sizeof/

回答by Mr Fooz

Is this what you're looking for?

这是你要找的吗?

string array[] = {"Example", "Example2", "Example3"};
int num_chars = 0;
int num_strings = sizeof(array)/sizeof(array[0]);
for (int i = 0; i < num_strings; i++) {
    num_chars += array[i].size();
}

回答by Luchian Grigore

Mandatory advice: use std::vector<std::string>.

强制性建议:使用std::vector<std::string>.

A function like this can help:

像这样的函数可以帮助:

template<typename T, int sz>
int getSize(T (&) [sz])
{
    return sz;
}

Your method also works because the size of the elements don't vary - a std::stringhas constant size, regardless of the actual string it holds.

您的方法也有效,因为元素的大小不会改变 - astd::string具有恒定的大小,无论它包含的实际字符串如何。