c++ - 将一串数字解析为整数 vector 的最快方法

标签 c++ boost vector stl

我想知道将一串数字解析为整数 vector 的最快方法是什么。我的情况是我将有数百万行数据,格式如下:

>Header-name
ID1    1    1   12
ID2    3    6   234
.
.
.
>Header-name
ID1    1    1   12
ID2    3    6   234
.
.
.

我想丢弃“Header-name”字段(或者可能稍后将其用于排序),然后忽略 ID 字段,然后将剩余的三个整数放入一个 vector 中。 我意识到我可以只使用 boost split,然后在几个 for 循环中使用词法转换,逻辑忽略某些数据,但我不确定这是否会给我最快的解决方案。我看过 boost spirit 但我真的不明白如何使用它。 Boost 或 STL 都可以。

最佳答案

一定要用boost吗? 我已经使用这个功能一段时间了。我相信我是从 Accelerated C++ 中得到它的,并且从那以后就一直在使用它。您的定界符似乎是制表符或多个空格。如果您将分隔符传递给“”,它可能会起作用。不过,我认为这将取决于实际情况。

std::vector<std::string> split( const std::string& line, const std::string& del )
{
        std::vector<std::string> ret;
        size_t i = 0;

        while ( i != line.size() ) {

                while ( ( i != line.size() ) && ( line.substr(i, 1) == del ) ) {
                        ++i;
                }

                size_t j = i;

                while ( ( j != line.size() ) && ( line.substr(j, 1) != del ) ) {
                        ++j;
                }

                if ( i != j ) {
                        ret.push_back( line.substr( i, j - i ) );
                        i = j;
                }
        }

        return ret;
}

你可以得到每一行:

int main() {
    std::string line;
    std::vector<std::string> lines; 
    while ( std::getline( std::cin, line ) ) {
        lines.push_back( line );
    }

    for ( auto it = lines.begin(); it != lines.end(); it++ ) {
        std::vector<string> vec = split( (*it) );
        // Do something
    }
}

您可以通过快速修改让它返回 std::vector。 使用 atoi( myString.c_str() ) 将每个字符串设为 int 此外,您还需要 checkin 以跳过标题。应该是微不足道的。

请注意,我没有在上面编译。 ;)

关于c++ - 将一串数字解析为整数 vector 的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25797779/

相关文章:

c++ - GLFW 设置回调函数

c++ - 如何使用特定对象的函数指针调用成员函数

c++ - 试图删除 vector 指针重复项。为什么我不能使用 .erase()?

C++:vector 中的 shared_ptr 没有更新原始的 shared_ptr

c++ - 在 QT 中创建一个简单的时钟

c++ - 在使用 git 的企业 C++ 项目中管理 Makefile

c++ - 如何将单个对象转换为boost::any_range?

c++ - boost::variant 获取最后访问的类型

c++ - boost::mutex 在模板中使用时不起作用

matlab - 在matlab上绘制矩阵的点