取代固定大小的数组用的std

取代固定大小的数组用的std

本文介绍了取代固定大小的数组用的std ::数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与传统$ C $工作c,我问自己,我应该取代固定大小的C风格的数组新的std ::数组? E.克

Working with legacy code, I asked myself should I replace fixed sized C-style arrays with the new std::array? E. g.

static const int TABLE_SIZE = 64;
double table[TABLE_SIZE];

替换为

std::array<double, TABLE_SIZE> table;

当我看到使用的std ::可变大小的数组向量的好处,我不认为他们有固定的大小。 table.size()反正是已知的,的std ::开始()的std ::结束()免费功能可用于STL的算法使用C风格的数组了。因此,除了被越来越符合标准,我错过更多的好处?是值得的工作,以全部替换还是被认为是最好的做法?

While I see the benefits from using std::vector for variable size arrays, I don't see them with fixed size. table.size() is known anyways, std::begin(), std::end() as free functions can be used for STL-algorithms with C-style arrays too. So besides being more standard compliant, do I miss more benefits? Is it worth the work to replace all occurrences or is it considered to be best practice?

推荐答案

据我所知的std ::阵列只是提供了一个更好的STL一样的界面来处理,而不是普通的C -arrays。在性能和功能方面的两个选择归结为pretty大致相同,但的std ::阵列可以作为一个标准集装箱。

AFAIK std::array just provides a nicer STL-like interface to deal with rather than normal C-arrays. In terms of performances and capabilities the two choices boil down to be pretty much the same but std::array can be used as a standard container.

另一个特点:它​​们可能像对待因为它们提供的元组一样访问功能

Another feature: they might be treated like tuples since they provide tuple-like access functions.

最后但并非最不重要的user2079303注意:如果你的code将是由程序员新手使用,它可以prevent路过时,它作为一个参数数组腐烂的过程

Last but not the least as user2079303 noticed: if your code is going to be used by novice programmers, it can prevent the array decaying process when passing it as an argument.

如果你想知道,如果你应该替换的std ::阵列的所有C风格的数组,答案是肯定的,如果你要开发一些新可用的功能和/或重写一些你的code到利用这些功能的优势。如果你只是简单的替换C-阵列,的std ::阵列(不接触任何东西),它可能不是值得的。

If you're wondering if you should just replace all your C-style arrays with std::arrays, the answer is yes if you're going to exploit some of the newly available features and/or rewrite some of your code to take advantage of those capabilities. If you're just plain substituting C-arrays with std::arrays (without touching anything else) it might not be worth it.

这篇关于取代固定大小的数组用的std ::数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:19