How do I find the length of an array?
Asked Answered
N

31

691

Is there a way to find how many values an array has? Detecting whether or not I've reached the end of an array would also work.

Navelwort answered 5/11, 2010 at 17:15 Comment(5)
Where is the array coming from? Usually functions that take arrays also take a length parameter to deal with this problem.Feigned
Well, I'm making a "mad libs" program that has an array with all the text, as well as the locations of nouns/verbs that the user has to fill in. I'd like to use a function to run through the entire array, replacing the "[noun]" and "[verb]" values with text entered by the user.Navelwort
Please note that in C arrays are not objects or structures. As such, they have no length parameter stored anywhere by default. If you want to work with them as objects in C++, use C++ objects std::vector, or std::array of C++11 if you can. If you have to use pointers, always pass length of array as second parameter to every function that works with it.Jewbaiting
If you're using C++20, then I have added answer for that as well. It could be missed easily as there are so many answers here.Ashlan
std::size()Paunchy
M
652

If you mean a C-style array, then you can do something like:

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

This doesn't work on pointers (i.e. it won't work for either of the following):

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

or:

void func(int *p)
{
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}

int a[7];
func(a);

In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector.

Meritocracy answered 5/11, 2010 at 17:18 Comment(13)
It also doesn't work if you pass the array to a different function and try to do it there :)Davy
@San : In that case create a function templateUnchaste
@San Jacinto: No, this works (on arrays) no matter what function you are in. Passing an array of variable length to a function as a parameter, however, is impossible (it decays into a pointer) - but if you pass an array inside a struct, then this works as expected.Bonni
Is there an easier way in C++11?Rohr
@OliverCharlesworth also if you passed the array by value to another function and tried it there, it won't work, right? The question is whyHearts
@Hearts - You can't pass an array by value in C or C++.Meritocracy
@Dineshkumar: it does work in C++. But in C++, you shouldn't need to do this.Meritocracy
Can someone explain what sizeof(p) and sizeof(*p) does?Anchor
@larryk: in what context? For a start, **p won't even compile for my code examples.Meritocracy
Why not sizeof(a) / sizeof(int) ?Yasmeen
The compiler errors regarding attempts to pass an array can be a little misleading, because the offending line would report no matching function for call to 'foo(int [2])' (types are listed verbatim, not decayed/etc.) and then cite couldn't deduce template parameter 'N' as the reason for substitution failure. Just putting it out there. Oh, and I should mention int[] myArray = {0, 1}; foo<2>(myArray); compiles and runs correctly, one rare exception (or rather nuance) to the rule. (C++11)Subbase
"because the above works for any type" It certainly doesn't. IMO the template solution should be much more prominent (read: included at all) in an accepted answer of this score! :)Fairminded
Does *( (&p + 1) - p )/sizeof(*p) work for the pointer case? (It's good for the array case.)Ultrafilter
S
189

As others have said, you can use the sizeof(arr)/sizeof(*arr), but this will give you the wrong answer for pointer types that aren't arrays.

template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }

This has the nice property of failing to compile for non-array types (Visual Studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).

You can also consider using std::array from C++11, which exposes its length with no overhead over a native C array.

C++17 has std::size() in the <iterator> header which does the same and works for STL containers too (thanks to @Jon C).

