在过去的几年里,我并没有非常使用过C语言.当我今天读到这个问题时,我遇到了一些我不熟悉的C语法.
显然在C99中,以下语法有效:
void foo(int n) {
int values[n]; //Declare a variable length array
}
Run Code Online (Sandbox Code Playgroud)
这似乎是一个非常有用的功能.有没有关于将它添加到C++标准的讨论,如果是这样,为什么它被省略?
一些潜在的原因:
C++标准规定数组大小必须是常量表达式(8.3.4.1).
是的,当然我意识到在玩具示例中可以使用std::vector<int> values(m);,但这会从堆中分配内存而不是堆栈.如果我想要一个多维数组,如:
void foo(int x, int y, int z) {
int values[x][y][z]; // Declare a variable length array
}
Run Code Online (Sandbox Code Playgroud)
该vector版本变得很笨拙:
void foo(int x, int y, int z) {
vector< vector< vector<int> > > values( /* Really painful expression here. */);
}
Run Code Online (Sandbox Code Playgroud)
切片,行和列也可能遍布整个内存.
看一下comp.std.c++这个问题的讨论很明显,这个问题在争论的两个方面都有一些非常重要的名字引起争议.毫无疑问,a std::vector总是更好的解决方案.
我一直认为这std::vector是"作为阵列实施的一般智慧",等等等等等等.今天我去了测试它,似乎不是这样:
这是一些测试结果:
UseArray completed in 2.619 seconds
UseVector completed in 9.284 seconds
UseVectorPushBack completed in 14.669 seconds
The whole thing completed in 26.591 seconds
Run Code Online (Sandbox Code Playgroud)
这大约慢了3-4倍!没有真正证明" vector可能会慢几纳米"的评论.
我使用的代码:
#include <cstdlib>
#include <vector>
#include <iostream>
#include <string>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/microsec_time_clock.hpp>
class TestTimer
{
public:
TestTimer(const std::string & name) : name(name),
start(boost::date_time::microsec_clock<boost::posix_time::ptime>::local_time())
{
}
~TestTimer()
{
using namespace std;
using namespace boost;
posix_time::ptime now(date_time::microsec_clock<posix_time::ptime>::local_time());
posix_time::time_duration d = now - start;
cout << name << " completed in " << …Run Code Online (Sandbox Code Playgroud) 在我们的C++课程中,他们建议不再在新项目中使用C++数组.据我所知,Stroustroup本人建议不要使用数组.但是有显着的性能差异吗?