STL中的container各有专长,最常用的是std::vector,可以完全取代array,第二常用的是std::list。std::vector的优点在于non-sequential access超快,新增数据于数据后端超快,但insert和erase任意资料则相当缓慢;std::list则是insert和erase速度超快,但non-sequential access超慢,此范例以实际时间比较vector和list间的优缺点。

  1}

执行结果

(Debug mode)
 1(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector Insertion at the end Process time:3.094 sec
 2(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List Insertion at the end Process time:10.205 sec
 3(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Insertion at the end : Vector wins
 4(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector Insertion anywhere Process time:5.548 sec
 5(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List Insertion anywhere Process time:0.01 sec
 6(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Insertion anywhere : List wins
 7(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector deletion anywhere Process time:4.756 sec
 8(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List deletion anywhere Process time:0.011 sec
 9(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Deletion anywhere : List wins
10(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector non-sequential access Process time:0.11 sec
11(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List non-sequential access Process time:21.12 sec
12(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Non-sequential : Vector wins

(Release Mode)
 1(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector Insertion at the end Process time:0.06 sec
 2(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List Insertion at the end Process time:0.39 sec
 3(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Insertion at the end : Vector wins
 4(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector Insertion anywhere Process time:4.757 sec
 5(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List Insertion anywhere Process time:0 sec
 6(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Insertion anywhere : List wins
 7(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector deletion anywhere Process time:4.717 sec
 8(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List deletion anywhere Process time:0 sec
 9(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Deletion anywhere : List wins
10(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Vector non-sequential access Process time:0 sec
11(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)List non-sequential access Process time:0.491 sec
12(原創) std::vector与std::list的执行速度比较 (C/C++) (STL)Non-sequential : Vector wins

可见经过compiler优化后,速度差异非常明显。

相关文章: