How do I figure out the length of the array?

Asked 2 years ago, Updated 2 years ago, 109 views

How do I figure out how many elements can fit in an array?

It's not how many values I've allocated I'd like to know how many can fit.

c++ array size len

2022-09-21 23:17

1 Answers

For an array in style C, you can determine the size of the array in the following ways: *Not available for pointers (such as receiving dynamic assignments).

int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;

In most container classes,

The method is already defined.

std::array always has the same size() and max_size(/a).

std::vector lets you determine the number of elements in the current vector with vector:size().

#include <vector>
int main(){
    vector<int> myvector;
    myvector.insert(myvector.end(), 1);
    myvector.insert(myvector.end(), 2);
    myvector.insert(myvector.end(), 3);
    cout << myvector.size() << endl;
}


2022-09-21 23:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.