[英]c++ vectors with ostream and istream
我遇到了這樣的一堆代碼,但我沒辦法將其包裝起來。 前提是輸入一組數字: 3 4 5 6 7 ,它將使用istream和ostream輸出: 4x ^(3)+ 5x ^(2)+ 6x ^(1)+ 7x ^(0) 。 我正在對數字使用向量,而我遇到的問題是向量無法正確填充。
例如,如果將向量稱為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的評論進行了修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.