clamchowder314
clamchowder314

Reputation: 223

How do I determine the number of items I have stored in an array?

I have a string array of size 5, and I have n elements in it. How could I determine n? I have tried sizeof(array)/sizeof(array[0]), but that returns the size of the array, which is 5. My code is:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string array[5];
    array[0] = "pie";
    array[1] = ":P";
    array[2] = "YELLOW";
    cout << sizeof(array)/sizeof(array[0]);
}

Upvotes: 1

Views: 129

Answers (4)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145259

A built-in array, called a raw array, has no support for a dynamic length. It has a fixed length. For a declared array that fixed length can be found in many ways, including the not-very-safe C idiom you used.


std::vector<Itemtype> from the standard library (header <vector>), manages a raw array plus a dynamic length. And that's apparently exactly what you need. The internal array, called the vector “buffer”, is automatically replaced with a larger one as needed, so you do not even have to specify the capacity up front – you can just add items to the vector.

Adding items to a vector is usually done via a method called push_back, and finding the current number of items, the length, is usually done via the size method, like this:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    vector<string> a;
    a.push_back( "pie" );
    a.push_back( ":P" );
    a.push_back( "YELLOW" );
    cout << a.size() << endl;
}

But since std::vector supports initialization via a brace initialization list, you do not have to use push_back for known initial items:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    vector<string> a = { "pie", ":P", "YELLOW" };
    cout << a.size() << endl;
}

A final refinement is to use const if it's not intended for that vector to change. This makes it easier to reason about the code. With const you see up front that none of all that code below will be changing this vector, so you can be sure of what values it provides at any point:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    vector<string> const a = { "pie", ":P", "YELLOW" };
    cout << a.size() << endl;
}

Disclaimer: code not touched by compiler's dirty hands.


Where you really want a fixed size array, you should preferably use std::array<Itemtype>. It works well with a range-based loop. And it has a size method, like vectors, so you can do things like this:

#include <algorithm>        // std::count
#include <iostream>
#include <string>           // std::string
#include <array>            // std::array
using namespace std;

int main()
{
    array<string, 5> const a = { "pie", ":P", "YELLOW" };
    cout << "Fixed size: " << a.size() << endl;
    int const n_empty = count( begin( a ), end( a ), "" );
    cout << "Non-empty strings: " << a.size() - n_empty << endl;
}

Upvotes: 6

Emil Laine
Emil Laine

Reputation: 42828

I have a string array of size 5, and I have n elements in it. How could I determine n?

n is 5. Your array has 5 elements, because you declared it to be an array of 5 strings. array[3] and array[4] are just empty strings (""), but they're still there, and completely valid elements.

If you want to count how many non-empty strings your array has, you could use e.g. std::count_if with a lambda:

int numberOfNonEmptyStrings = count_if(begin(array), end(array),
                                       [](string const& s) { return !s.empty(); });

or a handmade loop:

int numberOfNonEmptyStrings = 0;
for (auto const& s : array)
    if (!s.empty())
        ++numberOfNonEmptyStrings;

Upvotes: 8

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

Standard class std::string has methods size and length that return the number of characters in a string.

For example relative to your code snippet

array[0] = "pie";
array[1] = ":P";
array[2] = "YELLOW";

array[0].size() will return 3,

array[1].size() will return 2,

array[2],size() will return 6

Upvotes: 0

M.M
M.M

Reputation: 141554

You need to make a variable which holds the value of how many strings you have stored so far, and update that variable when you store a string.

Alternatively you could use a standard container instead of a C-style array:

#include <vector>

// ... in main

vector<string> array;
array.push_back("pie");
array.push_back(":P");
array.push_back("YELLOW");
cout << array.size() << '\n';

Upvotes: 2

Related Questions