将字符串转换为整数数组
Convert a string into an array of integers
>我有一个字符串,它是空格分隔的整数,我想将其转换为中间体向量数组。我的字符串是这样的:
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);
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组