[英]Retrieve array name
我已经用c ++编写了一个函数,该函数接收一个结构作为输入。 收到的struct对象有两个数组。 我需要将两个数组用于不同的目的。 阵列名称已以某种格式创建。 如何检索字符串中的数组名称。
struct INFO
{
float fADataLHS[3] = {1,2,3};
float fADataRHS[3] = {4,5,6};
已经定义了结构INFO,其中已定义了两个数组。 函数useStruct将这两个函数用于不同的目的。
void useStruct(struct *INFO)
{
--------;
--------;
}
int main()
{
struct INFO info;
useStruct(info);
}
我想要一种方法,可以像以前一样检索数组的名称。 fAdataLHS并将其存储到字符串中。 想法是从字符串名称中找到子字符串LHS和RHS,然后进行相应处理。
PS:我是C ++的新手。
我会很简单,因为您是C ++的入门者。
如果您想将两个数组用于不同的目的,那就去做。 例如:
void use_array_for_different_purposes(INFO *info)
{
// Purpose one, printing values using fADataLHS.
for (int i = 0; i < 3; i++) {cout << info->fADataLHS[i] << endl;}
// Purpose two, computing total sum using fADataRHS.
int acum;
for (int i = 0; i < 3; i++) {acum += info->fADataRHS[i];}
}
如您所见,您无需获取数组名称作为字符串值。
如果我完全理解,则您的用例是这样的:您有两个(或更多)名称,每个名称都有一个与之关联的float数组。 您想按名称获取数组并处理数据。
考虑以下代码:
class INFO
{
std::map<std::string, std::vector<float>> vectors;
public:
INFO() : vectors{}
{
vectors["fADataLHS"] = { 1, 2, 3 };
vectors["fADataRHS"] = { 4, 5, 6 };
}
const std::vector<float>& operator[](const std::string& key) const // access vector by key
{
return vectors.at(key);
}
};
void useStruct(const INFO& info) // pass instance by const reference
{
std::cout << info["fADataLHS"][0] << "\n"; // access element 0 from the fADataLHS array
// get the entire array:
const auto& arr = info["fADataRHS"];
// this will throw a std::out_of_bounds
const auto& arr = info["non-existent-key"];
}
编辑 :其他一些注意事项:
float
而是使用double
operator[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.