Spineless answered 6/8, 2013 at 11:4 Comment(10)
I get two errors when compiling (I'm not even trying to use it): error C2265: '<Unknown>' : reference to a zero-sized array is illegal error C2266: '<Unknown>' : reference to a non-constant bounded array is illegal What's the problem?Zonazonal
@Zonazonal can you supply a IDEone link or code sample so I can see? Either that or you can ask a question on SO since this code is well known to work (sample)Spineless
#18482609Zonazonal
Maybe it's too late, but I'm quite confused about the parameter syntax T (&)[N]. Could someone provide a hint to Google that up?Idiomorphic
@Idiomorphic it's how you write a reference to an array, see this answer. My version looks a bit different since I've left out the parameter's name since the parameter isn't used, only its type is needed. With a name it would be T(arg&)[N].Spineless
Thanks Motti! The left out parameter name was already clear to me. But unbelievable that I apparently had no use of refs/pointers to arrays ever before. And probably won't in the future, as such arrays are dying out even more.Idiomorphic
Why is your template soln not in the std lib???? I guess they assume that nobody uses arrays anymore now that there is std::vector and std::array????Hoisch
The old way of doing it in C++03 is described in this answer, which is useful if you don't have constexpr and need the compile time constant.Trigraph
If use C++11 is not std::extent a better solution???? en.cppreference.com/w/cpp/types/extentPoisoning
@IsaacPascual I wasn't familiar with extent, looking at it now there two characteristics with it that make it less useful than the function above (for this usecase). (1) It returns zero for pointers (rather than a compilation error). (2) It requires a type parameter so in order to check a variable you would have to do decltypeSpineless
C
128

While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size(), which returns the number of elements in both a std container or a C-style array. For example:

#include <iterator>

uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4
Cloying answered 31/1, 2018 at 13:46 Comment(2)
and with C++20, std::ssize() to get the std::size() of any range as a signed integer, useful for avoiding wrapping horror in loops, verbose casts to avoid the former, etc.Louettalough
You should note that this doesn't work for arrays passed into a function, you need to do it in the block where the array is defined and pass it as an additional parameter to the function.Carping
F
113

Doing sizeof myArray will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof myArray[0]

So, you get something like:

size_t LengthOfArray = sizeof myArray / sizeof myArray[0];

Since sizeof yields a size_t, the result LengthOfArray will also be of this type.

Fbi answered 5/11, 2010 at 17:20 Comment(4)
This is a very simple and easy solution to overcome what seems to be an age old problem.Terzetto
Doesn't work for C++ "new" arrays held by a pointer. You get the size of the pointer (4 bytes) or the size of its first element if you dereference it.Circumspection
@Circumspection yes, although anyone declaring the size of the array using the keyword new will already know the size of the array at runtime, so there's no need to use the sizeof operator to find the size of the array in that case. I'm sure you know that. This is just for the benefit of anyone who doesn't.Devoir
@surega It won't crashBanded
U
67

Is there a way to find how many values an array has?

Yes!

Try sizeof(array)/sizeof(array[0])

Detecting whether or not I've reached the end of an array would also work.

I dont see any way for this unless your array is an array of characters (i.e string).

P.S : In C++ always use std::vector. There are several inbuilt functions and an extended functionality.

Unchaste answered 5/11, 2010 at 17:19 Comment(5)
This wouldn't work for variable individual array sizesDevinne
+1 for vectors. There's very few strong cases to be using the old-style C++ arrays any more. Unless the size of the array is never going to change, but even then, you should use the array container class instead. It's better to use a container class like vector for dynamic array storage. The pros of using container classes far outweigh the cons of having to manage your own memory.Devoir
@MartynShutt When you are cache-bound, like in gamedev, you can't afford to use a vector sometimes.Coady
If an array has 0 elements, is array[0] legal then?Swagman
@Swagman 0 length arrays are illegal in C++. And even if they weren't, you're still allowed to evaluate the sizeof operator on array[0], since it doesn't actually evaluate it at runtime, just finds the type of it at compile time to get the size.Digger
C
36
#include <iostream>

int main ()
{
    using namespace std;
    int arr[] = {2, 7, 1, 111};
    auto array_length = end(arr) - begin(arr);
    cout << "Length of array: " << array_length << endl;
}
Centromere answered 5/8, 2014 at 16:51 Comment(2)
I believe this one only works for local variables that are on the stack.Circumspection
This is the best answer. @DragonLord, it works for member vars as well. See cpp.sh/92xvv.Itch
B
33

std::vector has a method size() which returns the number of elements in the vector.

(Yes, this is tongue-in-cheek answer)

Bonni answered 5/11, 2010 at 17:22 Comment(5)
Tongue in cheek it may be, but it's almost certainly the right approach.Finke
why do you say it's tongue in cheek? to me (a c++ newbie) it just seems like the right answer.Freytag
@dbliss It's tongue-in-cheek because the OP asked about the length of an array and eq- tells them how to get the length of a vector, which is a different thing in C++. However, it's correct at a deeper level because if you need to get the length at run time, a vector is a much better choice.Codycoe
You could also use std::list or some other containers I believe.Aspergillum
What's especially great about this answer is that you can initialize a vector or list with an array literal.Aspergillum
A
33

This is pretty much old and legendary question and there are already many amazing answers out there. But with time there are new functionalities being added to the languages, so we need to keep on updating things as per new features available.

I just noticed any one hasn't mentioned about C++20 yet. So thought to write answer.

C++20

In C++20, there is a new better way added to the standard library for finding the length of array i.e. std:ssize(). This function returns a signed value.

#include <iostream>

int main() {
    int arr[] = {1, 2, 3};
    std::cout << std::ssize(arr);
    return 0;
}

C++17

In C++17 there was a better way (at that time) for the same which is std::size() defined in iterator.

#include <iostream>
#include <iterator> // required for std::size

int main(){
    int arr[] = {1, 2, 3};
    std::cout << "Size is " << std::size(arr);
    return 0;
}

P.S. This method works for vector as well.

Old

This traditional approach is already mentioned in many other answers.

#include <iostream>

int main() {
    int array[] = { 1, 2, 3 };
    std::cout << sizeof(array) / sizeof(array[0]);
    return 0;
}

Just FYI, if you wonder why this approach doesn't work when array is passed to another function. The reason is,

An array is not passed by value in C++, instead the pointer to array is passed. As in some cases passing the whole arrays can be expensive operation. You can test this by passing the array to some function and make some changes to array there and then print the array in main again. You'll get updated results.

And as you would already know, the sizeof() function gives the number of bytes, so in other function it'll return the number of bytes allocated for the pointer rather than the whole array. So this approach doesn't work.

But I'm sure you can find a good way to do this, as per your requirement.

Happy Coding.

Ashlan answered 8/5, 2020 at 1:12 Comment(0)
S
29

Since C++11, some new templates are introduced to help reduce the pain when dealing with array length. All of them are defined in header <type_traits>.

  • std::rank<T>::value

    If T is an array type, provides the member constant value equal to the number of dimensions of the array. For any other type, value is 0.

  • std::extent<T, N>::value

    If T is an array type, provides the member constant value equal to the number of elements along the Nth dimension of the array, if N is in [0, std::rank<T>::value). For any other type, or if T is array of unknown bound along its first dimension and N is 0, value is 0.

  • std::remove_extent<T>::type

    If T is an array of some type X, provides the member typedef type equal to X, otherwise type is T. Note that if T is a multidimensional array, only the first dimension is removed.

  • std::remove_all_extents<T>::type

    If T is a multidimensional array of some type X, provides the member typedef type equal to X, otherwise type is T.

To get the length on any dimension of a multidimential array, decltype could be used to combine with std::extent. For example:

#include <iostream>
#include <type_traits> // std::remove_extent std::remove_all_extents std::rank std::extent

template<class T, size_t N>
constexpr size_t length(T(&)[N]) { return N; }

template<class T, size_t N>
constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }

