How to find number of initialized elements in an array of structures?

Hey guys,
I am supposed to make a struct that holds make, model, year, etc for a car.
I named my struct Car. I have to create an array that holds these structure variables. I have to initialize the array to have an element size of 10 elements. However I need to fill the first 3 elements with the car struct variables by initializing. Then the 4th element will be set through user input.
Basically I am only using 4 elements out of the possible 10. How can I use this as my max size for a for loop that I use later in the code? Say that I have a for loop such as

for (int x = 0; x < SomeSize; x++)
{
//.......statements...
}

How can I find the number of initialized values in the array that stores the structure and its member variables?

I don't think I am intentionally allowed to have 'SomeSize' in that for loop above to be explicitly = 4 (total elements that I personally need).
The actual total number of element locations created for the array was 10 originally. So if I am displaying the array through an index with a for loop how can I set the x < SomeSize to be 4 and not 10. Without explicitly setting the SomeSize = 4?

Is there a length or sizeof or something along those lines that I can use to check the array of structs?
Last edited on
I have to initialize the array to have an element size of 10 elements. However I need to fill the first 3 elements with the car struct variables by initializing. Then the 4th element will be set through user input.
Basically I am only using 4 elements out of the possible 10.


It sounds to me that you are confusing the initializing of the struct with the initializing of the array.

When you put info into the array, could you just count how many have been put in as you or the user do it?

To find out how many elements of an array have been used, it is possible to assign a begin and end iterator to particular items in the array, then use a range based for loop. I will look for an example of that, I know that JLBorges has posted some of those.
Try this is if you need it:

http://en.cppreference.com/w/cpp/iterator/end

Regards :+)
> How can I find the number of initialized values in the array that stores the structure and its member variables?

Keep track of it in your code.

For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

struct car { std::string name ; /* ... */ };

int main()
{
    std::size_t MAX_SIZE = 10 ;
    car my_cars[MAX_SIZE] = { { "one" }, { "two" }, { "three" } } ;
    std::size_t actual_size = 3 ; // initial size is 3

    std::cout << "my cars: [ " ;
    for( std::size_t i = 0 ; i < actual_size ; ++i ) std::cout << my_cars[i].name << ' ' ;
    std::cout << "]\n" ;

    if( actual_size < MAX_SIZE ) // if there is space for another car
    {
        my_cars[actual_size] = { "four" } ; // add another car
        ++actual_size ; // the actual size is now one greater
    }

    std::cout << "my cars: [ " ;
    for( std::size_t i = 0 ; i < actual_size ; ++i ) std::cout << my_cars[i].name << ' ' ;
    std::cout << "]\n" ;
}


TheIdeasMan,

I don't think I am confusing the two ideas? Here is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// enumerated type
enum Purpose { BUSINESS, PERSONAL };

struct Car
{
	string carMake;
	string carModel;
	int yearModel;
	double cost;
	Purpose prps;

};
//function prototype
void displayCar(Car *, int);

int main()
{
	const int SIZE = 10;
	int purpose;
	
	Car carArray[SIZE] = {
		{"Ford", "Taurus", 1997, 21000, BUSINESS},
		{"Honda", "Accord", 1992, 11000, BUSINESS},
		{"Lamborghini", "Aventador", 2011, 390000, BUSINESS}
	};

	cout << "Please enter a Car Make: ";
	getline(cin, carArray[3].carMake);
	cout << "Please enter Car Model: ";
	getline(cin, carArray[3].carModel);
	cout << "Please enter Car Year: ";
	cin >> carArray[3].yearModel;
	cin.ignore(10000000, '\n');
	cout << "Please enter Car Cost: ";
	cin >> carArray[3].cost;
	cin.ignore(10000000, '\n');
	cout << "Please enter Car Purpose (1=BUSINESS, 2=PERSONAL) : ";
	cin >> purpose;
	cin.ignore(1000000, '\n');

	carArray[3].prps = static_cast <Purpose>(purpose); //static cast to input the purpose of the vehicle

	for (int index = 0; index < 4; index++)
	{
		cout << "\nCar #" << index + 1 << endl;
		displayCar(carArray, index);
	}
	return 0;
}

void displayCar(Car *vehicle, int element)
{
	cout << "Make: " << vehicle[element].carMake << endl;
	cout << "Model: " << vehicle[element].carModel << endl;
	cout << "Year: " << vehicle[element].yearModel << endl;
	cout << fixed << setprecision(2);
	cout << "Cost: " << vehicle[element].cost << endl;
	cout << "Purpose: ";

	switch (vehicle[element].prps)
	{
	case BUSINESS:
		cout << "Business" << endl;
		break;
	case PERSONAL:
		cout << "Personal" << endl;
		break;
	}
	cout << endl;
}


