简体   繁体   English

如何将此C代码转换为C ++?

[英]How to convert this C code to C++?

I have some arrays that are declared like this: 我有一些这样声明的数组:

static double covalent_radius[256] = {
    [ 0 ] = 0.85,
    [ 1 ] = 0.37,
    ...
};

C++ doesn't allow this kind of declaration. C ++不允许这种声明。 Is there any way to achieve this? 有什么办法可以做到这一点?

static double covalent_radius[256] = {
    0.85, /* ?,  Unknown    */
    0.37, /* H,  Hydrogen   */
    ...
};

It's C89, not C99 so I suppose it should work. 它是C89,而不是C99,所以我想它应该可以工作。

Why don't you do this: 您为什么不这样做:

static double covalent_radius[256] = {
    0.85, /* 0: ?,  Unknown    */
    0.37, /* 1: H,  Hydrogen   */
    ...
};

You could use a std::vector of a std::tuple of two std::string and a double 您可以使用两个std::string和一个doublestd::tuplestd::vector

#include <iostream>
#include <string>
#include <tuple>
#include <vector>

static auto periodic_table = std::vector<std::tuple<std::string, std::string, double>> 
{
    std::make_tuple("?", "Unknown", 0.85),
    std::make_tuple("H", "Hydrogen", 0.37)
};

std::string element_symbol(int neutrons)
{
    return std::get<0>(periodic_table[neutrons]);    
}

std::string element_name(int neutrons)
{
    return std::get<1>(periodic_table[neutrons]);    
}

double covalent_radius(int neutrons)
{
    return std::get<2>(periodic_table[neutrons]);    
}

int main() 
{
    std::cout << element_symbol(1) << "\n";
    std::cout << element_name(1) << "\n";
    std::cout << covalent_radius(1) << "\n";
}

Live Example (using C++11 initializer-lists). 实时示例 (使用C ++ 11初始化程序列表)。

Note : I'd make the periodic table std::vector instead of an array because they keep synthesizing new (unstable) elements. 注意 :我会使用元素周期表std::vector而不是数组,因为它们会不断合成新的(不稳定的)元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM