简体   繁体   中英

What's the correct way to work with bounded arrays in C++?

I'm trying to understand how bounded arrays work in C++. I need to have a quick length method to return the size of my bounded array. In Java I would do something like that:

int[] array = new int[10];

System.out.println(array.length); // 10
System.out.println(array[5]); // 0

array[5] = 11;

System.out.prinltn(array[5]); // 11

If possible I would like to use an object array (ie a class implementing an array functionality) instead of pointers . Would I be correct to say that it feels much more natural to use an object array instead of a memory pointer to work with arrays?

C++ has a class std::array<type, size> which is basically just a wrapper for stack-allocated arrays. C++ also has a class std::vector<type> which is a wrapper for heap-allocated arrays (like what you're used to in Java) but which also has ArrayList -like functionality.

In your case, writing code which is logically and semantically identical to yours is:

std::vector<int> array(10, 0); //EDIT: I added the second parameter because I don't think all implementations zero the memory when allocating it. This ensures that the memory is zeroed before use, like it would be in Java.
std::cout << array.size() << std::endl;
std::cout << array[5] << std::endl;
array[5] = 11;
std::cout << array[5] << std::endl;

Though, I wouldn't name the variable array , since that could be confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM