什么是存储变量的更有效方法?

时间:2018-09-29 21:49:59

标签: c++ variables memory int constexpr

我正在研究一个音乐程序,该程序根据间隔从半音阶调用音符。这些间隔变量(h-半步,w-整步,wh-整个半步)将用于确定音阶增量(Major = WWHWWWH),稍后将用于测量整个字符串向量的间隔长度,以潜在地输出测量结果,例如“ 3个整步和一个半步”。

我想知道存储简单变量的更有效方法是什么,因为我最终想用它来制作手机应用程序,并希望它在电池/内存上尽可能地容易。 。而且我还在学习。这是我的想法:

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..

我主要对初始化的差异将如何影响内存和性能产生任何兴趣?

我知道我不应该拥有全部内容,但这是一个正在进行的工作,而且我显然是编程新手-因此,请仔细阅读布局..这是目前正在使用的代码.. < / p>

#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;
}

1 个答案:

答案 0 :(得分:0)

我会选择一个表示“'W'是'H'的两倍”的版本。因此,我的首选方式是:

constexpr int H = 1;
constexpr int W = 2*H;
constexpr int WH = W+H;

请注意,您的版本int W = H++不是您可能想要的版本,因为H++不等于H+1;它实际上等于int W = H; H = H + 1

相关问题