int main()
{
    int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};

    // New way
    constexpr auto l1 = std::extent<decltype(a)>::value;     // 5
    constexpr auto l2 = std::extent<decltype(a), 1>::value;  // 4
    constexpr auto l3 = std::extent<decltype(a), 2>::value;  // 3
    constexpr auto l4 = std::extent<decltype(a), 3>::value;  // 0

    // Mixed way
    constexpr auto la = length(a);
    //constexpr auto lpa = length(*a);  // compile error
    //auto lpa = length(*a);  // get at runtime
    std::remove_extent<decltype(a)>::type pa;  // get at compile time
    //std::remove_reference<decltype(*a)>::type pa;  // same as above
    constexpr auto lpa = length(pa);
    std::cout << la << ' ' << lpa << '\n';

    // Old way
    constexpr auto la2 = sizeof(a) / sizeof(*a);
    constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
    std::cout << la2 << ' ' << lpa2 << '\n';

    return 0;
}

BTY, to get the total number of elements in a multidimentional array:

constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);

Or put it in a function template:

#include <iostream>
#include <type_traits>
    

template<class T>
constexpr size_t len(T &a)
{
    return sizeof(a) / sizeof(typename std::remove_all_extents<T>::type);
}

int main()
{
    int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
    constexpr auto ttt = len(a);
    int i;
    std::cout << ttt << ' ' << len(i) << '\n';
    
    return 0;
}

