将一串数字转换为整数向量 c++
Converting a string of numbers into an int vector c++
有没有一种简单的方法可以将一串由空格分隔的数字转换为整数向量或我可以轻松转换为向量的东西?
我正在创建一个输入运算符 (>>) 以使用从命令行输入的值制作二叉树。这是随之而来的主要内容
int main(int argc, char **argv)
{
stringstream stream;
stream << " 10" << " 11" << " 10" << " 2" << endl;
tree = new binary_tree();
stream >> *tree;
if (tree->inorder() != string("7 10 11")) //inorder() prints the tree in order
cout << "Test passed" << endl;
delete tree;
return 0;
}
我遇到的问题是,虽然我可以创建和打印我需要的值,但我无法转换它们并将它们放入向量中 - 为此我有一个工作定义的方法,可以从值创建树。
std::istream& operator>>(std::istream &in, binary_tree &value)
{
vector<int> input_tree;
string readline;
getline(in, readline);
cout << "(" << readline << ")" << endl; //prints correctly - (10 11 10 2)
//where I need to insert insert values into vector
for(int i = 0; i < input_tree.size(); i++)
{
insert(input_tree[i], value); //inserts the values from a vector into a binary tree
}
return in;
}
我尝试遍历字符串并在每个字符上使用 stoi(),但每当空格导致错误时,它总是出错。
感谢您的任何帮助,如果我错过了任何重要信息,请深表歉意。
我认为更容易理解的解决方案(虽然不那么简洁):
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s= "4 5 6";
stringstream ss(s);
vector<int> v;
int hlp;
while(ss >> hlp)
{
v.push_back(hlp);
}
for(auto i: v)
cout << i << 'n';
return 0;
}
您可以使用stringstream
,就像使用cin
一样。
http://ideone.com/Y6UfuW
你可以这样做:
vector<int> vec((istream_iterator<int>(in)), istream_iterator<int>());
这将从in
中读取整数并将它们插入vec
一行中。 这是对istream_iterator
的非常规范的使用,它是标准库的一部分。 然后,您无需阅读每一行并自己解析它。
如果您想阅读有关其工作原理的更多信息,请参阅此处:std::copy 如何与流迭代器配合使用
至于为什么第一个参数周围似乎有一对额外的括号,那是因为"最令人烦恼的解析":https://en.wikipedia.org/wiki/Most_vexing_parse - 只是C++语法的一个愚蠢的怪癖。
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 如何在C++中将整数转换为其数字数组
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 如何将整数字符串转换为整数的二维向量?
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何检测 std::vector::emplace_back 上的隐式转换损失整数精度
- 如何防止双精度值到整数的隐式转换
- 为什么此指针值不能转换为整数的规则是什么?
- 如何解决隐式转换丢失整数精度:'size_t'(又名"无符号长")到'int'警告?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 无法将"整数 (*)[m]"转换为"整数 (*)[100000]
- 静态强制转换允许转换对象指针,但不允许转换整数