c++将数组大小扩大两倍的方法?

标签 c++

这是我当前的代码。有没有更好的方法在 C++ 中做同样的事情?

{
            // create more room in array
            Point *temp = new Point[pointList.getSize()*ENLARGE_TIMES];

            memcpy(temp,pointList._pointList,sizeof(Point)*pointList.getSize());
            pointList.~PointList();
            pointList._pointList = temp;
            pointList.setSize(pointList.getSize()*ENLARGE_TIMES);
            pointList._pointList[iterator] = point;
            iterator++;
            pointsCounter++;

            continue;
}

编辑:不能使用 vector

最佳答案

正如 Chris 指出的那样,您真的想使用 std::vector 以及方法 reserve() 和 push_back(),如下所示:

vector<Point> pointList; // could be a member variable
pointList.reserve(INITIAL_CAPACITY); // up to you
pointList.push_back(point); // adding new elem
pointList.end();  // replaces your iterator

// Some idiomatic iteration code to go with it:
for( auto iter = begin(pointList); iter != end(pointList); ++iter )
{
  Point p = *iter; // deref iterator and use result
}

关于c++将数组大小扩大两倍的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16269413/

相关文章:

c++ - 在 OpenCV 中将灰度图像转换为单色

C++ std::set 比较器

c++ - 如何在 C++ Win32 应用程序中创建 Windows 风格的文本框

c++ - 在 Qt C++ 应用程序中使用 Windows.Media.Speechrecognition 命名空间

c++ - 如何让 std::istringstream 将给定字符视为空格?

c++ - 读取 boost 图 (boost::read_graphviz),其中顶点包含 vector

c++ - MPI 发送矩阵列 (C++)

C++,抽象类和继承

c++ - 当入口和导出指向不同的节点时,如何使用 boost::graph 来(大约)解决旅行商问题?

c++ - 使用 boost over socket 发送和接收压缩文件