I’m trying to use C code with opencv in face
detection and counting, but I cannot build the source.
I am trying to compile my project and I am
having a lot of problems with a line in the xutility file.
The error message shows that it is giving errors in the xutility file.
Please help me solve this problem?
Code
// Include header files
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <time.h>
#include <ctype.h>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#ifdef _EiC
#define WIN32
#endif
int countfaces=0;
int numFaces = 0;
int k=0 ;
int list=0;
char filelist[512][512];
int timeCount = 0;
static CvMemStorage* storage = 0;
static CvHaarClassifierCascade* cascade = 0;
void detect_and_draw( IplImage* image );
void WriteInDB();
int found_face(IplImage* img,CvPoint pt1,CvPoint pt2);
int load_DB(char * filename);
const char* cascade_name = "C:\Program Files\OpenCV\OpenCV2.1\data\haarcascades\haarcascade_frontalface_alt_tree.xml";
// BEGIN NEW CODE
#define WRITEVIDEO
char* outputVideo = "c:\face_counting1_tracked.avi";
//int faceCount = 0;
int posBuffer = 100;
int persistDuration = 10; //faces can drop out for 10 frames
int timestamp = 0;
float sameFaceDistThreshold = 30; //pixel distance
CvPoint facePositions[100];
int facePositionsTimestamp[100];
float distance( CvPoint a, CvPoint b ) {
float dist = sqrt(float ( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) ) );
return dist;
}
void expirePositions()
{
for (int i = 0; i < posBuffer; i++)
{
if (facePositionsTimestamp[i] <= (timestamp - persistDuration)) //if a tracked pos is older than three frames
{
facePositions[i] = cvPoint(999,999);
}
}
}
void updateCounter(CvPoint center)
{
bool newFace = true;
for(int i = 0; i < posBuffer; i++)
{
if (distance(center, facePositions[i]) < sameFaceDistThreshold)
{
facePositions[i] = center;
facePositionsTimestamp[i] = timestamp;
newFace = false;
break;
}
}
if(newFace)
{
//push out oldest tracker
for(int i = 1; i < posBuffer; i++)
{
facePositions[i] = facePositions[i - 1];
}
//put new tracked position on top of stack
facePositions[0] = center;
facePositionsTimestamp[0] = timestamp;
countfaces++;
}
}
void drawCounter(IplImage* image) {
// Create Font
char buffer[5];
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, .5, .5, 0, 1);
cvPutText(image, "Faces:", cvPoint(20, 20), &font, CV_RGB(0,255,0));
cvPutText(image, itoa(countfaces, buffer, 10), cvPoint(80, 20), &font, CV_RGB(0,255,0));
}
#ifdef WRITEVIDEO
CvVideoWriter* videoWriter = cvCreateVideoWriter(outputVideo, -1, 30, cvSize(240, 180));
#endif
//END NEW CODE
int main( int argc, char** argv )
{
CvCapture* capture = 0;
IplImage *frame, *frame_copy = 0;
int optlen = strlen("--cascade=");
const char* input_name;
if( argc > 1 && strncmp( argv[1], "--cascade=", optlen ) == 0 )
{
cascade_name = argv[1] + optlen;
input_name = argc > 2 ? argv[2] : 0;
}
else
{
cascade_name = "C:\Program Files\OpenCV\OpenCV2.1\data\haarcascades\haarcascade_frontalface_alt_tree.xml";
input_name = argc > 1 ? argv[1] : 0;
}
cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );
if( !cascade )
{
fprintf( stderr, "ERROR: Could not load classifier cascaden" );
fprintf( stderr,
"Usage: facedetect --cascade="<cascade_path>" [filename|camera_index]n" );
return -1;
}
storage = cvCreateMemStorage(0);
//if( !input_name || (isdigit(input_name[0]) && input_name[1] == '') )
// capture = cvCaptureFromCAM( !input_name ? 0 : input_name[0] - '0' );
//else
capture = cvCaptureFromAVI( "c:\face_counting1.avi" );
cvNamedWindow( "result", 1 );
if( capture )
{
for(;;)
{
if( !cvGrabFrame( capture ))
break;
frame = cvRetrieveFrame( capture );
if( !frame )
break;
if( !frame_copy )
frame_copy = cvCreateImage( cvSize(frame->width,frame->height),
IPL_DEPTH_8U, frame->nChannels );
if( frame->origin == IPL_ORIGIN_TL )
cvCopy( frame, frame_copy, 0 );
else
cvFlip( frame, frame_copy, 0 );
detect_and_draw( frame_copy );
if( cvWaitKey( 30 ) >= 0 )
break;
}
cvReleaseImage( &frame_copy );
cvReleaseCapture( &capture );
}
else
{
if( !input_name || (isdigit(input_name[0]) && input_name[1] == ''))
cvNamedWindow( "result", 1 );
const char* filename = input_name ? input_name : (char*)"lena.jpg";
IplImage* image = cvLoadImage( filename, 1 );
if( image )
{
detect_and_draw( image );
cvWaitKey(0);
cvReleaseImage( &image );
}
else
{
/* assume it is a text file containing the
list of the image filenames to be processed - one per line */
FILE* f = fopen( filename, "rt" );
if( f )
{
char buf[1000+1];
while( fgets( buf, 1000, f ) )
{
int len = (int)strlen(buf);
while( len > 0 && isspace(buf[len-1]) )
len--;
buf[len] = '';
image = cvLoadImage( buf, 1 );
if( image )
{
detect_and_draw( image );
cvWaitKey(0);
cvReleaseImage( &image );
}
}
fclose(f);
}
}
}
cvDestroyWindow("result");
#ifdef WRITEVIDEO
cvReleaseVideoWriter(&videoWriter);
#endif
return 0;
}
void detect_and_draw( IplImage* img )
{
static CvScalar colors[] =
{
{{0,0,255}},
{{0,128,255}},
{{0,255,255}},
{{0,255,0}},
{{255,128,0}},
{{255,255,0}},
{{255,0,0}},
{{255,0,255}}
};
double scale = 1.3;
IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );
IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),
cvRound (img->height/scale)),
8, 1 );
CvPoint pt1, pt2;
int i;
cvCvtColor( img, gray, CV_BGR2GRAY );
cvResize( gray, small_img, CV_INTER_LINEAR );
cvEqualizeHist( small_img, small_img );
cvClearMemStorage( storage );
if( cascade )
{
double t = (double)cvGetTickCount();
CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,
1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,
cvSize(30, 30) );
t = (double)cvGetTickCount() - t;
printf( "detection time = %gmsn", t/((double)cvGetTickFrequency()*1000.) );
if (faces)
{
//To save the detected faces into separate images, here's a quick and dirty code:
char filename[6];
for( i = 0; i < (faces ? faces->total : 0); i++ )
{
/* CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
CvPoint center;
int radius;
center.x = cvRound((r->x + r->width*0.5)*scale);
center.y = cvRound((r->y + r->height*0.5)*scale);
radius = cvRound((r->width + r->height)*0.25*scale);
cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );*/
// Create a new rectangle for drawing the face
CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
// Find the dimensions of the face,and scale it if necessary
pt1.x = r->x*scale;
pt2.x = (r->x+r->width)*scale;
pt1.y = r->y*scale;
pt2.y = (r->y+r->height)*scale;
// Draw the rectangle in the input image
cvRectangle( img, pt1, pt2, CV_RGB(255,0,0), 3, 8, 0 );
CvPoint center;
int radius;
center.x = cvRound((r->x + r->width*0.5)*scale);
center.y = cvRound((r->y + r->height*0.5)*scale);
radius = cvRound((r->width + r->height)*0.25*scale);
cvCircle( img, center, radius, CV_RGB(255,0,0), 3, 8, 0 );
//update counter
updateCounter(center);
int y=found_face(img,pt1,pt2);
if(y==0)
countfaces++;
}//end for
printf("Number of detected faces: %dt",countfaces);
}//end if
//delete old track positions from facePositions array
expirePositions();
timestamp++;
//draw counter
drawCounter(img);
#ifdef WRITEVIDEO
cvWriteFrame(videoWriter, img);
#endif
cvShowImage( "result", img );
cvDestroyWindow("Result");
cvReleaseImage( &gray );
cvReleaseImage( &small_img );
}//end if
} //end void
int found_face(IplImage* img,CvPoint pt1,CvPoint pt2)
{
/*if (faces)
{*/
CvSeq* faces = cvHaarDetectObjects( img, cascade, storage,
1.1, 2, CV_HAAR_DO_CANNY_PRUNING,
cvSize(40, 40) );
int i=0;
char filename[512];
for( i = 0; i < (faces ? faces->total : 0); i++ )
{//int scale = 1, i=0;
//i=iface;
//char filename[512];
/* extract the rectanlges only */
// CvRect face_rect = *(CvRect*)cvGetSeqElem( faces, i);
CvRect face_rect = *(CvRect*)cvGetSeqElem( faces, i);
//IplImage* gray_img = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
IplImage* clone = cvCreateImage (cvSize(img->width, img->height),
IPL_DEPTH_8U, img->nChannels );
IplImage* gray = cvCreateImage (cvSize(img->width, img->height),
IPL_DEPTH_8U, 1 );
cvCopy (img, clone, 0);
cvNamedWindow ("ROI", CV_WINDOW_AUTOSIZE);
cvCvtColor( clone, gray, CV_RGB2GRAY );
face_rect.x = pt1.x;
face_rect.y = pt1.y;
face_rect.width = abs(pt1.x - pt2.x);
face_rect.height = abs(pt1.y - pt2.y);
cvSetImageROI ( gray, face_rect);
//// * rectangle = cvGetImageROI ( clone );
face_rect = cvGetImageROI ( gray );
cvShowImage ("ROI", gray);
k++;
char *name=0;
name=(char*) calloc(512, 1);
sprintf(name, "Image%d.pgm", k);
cvSaveImage(name, gray);
////////////////
for(int j=0;j<512;j++)
filelist[list][j]=name[j];
list++;
WriteInDB();
//int found=SIFT("result.txt",name);
cvResetImageROI( gray );
//return found;
return 0;
// }//end if
}//end for
}//end void
void WriteInDB()
{
ofstream myfile;
myfile.open ("result.txt");
for(int i=0;i<512;i++)
{
if(strcmp(filelist[i],"")!=0)
myfile << filelist[i]<<"n";
}
myfile.close();
}
Error messages
Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 8 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 13 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:program filesmicrosoft visual studio 9.0vcincludexutility 766
Error 18 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:program filesmicrosoft visual studio 9.0vcincludexutility 768
Error 23 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:program filesmicrosoft visual studio 9.0vcincludexutility 769
Error 10 error C2868: 'std::iterator_traits<_Iter>::value_type' : illegal syntax for using-declaration; expected qualified-name c:program filesmicrosoft visual studio 9.0vcincludexutility 765
Error 25 error C2868: 'std::iterator_traits<_Iter>::reference' : illegal syntax for using-declaration; expected qualified-name c:program filesmicrosoft visual studio 9.0vcincludexutility 769
Error 20 error C2868: 'std::iterator_traits<_Iter>::pointer' : illegal syntax for using-declaration; expected qualified-name c:program filesmicrosoft visual studio 9.0vcincludexutility 768
Error 5 error C2868: 'std::iterator_traits<_Iter>::iterator_category' : illegal syntax for using-declaration; expected qualified-name c:program filesmicrosoft visual studio 9.0vcincludexutility 764
Error 15 error C2868: 'std::iterator_traits<_Iter>::difference_type' : illegal syntax for using-declaration; expected qualified-name c:program filesmicrosoft visual studio 9.0vcincludexutility 766
Error 9 error C2602: 'std::iterator_traits<_Iter>::value_type' is not a member of a base class of 'std::iterator_traits<_Iter>' c:program filesmicrosoft visual studio 9.0vcincludexutility 765
Error 24 error C2602: 'std::iterator_traits<_Iter>::reference' is not a member of a base class of 'std::iterator_traits<_Iter>' c:program filesmicrosoft visual studio 9.0vcincludexutility 769
Error 19 error C2602: 'std::iterator_traits<_Iter>::pointer' is not a member of a base class of 'std::iterator_traits<_Iter>' c:program filesmicrosoft visual studio 9.0vcincludexutility 768
Error 4 error C2602: 'std::iterator_traits<_Iter>::iterator_category' is not a member of a base class of 'std::iterator_traits<_Iter>' c:program filesmicrosoft visual studio 9.0vcincludexutility 764
Error 14 error C2602: 'std::iterator_traits<_Iter>::difference_type' is not a member of a base class of 'std::iterator_traits<_Iter>' c:program filesmicrosoft visual studio 9.0vcincludexutility 766
Error 7 error C2146: syntax error : missing ';' before identifier 'value_type' c:program filesmicrosoft visual studio 9.0vcincludexutility 765
Error 22 error C2146: syntax error : missing ';' before identifier 'reference' c:program filesmicrosoft visual studio 9.0vcincludexutility 769
Error 17 error C2146: syntax error : missing ';' before identifier 'pointer' c:program filesmicrosoft visual studio 9.0vcincludexutility 768
Error 2 error C2146: syntax error : missing ';' before identifier 'iterator_category' c:program filesmicrosoft visual studio 9.0vcincludexutility 764
Error 12 error C2146: syntax error : missing ';' before identifier 'difference_type' c:program filesmicrosoft visual studio 9.0vcincludexutility 766
Error 6 error C2039: 'value_type' : is not a member of 'CvPoint' c:program filesmicrosoft visual studio 9.0vcincludexutility 765
Error 21 error C2039: 'reference' : is not a member of 'CvPoint' c:program filesmicrosoft visual studio 9.0vcincludexutility 769
Error 16 error C2039: 'pointer' : is not a member of 'CvPoint' c:program filesmicrosoft visual studio 9.0vcincludexutility 768
Error 1 error C2039: 'iterator_category' : is not a member of 'CvPoint' c:program filesmicrosoft visual studio 9.0vcincludexutility 764
Error 11 error C2039: 'difference_type' : is not a member of 'CvPoint' c:program filesmicrosoft visual studio 9.0vcincludexutility 766
Код в 100 строк, скину суда: https://pastebin.com/xcUnQzjK
Ошибки:
«_UDest»: требуется инициализация объекта типа класса, квалифицированного как const xutility
iterator_category: не является прямым или косвенным базовым классом для «std::iterator_traits<_Iter>» xutility
«std::_Iter_cat_t»: не удалось специализировать шаблон псевдонима xutility
«unknown-type» не требуется xutility
«_Get_unwrapped_n»: не найдена соответствующая перегруженная функция xutility
auto std::_Get_unwrapped_n(const _Iter &,const _Diff): не удается составить аргумент шаблон для «__formal» xutility
_UDest: не может использоваться до инициализации xutility
|
Matubo 0 / 0 / 0 Регистрация: 12.01.2014 Сообщений: 10 |
||||||||||||
|
1 |
||||||||||||
|
26.05.2014, 12:04. Показов 3308. Ответов 4 Метки нет (Все метки)
Не могу разобраться с ошибкой :error C2064: результатом вычисления фрагмента не является функция, принимающая 2 аргументов.
Не могу понять как с ней разобраться, буду рад любой помощи.
сруктура.h
0 |
|
4773 / 3267 / 497 Регистрация: 19.02.2013 Сообщений: 9,046 |
|
|
26.05.2014, 14:04 |
2 |
|
что за тип str (строка 29)?
0 |
|
0 / 0 / 0 Регистрация: 12.01.2014 Сообщений: 10 |
|
|
27.05.2014, 12:27 [ТС] |
3 |
|
что за тип str (строка 29)? Объявление структуры str именем m
0 |
|
Tulosba 4773 / 3267 / 497 Регистрация: 19.02.2013 Сообщений: 9,046 |
||||
|
27.05.2014, 14:34 |
4 |
|||
|
РешениеMatubo, чтобы собиралось, исправьте начало файла:
Корректность алгоритма не проверял.
0 |
|
0 / 0 / 0 Регистрация: 12.01.2014 Сообщений: 10 |
|
|
29.05.2014, 22:07 [ТС] |
5 |
|
чтобы собиралось, исправьте начало файла: Спасибо большое, все собирается)
0 |
- Remove From My Forums
-
Question
-
I have a code as below:
Code Block
class CSIStructure {…}
struct SIPidTables {
SIPidTables(long p, TableColl *t) : m_Pid(p), m_Tables(t) {}
long m_Pid;
TableColl *m_Tables;
};inline bool operator<(const SIPidTables &l, const SIPidTables &r) // The error marker shows on this line
{
return l.m_Pid < r.m_Pid;
}I am getting compilation error as below: (I have included the entire compilation log)
f:program filesmicrosoft visual studio 8vcincludexutility(267) : error C2678: binary ‘<‘ : no operator found which takes a left-hand operand of type ‘const CSIStructure:ITableType’ (or there is no acceptable conversion)
z:india-mpeg-internalcodebasesmultiplexersrcei243 (muxnavigator)sitreeitems.h(145): could be ‘bool operator <(const SIPidTables &,const SIPidTables &)’ [found using argument-dependent lookup]
1> z:india-mpeg-internalcodebasesmultiplexersrcei243 (muxnavigator)sitreeitems.h(122): or ‘bool CSIStructure:ITableType:
perator <(const CSIStructure:
ITableType &)’
1> while trying to match the argument list ‘(const CSIStructure:ITableType, CSIStructure:
ITableType)’
1> f:program filesmicrosoft visual studio 8vcincludealgorithm(1992) : see reference to function template instantiation ‘bool std::_Debug_lt(_Ty1 &,const _Ty2 &,const wchar_t *,unsigned int)’ being compiled
1> with
1> [
1> _Ty=CSIStructure:ITableType,
1> _Ty1=CSIStructure:ITableType,
1> _Ty2=CSIStructure:ITableType
1> ]
1> f:program filesmicrosoft visual studio 8vcincludealgorithm(2004) : see reference to function template instantiation ‘_FwdIt std::_Lower_bound<std::_Vector_iterator,_Ty,__w64 int>(_FwdIt,_FwdIt,const _Ty &,_Diff *)’ being compiled
1> with
1> [
1> _FwdIt=std::_Vector_iterator<CSIStructure::SITableType,std::allocator>,
1> _Ty=CSIStructure:ITableType,
1> _Alloc=std::allocator,
1> _Diff=__w64 int
1> ]
1> z:india-mpeg-internalcodebasesmultiplexersrcei243 (muxnavigator)sitreeitems.cpp(69) : see reference to function template instantiation ‘_FwdIt std::lower_bound<std::_Vector_iterator,CSIStructure:ITableType>(_FwdIt,_FwdIt,const _Ty &)’ being compiled
1> with
1> [
1> _FwdIt=std::_Vector_iterator<CSIStructure::SITableType,std::allocator>,
1> _Ty=CSIStructure:ITableType,
1> _Alloc=std::allocator
1> ]
The code around xutility(267)Code Block
template inline
bool __CLRCALL_OR_CDECL _Debug_lt(_Ty1& _Left, const _Ty2& _Right,
const wchar_t *_Where, unsigned int _Line)
{ // test if _Left < _Right and operator< is strict weak ordering
if (!(_Left < _Right))
return (false);
else if (_Right < _Left) // The error marker shows on this line
_DEBUG_ERROR2(«invalid operator<«, _Where, _Line);
return (true);
}(I have no idea how to stop those smileys from appearing)
</CSIStructure::SITableType,std::allocator</std::_Vector_iterator</CSIStructure::SITableType,std::allocator</std::_Vector_iterator
Answers
-
According to error messages, maybe you should use the predicate version of lower_bound function at line 126 of sitreeitems.cpp file?
I wrote a program in C# for my discrete mathematics class and it worked absolutely fine. My teacher asked me to submit the code in c++ so she can run it on her mac and so I created a new project and typed the code in. After changing everything required (basic syntax editing and changing Lists to vectors) I tried compiling my program and got these errors. I am using visual studio 2010.
Error 6 error C4430: missing type specifier — int assumed. Note: C++ does not support default-int c:program files (x86)microsoft visual studio 10.0vcincludexutility 373 1 hw9_2_cpp
Error 8 error C2868: ‘std::iterator_traits<_Iter>::iterator_category’ : illegal syntax for using-declaration; expected qualified-name c:program files (x86)microsoft visual studio 10.0vcincludexutility 373 1 hw9_2_cpp
Error 7 error C2602: ‘std::iterator_traits<_Iter>::iterator_category’ is not a member of a base class of ‘std::iterator_traits<_Iter>’ c:program files (x86)microsoft visual studio 10.0vcincludexutility 373 1 hw9_2_cpp
Error 5 error C2146: syntax error : missing ‘;’ before identifier ‘iterator_category’ c:program files (x86)microsoft visual studio 10.0vcincludexutility 373 1 hw9_2_cpp
Error 4 error C2039: ‘iterator_category’ : is not a member of ‘std::vector<_Ty,_Ax>’ c:program files (x86)microsoft visual studio 10.0vcincludexutility 373 1 hw9_2_cpp
I haven’t posted the source code yet, because my program compiles successfully using g++ on a linux machine. I get no warnings and errors using that and the execution of program is fine too.
I have no idea why I am getting this error. Could it possible be that I messed up that xutility file?
Do you suggest replacing that file (I really don’t want to get into a version mismatch and get screwed up!) ?
Any help/suggestions are highly appreciated.
Thank you,
-T2
P.S.: I came back here after an year and now it reads «Contribute New Article» instead of posting a question or something. I couldn’t find anything like that and I think it’s just that way. I was just wondering as it’s not really an article but a question.
I’m using a Windows 10 computer and Visual Studio 2022. I’m trying to compile C++ code that was initially written on Linux in 2014. This required rebuilding the code from source files.
At this point, I’ve managed to solve every error in the codebase except for one, which says this:
Error C3848 expression having type 'const compit' would lose some const-volatile qualifiers in order to call 'bool compit::operator ()(const std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> &,const std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> &)'
When I am compiling with a ‘Debug’ configuration, this error comes from C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includexutility line 1528. The code block where this error is thrown is below:
template <class _Pr, class _Ty1, class _Ty2,
enable_if_t<is_same_v<_Remove_cvref_t<_Ty1>, _Remove_cvref_t<_Ty2>>, int> = 0>
constexpr bool _Debug_lt_pred(_Pr&& _Pred, _Ty1&& _Left, _Ty2&& _Right) noexcept(
noexcept(_Pred(_Left, _Right)) && noexcept(_Pred(_Right, _Left))) { //ERROR ON THIS LINE
// test if _Pred(_Left, _Right) and _Pred is strict weak ordering, when the arguments are the cv-same-type
const auto _Result = static_cast<bool>(_Pred(_Left, _Right));
if (_Result) {
_STL_VERIFY(!_Pred(_Right, _Left), "invalid comparator");
}
return _Result;
}
If I change to a ‘Release’ build, the exact same error arises twice in the standard xline file instead of xutility, in the following code block:
template <class _Keyty>
bool _Lower_bound_duplicate(const _Nodeptr _Bound, const _Keyty& _Keyval) const {
return !_Bound->_Isnil && !_DEBUG_LT_PRED(_Getcomp(), _Keyval, _Traits::_Kfn(_Bound->_Myval)); //ERROR ON THIS LINE
}
template <class _Keyty>
_Tree_find_result<_Nodeptr> _Find_lower_bound(const _Keyty& _Keyval) const {
const auto _Scary = _Get_scary();
_Tree_find_result<_Nodeptr> _Result{{_Scary->_Myhead->_Parent, _Tree_child::_Right}, _Scary->_Myhead};
_Nodeptr _Trynode = _Result._Location._Parent;
while (!_Trynode->_Isnil) {
_Result._Location._Parent = _Trynode;
if (_DEBUG_LT_PRED(_Getcomp(), _Traits::_Kfn(_Trynode->_Myval), _Keyval)) { //ERROR ON THIS LINE
_Result._Location._Child = _Tree_child::_Right;
_Trynode = _Trynode->_Right;
} else {
_Result._Location._Child = _Tree_child::_Left;
_Result._Bound = _Trynode;
_Trynode = _Trynode->_Left;
}
}
return _Result;
}
Things I’ve Tried
In this stack overflow answer, a similar error is thrown and the solution is to add const to the comparison operator. However, I can’t edit a standard library file (it forces me to ‘save as’). I’ve Ctrl+F’d my entire solution and didn’t find any std::_List_iterator object, either.
In this github forum, a similar error was thrown due to an out-of-date 3rd party library. My code does use a legacy 3rd party Prosilica camera library, which was downloaded at https://www.alliedvision.com/en/support/software-downloads/. PvAPI.lib and PvAPI.h are included in the project settings. However, these files aren’t mentioned in the error message, and I don’t think I’m able to edit an external library like PvAPI.lib anyway.
What else can I try to solve this problem? I apologize if I’ve missed something obvious, as I’m relatively new to C++.
Additional Info For Comments
Here is more of the error message, from the compiler output. I’m not 100% sure what is relevant, so I’ve posted most of it.
1>C:<path>stabiliser.cpp(261): message : see reference to function template instantiation 'void TooN::IRLS<2,double,TooN::RobustI>::add_mJ<2,TooN::DefaultPrecision,TooN::Internal::VBase>(Precision,const TooN::Vector<2,Precision,TooN::Internal::VBase> &)' being compiled
1> with
1> [
1> Precision=double
1> ]
1>C:<path>stabiliser.cpp(261): message : see reference to function template instantiation 'void TooN::IRLS<2,double,TooN::RobustI>::add_mJ<2,TooN::DefaultPrecision,TooN::Internal::VBase>(Precision,const TooN::Vector<2,Precision,TooN::Internal::VBase> &)' being compiled
1> with
1> [
1> Precision=double
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includexutility(1528,1): error C3848: expression having type 'const compit' would lose some const-volatile qualifiers in order to call 'bool compit::operator ()(const std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> &,const std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> &)'
1> with
1> [
1> _Ty=Chain
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includexutility(1527): message : see reference to function template instantiation 'bool std::_Debug_lt_pred<const compit&,const _Kty&,const _Keyty&,0>(_Pr,_Ty1,_Ty2) noexcept(<expr>)' being compiled
1> with
1> [
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Keyty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=const compit &,
1> _Ty1=const std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>> &,
1> _Ty2=const std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>> &
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includextree(1353): message : see reference to function template instantiation 'std::_Tree_find_result<std::_Tree_node<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>,std::_Default_allocator_traits<_Alloc>::void_pointer> *> std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>::_Find_lower_bound<_Other>(const _Keyty &) const' being compiled
1> with
1> [
1> _Ty=Chain,
1> _Alloc=std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>>,
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=compit,
1> _Other=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Keyty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includextree(1353): message : see reference to function template instantiation 'std::_Tree_find_result<std::_Tree_node<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>,std::_Default_allocator_traits<_Alloc>::void_pointer> *> std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>::_Find_lower_bound<_Other>(const _Keyty &) const' being compiled
1> with
1> [
1> _Ty=Chain,
1> _Alloc=std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>>,
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=compit,
1> _Other=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Keyty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includextree(1363): message : see reference to function template instantiation 'std::_Tree_node<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>::_Find<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>(const _Other &) const' being compiled
1> with
1> [
1> _Ty=Chain,
1> _Alloc=std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>>,
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=compit,
1> _Other=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includextree(1363): message : see reference to function template instantiation 'std::_Tree_node<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>,std::_Default_allocator_traits<_Alloc>::void_pointer> *std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>::_Find<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>(const _Other &) const' being compiled
1> with
1> [
1> _Ty=Chain,
1> _Alloc=std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>>,
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=compit,
1> _Other=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includextree(1362): message : while compiling class template member function 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>>> std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>::find(const std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> &)'
1> with
1> [
1> _Ty=Chain,
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=compit,
1> _Alloc=std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>>
1> ]
1>C:<path>stabiliser.cpp(458): message : see reference to function template instantiation 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>>> std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>::find(const std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>> &)' being compiled
1> with
1> [
1> _Ty=Chain,
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=compit,
1> _Alloc=std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>>
1> ]
1>C:Program FilesMicrosoft Visual Studio2022CommunityVCToolsMSVC14.33.31629includeset(52): message : see reference to class template instantiation 'std::_Tree<std::_Tset_traits<_Kty,_Pr,_Alloc,false>>' being compiled
1> with
1> [
1> _Kty=std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>,
1> _Pr=compit,
1> _Alloc=std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<Chain>>>>
1> ]
1>C:<path>stabiliser.h(82): message : see reference to class template instantiation 'std::set<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>,compit,std::allocator<std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>>>' being compiled
1> with
1> [
1> _Ty=Chain
1> ]
1>system.cpp
The first message is concerning stabiliser.cc line 260. The relevant code block is below:
for (int iteration = 0; iteration < 6; iteration++) {
irls.clear();
ImageRef pixel_offset = ir_rounded(this_offset + offset);
Vector<2> offset_error = vec(pixel_offset) - (this_offset + offset);
for (int i = 0; i < num_trackers; i++) {
double movement = vessel_edgels[i].best_match(im, pixel_offset);
if (movement != VesselEdge::not_found) {
irls.add_mJ(movement, vessel_edgels[i].my_direction); /// ERROR HERE
}
}
irls.compute();
this_offset += irls.get_mu() + offset_error;
}
Apparently, vessel_edgels[i].my_direction is not const and needs to be, since the template I get by CTRL+clicking add_mj is
inline void add_mJ(Precision m, const Vector<Size2,Precision2,Base2>& J)
I’ve tried adding const to the definition of my_direction, but the variable is changed in another file, so it throws an error. I also tried defining a temporary constant variable, like so:
for (int i = 0; i < num_trackers; i++) {
double movement = vessel_edgels[i].best_match(im, pixel_offset);
if (movement != VesselEdge::not_found) {
const TooN::Vector<2> temp = vessel_edgels[i].my_direction; //ADDED THIS LINE
irls.add_mJ(movement, temp);
}
}
But that didn’t change the error message from the Output of the compiler, which still referred to line 261 of stabiliser.cc.
I’ll keep working on this; a lot to google. Thank you for the help in the comments so far. What is stack overflow etiquette at this point? Should I delete the question, or post any solution I find?
Я пытаюсь написать простую программу с использованием std, но всякий раз, когда я делаю это, Visual Studio выдает ошибку, основанную на файле Xutility.
файл является основным, но я хотел проверить некоторые функции, это код:
#include <iostream>
std::string text = "racecar", temp, revText;
bool yes;
void init(){
//std::cin >> text ;
reverseFunction(text);}
void reverseFunction(std::string userWord){
std::reverse(userWord, revText);}
int main(int argc, char *argv[]){
init();}
Я использую VS 2015, но я установил 2017 на новом ноутбуке, и у обоих та же проблема … это ошибки, которые мне дают
C2794 ‘iterator_category’: не является членом какого-либо прямого или косвенного базового класса ‘std :: iterator_traits<_InIt> ‘Project1 c: program files (x86) Microsoft Visual Studio 14.0 vc include xutility 967
ошибка
C2938 ‘_Iter_cat_t’: не удалось специализировать шаблон псевдонима Project1 c: program files (x86) microsoft visual studio 14.0 vc include xutility 967
ошибка
C2062 тип «неизвестного типа» неожиданный Project1 c: program files (x86) microsoft visual studio 14.0 vc include xutility 967
ошибка
C2675 унарный ‘-‘: ‘std :: string’ не определяет этот оператор или преобразование в тип, приемлемый для предопределенного оператора Project1 c: program files (x86) microsoft visual studio 14.0 vc include xutility 3547
ошибка
C2675 унарный ‘++’: ‘std :: string’ не определяет этот оператор или преобразование в тип, приемлемый для предопределенного оператора Project1 c: program files (x86) microsoft visual studio 14.0 vc include xutility 3547
Есть ли какое-то решение для этого, так как у меня есть две машины, работающие в разных версиях, и обе имеют одну и ту же проблему, и я не могу скомпилировать с ошибками
0
Решение
Эта версия кода исправляет это?
#include <iostream>
#include <string>
#include <algorithm>
std::string text = "racecar", temp, revText;
bool yes;
void reverseFunction(std::string userWord)
{
revText = userWord;
std::reverse(revText.begin(), revText.end());
}
void init()
{
//std::cin >> text ;
reverseFunction(text);
}
int main(int argc, char *argv[])
{
init();
}
Были некоторые ошибки:
stringа такжеalgorithmв том числе отсутствовалиreverseFunction()был определен послеinit()следовательно, компилятор не может его найти-
В соответствии с документы,
std::reverseпринимаетbeginа такжеendитераторы как параметры, а не строка, которую вы хотите изменить, и где вы хотите ее сохранить. Есть причины для этого:1- Преобразование данных выполняется на месте,
2. Алгоритмы STL должны быть универсальными и не зависящими от контейнера: они должны работать с любой коллекцией, которая каким-то образом повторяется. Чтобы убедить себя, вы можете попробовать этот кусок кода:
#include <algorithm> #include <iostream> int main() { int t[] = { 0, 1, 2, 3, 4, 5 }; int len = sizeof t / sizeof(int); std::cout << "Before: "; for (int i = 0; i < len; ++i) std::cout << t[i] << " "; std::cout << std::endl; std::reverse(t, t + len); std::cout << "After: "; for (int i = 0; i < len; ++i) std::cout << t[i] << " "; std::cout << std::endl; return 0; }
Это должно дать вам следующий вывод:
Before: 0 1 2 3 4 5
After: 5 4 3 2 1 0
Как видите, алгоритм все еще работает, даже если мы не используем контейнеры STL, мы просто предоставили итератор типа входы.
0
Другие решения
Других решений пока нет …
пытаясь создать функцию которая бы выдавала случайное простое число, я получаю следующие ошибки при компиляции:
Severity Code Description Project File Line Suppression State
Error C2065 ‘_Ty1’: undeclared identifier Project4 c:program files
(x86)microsoft visual
studio2017communityvctoolsmsvc14.12.25827includexutility 3931
Warning C4244 ‘argument’: conversion from ‘time_t’ to ‘unsigned int’,
possible loss of data Project4 c:usersandriidocumentsvisual studio
2017projectsproject4project4source.cpp 8 Error C2825 ‘_Urng’:
must be a class or namespace when followed by ‘::’ Project4 c:program
files (x86)microsoft visual
studio2017communityvctoolsmsvc14.12.25827includexutility 3929
Error C2510 ‘_Urng’: left of ‘::’ must be a
class/struct/union Project4 c:program files (x86)microsoft visual
studio2017communityvctoolsmsvc14.12.25827includexutility 3929
Error C2061 syntax error: identifier ‘result_type’ Project4 c:program
files (x86)microsoft visual
studio2017communityvctoolsmsvc14.12.25827includexutility 3929
Error C2238 unexpected token(s) preceding ‘;’ Project4 c:program
files (x86)microsoft visual
studio2017communityvctoolsmsvc14.12.25827includexutility 3929
Error C2065 ‘_Ty1’: undeclared identifier Project4 c:program files
(x86)microsoft visual
studio2017communityvctoolsmsvc14.12.25827includexutility 3931
Error C2923 ‘std::conditional_t’: ‘_Ty1’ is not a valid template type
argument for parameter ‘_Ty2’ Project4 c:program files
(x86)microsoft visual
studio2017communityvctoolsmsvc14.12.25827includexutility 3931
#include<iostream>
#include <cstddef>
#include <random>
#include <ctime>
int GetRandomNumber(std::size_t f = 300, std::size_t d = 1000)
{
static std::default_random_engine dre(std::time(nullptr));
return std::uniform_int_distribution<>()(f, d);
}
int main()
{
std::cout << GetRandomNumber() << std::endl;
return 0;
system("pause");
}
Буду очень благодарен всем, кто объяснит мне мои ошибки.



Сообщение было отмечено Matubo как решение