More examples of how to use them could be found by following the links.

Sconce answered 17/12, 2016 at 4:48 Comment(0)
C
19

There's also the TR1/C++11/C++17 way (see it Live on Coliru):

const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n       = std::extent<   decltype(s) >::value; // From <type_traits>
constexpr auto n2      = std::extent_v< decltype(s) >;        // C++17 shorthand

const auto     a    = std::array{ "1"s, "2"s, "3"s };   // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
constexpr auto size = std::tuple_size_v< decltype(a) >;

std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3
Clothier answered 2/6, 2014 at 13:0 Comment(0)
B
11

Instead of using the built in array function aka:

 int x[3] = {0, 1, 2};

you should use the array class and the array template. Try:

#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};

So now if you want to find the length of the array, all you have to do is using the size function in the array class.

Name_of_Array.size();

and that should return the length of elements in the array.

Befuddle answered 13/4, 2014 at 15:35 Comment(0)
N
8

ANSWER:

int number_of_elements = sizeof(array)/sizeof(array[0])

EXPLANATION:

Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:

int number_of_elements = sizeof(array)/sizeof(array[0]) which equates to

number_of_elements = 720/24

Note that you don't need to know what data type the array is, even if it's a custom data type.

Nace answered 29/11, 2019 at 15:50 Comment(2)
No need for this antiquated and error prone approach in 2019. https://mcmap.net/q/64735/-how-can-i-know-in-c-how-many-elements-an-array-contains-duplicate Also it's just a dupe of existing answers.Fairminded
It is, however, simple, eloquent, quick, low-demand, platform independent and eliminates the need to include vector or pointers. As far as duping other answers, there seems to be only one other answer with the same algorithm, and that one gives no explanation as to the underlying mechanics of the problem as my answer does. I respectfully suggest that, rather than being error-prone, it is quite robust.Nace
G
6

In C++, using the std::array class to declare an array, one can easily find the size of an array and also the last element.

#include<iostream>
#include<array>
int main()
{
    std::array<int,3> arr;

    //To find the size of the array
    std::cout<<arr.size()<<std::endl;

    //Accessing the last element
    auto it=arr.end();
    std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);

    return 0;
}

In fact, array class has a whole lot of other functions which let us use array a standard container.
Reference 1 to C++ std::array class
Reference 2 to std::array class
The examples in the references are helpful.

Glazunov answered 18/7, 2016 at 6:37 Comment(1)
Nice; I see you got many skills; and ... great approach. I think should write more answers to such famous questions myself, too ;-)Experimentalize
M
6

sizeof(array_name) gives the size of whole array and sizeof(int) gives the size of the data type of every array element.

So dividing the size of the whole array by the size of a single element of the array gives the length of the array.

 int array_name[] = {1, 2, 3, 4, 5, 6};
 int length = sizeof(array_name)/sizeof(int);
Millipede answered 9/9, 2017 at 9:31 Comment(1)
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestionBesmear
E
6

You have a bunch of options to be used to get a C array size.

int myArray[] = {0, 1, 2, 3, 4, 5, 7};

1) sizeof(<array>) / sizeof(<type>):

std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;

2) sizeof(<array>) / sizeof(*<array>):

std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;

3) sizeof(<array>) / sizeof(<array>[<element>]):

std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;
Elegit answered 29/4, 2019 at 18:59 Comment(0)
T
4

you can find the length of an Array by following:

