带有 ostream 和 istream 的 C++ 向量

c++ vectors with ostream and istream

本文关键字:C++ 向量 istream ostream 带有      更新时间:2023-10-16

我有一个代码的鼻屎,我一直无法绕开我的头。前提是输入一组数字: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的评论修改编辑。