C++核心準則??SL.con.2:除非有理由使用其他容器,默認使用STL vector

小編:啊南 65閱讀 2020.11.17

SL.con.2:除非有理由使用其他容器,默認使用STL vector


vector and array are the only standard containers that offer the following advantages:


  • the fastest general-purpose access (random access, including being vectorization-friendly); 最快的一般目的訪問(隨機訪問,包含矢量化友好)
  • the fastest default access pattern (begin-to-end or end-to-begin is prefetcher-friendly);
  • 最快的默認訪問模式(從前到后,從后到前都對預抓取友好)
  • the lowest space overhead (contiguous layout has zero per-element overhead, which is cache-friendly).
  • 最小的空間代價(連續的內存布局沒有任何多余元素,對緩存友好)

Usually you need to add and remove elements from the container, so use vector by default; if you don't need to modify the container's size, use array.


Even when other containers seem more suited, such as map for O(log N) lookup performance or a list for efficient insertion in the middle, a vector will usually still perform better for containers up to a few KB in size.



string should not be used as a container of individual characters. A string is a textual string; if you want a container of characters, use vector</*char_type*/> or array</*char_type*/> instead.

string不應該作為單獨字符的容器使用,string就是文本字符串;如果你需要字符容器,使用vector</*char_type*/> 或者 array</*char_type*/>而不是std::string。


If you have a good reason to use another container, use that instead.


For example(例如):

  • If vector suits your needs but you don't need the container to be variable size, use array instead. 如果vector可以滿足你的需求,但是你不需要長度可變,使用array。
  • If you want a dictionary-style lookup container that guarantees O(K) or O(log N) lookups, the container will be larger (more than a few KB) and you perform frequent inserts so that the overhead of maintaining a sorted vector is infeasible, go ahead and use an unordered_map or map instead. 如果你需要字典風格的搜索容器保證O(K)或O(log N)復雜度的搜索,容器會更大(大于數KB)而且你需要頻繁執行插入操作,從而無法導致無法維護有序vector,可以使用unordered_map或者map。

To initialize a vector with a number of elements, use ()-initialization. To initialize a vector with a list of elements, use {}-initialization.


vector<int> v1(20);  // v1 has 20 elements with the value 0 (vector<int>{})
vector<int> v2 {20}; // v2 has 1 element with the value 20

Prefer the {}-initializer syntax.



  • Flag a vector whose size never changes after construction (such as because it's const or because no non-const functions are called on it). To fix: Use an array instead. 標記構造之后長度從來沒有發生變化的vector(由于它本身為const或者沒有非const函數使用它)。改正方法:使用array代替vector。
华东15选5彩票奖结果 购买彩票合买 超级搞笑斗地主视频 3分赛车计划软件 兴动甘南麻将代理商 齐鲁风采七乐彩查询 低风险理财网站 云南快乐十分出奖结果 腾讯麻将好友房玩不了 山东群英会怎样是中奖 手机现金捕鱼送体验 og电子竞技网站 山西快乐十分前三遗漏 广东闲来麻将外桂下载苹果版 足彩胜负彩 开元棋牌网址玩 乐赢国际官方网站-点击进入