Static Arrays in C++ (std::array)

แชร์
ฝัง
  • เผยแพร่เมื่อ 29 ธ.ค. 2024

ความคิดเห็น • 323

  • @seditt5146
    @seditt5146 7 ปีที่แล้ว +728

    New drinking game: Take a shot everytime Cherno tells us he will cover it in a future video. :D

    • @iamk5686
      @iamk5686 5 ปีที่แล้ว +21

      I'd be falling out of my fucking chair.

    • @geiger21
      @geiger21 5 ปีที่แล้ว +57

      I know it's quite funny, maybe little annoying but really, he can't cover everything in one video. We should be thankful for him even making those videos for free, for us. Hope you guys understand him.

    • @matanshtepel1230
      @matanshtepel1230 4 ปีที่แล้ว +5

      ahhaha it's a suicide pact

    • @seditt5146
      @seditt5146 4 ปีที่แล้ว +8

      @@geiger21 Yeah it ain't no big deal to me man, I completely get it. Can't speak for others of course. I just thought it was funny and figured I would make light of it is all.

    • @matt-g-recovers
      @matt-g-recovers 3 ปีที่แล้ว +1

      I know right!
      It is comical and want to give him hell but I know how complicated this is and impossible to cover in a few minutes.
      I have to say he has covered quite a lot

  • @dXXPacmanXXb
    @dXXPacmanXXb 7 ปีที่แล้ว +418

    The hardest part in C++ is deciding which thing to use

    • @iamk5686
      @iamk5686 5 ปีที่แล้ว +15

      So true man. I guess it just comes with practice.

    • @geiger21
      @geiger21 5 ปีที่แล้ว +18

      that was big problem for me when I tried OpenGL. So I gave it a try in C. The difference is huge. I no longer need to decide whether to use std::vector, regular array, something else, I just need to use malloc and then eventually realloc. I like that simplicity.

    • @67hutch
      @67hutch 2 ปีที่แล้ว

      ^^^^^^^^

    • @sophiacristina
      @sophiacristina ปีที่แล้ว +2

      @@geiger21 Well, you can write C++ codes without using STL stuffs...

  • @LordVysh
    @LordVysh 6 ปีที่แล้ว +86

    Doesn't really matter what the size is.
    template
    void printArray(array a)
    {
    for (auto &i : a)
    {
    cout

    • @Dhruvpatel-gb4pv
      @Dhruvpatel-gb4pv 2 ปีที่แล้ว +4

      we can also use "auto&" in the function parameter.

    • @greysonyu5626
      @greysonyu5626 2 ปีที่แล้ว +2

      @@Dhruvpatel-gb4pv I actually don't know using auto in a parameter of a function is good or not, that sounds dangerous.

    • @Adam_Lyskawa
      @Adam_Lyskawa 2 ปีที่แล้ว +4

      @@Dhruvpatel-gb4pv I'm surprised, but it works. I just guess the compiler treats it as a kind of template. As long as you don't call it in the code, it doesn't check if the argument has a size function. Or if it provides [] operator. If you pass something that, when substituted for auto is not valid you just get a compiler error. I've just checked it - it behaves exactly like a template. I tried to create a header file and definition file containing a function with auto argument - it works only when it's defined in the header. So - you can use a proper template instead, or just leave auto. Compiler doesn't seem to care, however VS autocomplete prefers a template over auto.

    • @Sergeant_Mahdi
      @Sergeant_Mahdi ปีที่แล้ว

      @@Dhruvpatel-gb4pv didn't work for me, I don't know why

    • @jiranmo894
      @jiranmo894 ปีที่แล้ว

      @@Dhruvpatel-gb4pv I tried at first. But it doesn't work. Visual Studio threw an error.

  • @khatharrmalkavian3306
    @khatharrmalkavian3306 3 ปีที่แล้ว +124

    It's worth noting that the size() function is also constexpr, so it doesn't actually return 5, but rather the compiler will just replace the function call itself with 5, so something like:
    int s = ary.size();
    literally becomes
    int s = 5;
    with no function call at runtime.

    • @bbx5617
      @bbx5617 ปีที่แล้ว +1

      Thanks for the elaboration.

    • @toao_rainys
      @toao_rainys 11 หลายเดือนก่อน

      what’s the difference between inline and constexpr then?

    • @AndreiSokolov-k7j
      @AndreiSokolov-k7j 9 หลายเดือนก่อน

      thanks bro from steins gate

    • @khatharrmalkavian3306
      @khatharrmalkavian3306 9 หลายเดือนก่อน +7

      @@toao_rainyssorry for the delayed response. I didn't get a notification for this comment. inline means "please copy this code body into the places that call it instead of having it be an actual function call" and constexpr means "please calculate this out at compile time instead of figuring it out at runtime". This is strongly preferred to declaring constants with #define, etc. These days you don't really need to tell the compiler to inline, as it will do so when appropriate, and if it's not appropriate then it will ignore the directive even if you use it.

    • @RamunDev
      @RamunDev 5 หลายเดือนก่อน

      @@khatharrmalkavian3306Your explanation really helped, thanx

  • @Str33tF1ght1
    @Str33tF1ght1 7 ปีที่แล้ว +189

    the best solution in my opinion is this:
    template
    void PrintArray(const std::array& data) {
    for(int i = 0; i < data.size(); ++i) {
    }
    }

    • @alanyoung7045
      @alanyoung7045 5 ปีที่แล้ว +30

      will not work, replace it with

    • @fluffypinkpanda28
      @fluffypinkpanda28 5 ปีที่แล้ว +4

      @@alanyoung7045 Why so? Can you explain a bit more? I'm interested.

    • @rysiexo
      @rysiexo 5 ปีที่แล้ว +8

      template
      void printArray(T(&arr)[size])
      {
      }
      I know, I digged your comment up, yeay a golden shovel for me.

    • @CacheTaFace2
      @CacheTaFace2 4 ปีที่แล้ว +1

      @@rysiexo Hey, I'm new to templates. What is this syntax you are you using in the printArray parameters list (T(&arr)[size])?

    • @t0msa
      @t0msa 4 ปีที่แล้ว +2

      @@alanyoung7045 or just call it template, since size_t is just a typedef of unsigned integer

  • @yusinwu
    @yusinwu 6 หลายเดือนก่อน +2

    I think there is one crucial thing to note:
    Bounds checking with std::array [] operator is not guaranteed in debug mode. If anyone wants to make sure that they have bounds checking, they should use the .at() instead of the [] operator to access array elements since bounds checking with .at() method is required by c++ standard, but it is not the case for the [] operator. Bounds checking is always enabled with .at() method, regardless of the build type of your program, meaning it's built into the program even when compiling in release mode with compiler optimization.
    For MSVC, as @cherno has shown, the [] operator supports bounds checking and disables it during release builds. But for the compiler I am using, which is GCC, bounds checking is completely none-existent with [] operator.
    Anyways, thanks for your awesome videos. I have learned a lot from your content and your videos are with all seriousness life-changing to me.

  • @imankalyanmaity
    @imankalyanmaity 5 ปีที่แล้ว +50

    template
    void PrintArray(std::array& arr)
    {
    for (int i = 0; i < arr.size(); i++)
    {
    std::cout

    • @Cheddar2012
      @Cheddar2012 5 ปีที่แล้ว +22

      Imankalyan maity To improve on this, you could just use N in your for loop instead of arr.size(). This way, you do not incur any runtime cost of evaluating the size() function and instead just use an int literal.

    • @valizeth4073
      @valizeth4073 5 ปีที่แล้ว +3

      @@Cheddar2012 You should always used unsigned integers to keep the size, but nevertheless this was pretty much the solution.

    • @traywor
      @traywor 5 ปีที่แล้ว +20

      @@Cheddar2012 I bet arr.size() is a constexpr, so no runtime cost anyway.

    • @Nick-kq8pg
      @Nick-kq8pg 4 ปีที่แล้ว

      @@valizeth4073 Is there a cpu cost difference between signed and unsigned, or are you just saying out of principle?

    • @serkratos1216
      @serkratos1216 4 ปีที่แล้ว

      That doesn't work for me.

  • @Katniss218
    @Katniss218 4 ปีที่แล้ว +27

    "Stacks are stored in the arrays" - Cherno 2018. Well.. He *almost* said it.

  • @ToyMachine22122
    @ToyMachine22122 4 ปีที่แล้ว +2

    Without checking if this compiles, I think the answer to the question at 4:00 is
    template
    void PrintArray(const array& data) {
    // Do Stuff
    }
    Amirite?

    • @cockoroach
      @cockoroach 4 ปีที่แล้ว

      This is what I came up with, too. Unless we wanted to modify the array, but that’s an easy fix lol

  • @Sergeant_Mahdi
    @Sergeant_Mahdi ปีที่แล้ว

    explanation to your question:
    We use template to get the data and size
    template
    void print( const std::array & Data)
    {
    for ( T i : Data)
    std::cout

  • @expurple
    @expurple 4 ปีที่แล้ว +2

    As most of the guys here have guessed, the correct way to print an std::array is to use a template function.
    Hohewer, I need to show off, so here's a function to print any iterable collection passing its begin() and end()
    .
    template
    void printCollection(Iterator first, Iterator last)
    {
    for (auto it = first; it < last; ++it) {
    std::cout

    • @VarunSingh000
      @VarunSingh000 4 ปีที่แล้ว

      that's like . . . pythonic? idk

    • @expurple
      @expurple 4 ปีที่แล้ว

      @@VarunSingh000 ​ I don't know Python much, but this reminds me of C#'s methods for working with any IEmumerable collections. It's better than C++ STL way like in my example, as from the outside you just pass a collection itself, not these two separate "begin" and "end" things. And this collection later provides means to iterate over itself, but this happens INSIDE of a method. So iterators are hidden, as all implementation details should be.
      Python is a beautuful language, by the way. I just prefer typed languages

  • @kzm1934
    @kzm1934 3 ปีที่แล้ว +30

    I think the best solution to the array size function parameter function is to make use of auto declarations as function arguments from C++20. The below compiles perfectly (tested on gcc):
    #include
    #include
    void PrintArray(const auto& data)
    {
    std::cout

    • @mario_luis_dev
      @mario_luis_dev 2 ปีที่แล้ว +2

      you may want to reconsider using unnecessary if-else statements, as those seriously slow down your code.

    • @michaplucinski142
      @michaplucinski142 2 ปีที่แล้ว +1

      that's really good

    • @Adam_Lyskawa
      @Adam_Lyskawa 2 ปีที่แล้ว +2

      #include
      #include
      void test(auto& array) { for (auto &element : array) { std::cout

    • @thewelder3538
      @thewelder3538 ปีที่แล้ว

      ​@@germanassasin1046This is mostly untrue. If/else statements are nearly ALWAYS more performant if written branchless. The branch prediction will do most of the heavy lifting, but an if/else nearly always ends up as a test/je/jnz. In the above example the predictor is only "warming up" on such a small array so branchless will out perform if/else. On a larger array, well, now you start to get a win/break-even with branchless because the condition only occurs at the end of the array. But start to use variable sized arrays and branchless will always will however good your optimizing compiler is. The downside to branchless is really the complexity and understandable logic.

    • @thewelder3538
      @thewelder3538 ปีที่แล้ว

      I dislike this C++20 feature badly. Now you completely obscure what the incoming argument type is. It's one stage away from writing ... auto i = 0 and use auto everywhere.

  • @AdityaKumar-xw2yx
    @AdityaKumar-xw2yx 9 หลายเดือนก่อน

    Great!! so sensible. I would like to add two point, hope you will be aligned with me.
    1. Usage of static_assert and assert Functions with std::array:
    static_assert and other assertion functions work effectively with std::array because its result is a compile-time constant, and conditions are evaluated at compile time.
    Since std::array has a fixed size known at compile time, it is suitable for use in compile-time checks like static_assert.
    2. Applicability of constexpr with std::array and std::vector:
    constexpr can be effectively used with std::array as it is resolved at compile time and its size is known at compile time.
    On the other hand, std::vector is a runtime container, and its size is determined at runtime. Therefore, it is not suitable for use in constexpr contexts.

  • @DrAuraHxC
    @DrAuraHxC 7 ปีที่แล้ว +1

    using gsl::span of the Guidelines Support Library (is a Microsoft implementation of some of the types and functions described in the C++ Core Guidelines)

  • @עומרפריאל
    @עומרפריאל 4 ปีที่แล้ว

    In 4:17, You can use Template

  • @TheHeadHunter105
    @TheHeadHunter105 7 ปีที่แล้ว +109

    Have you considered making a tutorial on CMake? It might come in very useful for people looking to do cross-platform projects

    • @pedrocalorio1655
      @pedrocalorio1655 3 ปีที่แล้ว +1

      what is cross-platform projects? is it the same as mixing languages in a project?

    • @danielji2742
      @danielji2742 3 ปีที่แล้ว +6

      @@pedrocalorio1655 cross platform = windows, mac or linux + others

    • @felipebonilla7679
      @felipebonilla7679 ปีที่แล้ว +1

      @@pedrocalorio1655 It reffers than you don't depend on the IDE+OS to have a proper portable project. Due to Make is cross platform, and some IDEs are too (like VSCode), you can set up an environment of c++, make and visual studio code in any OS.

    • @thewelder3538
      @thewelder3538 ปีที่แล้ว

      CMake is just for people who aren't good enough to write a proper makefile.

  • @pc19937
    @pc19937 2 หลายเดือนก่อน

    4:03 I was randomly trying stuff, and the one that executed without compile time error was to make the printArray() function a template with size and types as parameters like so:
    template
    printArray(const std::array &array) {}

  • @TuanAnh-oj4ps
    @TuanAnh-oj4ps 5 ปีที่แล้ว +1

    template
    void PrintArray(T& a)
    {
    for (int i = 0; i < a.size(); i++)
    {
    std::cout

  • @DenysYeroshenko
    @DenysYeroshenko 3 ปีที่แล้ว

    Thank you, i am grateful that there is person such you. It really helps to figure out in c++

  • @koungmeng
    @koungmeng 5 ปีที่แล้ว +12

    you can use initializer list just like array:
    eg:
    std::array arr{1,2,3,4,5};
    or:
    std::array arr = {1,2,3,4,5};

  • @jannesopanen8032
    @jannesopanen8032 4 หลายเดือนก่อน

    For regular arrays, you can increase its size by one and add one special character at the end of it. Inside printArray() just loop until you hit special character and voila you have the correct size. You must use the type of the array element to calculate the correct size. Its not very fast I think but it works.

    • @jannesopanen8032
      @jannesopanen8032 4 หลายเดือนก่อน

      Or you can assign the size of the array to the first element of array.

  • @ashrafrasulov4353
    @ashrafrasulov4353 หลายเดือนก่อน

    Thank you for your lesson, it perfect. Super...

  • @Erebus2075
    @Erebus2075 5 ปีที่แล้ว +4

    awesome series.
    you should edit out the "challenges". not many watches youtube guides to be told to google or find another vid explaining the details of the vid you are watching to learn the details ;)
    but awesome c++ series ^^

  • @skewbinge6157
    @skewbinge6157 2 ปีที่แล้ว

    templates right away answer thanks to you man

  • @harshkn
    @harshkn 7 ปีที่แล้ว +2

    Solution to pass the size as param when using STL Array.
    Pass the size as a template.
    Example
    template
    void PrintArray(std::array& data) {
    /* do something* /
    }

  • @callingpizza1208
    @callingpizza1208 3 ปีที่แล้ว

    4:20 solution:
    template
    void PrintArray(std::array data)
    {
    for (int i = 0; i < _Size; i++)
    std::cout

  • @KingCitaldo125
    @KingCitaldo125 4 ปีที่แล้ว +2

    template
    void PrintArray(const array_type& m_array)
    {
    cout

  • @vikramkumarbathala5432
    @vikramkumarbathala5432 6 ปีที่แล้ว

    template
    void print(array&array){
    int size = array.size();
    for (int i = 0; i < size; i++){
    cout

  • @Deeredman4
    @Deeredman4 2 ปีที่แล้ว +2

    I think that if you don't know the size, you can either use a template or a macro but I think you have explicitly said that macros are mostly bad except for debugging and too much templating can become dubious. Based on my current knowledge I would probably use a template.

  • @kitlaw2494
    @kitlaw2494 5 ปีที่แล้ว +3

    You could write it using a template:
    This has the drawbacks of longer compile time (not that noticeable) and the exe file would be slightly larger because every different variant of that function needs to be created and compiled. Right?
    template
    void PrintArray(const std::array& data)

  • @bingusiswatching6335
    @bingusiswatching6335 8 หลายเดือนก่อน

    You can get the size of an array by dividing the total size by the size of one element which works cuz its contiguous memory:
    int size = sizeof(arr)/sizeof(arr[0])

  • @bessermt
    @bessermt 4 ปีที่แล้ว

    It is quite easy to get the size of a standard C array by sizeof(array)/sizeof(array[0]) or there's a C++ standard library method if you prefer.

    • @bessermt
      @bessermt 3 ปีที่แล้ว

      @Ralph Reilly A decayed array is not an array so your comment is a non sequitur.

  • @egor.okhterov
    @egor.okhterov 4 ปีที่แล้ว

    Iterator mimics pointer arithmetic, so std::array iterators are not an advantage over usual c++ array, but a way to get closer in functionality to the usual c++ array.
    All standard algorithms, like sort(), work on bare c++ arrays:
    int a[] = {3, 2, 1};
    sort(a, a + 3); // it works

  • @tamriel_x
    @tamriel_x 5 ปีที่แล้ว +2

    something strange is happening here.. when i turn on subtitles it only allows russian, when i change it to auto gen russian to >>English, the only subtitle that comes up is "high five i have beyonce and funding"+"intensive and accessories and frill"+ "new style extract"+"whats the trouble"+ "he contracted st"+"bad girl i like slow mo guys"

  • @VanYang-eq5ub
    @VanYang-eq5ub ปีที่แล้ว

    template
    void func(const std::array& arr) {
    cout

  • @PythonPlusPlus
    @PythonPlusPlus 6 ปีที่แล้ว +4

    To get around the problem of not knowing the size of the array, you can add a template to your function which asks for the array size.

    • @swackyduk
      @swackyduk ปีที่แล้ว

      then of course use a for(auto& element : array) loop

  • @rcookie5128
    @rcookie5128 7 ปีที่แล้ว

    nice overview once again! ^^

  • @avocadopeel7536
    @avocadopeel7536 3 ปีที่แล้ว +1

    To the people suggesting templates with std::array, why not
    template
    void PrintArray(int *array) {
    for(int i=0; i

  • @vivekkumar-bq2ln
    @vivekkumar-bq2ln 3 ปีที่แล้ว +2

    Isn't adding too many std::array with varying sizes (say for the same data type) will increase the size of program memory (code segment)? The size stored as a literal in the compiled program and that template is for every size type at the cost of program size.

  • @aryanwolfox6390
    @aryanwolfox6390 3 ปีที่แล้ว +1

    Answer is by template :
    template
    void printArray(const std::array< T, size >&data)
    {
    // now we don’t need to pass type and size explicitly
    }

  • @michaelswahla4927
    @michaelswahla4927 11 หลายเดือนก่อน

    I attempted the challenge using a template function and extra feature for type of the array too:
    template
    void printArray(const std::array& arr) {
    for(dataType& value : arr) {
    std::cout

  • @fireballgfx
    @fireballgfx ปีที่แล้ว

    template void foo(std::array){...}

  •  7 ปีที่แล้ว +8

    I think you should make qt and qt-opengl tutorial.

  •  4 ปีที่แล้ว

    My solution would be a bit more general purpose:
    template
    void PrintArray(const std::array& array)
    {
    for(auto& x : array)
    std::cout

  • @RiverBeard
    @RiverBeard 4 ปีที่แล้ว

    can we just print until we hit the terminating zero? 4:20

  • @169mayan
    @169mayan 5 ปีที่แล้ว +5

    My Solution:
    template // cant use int instead of size_t because the size of container(std::array) is in *size_t*
    void printData(std::array& data1)
    {
    for(auto val : data1)
    std::cout

  • @goldenlava1019
    @goldenlava1019 4 ปีที่แล้ว +2

    Templates (:
    template
    void PrintArray(const std::array& data)
    {
    for (int i = 0; i < data.size(); i++)
    std::cout

  • @CriticRoshun
    @CriticRoshun 3 ปีที่แล้ว

    template
    void PrintArray(const T& arr){
    for (int i=0; i

  • @cocbuilds
    @cocbuilds 6 ปีที่แล้ว +2

    To answer 4:20, would you just not specify the size in the angular brackets? Or perhaps you'd make PrintArray a function taking a template argument?

    • @tomhaswell6283
      @tomhaswell6283 4 ปีที่แล้ว

      template is correct. Otherwise your code would get pretty messy.

  • @mamertvonn
    @mamertvonn 4 ปีที่แล้ว

    3:50 so does anyone know the answer? Pls enlighten me. Is it just templates?

  • @ashrafrasulov4353
    @ashrafrasulov4353 หลายเดือนก่อน

    my version of the answer to the question is: what if I recreate it whenever I use or change it every time, like a static variable. creating a new pointer and pointing to the new pointer then removing an array old version.

  • @valizeth4073
    @valizeth4073 5 ปีที่แล้ว

    Just gonna mention that the size is almost impossible to determain for a pointer, there are tricks but they are definitivly not guaranteed to reveal the size. That's why you always write: (int argc, char** argv). The argv is just an array of string, but the size is unknown, so argc is passed as the size for argv.

  • @cactusmamelu313
    @cactusmamelu313 3 ปีที่แล้ว

    Forty degree, finally a sane person that doesn't use square feet by crate inch type of unit !

  • @mattt2684
    @mattt2684 6 ปีที่แล้ว +6

    4:18 maybe try using a void* to the reference of the array and then go from there...

    • @Netrole
      @Netrole 4 ปีที่แล้ว +1

      Go how far though? That is the question, and also why we need the length

  • @platin2148
    @platin2148 7 ปีที่แล้ว +4

    You should probably use complier explorer for showing code that is compiled. Real difference between an Fixed size array and a pool allocator?

  • @gage2560
    @gage2560 7 ปีที่แล้ว +2

    template
    void func(std::array& array)
    {
    std::cout

    • @nathanm988
      @nathanm988 7 ปีที่แล้ว

      THAT IS GENIUS!

    • @PythonPlusPlus
      @PythonPlusPlus 6 ปีที่แล้ว +1

      This would work, however you should probably use something other than T because is is meant for Type names.

    • @misana77
      @misana77 5 ปีที่แล้ว

      And yeah, it's not necessary to pass the template argument to a template function, because the compiler calculates it itself at the compile time. However, you have to pass template arguments, when you create an object of a template class.
      So, the function call like this - func(testing) - will work just fine.

  • @kishanthakur__7813
    @kishanthakur__7813 3 หลายเดือนก่อน

    template
    void PrintData(const std::array& data)
    {
    for(int i = 0; i < data.size(); ++i)
    {
    std::cout

  • @venkateswarans1012
    @venkateswarans1012 5 ปีที่แล้ว +1

    We should use template to pass STL array with size to function in
    C++11 or we can use auto keyword in C++17

  • @MartialBarts
    @MartialBarts 7 ปีที่แล้ว +3

    When can we expect a video on namespaces? They seem like such a powerful tool especially when wanting to optionally include libraries. I am sure there are many other uses beyond just code structure.
    Other topic I would like to see is the exploration of extern "C" to prevent name mangling. Why is this used so much? What benefits/drawbacks does it provide.
    Thanks for the vids. Been a good supplement to my learning by providing good context to concepts.

    • @The_Codemaster144k
      @The_Codemaster144k 2 ปีที่แล้ว +1

      Not sure if you still have this problem 4 years later, but he has a dedicated video in the learning C++ series that you should take a look at. Coming from C# namespaces used to confuse me in C++

  • @KillzoneKid
    @KillzoneKid 7 ปีที่แล้ว

    template void PrintArray(std::array array)...

  • @LucidStew
    @LucidStew 6 ปีที่แล้ว +3

    10mins is a good length. Didn't feel short.

  • @Vasily.Vasilyev
    @Vasily.Vasilyev 7 ปีที่แล้ว +12

    Another solution for printing most of STL containers (except std::map):
    #include
    #include
    #include
    #include
    #include
    #include
    template
    void print(const Container& container)
    {
    std::copy(std::begin(container), std::end(container), std::ostream_iterator(std::cout, " "));
    }
    int main()
    {
    std::array arr{ 1, 2, 3, 4, 5};
    std::vector vec{ 6, 7, 8, 9, 10 };
    std::list lst{ 11, 12, 13, 14, 15 };
    std::set st{ 16, 17, 18, 19, 20 };
    print(arr);
    std::cout

    • @Vasily.Vasilyev
      @Vasily.Vasilyev 7 ปีที่แล้ว

      Yeah, thanks) Fixed it.
      I forgot that *value_type* of *std::set* is Key in constructor. But *std::map* needs additional processing anyway.

  • @voidnull7329
    @voidnull7329 4 ปีที่แล้ว +1

    Make a video on naming conventions for c++ like function name ,class ,private member,..etc

  • @yufang9109
    @yufang9109 4 ปีที่แล้ว +1

    A solution to handle both value type and array size
    template
    void printArray(const std::array& array)
    {
    for (int i = 0; i < N; i++)
    {
    std::cout

  • @rakeshtm2750
    @rakeshtm2750 4 ปีที่แล้ว

    We can use "auto" in function parameter as of C++14 instead of mentioning the type name and array size.

  • @misana77
    @misana77 5 ปีที่แล้ว

    You're not right. You can use standard algorithms with C-style array. For begin iterator you use a name of an array and for the end one - name + size.
    To use differently sized std::array's in one function you need to make this function a template one like this:
    template
    void func(const std::array arr);
    But you can use it for C-style arrays either:
    template
    void func(int arr[size]);
    But yeah, the debugging layout is useful

  • @milosorevic927
    @milosorevic927 ปีที่แล้ว

    void PrintArray(const auto& data) {
    for (const auto& value : data) {
    std::cout

  • @serkratos1216
    @serkratos1216 4 ปีที่แล้ว

    2:38 lol the captions.

  • @CoolDude911
    @CoolDude911 5 ปีที่แล้ว

    Arrays should be constant at compile time so whatever size the array is should be tied to some constant.

  • @samiam4039
    @samiam4039 7 ปีที่แล้ว

    obj c stl array constructs allow for compile time checking for array sizes and types in its functions.

  • @VanYang-eq5ub
    @VanYang-eq5ub ปีที่แล้ว

    it totally can work pretty well。

  • @valrossenOliver
    @valrossenOliver 7 ปีที่แล้ว +13

    My solution looks like something like this:
    (in this case its always ints, but you could do a typename version too)
    template
    void PrintArraySize(const std::array& data)
    {
    for (size_t i = 0; i < data.size(); i++)
    {
    std::cout

    • @valrossenOliver
      @valrossenOliver 7 ปีที่แล้ว +5

      For a version that takes any type we could write:
      template
      void PrintArraySize(const std::array& data)
      {
      for (size_t i = 0; i < data.size(); i++)
      {
      std::cout

    • @tommymuir6750
      @tommymuir6750 6 ปีที่แล้ว +1

      I realise this video is 10 months old, but I wanted to point out you can just use the auto keyword, no template needed:
      void PrintArray(const auto& data)
      {
      for (int i = 0; i < data.size(); i++)
      {
      cout

    • @gravity5898
      @gravity5898 6 ปีที่แล้ว +2

      @@tommymuir6750 I too tried this but msvc says that 'auto' keyword isn't allowed here.

    • @JimitRupani
      @JimitRupani 5 ปีที่แล้ว

      @@tommymuir6750 why constant I mean why not without constant. Anyway array will be in local scope so why to use constant in particular

  • @aryesegal1988
    @aryesegal1988 7 ปีที่แล้ว +1

    Cherno, bruh, correct me if I'm wrong but isn't returning 5 actaully means the function stores this constant internally as an int? So yeah, it is not a variable in the sense that you can not change its value, but still, it must store this value somewhere. (Perhaps as a 'const int'.)
    I mean, what does a compiler do when it encounters a constant like 5 through code? Doesn't it store it somewhere?
    Thanks for all the effort you're taking to share with us. This channel is awesome! And fix that AC! ;)

    • @Tom-um7zd
      @Tom-um7zd 6 ปีที่แล้ว

      It is just CPU instruction, so its hard-coded in your binary file. It wont be stored in memory at all.
      compiler gives you just assembly code, something like:
      add ax, 42
      (add 42 (2E) to accumulator)
      which looks in binary file like this (HEX):
      05 2A 00

  • @breakmon218
    @breakmon218 6 ปีที่แล้ว +5

    Are you going to talk about linked list? :))

  • @munjalparmar8455
    @munjalparmar8455 9 หลายเดือนก่อน

    can we have template there.

  • @rickygable
    @rickygable 6 ปีที่แล้ว

    template
    void PrintContainer(const T& container) {
    for(int i=0; i < container.size(); i++ ){
    std::cout

  • @chainonsmanquants1630
    @chainonsmanquants1630 4 ปีที่แล้ว

    Thanks

  • @r0n1n-
    @r0n1n- 7 ปีที่แล้ว +3

    {
    cout

  • @maga8289
    @maga8289 3 ปีที่แล้ว

    You can pass the address of std::array as void* ptr in function argument and by knowning the offset of size inside array class you can find it like this: int size = *(int*)(uintptr_t(ptr) + *size_offset*)

    • @ДмитроПрищепа-д3я
      @ДмитроПрищепа-д3я 2 ปีที่แล้ว

      you surely can, but why? You can just make that a template function and pass a reference to the array and make the compiler infer the size.

    • @maga8289
      @maga8289 2 ปีที่แล้ว

      @@ДмитроПрищепа-д3я Да, меня что-то понесло. Можно и так)

    • @thewelder3538
      @thewelder3538 ปีที่แล้ว

      ​@@ДмитроПрищепа-д3яYou could do this, but the problem is that you're relying on the internal structure of the array object. Now whilst this might work, if you used a different compiler that lays out the object structure differently, it'll break badly.
      I'm not objecting completely because using a pointer is easily the most efficient way of passing the array object. The problem really is that inside the function, you have to cast it back and as a void pointer, you don't know its actual type. A template is a good idea, but it's only really the same as having a function take an array and size argument.

  • @OneShot_cest_mieux
    @OneShot_cest_mieux 5 ปีที่แล้ว +2

    How do writing
    template
    void PrintArray(const std::array& data)
    {...}
    and then
    PrintArray(data);
    will work ? I thought it should be wrote like that:
    PrintArray(data);
    Sorry if my english is bad I am french

    • @zlfu3020
      @zlfu3020 5 ปีที่แล้ว +1

      As far as I understand, value of size is deduced before compiling, so you dont have to specify.

    • @Luca-hn2ml
      @Luca-hn2ml 4 ปีที่แล้ว

      Class template argument deduction (CTAD) (since C++17):
      As Zhuolin Fu said, in THIS case the compiler is going to deduce the template argument from the type of "data".

  • @jovialcupid9687
    @jovialcupid9687 ปีที่แล้ว

    Challenge accepted:
    Use for each or just calculate size of the array. I'm I stupid and I'm not understanding something or what?
    Void printArray( int* arr)
    {
    for (auto i: arr) serial.println(i);
    // or
    For (int I = 0; I < sizeof(arr) / sizeof(int); i++)
    //Int is default cuz this is parameter type, u can make template out of it
    }

  • @mario_luis_dev
    @mario_luis_dev 2 ปีที่แล้ว

    I don’t think std::arrays do bounds checking using the overloaded [] operator. You would have to use the `at(i)` method instead of [i].

  • @creatork999
    @creatork999 4 ปีที่แล้ว

    template
    void Print(std::array& arr) {
    for (int i = 0; i < Size; i++) {
    println(arr[i]);
    }
    }

  • @benjitigg3490
    @benjitigg3490 4 ปีที่แล้ว

    my solution is:
    template
    void PrintArray(const std::array & data)
    {
    for (int i= 0; i < N; I++)
    {
    std::cout

  • @DarKingAmir
    @DarKingAmir 4 ปีที่แล้ว

    intusiastic!!!!!!!!!!!

  • @Ghasakable
    @Ghasakable 10 หลายเดือนก่อน

    Passing as a const int for the size as
    const int size = 5;
    void print_std_array(std::array my_array) {
    for (size_t i = 0; i < my_array.size(); i++) {
    std::cout

  • @OneShot_cest_mieux
    @OneShot_cest_mieux 5 ปีที่แล้ว

    I do have questions about performances:
    1/ Imagine you want to create 1000 array with differents size. Because of the template behavior, wouldn't it copy theses 500 lines of code every time and makes your executable much much larger ?
    2/ When you do data.size() in the for loop, because it is not an "inline" function doesn't it makes a function call every time it reaches data.size(), making your code slower ? Same question with the operator[] which is a not inline function
    Thank you for thoses who will answer me and sorry for my bad english, I am french and I try to improve myself.

  • @Joscha1996
    @Joscha1996 6 ปีที่แล้ว

    So i figured i could use
    void PrintArray(auto array) {
    ...
    }
    to print any array.
    However... I'm not sure why, but this seems to have problems as my IDE marks it as error and my compiler yells at me for using it even so the code compiled and worked just fine.
    Compiler said: 'warning: use of 'auto' in parameter declaration only available with -fconcepts'

  • @HappyGoKaboom
    @HappyGoKaboom 6 ปีที่แล้ว

    A Template solution works nicely.
    template
    void printArray(const std::array& array) {
    for (size_t i = 0; i < S; ++i) { // pre increment eliminates a copy that post increment performs. a little faster
    std::cout

  • @jameshetfield4144
    @jameshetfield4144 5 ปีที่แล้ว +1

    Hey Cherno sorry for posting this late
    4:05
    Templates?

    • @inx1819
      @inx1819 4 ปีที่แล้ว +1

      yes

  • @tralamysamy8465
    @tralamysamy8465 3 ปีที่แล้ว

    The best solution with C++ 20 ➡
    void PrintArray (const std::span& data) {
    for (auto& : data) {
    std::cout

  • @Nick-tv5pu
    @Nick-tv5pu 4 ปีที่แล้ว

    4:15 Using a template?

  • @seba_mestre_ips
    @seba_mestre_ips 7 ปีที่แล้ว +17

    template
    void printArray (const std::array & data){
    for(int i = 0; i < data.size(); i++){
    std::cout

    • @jamesmnguyen
      @jamesmnguyen 7 ปีที่แล้ว +4

      Why do you have a redundant return statement?

    • @seba_mestre_ips
      @seba_mestre_ips 7 ปีที่แล้ว

      James Nguyen because i like it

    • @EnrageGames
      @EnrageGames 7 ปีที่แล้ว

      Over specialised method signature - see my answer below.

    • @TheReficul
      @TheReficul 7 ปีที่แล้ว

      Enrage Your answer is less safe though. If you pass in for example an std::map accidentally things will go bad real quick.

    • @nmmm2000
      @nmmm2000 7 ปีที่แล้ว +1

      // simpler and works with std::vector / std::deque too
      // also C++11 for
      template
      void printArray (const T& data){
      for(auto &element : data)
      std::cout

  • @rishimenon5632
    @rishimenon5632 4 ปีที่แล้ว

    Since its a template, it produces different copies, right? So would the intermediate object file and/or the executable file occupy more space?

  • @jordanjackson8867
    @jordanjackson8867 7 ปีที่แล้ว

    template
    void PrintArray(const std::array& data)
    {
    for (unsigned int i = 0; i < size; i++)
    {
    std::cout

  • @perajarac
    @perajarac ปีที่แล้ว +1

    hope u got aircondition after 5 years of hard work

  • @matrix9140
    @matrix9140 ปีที่แล้ว

    Solution to your question:
    #include
    #include
    template
    void Print(const std::array& arr)
    {
    for (int i = 0; i < arr.size(); i++)
    {
    std::cout

  • @antagonista8122
    @antagonista8122 4 ปีที่แล้ว +2

    template
    void printArray(const std::array& arr) {
    for (const T& item : arr)
    std::cout

  • @ash2989
    @ash2989 4 ปีที่แล้ว

    template
    void printArray(const std::array& data)
    {
    for(int i=0;i

  • @alltheway99
    @alltheway99 4 ปีที่แล้ว

    @Cherno : please do a STL container comparison video