【问题标题】:Convert (for example) 12345:12-34 into three ints: (12345, 12, 34) C++ string? [duplicate]将(例如)12345:12-34 转换为三个整数: (12345, 12, 34) C++ 字符串? [复制]
【发布时间】:2021-07-31 19:04:21
【问题描述】:

将这些分成 3 个整数的最快方法是什么?我觉得这应该是可能的,但我能找到的最接近的是:

#include <ostream> 
#include <iostream> 
#include <string> 
#include <sstream> 
#include <vector> 
 
std::vector<int> extract_ints(std::string const& input_str) 
{ 
    std::vector<int> ints; 
    std::istringstream input(input_str); 
 
    std::string number; 
    while (std::getline(input, number, ':')) 
    { 
        std::istringstream iss(number); 
        int i; 
        iss >> i; 
        ints.push_back(i); 
    } 
 
    return ints; 
} 
int main() 
{ 
    typedef std::vector<int> ints_t; 
 
    ints_t const& ints = extract_ints("3254:23-45"); 
    for (ints_t::const_iterator i = ints.begin(), i_end = ints.end(); i != i_end; ++i) 
        std::cout << *i << std::endl; 
 
    return 0; 
} 

在这里找到:https://social.msdn.microsoft.com/Forums/vstudio/en-US/411271cd-5e8a-46f9-a78b-a49a347741c0/comma-delimited-string-to-integer-array?forum=vcgeneral

实际操作的链接在这里:https://godbolt.org/z/8sP9vvqfv 但首先它只会在 ':' 之间分开,不知道如何扩展为 ':' 和 '-'。但其次,这似乎过于复杂......这真的是最好的方法吗?

谢谢

【问题讨论】:

  • 扩展:int a, b, c; char colon, dash; if (iss &gt;&gt; a &gt;&gt; colon &gt;&gt; b &gt;&gt; dash &gt;&gt; c &amp;&amp; colon == ':' &amp;&amp; dash == '-') return {a, b, c}; else return {};
  • 寻求“最佳方式”是在征求意见,这对于 stackoverflow 来说是题外话。您能否改为根据事实和技术术语重新构建您的问题?

标签: c++ string type-conversion integer data-conversion


【解决方案1】:

如何展开为':'s

您从输入中读取一个字符并检查它是否为:。例如:

#include <iostream>
#include <exception>
#include <vector>
#include <sstream>
#include <exception>
std::vector<int> extract_ints(std::string const& input_str) 
{ 
    std::vector<int> r(3); 
    std::istringstream iss(input_str); 
    char c1;
    char c2;
    if (!(
         iss >> r.at(0) >> c1 >> r.at(1) >> c2 >> r.at(2) &&
         c1 == ':' && c2 == '-' &&
         !(iss >> c1)  // test if we are at EOF
    )) {
        throw std::runtime_error("Och och, invalid string");
    }
    return r;
}
int main() {
    for (auto&& i : extract_ints("3254:23-45")) {
        std::cout << i << '\n';
    }
}

【讨论】:

  • 很好,这完全符合预期,甚至比给定的代码更简洁。我现在很想立即将其标记为答案,您能想到这里的速度问题吗?我想这是执行此操作的最快方法吗?
  • 我遵循rules of optimization的第一条规则。我不关心这段代码的速度,因为我没有分析过它。 IE。我非常怀疑优化它有什么意义。无论如何 - are there any issues with speed - 是的,它是 C++,你正在使用 vector&lt;int&gt; 和 istringstream,两者都在分配动态内存。根本不要使用它们(if 这个函数已被分析为瓶颈......),istringstream(我认为)也依赖于语言环境。如果您想要速度,我会自己编写所有扫描功能。
猜你喜欢
  • 2018-05-03
  • 2022-01-17
  • 2020-11-23
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多