将字符串转换为整数数组

Convert a string into an array of integers

本文关键字:整数 数组 转换 字符串      更新时间:2023-10-16

>我有一个字符串,它是空格分隔的整数,我想将其转换为中间体向量数组。我的字符串是这样的:

6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 7 3 19 12 2 22 3 6 3 1 2 1 5 17 13 5 1 6 0 12 6 9 15 2 22 0 27 2 3 4 7 2 8 2 8 6 11 22 4 9 4 1 1 2 2 16 8 3 1 8 0 4 4 2 1 10 24 15 8 2 6 9

如何将其转换为数组/矢量?

使用 std::istream_iterator .例:

std::vector<int> vector(std::istream_iterator<int>(std::cin), std::istream_iterator<int>());

或者,使用std::string

std::string s = "6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 7 3 19 12 2 22 3 6 3 1 2 1 5 17 13 5 1 6 0 12 6 9 15 2 22 0 27 2 3 4 7 2 8 2 8 6 11 22 4 9 4 1 1 2 2 16 8 3 1 8 0 4 4 2 1 10 24 15 8 2 6 9";
std::stringstream ss(s);
std::vector<int> vec((std::istream_iterator<int>(ss)), (std::istream_iterator<int>()));

以下代码执行您需要的操作:

std::istringstream iss(my_string);
std::vector<int> v((std::istream_iterator<int>(iss)),
                   (std::istream_iterator<int>()));

这是一个现成的示例,其中包含所有必需的标头

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
    std::string s = "6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 ";
    std::istringstream is( s );
    std::vector<int> v;
    std::transform( std::istream_iterator<std::string>( is ),
                    std::istream_iterator<std::string>(),
                    std::back_inserter( v ),
                    []( const std::string &s ) { return ( std::stoi( s ) ); } );

    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;
    return 0;
}

或者实际上,您可以简单地使用类 std::vector 的构造函数来代替算法 std::transform,它接受两个迭代器,例如

std::vector<int> v( ( std::istream_iterator<int>( is ) ),
                    std::istream_iterator<int>() );

std::vector<int> v( { std::istream_iterator<int>( is ),
                      std::istream_iterator<int>() } );

我看到了一些更古老、更聪明的方法:

#include <stdlib.h>     /* strtol */
    char *numbers = "6 9 17 5 3 4 10 12 7 3 5 10 6 5 0 10 10 10 13 3 6 10 2 11 33 9 14 7 0 8 7 6 38 2 23 8 4 52 7 3 19 12 2 22 3 6 3 1 2 1 5 17 13 5 1 6 0 12 6 9 15 2 22 0 27 2 3 4 7 2 8 2 8 6 11 22 4 9 4 1 1 2 2 16 8 3 1 8 0 4 4 2 1 10 24 15 8 2 6 9"
    long table[512];
    char *pt;
    int i=0;
    pt = numbers;
    while(pt != NULL)
    table[i++] = strtol (pt,&pt,10);