【问题标题】:Range to integral type conversion范围到整数类型的转换
【发布时间】:2014-09-11 22:10:32
【问题描述】:

我正在寻找将范围转换为整数类型的模板函数。它看起来像这样:

template<typename InputIterator, typename IntegralType>
IntegralType convert(InputIterator first, InputIterator last)
{
...
}

它可以这样使用:

vector<char> buf;
int tag=convert<int>(buf.begin(), buf.end());

有没有标准的方法来做到这一点?以前有人这样做过吗?

谢谢

【问题讨论】:

  • 范围的内容如何映射到积分输出?
  • <algorithm><numeric>中定义了很多将范围转换为数字的标准方法
  • 从值范围到单个值的映射是什么?和?意思是?中位数?标准差?最大限度?分钟?

标签: c++ iterator type-conversion


【解决方案1】:

我正在尝试从缓冲区中解析 tag=value 格式的文本消息。 我们在 C++11 中有 stoi(str, pos, base) 函数,但为了调用它,您需要“str”对象存在并包含正确的值。我需要一种 stoi() 但有一个范围作为参数,可以这样调用:

string str { "49=SenderCompID|50=SenderSubID|..." };
int tag1 = stoi(str.begin(), str.begin() + str.find('='));
int tag2 = stoi(str.begin()+17, str.begin() + 19);

甚至更好:

vector<char> buf { str.begin(), str.end() };
unsigned tag = stointegral<unsigned>(buf.begin(), buf.begin() + 2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多