지도 및 노드를 사용하여 다항식을 읽고 추가하기 위해이 코드를 작성했습니다.지도 및 노드, 오류 IntelliSense : "const std :: pair <const int, double>"에서 "Node"로 사용자 정의 변환이 없습니다.
연산자 +에서 오류가 발생합니다. 노드에 맵을 관련시키는 코드가 없다는 것을 알고 있습니다. "std :: map PolynomialMap"에서 뭔가를 사용해야한다고 생각합니다. 목록과 비슷하지만 무엇이 확실하지 않습니다. 아니면 코드를 완전히 변경하고 다른 방법을 사용해야합니까? 이 충분하지 있다면 내 질문을 향상시키는 방법을 알려 주시기 바랍니다
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <vector>
#include <map>
using namespace std;
typedef struct Node
{
double cof; // coefficient
int deg; // degree
} Node; // the node of polynomial
class CPolynomial
{
private:
std::map<int, double> PolynomialMap;
public:
CPolynomial();
CPolynomial(const string& file);
virtual ~CPolynomial();
CPolynomial operator+(const CPolynomial &right);
CPolynomial& operator=(const CPolynomial &right);
private:
void AddOneTerm(Node term); // add one term into m_Polynomial
};
int main()
{
CPolynomial p1("P3.txt");
CPolynomial p2("P4.txt");
CPolynomial p3;
p3 = p1 + p2;
return 0;
}
CPolynomial::CPolynomial()
{
;
}
CPolynomial::CPolynomial(const string& file)
{
Node term;
fstream MyFile;
string p;
int num;
MyFile.open(file);
if (!MyFile.is_open())
{
cerr << "Unable to open input file" << endl;
exit(EXIT_FAILURE);
}
else
{
MyFile >> p >> num;
map <int, double>::iterator it = PolynomialMap.begin();
for (int i = 0; i < num; i++)
{
MyFile >> term.deg >> term.cof;
AddOneTerm(term);
}
MyFile.close();
}
}
CPolynomial CPolynomial:: operator+(const CPolynomial &right)
{
CPolynomial temp_polynomial;
temp_polynomial.PolynomialMap = PolynomialMap;
map <int, double> ::const_iterator it; it = right.PolynomialMap.begin();
for (; it != right.PolynomialMap.end(); ++it) //
{
AddOneTerm(*it); //error C2664: 'void CPolynomial::AddOneTerm(Node)' : cannot convert argument 1 from 'const std::pair<const _Kty,_Ty>' to 'Node'
//IntelliSense: no suitable user-defined conversion from "const std::pair<const int, double>" to "Node" exists
}
map <int, double> sum_result = PolynomialMap;
PolynomialMap = temp_polynomial.PolynomialMap;
temp_polynomial.PolynomialMap = sum_result;
sum_result.clear();
return temp_polynomial;
}
CPolynomial& CPolynomial:: operator=(const CPolynomial &right)
{
this->PolynomialMap = right.PolynomialMap;
return *this;
}
void CPolynomial::AddOneTerm(Node term)
{
auto it = PolynomialMap.begin();
while (it != PolynomialMap.end() && it->first < term.deg)
{
++it;
}
if (it != PolynomialMap.end() && term.deg == it->first)
{
it->second += term.cof;
}
else
{
PolynomialMap.insert(pair<int, double>(term.deg, term.cof));
}
}
CPolynomial::~CPolynomial()
{
PolynomialMap.clear();
}
에반 감사합니다. 간단하고 유용한 해결책이었습니다. 이 문제에 대해 다른 방법을 알려주십시오. – Saeedeh
문제를 해결하는 다른 두 가지 방법은 (1)'Node'를 생성하고 기존의'AddOneTerm'을 호출하는 메소드 서명'void AddOneTerm (const pair)을 사용하여'CPolynomial'에 또 다른 메소드를 추가하십시오. (2)'AddOneTerm' 메소드를'int' 인수와'Node' 인수 대신에'double' 인수로 바꾸고, 호출 할 때'it-> first'와'it-second'에 쌍을 풉니 다. 'AddOneTerm' 메소드를 호출하고'CPolynomial' 생성자에서'deg'와'cof' 변수로 직접 작업합니다. 접근법 (2)을 사용하면'Node' 구조체를 삭제할 수 있습니다. –