带有 ostream 和 istream 的 C++ 向量
c++ vectors with ostream and istream
我有一个代码的鼻屎,我一直无法绕开我的头。前提是输入一组数字:3 4 5 6 7,它将输出:4x^(3(+5x^(2(+6x^(1(+7x^(0( 使用 istream 和 ostream。我正在使用向量来表示数字,我遇到的问题是向量没有正确填充。
例如,如果向量称为 vec1,则上面的输入将给出:
`vec1[0]==4
vec1[1]==5
vec1[2]==6
vec1[3]==4
vec1[4]==4`
但我希望它输出:
`vec1[0]==3
vec1[1]==4
vec1[2]==5
vec1[3]==6
vec1[4]==7`
我找不到任何将 istream 与矢量一起使用的示例教程,所以我希望有人可以帮助我了解将 istream 与矢量一起使用的基础知识?只是一个一般的例子绝对很棒!
PS:我是 c++ 的新手,所以如果我在任何地方使用术语都是错误的,我很抱歉。
编辑:(这是我目前的iStream代码(:
istream& operator>>(istream& left, Polynomial& right) //input
{
int tsize, tmp;
while (!(left >> tsize))
{
left.clear();
left.ignore();
}
if (tsize < 0)
{
tsize *= -1;
}
vector<double>tmp1;
for (int i = 0; i < tsize; i++)
{
tmp1.push_back(0);
}
right.setPolynomial(tmp1);
for (int i = 0; i < tsize; i++)
{
while (!(left >> tmp))
{
left.clear();
left.ignore();
}
right[i]=tmp;
}
//return a value
return left;
}
'
void Polynomial::setPolynomial(vector<double>vec1)
{
for (int i = 0; i < vec1.size(); i++)
polynomial.push_back(vec1[i]);
}
啊,我明白了。像这样的事情怎么样:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
// A polynomial is represented as a single non-negative integer N representing
// the degree, followed by N+1 floating-point values for the coefficients in
// standard left to right order. For example:
// 3 4 5 6 7
// represents the polynomial
// 4x**3 + 5x**2 + 6x + 7
std::istream& operator >> ( std::istream& ins, Polynomial& p )
{
// You could set p to something invalid/empty here
// ...
// Get the degree of the polynomial
int degree;
ins >> degree;
if (degree < 0) ins.setstate( std::ios::failbit );
if (!ins) return ins;
// Get the polynomial's coefficients
std::vector <double> coefficients( degree + 1 );
std::copy_n(
std::istream_iterator <double> ( ins ),
degree + 1,
coefficients.begin()
);
if (!ins) return ins;
// Update p
p.setPolynomial( coefficients );
return ins;
}
正确命名事物会有所帮助,并确保正确循环。如果出现问题,输入流将正确记录错误,除非度数为负数,为此我们需要特殊情况。
我使用了一些标准对象而不是循环;你可以使用任何你觉得更方便的对象:只要记住,在你的第一个整数值后面有 N+1 个双精度值。
最后,请记住公正地使用多项式的函数:如果您可以使用向量在一次传递中设置所有系数,那就这样做。
(顺便说一句,这段代码只是在我脑海中输入的。可能出现了拼写错误和愚蠢的错误。
根据Caleth的评论修改编辑。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么