At this part in the code where I do a for loop to pass the index of the element and do the for loop to also call the displayCar function. I don't like that I am using index < 4.
Is there anything like length(), strlen(), or sizeof...So I could check up to what point in the array, the element location are initialized with values, and then use that for my condition in my for loop?

I am trying to find a way to find the number of currently initialized element locations. So 0 through 3 are occupied with data. Elements 0 through 2 are initialized when I created the array. Element 3 is created with user input.

1
2
3
4
5
for (int index = 0; index < 4; index++)
	{
		cout << "\nCar #" << index + 1 << endl;
		displayCar(carArray, index);
	}


Last edited on
Is there anything like length(), strlen(), or sizeof [to get the number of spaces occupied by assigned elements in the array].
No.

There are 10 elements in your array. At the point you initialize the array, three elements are initialized explicitly and the others are zero-initialized.

As you assign elements to the array, do so in sequence. When you assign a new element, place it at actual_size++.

1
2
3
4
5
6
7
8
9
10
int array[10] = { 1, 2, 3 };
int actual_size = 3; 

{ 
  int input; 
  std::cin >> input; 
  array[actual_size++] = input; 
}

for (int i = 0; i < actual_size; ++i) std::cout << array[i] << '\n';

See @JLBorges' example.

Since nobody has said so yet, you should prefer to use a vector instead of an array.
Keep track of it in your code.
Could there be any benefits from keeping track by a static member variable?
Also look at this snippet:
1
2
3
4
5
// enumerated type
enum Purpose { BUSINESS, PERSONAL };
...
    cout << "Please enter Car Purpose (1=BUSINESS, 2=PERSONAL) : ";
    cin >> purpose;


Do you realize that by default enums start at zero not one. If you want to start at one you need to specify this in the definition enum Purpose{BUSINESS = 1, PERSONAL};

Also, IMO, you're using the enum incorrectly (because of the use of the cast). Instead of having an enum type in your class I would recommend using an int then you wouldn't need that cast. Casting, IMO, should be a last resort.

Could there be any benefits from keeping track by a static member variable?

No, not really.

Since the array is external to the class/struct the "size" and "capacity" should also be held external to this class/struct. If you used a wrapper class you could then have a class that keeps track of the "size" and "capacity" along with insuring (by defining your destructor, copy constructor, assignment operator, etc,) that the memory is properly handled.


Since the array [...] is properly handled.

It makes eminent sense.
Many thanks, @jib.
Just for fun:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <string>

namespace car_pool
{
    struct car
    {
        std::string make;
        std::string model;
        int year = 0 ;
        // ...

        bool null() const { return make.empty() && model.empty() && year == 0 ; }
    };

    std::size_t size( const car* ntca ) // invariant: null terminated car array
    {
        auto p = ntca ;
        while( !p->null() ) ++p ;
        return p - ntca ;
    }

    // invariant: null terminated car array ntca is large enough to accommodate another car
    car* push_back( car* ntca, const car& a_car )
    {
        auto p = ntca ;
        while( !p->null() ) ++p ;

        *p = a_car ; // cat
        *++p = {} ; // null terminate

        return ntca ;
    }

    // invariant: size(ntca) != 0
    car* pop_back( car* ntca )
    {
        auto p = ntca ;
        while( !p->null() ) ++p ;

        *--p = {} ; // make the last car null
        return ntca ;
    }
    
    // etc.

    car* begin( car* ntca ) { return ntca ; }
    car* end( car* ntca ) { return ntca + size(ntca) ; }
    const car* begin( const car* ntca ) { return ntca ; }
    const car* end( const car* ntca ) { return ntca + size(ntca) ; }
}

int main()
{
    const std::size_t MAX_CARS = 10 ;
    car_pool::car my_cars[MAX_CARS+1] = // NTCA (null terminated car array)
    {
        {"Ford", "Taurus", 1997},
		{"Honda", "Accord", 1992},
		{"Lamborghini", "Aventador", 2011},
    };

    const std::size_t num_cars = size(my_cars) ;
    std::cout << "#cars == " << num_cars << '\n' ;

    std::cout << "-------------------------\n" ;

    push_back( my_cars, { "Ferrari", "Berlinetta", 2014 } ) ;
    std::cout << "#cars now == " << size(my_cars) << '\n' ;

    for( const auto& car : +my_cars ) // array-to-pointer-decay
        std::cout << car.make << ", " << car.model << " (" << car.year << ")\n" ;

    std::cout << "-------------------------\n" ;

    while( size(my_cars) > 2 ) pop_back(my_cars) ;
    std::cout << "#cars now == " << size(my_cars) << '\n' ;

    for( const auto& car : +my_cars ) // array-to-pointer-decay
        std::cout << car.make << ", " << car.model << " (" << car.year << ")\n" ;
}

http://coliru.stacked-crooked.com/a/38a1a34cf4dd20d2
Topic archived. No new replies allowed.