【发布时间】:2019-03-05 11:37:36
【问题描述】:
我正在开发一个音乐程序,该程序根据音程从半音阶中调用音符。这些区间变量(h - 半步、w - 整步和 wh - 整半步)将用于确定比例增量(Major = WWHWWWH),稍后将用于测量跨字符串向量的区间长度可能输出测量值,例如“3 Whole Steps and a Half Step”。
我想知道存储简单变量的更有效方法是什么,因为我最终想用它制作一个手机应用程序,并希望它在电池/内存上尽可能简单。 .而且我还在学习。以下是我的想法:
int H = 1;
int W = 2;
int WH = 3;
Int Fiv = 5;
Int Sev = 7;
或
int H = 1;
int W = H+H;
int WH = W + H;
int Fiv = WH+W;
int Sev = Fiv + W;
Int H = 1; int W = H*2; int WH = W+H; etc..
我主要感兴趣的是初始化的差异化将如何影响内存和性能?
我知道我不应该将所有内容都放在 main 中,但这是一项正在进行的工作,而且我显然是编程新手 - 所以请查看布局 .. 这是目前正在使用的代码..
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
#include <vector>
#include <map>
const std::vector<std::string> st_sharps{"C","C#","D","D#","E","F","F#","G","G#","A","A#","B" };
const std::vector<std::string> st_flats{"C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B" };
struct steps{ int maj = 0; int min = 0;} step;
constexpr int H = 1;
constexpr int W = 2;
constexpr int Tre = 3;
constexpr int Fif = 5;
constexpr int Sev = 7;
const int size = st_flats.size();
const std::vector<int> Major = { W, W, H, W, W, W, H };
struct circle{
std::stringstream sharp;
std::stringstream flat;
std::stringstream minor;
std::stringstream dimin; };
struct scales{
circle fifths;
std::stringstream maj;
std::stringstream min; } scale;
int main(){
//Circle of Fifths
for (int j = 0; j < size; j++){
int five = j * Sev;
scale.fifths.sharp << st_sharps[five % size] << " ";
scale.fifths.flat << st_flats[five % size] << " ";
scale.fifths.minor << st_sharps[((size - Tre) + five) % size] << " ";
scale.fifths.dimin << st_sharps[((size - H) + five) % size] << " ";
}
std::cout << "Circle of Fifths:\n";
std::cout << "Major >> Relative Minor >> Diminished " << std::endl;
std::cout << "Maj: " << scale.fifths.sharp.str() << std::endl;
std::cout << "Min: " << scale.fifths.minor.str() << std::endl;
std::cout << "Dim: " << scale.fifths.dimin.str() << std::endl;
std::cout << "\nflats: " << scale.fifths.flat.str() << "\n" << std::endl;
//Major and Minor Scales
for (int i = 0; i < Major.size(); i++) {
scale.maj << st_sharps[step.maj] << " ";
scale.min << st_flats[((size - Tre) + step.min) % size] << " ";
step.maj += Major[i];
step.min += Major[(i + Fif) % Major.size()];
}
std::cout << "C Major:\n" << scale.maj.str() << "\n" << std::endl;
std::cout << "A Minor:\n" << scale.min.str() << "\n" << std::endl;
return 0;
}
【问题讨论】:
-
我认为在考虑这些重要问题之前,首先需要多研究 C++ 运算符,因为相同代码的两个替代版本不等价,并且会产生不同的结果。在两个替代版本中,
H、W和WH将具有不同的值。 -
如果您要使用
constexpr,那么您应该在您的示例中使用。你不应该垃圾邮件一百万个不必要的标签,你应该尝试提出一个可以用事实回答的问题,而不仅仅是意见。如果您使用过 constexpr,您会很快得出@SamVarshavchik 指出的结论。 -
第一个很清楚,第二个有不同的含义,因为
int后增量改变了它的操作数,我只见过第三个用于轻松定义数学常数,即constexpr double tau = pi + pi; -
H 是一半。 W 是整体。 WH 是整个音乐间隔的一半.. 不是某些人可能认为的高度和宽度.. 我在移动设备上,所以我没有时间测试这些,但我想知道什么是最有效的记忆管理。所有这些答案都是我问负嘲笑的确切原因。
-
@RichardChristopher 你的问题毫无意义。在您的示例中, storage 正如您的问题所要求的那样,您的示例也没有说明您要做什么。如果您编辑您的问题以包含
constexpr的示例或所需用法以及vector和map的用法,那么您可能希望得到一个有意义的答案。
标签: c++ variables memory int constexpr