25

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

std::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?

einpoklum
  • 102,731
  • 48
  • 279
  • 553
turnt
  • 3,125
  • 5
  • 22
  • 37

10 Answers10

43

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:

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 sizeof operator 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.

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:

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:

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

Hope it helps. Good Luck!

  • Thank you! It now makes sense. – turnt Jan 13 '13 at 23:28
  • 1
    @user405725: str.empty returns 1 if str = "", so in your array-traversal code, the loop prematurely exits if any element is "", e.g. string array[] = {"Example", "", "Example3"}; – Gnubie Aug 20 '15 at 14:33
  • @user405725 :"It is not clear what do you mean by saying that size of elements vary" .I think he is trying to say that the length of each string in the array is different. eg : {"ab","abc","abcd"} these have lengths {1,2,3} – Chandra Shekhar Nov 18 '19 at 03:13
7

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.

  • @Vlad Lazarenko : You prefer Standard Library ? While, manual of sgi STL include containor (so std::array), I think STL is adapted to containors (like std::array). But, I don't think using "STL" or "Standard Library" is really important here (isn't the main subject, and use one or other don't disturb understanding). – Florian Blanchet Jan 14 '13 at 00:04
  • @FlorianBlanchet: Here is a good detailed explanation of why confusing the STL term is bad — http://stackoverflow.com/a/5205571/405725 –  Jan 14 '13 at 00:11
  • @Vlad Lazarenko : I know that, but except when it's really matter, I use one or other to the same meaning (I am in the For "STL" school of our linked post). Note that even committee use STL in some (recent) paper (not in standard), I pretty sure they refer to original STL extend with similar concept of C++11 (ie containors, algorithms and iterators of all C++11). It includes Stepanov ... – Florian Blanchet Jan 14 '13 at 00:36
4

There is standart function in stdlib library:

#include <stdlib.h>
static const char * const strings[] = {"str1", "str2", "str3"};
const int stringCount = _countof(strings);
vitperov
  • 1,287
  • 17
  • 18
  • 1
    Visual C++ supports this built-in macro called _countof to detect invalid inputs at compilation time but this solution is not standard. if you are building C++11, then this will not work – serup Feb 22 '17 at 14:44
4

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.

deerishi
  • 347
  • 3
  • 4
3

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

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.

Arslan Ahmad khan
  • 4,714
  • 1
  • 23
  • 31
1

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();
}
Mr Fooz
  • 103,571
  • 5
  • 68
  • 100
1

Mandatory advice: use 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::string has constant size, regardless of the actual string it holds.

Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
1

Here is a different example:

string array[] = {"Example", "Example2", "Example3"};
int numberofelements = 0; for(auto c: array) { numberofelements++; };
// now numberofelements will contain 3
serup
  • 3,295
  • 1
  • 28
  • 31
0
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/

Pygirl
  • 11,977
  • 4
  • 24
  • 38
0

no one actually counts duplicates so:

int count_duplicated(string cities[], size_t length) {
    string **cities_copy = new string *[length];
    for (size_t j = 0; j < length; j++)
        cities_copy[j] = &cities[j];

    string bom = "#";
    int counter = 0;
    for (size_t j = 0; j < length; j++) {
        string city = cities[j];
        bool is_duplicated = false;


        for (size_t k = j+1; k < length; k++) {
            if (city == *cities_copy[k]) {
                is_duplicated = true;
                cities_copy[k] = &bom;
            }
        }
        if (is_duplicated)
            counter++;
    }
    delete[] cities_copy;
    return counter;
}
Yuval Zilber
  • 119
  • 10