int  arr[] = {1, 2, 3, 4, 5, 6}; 
int size = *(&arr + 1) - arr; 
cout << "Number of elements in arr[] is "<< size; 
return 0;
Tifanie answered 16/12, 2018 at 19:53 Comment(1)
Simplifies to (&arr)[1] - arr;Erenow
L
3

Here is one implementation of ArraySize from Google Protobuf.

#define GOOGLE_ARRAYSIZE(a) \
  ((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;

ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling.

Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t.

This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.

Laclair answered 19/11, 2015 at 8:58 Comment(2)
with an array of integer like this following : int nombres[5] = { 9, 3 }; this function returns 5 instead of 2.Flatways
GOOGLE_ARRAYSIZE(new int8_t) returns 8 on my test env, instead of raising error. Casted part seems redundant, not mentioning screaming C macro. sizeof(a) / sizeof(*a) works way enough as legacy solution.Maulstick
R
3

A good solution that uses generics:

template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }

Then simply call arraysize(_Array); to get the length of the array.

Source

Rudie answered 26/1, 2016 at 17:43 Comment(2)
@bobbogo Works with inline or constexpr, maybe you had inline off or it is optional? ideone.com/VxogJ4Erenow
@QentinUK constexpr is the fix. inline is not. constexpr is pretty modern though. Are you sure your test program is not using another modern feature, where you can declare a local array whose length is given by a variable? Try it with two global arrays.Amend
G
3

For old g++ compiler, you can do this

template <class T, size_t N>
char (&helper(T (&)[N]))[N];

#define arraysize(array) (sizeof(helper(array)))

int main() {
    int a[10];
    std::cout << arraysize(a) << std::endl;
    return 0;
}
Gina answered 30/11, 2016 at 3:21 Comment(1)
This is the correct answer. Very portable amongst C++ versions, does not work with pointers, plus the answer is available at compile timeAmend
A
3

For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number of values in an array by simply using the size() function.

Source Code:

string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);

If you cout the size_of_array the output will be:

>>> 4
Annulus answered 6/6, 2017 at 18:58 Comment(0)
D
2

Just a thought, but just decided to create a counter variable and store the array size in position [0]. I deleted most of the code I had in the function but you'll see after exiting the loop, prime[0] is assigned the final value of 'a'. I tried using vectors but VS Express 2013 didn't like that very much. Also make note that 'a' starts at one to avoid overwriting [0] and it's initialized in the beginning to avoid errors. I'm no expert, just thought I'd share.

int prime[] = {0};
int primes(int x, int y){
    using namespace std; int a = 1;
    for (int i = x; i <= y; i++){prime[a] = i; a++; }
    prime[0] = a; return 0;
}
Delossantos answered 3/4, 2014 at 5:41 Comment(0)
T
2

Simply you can use this snippet:

#include <iostream>
#include <string>
#include <array>

using namespace std;

int main()
{

  array<int,3> values;
  cout << "No. elements in valuea array: " << values.size() << " elements." << endl;
  cout << "sizeof(myints): " << sizeof(values) << endl;

}

and here is the reference : http://www.cplusplus.com/reference/array/array/size/

There answered 21/1, 2019 at 13:13 Comment(0)
E
2

You can use the sizeof() operator which is used for the same purpose.

see below the sample code

#include <iostream>
using namespace std;
int main() {
  int arr[] = {10,20,30,40,50,60};
  int arrSize = sizeof(arr)/sizeof(arr[0]);
  cout << "The size of the array is: " << arrSize;
  return 0;
}
Emrick answered 11/10, 2021 at 5:56 Comment(0)
E
1

I provide a tricky solution here:

You can always store length in the first element:

// malloc/new

arr[0] = length;
arr++;

// do anything. 
int len = *(arr-1);

free(--arr); 

The cost is you must --arr when invoke free

Eulogium answered 7/5, 2018 at 10:31 Comment(2)
That works only when arr is of a type compatible with int and the array is not longer than the maximum value of the type. E.g. Pascal strings are actually byte arrays using this trick; the maximum length of strings in Pascal is 255 characters.Cristobal
I suppose one could reserve say 8 bytes at the beginning of each array and use an unsigned long if they wanted to store objects. I think a vector is probably easier. But definitely a good solution for embedded systems.Blockish
R
1

