the41's blog

By the41, history, 3 weeks ago, In English,

Hello,

I recently switched from java to C++ and encountered a question. I notice that everybody seems to use C-style arrays over C++ arrays. To me, it seems that C++ arrays, being easier to pass in functions and with the inclusion of bound checks, would be better, but this does not appear to be the case. Is it because of faster typing or tradition or why does everyone still use C-style arrays? Sorry if the question seems very basic; I searched for a while but could not find an answer.

To my understanding:

int a[3]; //C-style
array<int, 3> a; //C++ style

Thank you!

Tags c++
 
 
 
 
  • Vote: I like it
  • +12
  • Vote: I do not like it

»
3 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by the41 (previous revision, new revision, compare).

»
3 weeks ago, # |
  Vote: I like it -14 Vote: I do not like it

Because vectors allocate memory as you put stuff in it, it is usually slower and can hold less things as it uses more memory. As long as you can use normal arrays dont use vectors.

  • »
    »
    3 weeks ago, # ^ |
      Vote: I like it +9 Vote: I do not like it

    I believe C++ arrays from C++11 are implemented using arrays and not vectors. They are just a wrapper class and so should be nearly as fast as C-style arrays.

  • »
    »
    3 weeks ago, # ^ |
      Vote: I like it +6 Vote: I do not like it

    I always use vector instead of array since it fits with C++ STL more naturally. I don't think I've ever had a problem with vectors because of things that you've mentioned. They're very minor IMO.

    • »
      »
      »
      3 weeks ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      Vectors are usually very slow when you work with small size vectors a lot of times. I think that there's almost no difference if you're working with large vectors.

»
3 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

C++ std::array are almost always better. Except that they don't support VLA (GCC extension), make unoptimized code slower (not a problem), and is slightly longer to type.

Also, bound-checking is not supported unless you have _GLIBCXX_DEBUG defined, or use .at().

»
3 weeks ago, # |
  Vote: I like it +9 Vote: I do not like it

with the inclusion of bound checks

This is a terrible idea in CP. Why don't you validate the input in your code while you're at it?

You need to learn to live dangerously.