Array length: Difference between revisions

Content deleted Content added
m →‎{{header|C++}}: formatting
Line 612: Line 612:
C++ follows the same rules as C regarding static and dynamic arrays.
C++ follows the same rules as C regarding static and dynamic arrays.


However, C++ has an additional std::array type (amongst other collections) in its standard library:
However, C++ has an additional <code>std::array</code> type (amongst other collections) in its standard library:


<lang cpp>
<lang cpp>#include <array>
#include <array>
#include <iostream>
#include <iostream>
#include <string>
#include <string>
Line 624: Line 623:
std::cout << fruit.size();
std::cout << fruit.size();
return 0;
return 0;
}</lang>
}
</lang>


Note that char* or const char* could have been used instead of std::string.
Note that <code>char*</code> or <code>const char*</code> could have been used instead of <code>std::string</code>.


In addition to the std::array type, the C++ standard library also provides dynamically-sized containers to hold arbitrary objects.
In addition to the <code>std::array</code> type, the C++ standard library also provides dynamically-sized containers to hold arbitrary objects.
These all support similar interfaces, though their implementations have different performance characteristics.
These all support similar interfaces, though their implementations have different performance characteristics.
<lang cpp> std::vector<std::string> fruitV({ "apples", "oranges" });
<lang cpp>
std::vector<std::string> fruitV({ "apples", "oranges" });
std::list<std::string> fruitL({ "apples", "oranges" });
std::list<std::string> fruitL({ "apples", "oranges" });
std::deque<std::string> fruitD({ "apples", "oranges" });
std::deque<std::string> fruitD({ "apples", "oranges" });
std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;
std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;</lang>
</lang>


Of these, vector is probably the most widely used.
Of these, vector is probably the most widely used.