【问题标题】:Convert a string of characters string words[] to double feature[] in c++在c ++中将字符串words[]转换为double feature[]
【发布时间】:2020-08-19 14:51:08
【问题描述】:

我从我的 c++ 脚本中的文本文件中读取字符串,保存在 string words[3] 中的那些字符串采用这种形式:

abc[1]
abc[2]
abc[3]*abc[2]

读完这些字符串后,我想将string words[3] 转换为double feature[3],以便能够用double abc[3] = {1,2,3} 的值替换这些字符串。 所以我想得到一个double feature[3] = {abc[1],abc[2],abc[3]*abc[2]} 如何在 C++ 中进行这种转换?

【问题讨论】:

  • 似乎您必须评估基本的数学表达式才能进行转换。
  • 计算数学表达式是什么意思?
  • @Maklaizer 如果你有例如"abc[3]*abc[2]+abc[1]" 字符串,您解析它的方式与链接问题中的类似(尽管可能不完全相同),因此您的代码最后将计算 get("abc[3]") * get("abc[2]") 然后 + get("abc[1]") 得到结果。 get 函数将采用字符串参数 "abc[3]" 并解析数组名称 ("abc") 和索引 ("3" 然后您可以将其转换为数字 3)。您可以使用映射从适当的数组中获取数据:map<string,double *> m {{"abc", abc}}; 所以get 函数将访问此映射以获取包含数据的数组对象
  • 这不是一个简单的任务。如果您还不具备使用上述信息编写代码的知识,您可能想从更简单的开始。
  • 如果这是给初学者的赋值,我希望赋值将问题的范围限制在几个不同变量上的几个不同操作。对于初学者来说,更一般的问题可能太复杂了。

标签: c++


【解决方案1】:

我在评论中的意思是这样的。 Playground

请注意,我省略了最难的部分,即将任意表达式解析为基本操作。

#include <iostream>
#include <string>
#include <map>
#include <string_view>
#include <algorithm>

double abc[] { 
  /*0*/ 5.0, 
  /*1*/ 2.0, 
  /*2*/ 3.0,
  /*3*/ 4.0
};

std::map<std::string, double *> arrays_names {
    {"abc", abc}    
};

double get_value(std::string_view value_str) {
    auto name_end_pos = value_str.find('[');
    auto name = value_str.substr(0, name_end_pos);
    
    auto index_end_pos = value_str.find(']'); 
    auto index_len = index_end_pos - name_end_pos - 1;
    std::string index_str{value_str.substr(name_end_pos + 1, index_len)}; 
    auto index = std::stoi(index_str);

    return arrays_names[std::string(name)][index];
}

double evaluate_expression(const std::string& expr) {
  // I omit all the dirty code that you would need to make yourself
  // to parse the expression
   
  // so I just assume you parsed "abc[3]*abc[2]+abc[1]" to call this:
  return 
    get_value(expr.substr(0, 6)) * 
    get_value(expr.substr(7, 6)) + 
    get_value(expr.substr(14, 6));
}

int main() {
    std::string expr{"abc[3]*abc[2]+abc[1]"};
    std::cout << expr << std::endl;
    std::cout << evaluate_expression(expr) << std::endl;
}

【讨论】:

  • 如果赋值只有 1 个数组 abc get_value() 可以简化为不使用映射。这并不是要批评答案,而是帮助初学者避免不必要的更复杂的解决方案。
  • @drescherjm 是的,它还可以通过在get_value 中执行std::string(name) 来创建strings 的新实例
猜你喜欢
  • 2014-05-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
相关资源
最近更新 更多