0 / 0 / 1
Регистрация: 14.12.2013
Сообщений: 41
1
11.10.2014, 07:53. Показов 17212. Ответов 2
выдает ошибку, я посмотрел похожие темы, но ничего не помогло. в общем мож кто поймет в чем ошибка
| C++ | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
I’m trying to use STL, but the following doesn’t compile. main.cpp:
#include <set>
#include <algorithm>
using namespace std;
class Odp
{
public:
set<int> nums;
bool IsOdd(int i)
{
return i % 2 != 0;
}
bool fAnyOddNums()
{
set<int>::iterator iter = find_if(nums.begin(), nums.end(), &Odp::IsOdd);
return iter != nums.end();
}
};
int main()
{
Odp o;
o.nums.insert(0);
o.nums.insert(1);
o.nums.insert(2);
}
The error is:
error C2064: term does not evaluate to a function taking 1 arguments
1> c:program filesmicrosoft visual studio 10.0vcincludealgorithm(95) : see reference to function template instantiation '_InIt std::_Find_if<std::_Tree_unchecked_const_iterator<_Mytree>,_Pr>(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1> _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>,
1> _Pr=bool (__thiscall Odp::* )(int)
1> ]
1> main.cpp(20) : see reference to function template instantiation '_InIt std::find_if<std::_Tree_const_iterator<_Mytree>,bool(__thiscall Odp::* )(int)>(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1> _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>,
1> _Pr=bool (__thiscall Odp::* )(int)
1> ]
What am I doing wrong?
class Student {
// ...
bool Graduate() { return m_bGraduate; }
// ...
};
class School {
vector<Student*> m_vecStudents;
void DelAndNullify(Student* &pStd);
void Fun1();
};
void School::DelAndNullify(Student* &pStd)
{
if ( (pStd != NULL) && (pStd->Graduate()) )
{
delete pStd;
pStd = NULL;
}
}
void School::Fun1()
{
for_each(m_vecStudents.begin(), m_vecStudents.end(), mem_fun(&School::DelAndNullify));
}
Error 1 error C2064: term does not evaluate to a function taking 1 arguments C:Program FilesMicrosoft Visual Studio 10.0VCincludealgorithm 22 1 Simulation
Why do I get this error?
updated
change Student to pStd
updated // algorithm file
template<class _InIt, class _Fn1> inline
_Fn1 _For_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{
// perform function for each element
for (; _First != _Last; ++_First)
_Func(*_First); // <<<<<<<< this line!
return (_Func);
}
BTW, if I define the DelAndNullify as static then the following line passes the compiler
for_each(m_vecStudents.begin(), m_vecStudents.end(), ptr_fun(&School::DelAndNullify));
Updated 05/09/2012
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <iostream>
#include <iomanip>
#include <functional>
#include <boost/bind.hpp>
class Student {
public:
Student(int id, bool bGraduate) : m_iID(id), m_bGraduate(bGraduate) {}
bool Graduate() const { return m_bGraduate; }
private:
int m_iID;
bool m_bGraduate;
};
class School {
public:
School(int numStudent)
{
for (int i=0; i<numStudent; ++i)
{
m_vecStudents.push_back(new Student(i+1, false));
}
}
~School()
{
// deallocate the allocated student resource to prevent memory leak!
}
void DelAndNullify(Student* &pStd);
void Fun1();
private:
std::vector<Student*> m_vecStudents;
};
void School::DelAndNullify(Student* &pStd)
{
if ( (pStd != NULL) && (!pStd->Graduate()) )
{
delete pStd;
pStd = NULL;
}
}
void School::Fun1()
{ // http://stackoverflow.com/questions/6065041/error-c2064-term-does-not-evaluate-to-a-function-taking-1-arguments
std::for_each(m_vecStudents.begin(), m_vecStudents.end(), std::bind1st(std::mem_fun(&School::DelAndNullify), this));
//boost::bind(&School::DelAndNullify, this, _1);
}
int main(int /*argc*/, char* /*argv*/[])
{
School school(10);
school.Fun1();
return 0;
}
Error 1 error C2535: ‘void std::binder1st<_Fn2>::operator ()(Student
*&) const’ : member function already defined or declared c:Program FilesMicrosoft Visual Studio 10.0VCincludexfunctional 299
class Student {
// ...
bool Graduate() { return m_bGraduate; }
// ...
};
class School {
vector<Student*> m_vecStudents;
void DelAndNullify(Student* &pStd);
void Fun1();
};
void School::DelAndNullify(Student* &pStd)
{
if ( (pStd != NULL) && (pStd->Graduate()) )
{
delete pStd;
pStd = NULL;
}
}
void School::Fun1()
{
for_each(m_vecStudents.begin(), m_vecStudents.end(), mem_fun(&School::DelAndNullify));
}
Error 1 error C2064: term does not evaluate to a function taking 1 arguments C:Program FilesMicrosoft Visual Studio 10.0VCincludealgorithm 22 1 Simulation
Why do I get this error?
updated
change Student to pStd
updated // algorithm file
template<class _InIt, class _Fn1> inline
_Fn1 _For_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{
// perform function for each element
for (; _First != _Last; ++_First)
_Func(*_First); // <<<<<<<< this line!
return (_Func);
}
BTW, if I define the DelAndNullify as static then the following line passes the compiler
for_each(m_vecStudents.begin(), m_vecStudents.end(), ptr_fun(&School::DelAndNullify));
Updated 05/09/2012
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <iostream>
#include <iomanip>
#include <functional>
#include <boost/bind.hpp>
class Student {
public:
Student(int id, bool bGraduate) : m_iID(id), m_bGraduate(bGraduate) {}
bool Graduate() const { return m_bGraduate; }
private:
int m_iID;
bool m_bGraduate;
};
class School {
public:
School(int numStudent)
{
for (int i=0; i<numStudent; ++i)
{
m_vecStudents.push_back(new Student(i+1, false));
}
}
~School()
{
// deallocate the allocated student resource to prevent memory leak!
}
void DelAndNullify(Student* &pStd);
void Fun1();
private:
std::vector<Student*> m_vecStudents;
};
void School::DelAndNullify(Student* &pStd)
{
if ( (pStd != NULL) && (!pStd->Graduate()) )
{
delete pStd;
pStd = NULL;
}
}
void School::Fun1()
{ // http://stackoverflow.com/questions/6065041/error-c2064-term-does-not-evaluate-to-a-function-taking-1-arguments
std::for_each(m_vecStudents.begin(), m_vecStudents.end(), std::bind1st(std::mem_fun(&School::DelAndNullify), this));
//boost::bind(&School::DelAndNullify, this, _1);
}
int main(int /*argc*/, char* /*argv*/[])
{
School school(10);
school.Fun1();
return 0;
}
Error 1 error C2535: ‘void std::binder1st<_Fn2>::operator ()(Student
*&) const’ : member function already defined or declared c:Program FilesMicrosoft Visual Studio 10.0VCincludexfunctional 299
Can anyone tell me what to do to solve this error?
#include <iostream>
#define MATRIX_DIMENSION 4
int WSACleanup (void);
int main(int nArgs, char** pArgs)
{
int nDim = MATRIX_DIMENSION;
double fMatr[MATRIX_DIMENSION*MATRIX_DIMENSION] =
{
1.0, 2.0, -1.0, -2.0,
1.0, 3.0, -1.0, -2.0,
2.0, 1.0, 1.0, 1.0,
3.0, 1.0, 2.0, 1.0,
};
double fVec[MATRIX_DIMENSION] = {-6.0, -4.0, 11.0, 15.0};
double fSolution[MATRIX_DIMENSION];
int res;
int i;
int LinearEquationsSolving;
res = LinearEquationsSolving(&nDim, &fMatr, &fVec, &fSolution); // !!! Error C2064
if(res)
{
printf(«No solution!n»);
return 1;
}
else
{
printf(«Solution:n»);
}
return 0;
}
The line res = LinearEquationsSolving(&nDim, &fMatr, &fVec, &fSolution); is trying to assign to ‘res’ the value returned by a function but that function does not exist. ‘LinearEquationsSolving’ is an int.
EDIT* Also, prefer const over #define .
Last edited on
I am sorry but I forgot to put the whole code
#include <iostream>
#include <stdio.h>
#include <windows.h>
//==============================================================================
void VectorPrint(int nDim, double* pfVect)
{
int i;
printf(«——————————————————————n»);
for(i=0; i<nDim; i++)
{
printf(«%9.2lf «, pfVect[i]);
}
printf(«n»);
}
//==============================================================================
void MatrixPrint(int nDim, double* pfMatr)
{
int i,j;
printf(«——————————————————————n»);
for(i=0; i<nDim; i++)
{
for(j=0; j<nDim; j++)
{
printf(«%9.2lf «, pfMatr[nDim*i + j]);
}
printf(«n»);
}
}
//==============================================================================
// return 1 if system not solving
// nDim — system dimension
// pfMatr — matrix with coefficients
// pfVect — vector with free members
// pfSolution — vector with system solution
// pfMatr becames trianglular after function call
// pfVect changes after function call
//
// Developer: Henry Guennadi Levkin
//
//==============================================================================
int LinearEquationsSolving(int nDim, double* pfMatr, double* pfVect, double* pfSolution)
{
double fMaxElem;
double fAcc;
int i , j, k, m;
int fabs;
for(k=0; k<(nDim-1); k++) // base row of matrix
{
// search of line with max element
fMaxElem = fabs( pfMatr[k*nDim + k] );
m = k;
for(i=k+1; i<nDim; i++)
{
if(fMaxElem < fabs(pfMatr[i*nDim + k]) )
{
fMaxElem = pfMatr[i*nDim + k];
m = i;
}
}
// permutation of base line (index k) and max element line(index m)
if(m != k)
{
for(i=k; i<nDim; i++)
{
fAcc = pfMatr[k*nDim + i];
pfMatr[k*nDim + i] = pfMatr[m*nDim + i];
pfMatr[m*nDim + i] = fAcc;
}
fAcc = pfVect[k];
pfVect[k] = pfVect[m];
pfVect[m] = fAcc;
}
if( pfMatr[k*nDim + k] == 0.) return 1; // needs improvement !!!
// triangulation of matrix with coefficients
for(j=(k+1); j<nDim; j++) // current row of matrix
{
fAcc = — pfMatr[j*nDim + k] / pfMatr[k*nDim + k];
for(i=k; i<nDim; i++)
{
pfMatr[j*nDim + i] = pfMatr[j*nDim + i] + fAcc*pfMatr[k*nDim + i];
}
pfVect[j] = pfVect[j] + fAcc*pfVect[k]; // free member recalculation
}
}
for(k=(nDim-1); k>=0; k—)
{
pfSolution[k] = pfVect[k];
for(i=(k+1); i<nDim; i++)
{
pfSolution[k] -= (pfMatr[k*nDim + i]*pfSolution[i]);
}
pfSolution[k] = pfSolution[k] / pfMatr[k*nDim + k];
}
return 0;
}
//==============================================================================
// testing of function
//==============================================================================
#define MATRIX_DIMENSION 4
int main(int nArgs, char** pArgs)
{
int nDim = MATRIX_DIMENSION;
double fMatr[MATRIX_DIMENSION*MATRIX_DIMENSION] =
{
1.0, 2.0, -1.0, -2.0,
1.0, 3.0, -1.0, -2.0,
2.0, 1.0, 1.0, 1.0,
3.0, 1.0, 2.0, 1.0,
};
double fVec[MATRIX_DIMENSION] = {-6.0, -4.0, 11.0, 15.0};
double fSolution[MATRIX_DIMENSION];
int res;
int i;
void LinearEquationsSolving();
res = LinearEquationsSolving(nDim, fMatr, fVec, fSolution); // !!!
if(res)
{
printf(«No solution!n»);
return 1;
}
else
{
printf(«Solution:n»);
VectorPrint(nDim, fSolution);
}
return 0;
}
Above the line res = LinearEquationsSolving(nDim, fMatr, fVec, fSolution); // !!! you have void LinearEquationsSolving(); which isn’t valid. Also, in that function you are trying to use a function called fabs which doesn’t exist.
Topic archived. No new replies allowed.
This topic has been deleted. Only users with topic management privileges can see it.
I write Visual Studio 2019.
I had this mission:
Establish a structure describing the student group. Data
group number (e.g. AA-14), number
students in the group, number of other students, number of
foreign students. Create functions: general display
Number of students, total number of different
Students in the flow, the number of foreign students on the screen
stream, retrieval of structure data into source file.
File’s made, he’s.
#include <stdexcept> #include <iostream> #include <fstream> #include <vector>using namespace std;
void inostran(society& akvt);
void inogorodnie(society& akvt);
void obsh_kol(society& akvt);
void rewriting(society& akvt);struct society
{
string name_group; // наименование группы
int number_group; // номер группы
int amount_student; // количество студентов
int inogorodnie; // иногородние студенты
int inostran; // иностранные студенты
};int main()
{
int i = 0, a = 0, n = 1, x = 0;
setlocale(LC_ALL, "rus");
society akvt;
string name;
fstream Fout("D:structura.txt"); // открываем основной файл для записи в него значений
cout << " Введите название Группы - ";
cin >> name;
akvt.name_group = name;
Fout << name << "; "; // наименование группыcout << " Введите номер Группы - "; cin >> x; akvt.number_group = x; Fout << x << "; "; // номер группы cout << " Введите количество студентов - "; cin >> x; Fout << x << "; "; // количество студентов cout << " Введите кол-во иногородних студентов в группе - "; cin >> x; akvt.inogorodnie = x; Fout << x << "; "; // кол-во иногородних студентов cout << " Введите кол-во иностранцев в группе - "; cin >> x; akvt.inostran = x; Fout << x << "; "; // кол-во иностранцев Fout.close(); while (a != 5) { cout << " 1)Bывод на экран общего количества студентов. " << endl; cout << " 2)Bывод на экран общего количества иногородних студентов в потоке. " << endl; cout << " 3)Bывод на экран количества иностранных студентов в потоке. " << endl; cout << " 4)Перезапись данных структуры в исходный файл. " << endl; cout << " 5)Для выхода нажмите пятерочку(5) " << endl; cin >> a; switch (a) { case '1': obsh_kol(akvt); case '2': inogorodnie(akvt); case '3': inostran(akvt); case '4': rewriting(akvt); case '5': exit(1); } } system("pause"); return 0;}
void inostran(society& akvt)
{
cout << " Кол-во иностранных студентов равно " << akvt.inostran;
}void inogorodnie(society& akvt)
{
cout << " Кол-во иногородних студентов равно " << akvt.inogorodnie;
}void obsh_kol(society& akvt)
{
cout<< " Общее кол-во студентов равно " << akvt.amount_student;
}void rewriting(society& akvt)
{
int x;
string name;
fstream Fout("D:structura.txt"); // открываем основной файл для записи в него значений
cout << " Введите название Группы - ";
cin >> name;
akvt.name_group = name;
Fout << name << "; "; // наименование группыcout << " Введите номер Группы - "; cin >> x; akvt.number_group = x; Fout << x << "; "; // номер группы cout << " Введите количество студентов - "; cin >> x; akvt.amount_student = x; Fout << x << "; "; // количество студентов cout << " Введите кол-во иногородних студентов в группе - "; cin >> x; akvt.inogorodnie = x; Fout << x << "; "; // кол-во иногородних студентов cout << " Введите кол-во иностранцев в группе - "; cin >> x; akvt.inostran = x; Fout << x << "; "; // кол-во иностранцев Fout.close();}
Since the launch of the code, mistakes have been made:
1>C:UsersartemOneDriveРабочий столлабораторные работы5 практическая5 практическая.cpp(11,15): error C2065: society: необъявленный идентификатор1>C:UsersartemOneDriveРабочий столлабораторные работы5 практическая5 практическая.cpp(11,24): error C2065: akvt: необъявленный идентификатор
практическая.cpp(11,28): error C2182: inostran: недопустимое использование типа "void"
практическая.cpp(12,18): error C2065: society: необъявленный идентификатор
практическая.cpp(12,27): error C2065: akvt: необъявленный идентификатор
практическая.cpp(12,31): error C2182: inogorodnie: недопустимое использование типа "void"
практическая.cpp(13,15): error C2065: society: необъявленный идентификатор
практическая.cpp(13,24): error C2065: akvt: необъявленный идентификатор
практическая.cpp(13,28): error C2182: obsh_kol: недопустимое использование типа "void"
практическая.cpp(14,16): error C2065: society: необъявленный идентификатор
практическая.cpp(14,25): error C2065: akvt: необъявленный идентификатор
практическая.cpp(14,29): error C2182: rewriting: недопустимое использование типа "void"
практическая.cpp(67,19): error C2064: результатом вычисления фрагмента не является функция, принимающая 1 аргументов
практическая.cpp(68,19): error C2064: результатом вычисления фрагмента не является функция, принимающая 1 аргументов
практическая.cpp(69,19): error C2064: результатом вычисления фрагмента не является функция, принимающая 1 аргументов
практическая.cpp(70,19): error C2064: результатом вычисления фрагмента не является функция, принимающая 1 аргументов
практическая.cpp(77,6): error C2365: inostran: переопределение; предыдущим определением было "переменная данных"
практическая.cpp(11): message : см. объявление "inostran"
практическая.cpp(81,6): error C2365: inogorodnie: переопределение; предыдущим определением было "переменная данных"
практическая.cpp(12): message : см. объявление "inogorodnie"
практическая.cpp(85,6): error C2365: obsh_kol: переопределение; предыдущим определением было "переменная данных"
практическая.cpp(13): message : см. объявление "obsh_kol"
практическая.cpp(89,6): error C2365: rewriting: переопределение; предыдущим определением было "переменная данных"
практическая.cpp(14): message : см. объявление "rewriting"
Please help me.
Well, look, you’re declaring yourself. society FOLLOW announcements
void inostran(society& akvt);
I understand that the compiler is inconceivable. ♪ ♪
If you need more.
#include <string>
the code will even be compiled :