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

  Рет қаралды 114,258

The Cherno

The Cherno

Күн бұрын

Пікірлер: 326
@seditt5146
@seditt5146 7 жыл бұрын
New drinking game: Take a shot everytime Cherno tells us he will cover it in a future video. :D
@iamk5686
@iamk5686 5 жыл бұрын
I'd be falling out of my fucking chair.
@geiger21
@geiger21 5 жыл бұрын
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 жыл бұрын
ahhaha it's a suicide pact
@seditt5146
@seditt5146 4 жыл бұрын
@@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 4 жыл бұрын
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
@LordVysh
@LordVysh 7 жыл бұрын
Doesn't really matter what the size is. template void printArray(array a) { for (auto &i : a) { cout
@Dhruvpatel-gb4pv
@Dhruvpatel-gb4pv 2 жыл бұрын
we can also use "auto&" in the function parameter.
@greysonyu5626
@greysonyu5626 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 жыл бұрын
@@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.
@dXXPacmanXXb
@dXXPacmanXXb 7 жыл бұрын
The hardest part in C++ is deciding which thing to use
@iamk5686
@iamk5686 5 жыл бұрын
So true man. I guess it just comes with practice.
@geiger21
@geiger21 5 жыл бұрын
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 Жыл бұрын
@@geiger21 Well, you can write C++ codes without using STL stuffs...
@khatharrmalkavian3306
@khatharrmalkavian3306 3 жыл бұрын
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 Жыл бұрын
Thanks for the elaboration.
@toao_rainys
@toao_rainys Жыл бұрын
what’s the difference between inline and constexpr then?
@AndreiSokolov-k7j
@AndreiSokolov-k7j 10 ай бұрын
thanks bro from steins gate
@khatharrmalkavian3306
@khatharrmalkavian3306 10 ай бұрын
@@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 6 ай бұрын
@@khatharrmalkavian3306Your explanation really helped, thanx
@Str33tF1ght1
@Str33tF1ght1 7 жыл бұрын
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 жыл бұрын
will not work, replace it with
@fluffypinkpanda28
@fluffypinkpanda28 5 жыл бұрын
@@alanyoung7045 Why so? Can you explain a bit more? I'm interested.
@rysiexo
@rysiexo 5 жыл бұрын
template void printArray(T(&arr)[size]) { } I know, I digged your comment up, yeay a golden shovel for me.
@CacheTaFace2
@CacheTaFace2 4 жыл бұрын
@@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 жыл бұрын
@@alanyoung7045 or just call it template, since size_t is just a typedef of unsigned integer
@yusinwu
@yusinwu 7 ай бұрын
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 жыл бұрын
template void PrintArray(std::array& arr) { for (int i = 0; i < arr.size(); i++) { std::cout
@Cheddar2012
@Cheddar2012 5 жыл бұрын
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 жыл бұрын
@@Cheddar2012 You should always used unsigned integers to keep the size, but nevertheless this was pretty much the solution.
@traywor
@traywor 5 жыл бұрын
@@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.
@ToyMachine22122
@ToyMachine22122 4 жыл бұрын
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
@Katniss218
@Katniss218 4 жыл бұрын
"Stacks are stored in the arrays" - Cherno 2018. Well.. He *almost* said it.
@expurple
@expurple 4 жыл бұрын
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 жыл бұрын
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 жыл бұрын
you may want to reconsider using unnecessary if-else statements, as those seriously slow down your code.
@michaplucinski142
@michaplucinski142 2 жыл бұрын
that's really good
@Adam_Lyskawa
@Adam_Lyskawa 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.
@TheHeadHunter105
@TheHeadHunter105 7 жыл бұрын
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 жыл бұрын
what is cross-platform projects? is it the same as mixing languages in a project?
@danielji2742
@danielji2742 3 жыл бұрын
@@pedrocalorio1655 cross platform = windows, mac or linux + others
@felipebonilla7679
@felipebonilla7679 2 жыл бұрын
@@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.
@עומרפריאל
@עומרפריאל 4 жыл бұрын
In 4:17, You can use Template
@AdityaKumar-xw2yx
@AdityaKumar-xw2yx 10 ай бұрын
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 жыл бұрын
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)
@KingCitaldo125
@KingCitaldo125 4 жыл бұрын
template void PrintArray(const array_type& m_array) { cout
@pc19937
@pc19937 3 ай бұрын
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 жыл бұрын
template void PrintArray(T& a) { for (int i = 0; i < a.size(); i++) { std::cout
@koungmeng
@koungmeng 5 жыл бұрын
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};
@callingpizza
@callingpizza 3 жыл бұрын
4:20 solution: template void PrintArray(std::array data) { for (int i = 0; i < _Size; i++) std::cout
@fireballgfx
@fireballgfx Жыл бұрын
template void foo(std::array){...}
@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.
@vikramkumarbathala5432
@vikramkumarbathala5432 6 жыл бұрын
template void print(array&array){ int size = array.size(); for (int i = 0; i < size; i++){ cout
@Erebus2075
@Erebus2075 5 жыл бұрын
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 ^^
@bingusiswatching6335
@bingusiswatching6335 9 ай бұрын
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])
@DenysYeroshenko
@DenysYeroshenko 3 жыл бұрын
Thank you, i am grateful that there is person such you. It really helps to figure out in c++
@harshkn
@harshkn 7 жыл бұрын
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* / }
@alexkiecker4175
@alexkiecker4175 7 жыл бұрын
Here is one ^^
@VanYang-eq5ub
@VanYang-eq5ub Жыл бұрын
template void func(const std::array& arr) { cout
@aryanwolfox6390
@aryanwolfox6390 3 жыл бұрын
Answer is by template : template void printArray(const std::array< T, size >&data) { // now we don’t need to pass type and size explicitly }
@169mayan
@169mayan 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
@michaelswahla4927
@michaelswahla4927 Жыл бұрын
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
@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
@kitlaw2494
@kitlaw2494 5 жыл бұрын
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)
@avocadopeel7536
@avocadopeel7536 3 жыл бұрын
To the people suggesting templates with std::array, why not template void PrintArray(int *array) { for(int i=0; i
@ashrafrasulov4353
@ashrafrasulov4353 2 ай бұрын
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.
@PythonPlusPlus
@PythonPlusPlus 6 жыл бұрын
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
@Deeredman4
@Deeredman4 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.
@skipdrill373
@skipdrill373 2 жыл бұрын
Yes!
@mamertvonn
@mamertvonn 4 жыл бұрын
3:50 so does anyone know the answer? Pls enlighten me. Is it just templates?
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
@kishanthakur__7813
@kishanthakur__7813 4 ай бұрын
template void PrintData(const std::array& data) { for(int i = 0; i < data.size(); ++i) { std::cout
7 жыл бұрын
I think you should make qt and qt-opengl tutorial.
@munjalparmar8455
@munjalparmar8455 10 ай бұрын
can we have template there.
@goldenlava1019
@goldenlava1019 4 жыл бұрын
Templates (: template void PrintArray(const std::array& data) { for (int i = 0; i < data.size(); i++) std::cout
@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.
@yannisgoogleapps9249
@yannisgoogleapps9249 18 күн бұрын
Oh god, you put me on the spot with the question xD Maybe with templates?
@tamriel_x
@tamriel_x 5 жыл бұрын
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"
@CriticRoshun
@CriticRoshun 3 жыл бұрын
template void PrintArray(const T& arr){ for (int i=0; i
@OneShot_cest_mieux
@OneShot_cest_mieux 5 жыл бұрын
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 жыл бұрын
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".
@vivekkumar-bq2ln
@vivekkumar-bq2ln 3 жыл бұрын
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.
@KillzoneKid
@KillzoneKid 7 жыл бұрын
template void PrintArray(std::array array)...
@voidnull7329
@voidnull7329 4 жыл бұрын
Make a video on naming conventions for c++ like function name ,class ,private member,..etc
@ashrafrasulov4353
@ashrafrasulov4353 2 ай бұрын
Thank you for your lesson, it perfect. Super...
@MartialBarts
@MartialBarts 7 жыл бұрын
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 жыл бұрын
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++
@milosorevic927
@milosorevic927 Жыл бұрын
void PrintArray(const auto& data) { for (const auto& value : data) { std::cout
@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.
@misana77
@misana77 6 жыл бұрын
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
@CoolDude911
@CoolDude911 5 жыл бұрын
Arrays should be constant at compile time so whatever size the array is should be tied to some constant.
@rakeshtm2750
@rakeshtm2750 4 жыл бұрын
We can use "auto" in function parameter as of C++14 instead of mentioning the type name and array size.
@aryesegal1988
@aryesegal1988 7 жыл бұрын
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
@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 }
@gage2560
@gage2560 7 жыл бұрын
template void func(std::array& array) { std::cout
@nathanm988
@nathanm988 7 жыл бұрын
THAT IS GENIUS!
@PythonPlusPlus
@PythonPlusPlus 6 жыл бұрын
This would work, however you should probably use something other than T because is is meant for Type names.
@misana77
@misana77 6 жыл бұрын
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.
@stavroscho7798
@stavroscho7798 2 жыл бұрын
You can set the size with a template
@venkateswarans1012
@venkateswarans1012 5 жыл бұрын
We should use template to pass STL array with size to function in C++11 or we can use auto keyword in C++17
@creatork999
@creatork999 4 жыл бұрын
template void Print(std::array& arr) { for (int i = 0; i < Size; i++) { println(arr[i]); } }
@skewbinge6157
@skewbinge6157 2 жыл бұрын
templates right away answer thanks to you man
@mattt2684
@mattt2684 6 жыл бұрын
4:18 maybe try using a void* to the reference of the array and then go from there...
@Netrole
@Netrole 5 жыл бұрын
Go how far though? That is the question, and also why we need the length
@platin2148
@platin2148 7 жыл бұрын
You should probably use complier explorer for showing code that is compiled. Real difference between an Fixed size array and a pool allocator?
@LucidStew
@LucidStew 7 жыл бұрын
10mins is a good length. Didn't feel short.
@cocbuilds
@cocbuilds 6 жыл бұрын
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.
@benjitigg3490
@benjitigg3490 4 жыл бұрын
my solution is: template void PrintArray(const std::array & data) { for (int i= 0; i < N; I++) { std::cout
@rcookie5128
@rcookie5128 7 жыл бұрын
nice overview once again! ^^
@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
@Vasily.Vasilyev
@Vasily.Vasilyev 7 жыл бұрын
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.
@Ghasakable
@Ghasakable 11 ай бұрын
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
@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 жыл бұрын
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.
@valrossenOliver
@valrossenOliver 7 жыл бұрын
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 жыл бұрын
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 жыл бұрын
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 жыл бұрын
@@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
@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].
@Nick-tv5pu
@Nick-tv5pu 4 жыл бұрын
4:15 Using a template?
@samiam4039
@samiam4039 7 жыл бұрын
obj c stl array constructs allow for compile time checking for array sizes and types in its functions.
@rickygable
@rickygable 6 жыл бұрын
template void PrintContainer(const T& container) { for(int i=0; i < container.size(); i++ ){ std::cout
@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'
@breakmon218
@breakmon218 7 жыл бұрын
Are you going to talk about linked list? :))
@paragggoyal1552
@paragggoyal1552 Жыл бұрын
but the issue is we should know the size at compile time, if we don't know the size at compile time, we cannot specify the size in template argument.
@VanYang-eq5ub
@VanYang-eq5ub Жыл бұрын
so let's use template!by using template,we can do it when we creat it,not in complie stage
@KGhary
@KGhary 5 жыл бұрын
passing array as const pointer its like passing const char pointer and its mean string array
@yufang9109
@yufang9109 4 жыл бұрын
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
@valforeststorm6908
@valforeststorm6908 5 жыл бұрын
I know this video is oldish but I will still do the challenge. I tried using "auto" it works but I still get a warning though. did I win???
@valforeststorm6908
@valforeststorm6908 5 жыл бұрын
//never mind I used a template template void print(size& data){ for(int i = 0; i< data.size(); i++){ std::cout
@Ghasakable
@Ghasakable 11 ай бұрын
How about without using templates, we pass as const int variable, which can passed to the function easily: like ``` const int size = 5; std::array my_array{1, 2, 3, 4, 5}; for (size_t i = 0; i < my_array.size(); i++) { std::cout
@cactusmamelu313
@cactusmamelu313 3 жыл бұрын
Forty degree, finally a sane person that doesn't use square feet by crate inch type of unit !
@rishimenon5632
@rishimenon5632 5 жыл бұрын
Since its a template, it produces different copies, right? So would the intermediate object file and/or the executable file occupy more space?
@gooseman5578
@gooseman5578 5 жыл бұрын
on tests vector show same performance as array
@VanYang-eq5ub
@VanYang-eq5ub Жыл бұрын
it totally can work pretty well。
@alltheway99
@alltheway99 4 жыл бұрын
@Cherno : please do a STL container comparison video
@meer_kat5158
@meer_kat5158 3 жыл бұрын
Hi, if std::array is stored on stack, how is this code valid? std::array f() { return std::array {1, 2, 3}; }
@_Omni
@_Omni 3 жыл бұрын
You create a copy..
@cisimon7
@cisimon7 3 жыл бұрын
late to the party, but I'd go about the problem as below: template void printArray(std::array& data) { for (int i = 0; i
@Zero-yi5gw
@Zero-yi5gw 4 жыл бұрын
Are you using visual studio? If so, how is yours running so fast, mine takes like 4 seconds to realize there is an error somewhere. Whereas yours seems to highlight it in red immediately. How did you make it run so fast?
@Zero-yi5gw
@Zero-yi5gw 4 жыл бұрын
@Artem Katerynych Press X to doubt. 𝘊𝘗𝘜: 𝘐𝘯𝘵𝘦𝘭 𝘪5-9600𝘒 @ 4.6𝘎𝘏𝘻 𝘎𝘗𝘜: 𝘕𝘝𝘐𝘋𝘐𝘈 𝘎𝘦𝘍𝘰𝘳𝘤𝘦 𝘙𝘛𝘟 2070 𝘙𝘈𝘔: 2𝘹16𝘎𝘉 (𝘋𝘶𝘢𝘭 𝘊𝘩𝘢𝘯𝘯𝘦𝘭) 𝘋𝘋𝘙4 @ 2400𝘔𝘩𝘻
@Zero-yi5gw
@Zero-yi5gw 4 жыл бұрын
@Artem Katerynych It's pretty important that I specify I use visual STUDIO, not visual studio CODE, which is way faster because its more lightweight. Maybe that's what hes using, with a few extensions...
@Zero-yi5gw
@Zero-yi5gw 4 жыл бұрын
@Artem Katerynych Very weird. How the fuck is a laptop faster than my pc...
@tralamysamy8465
@tralamysamy8465 3 жыл бұрын
The best solution with C++ 20 ➡ void PrintArray (const std::span& data) { for (auto& : data) { std::cout
@perajarac
@perajarac Жыл бұрын
hope u got aircondition after 5 years of hard work
@SomilSrivastava2406
@SomilSrivastava2406 Жыл бұрын
😂
Function Pointers in C++
12:41
The Cherno
Рет қаралды 401 М.
Templates in C++
17:58
The Cherno
Рет қаралды 611 М.
GIANT Gummy Worm #shorts
0:42
Mr DegrEE
Рет қаралды 152 МЛН
번쩍번쩍 거리는 입
0:32
승비니 Seungbini
Рет қаралды 182 МЛН
Hilarious FAKE TONGUE Prank by WEDNESDAY😏🖤
0:39
La La Life Shorts
Рет қаралды 44 МЛН
Arrays in C++
18:31
The Cherno
Рет қаралды 438 М.
2 Years of C++ Programming
8:20
Zyger
Рет қаралды 317 М.
lvalues and rvalues in C++
14:13
The Cherno
Рет қаралды 332 М.
31 nooby C++ habits you need to ditch
16:18
mCoding
Рет қаралды 858 М.
How to Deal with Multiple Return Values in C++
17:20
The Cherno
Рет қаралды 212 М.
C++ Super Optimization: 1000X Faster
15:33
Dave's Garage
Рет қаралды 334 М.
Stack vs Heap Memory in C++
19:31
The Cherno
Рет қаралды 589 М.
ITERATORS in C++
17:09
The Cherno
Рет қаралды 217 М.
BENCHMARKING in C++ (how to measure performance)
14:52
The Cherno
Рет қаралды 161 М.
you will never ask about pointers again after watching this video
8:03