here you go:

#include <iostream>
using namespace std;

int main() {
 int arr[] = {10,20,30,40,50,60};
 int arrSize = sizeof(arr)/sizeof(arr[0]);
 cout << "The size of the array is: " << arrSize;
return 0;
}
Raised answered 27/6, 2022 at 9:37 Comment(1)
This solution is nearly identical to the accepted answer. Please add comments on that if you believe it require modification.Shandy
D
1

You can use std::end(arr) - std::begin(arr) method in C++11 and later.

It works with C-style arrays, uninitialized arrays, std::array, std::vector and I think other containers works.

For example:

int arr`[] = { 10, 20, 30, 40 };

std::cout << std::end(nums) - std::begin(nums) << '\n';
Disbranch answered 20/7, 2023 at 14:21 Comment(0)
A
0

One of the most common reasons you would end up looking for this is because you want to pass an array to a function, and not have to pass another argument for its size. You would also generally like the array size to be dynamic. That array might contain objects, not primitives, and the objects maybe complex such that size_of() is a not safe option for calculating the count.

As others have suggested, consider using an std::vector or list, etc in instead of a primitive array. On old compilers, however, you still wouldn't have the final solution you probably want by doing simply that though, because populating the container requires a bunch of ugly push_back() lines. If you're like me, want a single line solution with anonymous objects involved.

If you go with STL container alternative to a primitive array, this SO post may be of use to you for ways to initialize it: What is the easiest way to initialize a std::vector with hardcoded elements?

Here's a method that I'm using for this which will work universally across compilers and platforms:

Create a struct or class as container for your collection of objects. Define an operator overload function for <<.

class MyObject;

struct MyObjectList
{
    std::list<MyObject> objects;
    MyObjectList& operator<<( const MyObject o )
    { 
        objects.push_back( o );
        return *this; 
    }
};

You can create functions which take your struct as a parameter, e.g.:

someFunc( MyObjectList &objects );

Then, you can call that function, like this:

someFunc( MyObjectList() << MyObject(1) <<  MyObject(2) <<  MyObject(3) );

That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!

Aspergillum answered 12/10, 2016 at 13:53 Comment(0)
P
0

Avoid using the type together with sizeof, as sizeof(array)/sizeof(char), suddenly gets corrupt if you change the type of the array.

In visual studio, you have the equivivalent if sizeof(array)/sizeof(*array). You can simply type _countof(array)

Pertussis answered 15/12, 2016 at 8:20 Comment(0)
K
-1

I personally would suggest (if you are unable to work with specialized functions for whatever reason) to first expand the arrays type compatibility past what you would normally use it as (if you were storing values ≥ 0:

unsigned int x[] -> int x[]

than you would make the array 1 element bigger than you need to make it. For the last element you would put some type that is included in the expanded type specifier but that you wouldn't normally use e.g. using the previous example the last element would be -1. This enables you (by using a for loop) to find the last element of an array.

Keek answered 12/11, 2017 at 21:44 Comment(0)
E
-2

I think this will work:

for(int i=0;array[i];i++)
{
 //do_something
}  
Embroil answered 30/5, 2022 at 13:8 Comment(0)
L
-4

Lets say you have an global array declared at the top of the page

int global[] = { 1, 2, 3, 4 };

To find out how many elements are there (in c++) in the array type the following code:

sizeof(global) / 4;

The sizeof(NAME_OF_ARRAY) / 4 will give you back the number of elements for the given array name.

Lithea answered 21/4, 2014 at 10:17 Comment(4)
sizeof(int) is platform dependent. There is no guarantee that it will be 4 (though this is the most common case)Hamper
Than you for addition.Lithea
Magic numbers!!Fairminded
Sorry but A. the size of an int depends on the platform, and B, this contributes absolutely nothing to the discussion.Adjunction

© 2022 - 2024 — McMap. All rights reserved.