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;
}