Search Results

Search found 3389 results on 136 pages for 'const'.

Page 18/136 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Confused Why I am getting C1010 error?

    - by bluepixel
    I have three files: Main, slist.h and slist.cpp can be seen at http://forums.devarticles.com/c-c-help-52/confused-why-i-am-getting-c2143-and-c1010-error-259574.html I'm trying to make a program where main reads the list of student names from a file (roster.txt) and inserts all the names in a list in ascending order. This is the full class roster list (notCheckedIN). From here I will read all students who have come to write the exams, each checkin will transfer their name to another list (in ascending order) called present. The final product is notCheckedIN will contain a list of all those students that did not write the exam and present will contain the list of all students who wrote the exam Main File: // Exam.cpp : Defines the entry point for the console application. #include "stdafx.h" #include "iostream" #include "iomanip" #include "fstream" #include "string" #include "slist.h" using namespace std; void OpenFile(ifstream&); void GetClassRoster(SortList&, ifstream&); void InputStuName(SortList&, SortList&); void UpdateList(SortList&, SortList&, string); void Print(SortList&, SortList&); const string END_DATA = "EndData"; int main() { ifstream roster; SortList notCheckedIn; //students present SortList present; //student absent OpenFile(roster); if(!roster) //Make sure file is opened return 1; GetClassRoster(notCheckedIn, roster); //insert the roster list into the notCheckedIn list InputStuName(present, notCheckedIn); Print(present, notCheckedIn); return 0; } void OpenFile(ifstream& roster) //Precondition: roster is pointing to file containing student anmes //Postcondition:IF file does not exist -> exit { string fileName = "roster.txt"; roster.open(fileName.c_str()); if(!roster) cout << "***ERROR CANNOT OPEN FILE :"<< fileName << "***" << endl; } void GetClassRoster(SortList& notCheckedIN, ifstream& roster) //Precondition:roster points to file containing list of student last name // && notCheckedIN is empty //Postcondition:notCheckedIN is filled with the names taken from roster.txt in ascending order { string name; roster >> name; while(roster) { notCheckedIN.Insert(name); roster >> name; } } void InputStuName(SortList& present, SortList& notCheckedIN) //Precondition: present list is empty initially and notCheckedIN list is full //Postcondition: repeated prompting to enter stuName // && notCheckedIN will delete all names found in present // && present will contain names present // && names not found in notCheckedIN will report Error { string stuName; cout << "Enter last name (Enter EndData if none to Enter): "; cin >> stuName; while(stuName!=END_DATA) { UpdateList(present, notCheckedIN, stuName); } } void UpdateList(SortList& present, SortList& notCheckedIN, string stuName) //Precondition:stuName is assigned //Postcondition:IF stuName is present, stuName is inserted in present list // && stuName is removed from the notCheckedIN list // ELSE stuName does not exist { if(notCheckedIN.isPresent(stuName)) { present.Insert(stuName); notCheckedIN.Delete(stuName); } else cout << "NAME IS NOT PRESENT" << endl; } void Print(SortList& present, SortList& notCheckedIN) //Precondition: present and notCheckedIN contains a list of student Names present/not present //Postcondition: content of present and notCheckedIN is printed { cout << "Candidates Present" << endl; present.Print(); cout << "Candidates Absent" << endl; notCheckedIN.Print(); } Header File: //Specification File: slist.h //This file gives the specifications of a list abstract data type //List items inserted will be in order //Class SortList, structured type used to represent an ADT using namespace std; const int MAX_LENGTH = 200; typedef string ItemType; //Class Object (class instance) SortList. Variable of class type. class SortList { //Class Member - components of a class, can be either data or functions public: //Constructor //Post-condition: Empty list is created SortList(); //Const member function. Compiler error occurs if any statement within tries to modify a private data bool isEmpty() const; //Post-condition: == true if list is empty // == false if list is not empty bool isFull() const; //Post-condition: == true if list is full // == false if list is full int Length() const; //Post-condition: size of list void Insert(ItemType item); //Precondition: NOT isFull() && item is assigned //Postcondition: item is in list && Length() = Length()@entry + 1 void Delete(ItemType item); //Precondition: NOT isEmpty() && item is assigned //Postcondition: // IF items is in list at entry // first occurance of item in list is removed // && Length() = Length()@entry -1; // ELSE // list is not changed bool isPresent(ItemType item) const; //Precondition: item is assigned //Postcondition: == true if item is present in list // == false if item is not present in list void Print() const; //Postcondition: All component of list have been output private: int length; ItemType data[MAX_LENGTH]; void BinSearch(ItemType, bool&, int&) const; }; Source File: //Implementation File: slist.cpp //This file gives the specifications of a list abstract data type //List items inserted will be in order //Class SortList, structured type used to represent an ADT #include "iostream" #include "slist.h" using namespace std; // int length; // ItemType data[MAX_SIZE]; //Class Object (class instance) SortList. Variable of class type. SortList::SortList() //Constructor //Post-condition: Empty list is created { length=0; } //Const member function. Compiler error occurs if any statement within tries to modify a private data bool SortList::isEmpty() const //Post-condition: == true if list is empty // == false if list is not empty { return(length==0); } bool SortList::isFull() const //Post-condition: == true if list is full // == false if list is full { return (length==(MAX_LENGTH-1)); } int SortList::Length() const //Post-condition: size of list { return length; } void SortList::Insert(ItemType item) //Precondition: NOT isFull() && item is assigned //Postcondition: item is in list && Length() = Length()@entry + 1 // && list componenet are in ascending order of value { int index; index = length -1; while(index >=0 && item<data[index]) { data[index+1]=data[index]; index--; } data[index+1]=item; length++; } void SortList:elete(ItemType item) //Precondition: NOT isEmpty() && item is assigned //Postcondition: // IF items is in list at entry // first occurance of item in list is removed // && Length() = Length()@entry -1; // && list components are in ascending order // ELSE data array is unchanged { bool found; int position; BinSearch(item,found,position); if (found) { for(int index = position; index < length; index++) data[index]=data[index+1]; length--; } } bool SortList::isPresent(ItemType item) const //Precondition: item is assigned && length <= MAX_LENGTH && items are in ascending order //Postcondition: true if item is found in the list // false if item is not found in the list { bool found; int position; BinSearch(item,found,position); return (found); } void SortList::Print() const //Postcondition: All component of list have been output { for(int x= 0; x<length; x++) cout << data[x] << endl; } void SortList::BinSearch(ItemType item, bool found, int position) const //Precondition: item contains item to be found // && item in the list is an ascending order //Postcondition: IF item is in list, position is returned // ELSE item does not exist in the list { int first = 0; int last = length -1; int middle; found = false; while(!found) { middle = (first+last)/2; if(data[middle]<item) first = middle+1; else if (data[middle] > item) last = middle -1; else found = true; } if(found) position = middle; } I cannot get rid of the C1010 error: fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source? Is there a way to get rid of this error? When I included "stdafx.h" I received the following 32 errors (which does not make sense to me why because I referred back to my manual on how to use Class method - everything looks a.ok.) Error 1 error C2871: 'std' : a namespace with this name does not exist c:\..\slist.h 6 Error 2 error C2146: syntax error : missing ';' before identifier 'ItemType' c:\..\slist.h 8 Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 8 Error 4 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 8 Error 5 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 30 Error 6 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 34 Error 7 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 43 Error 8 error C2146: syntax error : missing ';' before identifier 'data' c:\..\slist.h 52 Error 9 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 52 Error 10 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\..\slist.h 52 Error 11 error C2061: syntax error : identifier 'ItemType' c:\..\slist.h 53 Error 12 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 41 Error 13 error C2761: 'void SortList::Insert(void)' : member function redeclaration not allowed c:\..\slist.cpp 41 Error 14 error C2059: syntax error : ')' c:\..\slist.cpp 41 Error 15 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 45 Error 16 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 45 Error 17 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 57 Error 18 error C2761: 'void SortList:elete(void)' : member function redeclaration not allowed c:\..\slist.cpp 57 Error 19 error C2059: syntax error : ')' c:\..\slist.cpp 57 Error 20 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 65 Error 21 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 65 Error 22 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 79 Error 23 error C2761: 'bool SortList::isPresent(void) const' : member function redeclaration not allowed c:\..\slist.cpp 79 Error 24 error C2059: syntax error : ')' c:\..\slist.cpp 79 Error 25 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 83 Error 26 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 83 Error 27 error C2065: 'data' : undeclared identifier c:\..\slist.cpp 95 Error 28 error C2146: syntax error : missing ')' before identifier 'item' c:\..\slist.cpp 98 Error 29 error C2761: 'void SortList::BinSearch(void) const' : member function redeclaration not allowed c:\..\slist.cpp 98 Error 30 error C2059: syntax error : ')' c:\..\slist.cpp 98 Error 31 error C2143: syntax error : missing ';' before '{' c:\..\slist.cpp 103 Error 32 error C2447: '{' : missing function header (old-style formal list?) c:\..\slist.cpp 103

    Read the article

  • asp.net C# Webcam api error

    - by Eyla
    Greeting, I'm tring to use webcam api with asp.net and C#. I included all the library and reverince I needed for that. the original code I'm use was for windows application and I'm trying to convert it to asp.net web application. I have start capturing button when I click it, it should start capturing but it gives me an error. the error at this line: hHwnd = capCreateCaptureWindowA(iDevice.ToString(), (WS_VISIBLE | WS_CHILD), 0, 0, 640, 480, picCapture.Handle.ToInt32(), 0); and the error message is: Error 1 'System.Web.UI.WebControls.Image' does not contain a definition for 'Handle' and no extension method 'Handle' accepting a first argument of type 'System.Web.UI.WebControls.Image' could be found (are you missing a using directive or an assembly reference?) C:\Users\Ali\Documents\Visual Studio 2008\Projects\Conference\Conference\Conference1.aspx.cs 63 117 Conference Please advice!! ................................................ here is the complete code ........................................... using System; using System.Collections; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Runtime.InteropServices; using System.Drawing.Imaging; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace Conference { public partial class Conference1 : System.Web.UI.Page { #region WebCam API const short WM_CAP = 1024; const int WM_CAP_DRIVER_CONNECT = WM_CAP + 10; const int WM_CAP_DRIVER_DISCONNECT = WM_CAP + 11; const int WM_CAP_EDIT_COPY = WM_CAP + 30; const int WM_CAP_SET_PREVIEW = WM_CAP + 50; const int WM_CAP_SET_PREVIEWRATE = WM_CAP + 52; const int WM_CAP_SET_SCALE = WM_CAP + 53; const int WS_CHILD = 1073741824; const int WS_VISIBLE = 268435456; const short SWP_NOMOVE = 2; const short SWP_NOSIZE = 1; const short SWP_NOZORDER = 4; const short HWND_BOTTOM = 1; int iDevice = 0; int hHwnd; [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SendMessageA")] static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)] object lParam); [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SetWindowPos")] static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags); [System.Runtime.InteropServices.DllImport("user32")] static extern bool DestroyWindow(int hndw); [System.Runtime.InteropServices.DllImport("avicap32.dll")] static extern int capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID); [System.Runtime.InteropServices.DllImport("avicap32.dll")] static extern bool capGetDriverDescriptionA(short wDriver, string lpszName, int cbName, string lpszVer, int cbVer); private void OpenPreviewWindow() { int iHeight = 320; int iWidth = 200; // // Open Preview window in picturebox // hHwnd = capCreateCaptureWindowA(iDevice.ToString(), (WS_VISIBLE | WS_CHILD), 0, 0, 640, 480, picCapture.Handle.ToInt32(), 0); // // Connect to device // if (SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) == 1) { // // Set the preview scale // SendMessage(hHwnd, WM_CAP_SET_SCALE, 1, 0); // // Set the preview rate in milliseconds // SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0); // // Start previewing the image from the camera // SendMessage(hHwnd, WM_CAP_SET_PREVIEW, 1, 0); // // Resize window to fit in picturebox // SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, iWidth, iHeight, (SWP_NOMOVE | SWP_NOZORDER)); } else { // // Error connecting to device close window // DestroyWindow(hHwnd); } } private void ClosePreviewWindow() { // // Disconnect from device // SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, iDevice, 0); // // close window // DestroyWindow(hHwnd); } #endregion protected void Page_Load(object sender, EventArgs e) { } protected void btnStart_Click(object sender, EventArgs e) { int iDevice = int.Parse(device_number_textBox.Text); OpenPreviewWindow(); } } }

    Read the article

  • Webcam api error when accessed from ASP.NET Server-side code

    - by Eyla
    I'm tring to use webcam api with asp.net and C#. I included all the library and references I needed for that. the original code I'm use was for windows application and I'm trying to convert it to asp.net web application. I have start capturing button when I click it, it should start capturing but it gives me an error. the error at this line: hHwnd = capCreateCaptureWindowA(iDevice.ToString(), (WS_VISIBLE | WS_CHILD), 0, 0, 640, 480, picCapture.Handle.ToInt32(), 0); and the error message is: Error 1 'System.Web.UI.WebControls.Image' does not contain a definition for 'Handle' and no extension method 'Handle' accepting a first argument of type 'System.Web.UI.WebControls.Image' could be found (are you missing a using directive or an assembly reference?) C:\Users\Ali\Documents\Visual Studio 2008\Projects\Conference\Conference\Conference1.aspx.cs 63 117 Conference Please advice!! ................................................ here is the complete code ........................................... using System; using System.Collections; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Runtime.InteropServices; using System.Drawing.Imaging; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace Conference { public partial class Conference1 : System.Web.UI.Page { #region WebCam API const short WM_CAP = 1024; const int WM_CAP_DRIVER_CONNECT = WM_CAP + 10; const int WM_CAP_DRIVER_DISCONNECT = WM_CAP + 11; const int WM_CAP_EDIT_COPY = WM_CAP + 30; const int WM_CAP_SET_PREVIEW = WM_CAP + 50; const int WM_CAP_SET_PREVIEWRATE = WM_CAP + 52; const int WM_CAP_SET_SCALE = WM_CAP + 53; const int WS_CHILD = 1073741824; const int WS_VISIBLE = 268435456; const short SWP_NOMOVE = 2; const short SWP_NOSIZE = 1; const short SWP_NOZORDER = 4; const short HWND_BOTTOM = 1; int iDevice = 0; int hHwnd; [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SendMessageA")] static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)] object lParam); [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SetWindowPos")] static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags); [System.Runtime.InteropServices.DllImport("user32")] static extern bool DestroyWindow(int hndw); [System.Runtime.InteropServices.DllImport("avicap32.dll")] static extern int capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID); [System.Runtime.InteropServices.DllImport("avicap32.dll")] static extern bool capGetDriverDescriptionA(short wDriver, string lpszName, int cbName, string lpszVer, int cbVer); private void OpenPreviewWindow() { int iHeight = 320; int iWidth = 200; // // Open Preview window in picturebox // hHwnd = capCreateCaptureWindowA(iDevice.ToString(), (WS_VISIBLE | WS_CHILD), 0, 0, 640, 480, picCapture.Handle.ToInt32(), 0); // // Connect to device // if (SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) == 1) { // // Set the preview scale // SendMessage(hHwnd, WM_CAP_SET_SCALE, 1, 0); // // Set the preview rate in milliseconds // SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0); // // Start previewing the image from the camera // SendMessage(hHwnd, WM_CAP_SET_PREVIEW, 1, 0); // // Resize window to fit in picturebox // SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, iWidth, iHeight, (SWP_NOMOVE | SWP_NOZORDER)); } else { // // Error connecting to device close window // DestroyWindow(hHwnd); } } private void ClosePreviewWindow() { // // Disconnect from device // SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, iDevice, 0); // // close window // DestroyWindow(hHwnd); } #endregion protected void Page_Load(object sender, EventArgs e) { } protected void btnStart_Click(object sender, EventArgs e) { int iDevice = int.Parse(device_number_textBox.Text); OpenPreviewWindow(); } } }

    Read the article

  • Undefined reference to ...

    - by Patrick LaChance
    I keep getting this error message every time I try to compile, and I cannot find out what the problem is. any help would be greatly appreciated: C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::List()' C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::add(int)' collect2: ld returned 1 exit status code: //List.h #ifndef LIST_H #define LIST_H #include <exception> //brief Definition of linked list class class List { public: /** \brief Exception for operating on empty list */ class Empty : public std::exception { public: virtual const char* what() const throw(); }; /** \brief Exception for invalid operations other than operating on an empty list */ class InvalidOperation : public std::exception { public: virtual const char* what() const throw(); }; /** \brief Node within List */ class Node { public: /** data element stored in this node */ int element; /** next node in list */ Node* next; /** previous node in list */ Node* previous; Node (int element); ~Node(); void print() const; void printDebug() const; }; List(); ~List(); void add(int element); void remove(int element); int first()const; int last()const; int removeFirst(); int removeLast(); bool isEmpty()const; int size()const; void printForward() const; void printReverse() const; void printDebug() const; /** enables extra output for debugging purposes */ static bool traceOn; private: /** head of list */ Node* head; /** tail of list */ Node* tail; /** count of number of nodes */ int count; }; #endif //List.cpp I only included the parts of List.cpp that might be the issue #include "List.h" #include <iostream> #include <iomanip> using namespace std; List::List() { //List::size = NULL; head = NULL; tail = NULL; } List::~List() { Node* current; while(head != NULL) { current = head-> next; delete current->previous; if (current->next!=NULL) { head = current; } else { delete current; } } } void List::add(int element) { Node* newNode; Node* current; newNode->element = element; if(newNode->element > head->element) { current = head->next; } else { head->previous = newNode; newNode->next = head; newNode->previous = NULL; return; } while(newNode->element > current->element) { current = current->next; } if(newNode->element <= current->element) { newNode->previous = current->previous; newNode->next = current; } } //main.cpp #include "List.h" #include <iostream> #include <string> using namespace std; //void add(int element); int main (char** argv, int argc) { List* MyList = new List(); bool quit = false; string value; int element; while(quit==false) { cin>>value; if(value == "add") { cin>>element; MyList->add(element); } if(value=="quit") { quit = true; } } return 0; } I'm doing everything I think I'm suppose to be doing. main.cpp isn't complete yet, just trying to get the add function to work first. Any help will be greatly appreciated.

    Read the article

  • I'm new to C++. Please Help me with the Linked List (What functions to add)?

    - by Igal
    DEAR All; Hi, I'm just beginner to C++; Please help me to understand: What functions should be in the Linked list class ? I think there should be overloaded operators << and ; Please help me to improve the code (style, errors, etc,) Thanks for advance. Igal. Please review the small code for the integer List (enclosed MyNODE.h and ListDriver1.cpp); MyNODE.h // This is my first attempt to write linked list. Igal Spector, June 2010. #include <iostream.h> #include <assert.h> //Forward Declaration of the classes: class ListNode; class TheLinkedlist; // Definition of the node (WITH IMPLEMENTATION !!!, without test drive): class ListNode{ friend class TheLinkedlist; public: // constructor: ListNode(const int& value, ListNode *next= 0); // note: no destructor, as this handled by TheLinkedList class. // accessor: return data in the node. // int Show() const {return theData;} private: int theData; //the Data ListNode* theNext; //points to the next node in the list. }; //Implementations: //constructor: inline ListNode::ListNode(const int &value,ListNode *next) :theData(value),theNext(next){} //end of ListNode class, now for the LL class: class TheLinkedlist { public: //constructors: TheLinkedlist(); virtual ~TheLinkedlist(); // Accessors: void InsertAtFront(const &); void AppendAtBack(const &); // void InOrderInsert(const &); bool IsEmpty()const;//predicate function void Print() const; private: ListNode * Head; //pointer to first node ListNode * Tail; //pointer to last node. }; //Implementation: //Default constructor inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {} //Destructor inline TheLinkedlist::~TheLinkedlist(){ if(!IsEmpty()){ //list is not empty cout<<"\n\tDestroying Nodes"<<endl; ListNode *currentPointer=Head, *tempPtr; while(currentPointer != 0){ //Delete remaining Nodes. tempPtr=currentPointer; cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl; currentPointer=currentPointer->theNext; delete tempPtr; } Head=Tail = 0; //don't forget this, as it may be checked one day. } } //Insert the Node to the beginning of the list: void TheLinkedlist::InsertAtFront(const int& value){ ListNode *newPtr = new ListNode(value,Head); assert(newPtr!=0); if(IsEmpty()) //list is empty Head = Tail = newPtr; else { //list is NOT empty newPtr->theNext = Head; Head = newPtr; } } //Insert the Node to the beginning of the list: void TheLinkedlist::AppendAtBack(const int& value){ ListNode *newPtr = new ListNode(value, NULL); assert(newPtr!=0); if(IsEmpty()) //list is empty Head = Tail = newPtr; else { //list is NOT empty Tail->theNext = newPtr; Tail = newPtr; } } //is the list empty? inline bool TheLinkedlist::IsEmpty() const { return (Head == 0); } // Display the contents of the list void TheLinkedlist::Print()const{ if ( IsEmpty() ){ cout << "\n\t The list is empty!!"<<endl; return; } ListNode *tempPTR = Head; cout<<"\n\t The List is: "; while ( tempPTR != 0 ){ cout<< tempPTR->theData <<" "; tempPTR = tempPTR->theNext; } cout<<endl<<endl; } ////////////////////////////////////// The test Driver: //Driver test for integer Linked List. #include <iostream.h> #include "MyNODE.h" // main Driver int main(){ cout<< "\n\t This is the test for integer LinkedList."<<endl; const int arraySize=11, ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12}; cout << "\n\tThe array is: "; //print the numbers. for (int i=0;i<arraySize; i++) cout<<ARRAY[i]<<", "; TheLinkedlist list; //declare the list for(int index=0;index<arraySize;index++) list.AppendAtBack( ARRAY[index] );//create the list cout<<endl<<endl; list.Print(); //print the list return 0; //end of the program. }

    Read the article

  • CSM DX11 issues

    - by KaiserJohaan
    I got CSM to work in OpenGL, and now Im trying to do the same in directx. I'm using the same math library and all and I'm pretty much using the alghorithm straight off. I am using right-handed, column major matrices from GLM. The light is looking (-1, -1, -1). The problem I have is twofolds; For some reason, the ground floor is causing alot of (false) shadow artifacts, like the vast shadowed area you see. I confirmed this when I disabled the ground for the depth pass, but thats a hack more than anything else The shadows are inverted compared to the shadowmap. If you squint you can see the chairs shadows should be mirrored instead. This is the first cascade shadow map, in range of the alien and the chair: I can't figure out why this is. This is the depth pass: for (uint32_t cascadeIndex = 0; cascadeIndex < NUM_SHADOWMAP_CASCADES; cascadeIndex++) { mShadowmap.BindDepthView(context, cascadeIndex); CameraFrustrum cameraFrustrum = CalculateCameraFrustrum(degreesFOV, aspectRatio, nearDistArr[cascadeIndex], farDistArr[cascadeIndex], cameraViewMatrix); lightVPMatrices[cascadeIndex] = CreateDirLightVPMatrix(cameraFrustrum, lightDir); mVertexTransformPass.RenderMeshes(context, renderQueue, meshes, lightVPMatrices[cascadeIndex]); lightVPMatrices[cascadeIndex] = gBiasMatrix * lightVPMatrices[cascadeIndex]; farDistArr[cascadeIndex] = -farDistArr[cascadeIndex]; } CameraFrustrum CalculateCameraFrustrum(const float fovDegrees, const float aspectRatio, const float minDist, const float maxDist, const Mat4& cameraViewMatrix) { CameraFrustrum ret = { Vec4(1.0f, 1.0f, -1.0f, 1.0f), Vec4(1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, 1.0f, -1.0f, 1.0f), Vec4(1.0f, -1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, -1.0f, 1.0f, 1.0f), }; const Mat4 perspectiveMatrix = PerspectiveMatrixFov(fovDegrees, aspectRatio, minDist, maxDist); const Mat4 invMVP = glm::inverse(perspectiveMatrix * cameraViewMatrix); for (Vec4& corner : ret) { corner = invMVP * corner; corner /= corner.w; } return ret; } Mat4 CreateDirLightVPMatrix(const CameraFrustrum& cameraFrustrum, const Vec3& lightDir) { Mat4 lightViewMatrix = glm::lookAt(Vec3(0.0f), -glm::normalize(lightDir), Vec3(0.0f, -1.0f, 0.0f)); Vec4 transf = lightViewMatrix * cameraFrustrum[0]; float maxZ = transf.z, minZ = transf.z; float maxX = transf.x, minX = transf.x; float maxY = transf.y, minY = transf.y; for (uint32_t i = 1; i < 8; i++) { transf = lightViewMatrix * cameraFrustrum[i]; if (transf.z > maxZ) maxZ = transf.z; if (transf.z < minZ) minZ = transf.z; if (transf.x > maxX) maxX = transf.x; if (transf.x < minX) minX = transf.x; if (transf.y > maxY) maxY = transf.y; if (transf.y < minY) minY = transf.y; } Mat4 viewMatrix(lightViewMatrix); viewMatrix[3][0] = -(minX + maxX) * 0.5f; viewMatrix[3][1] = -(minY + maxY) * 0.5f; viewMatrix[3][2] = -(minZ + maxZ) * 0.5f; viewMatrix[0][3] = 0.0f; viewMatrix[1][3] = 0.0f; viewMatrix[2][3] = 0.0f; viewMatrix[3][3] = 1.0f; Vec3 halfExtents((maxX - minX) * 0.5, (maxY - minY) * 0.5, (maxZ - minZ) * 0.5); return OrthographicMatrix(-halfExtents.x, halfExtents.x, -halfExtents.y, halfExtents.y, halfExtents.z, -halfExtents.z) * viewMatrix; } And this is the pixel shader used for the lighting stage: #define DEPTH_BIAS 0.0005 #define NUM_CASCADES 4 cbuffer DirectionalLightConstants : register(CBUFFER_REGISTER_PIXEL) { float4x4 gSplitVPMatrices[NUM_CASCADES]; float4x4 gCameraViewMatrix; float4 gSplitDistances; float4 gLightColor; float4 gLightDirection; }; Texture2D gPositionTexture : register(TEXTURE_REGISTER_POSITION); Texture2D gDiffuseTexture : register(TEXTURE_REGISTER_DIFFUSE); Texture2D gNormalTexture : register(TEXTURE_REGISTER_NORMAL); Texture2DArray gShadowmap : register(TEXTURE_REGISTER_DEPTH); SamplerComparisonState gShadowmapSampler : register(SAMPLER_REGISTER_DEPTH); float4 ps_main(float4 position : SV_Position) : SV_Target0 { float4 worldPos = gPositionTexture[uint2(position.xy)]; float4 diffuse = gDiffuseTexture[uint2(position.xy)]; float4 normal = gNormalTexture[uint2(position.xy)]; float4 camPos = mul(gCameraViewMatrix, worldPos); uint index = 3; if (camPos.z > gSplitDistances.x) index = 0; else if (camPos.z > gSplitDistances.y) index = 1; else if (camPos.z > gSplitDistances.z) index = 2; float3 projCoords = (float3)mul(gSplitVPMatrices[index], worldPos); float viewDepth = projCoords.z - DEPTH_BIAS; projCoords.z = float(index); float visibilty = gShadowmap.SampleCmpLevelZero(gShadowmapSampler, projCoords, viewDepth); float angleNormal = clamp(dot(normal, gLightDirection), 0, 1); return visibilty * diffuse * angleNormal * gLightColor; } As you can see I am using depth bias and a bias matrix. Any hints on why this behaves so wierdly?

    Read the article

  • Platformer Starter Kit - Collision Issues

    - by Cyral
    I'm having trouble with my game that is based off the XNA Platformer starter kit. My game uses smaller tiles (16x16) then the original (32x40) which I'm thinking may be having an effect on collision (Being it needs to be more precise). Standing on the edge of a tile and jumping causes the player to move off the the tile when he lands. And 80% of the time, when the player lands, he goes flying though SOLID tiles in a diagonal fashion. This is very annoying as it is almost impossible to test other features, when spawning and jumping will result in the player landing in another part of the level or falling off the edge completely. The code is as follows: /// <summary> /// Updates the player's velocity and position based on input, gravity, etc. /// </summary> public void ApplyPhysics(GameTime gameTime) { float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; Vector2 previousPosition = Position; // Base velocity is a combination of horizontal movement control and // acceleration downward due to gravity. velocity.X += movement * MoveAcceleration * elapsed; velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed); velocity.Y = DoJump(velocity.Y, gameTime); // Apply pseudo-drag horizontally. if (IsOnGround) velocity.X *= GroundDragFactor; else velocity.X *= AirDragFactor; // Prevent the player from running faster than his top speed. velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed); // Apply velocity. Position += velocity * elapsed; Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y)); // If the player is now colliding with the level, separate them. HandleCollisions(); // If the collision stopped us from moving, reset the velocity to zero. if (Position.X == previousPosition.X) velocity.X = 0; if (Position.Y == previousPosition.Y) velocity.Y = 0; } /// <summary> /// Detects and resolves all collisions between the player and his neighboring /// tiles. When a collision is detected, the player is pushed away along one /// axis to prevent overlapping. There is some special logic for the Y axis to /// handle platforms which behave differently depending on direction of movement. /// </summary> private void HandleCollisions() { // Get the player's bounding rectangle and find neighboring tiles. Rectangle bounds = BoundingRectangle; int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width); int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1; int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height); int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1; // Reset flag to search for ground collision. isOnGround = false; // For each potentially colliding tile, for (int y = topTile; y <= bottomTile; ++y) { for (int x = leftTile; x <= rightTile; ++x) { // If this tile is collidable, ItemCollision collision = Level.GetCollision(x, y); if (collision != ItemCollision.Passable) { // Determine collision depth (with direction) and magnitude. Rectangle tileBounds = Level.GetBounds(x, y); Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds); if (depth != Vector2.Zero) { float absDepthX = Math.Abs(depth.X); float absDepthY = Math.Abs(depth.Y); // Resolve the collision along the shallow axis. if (absDepthY < absDepthX || collision == ItemCollision.Platform) { // If we crossed the top of a tile, we are on the ground. if (previousBottom <= tileBounds.Top) isOnGround = true; // Ignore platforms, unless we are on the ground. if (collision == ItemCollision.Impassable || IsOnGround) { // Resolve the collision along the Y axis. Position = new Vector2(Position.X, Position.Y + depth.Y); // Perform further collisions with the new bounds. bounds = BoundingRectangle; } } else if (collision == ItemCollision.Impassable) // Ignore platforms. { // Resolve the collision along the X axis. Position = new Vector2(Position.X + depth.X, Position.Y); // Perform further collisions with the new bounds. bounds = BoundingRectangle; } } } } } // Save the new bounds bottom. previousBottom = bounds.Bottom; } It also tends to jitter a little bit sometimes, I'm solved some of this with some fixes I found here on stackexchange, But Ive only seen one other case of the flying though blocks problem. This question seems to have a similar problem in the video, but mine is more crazy. Again this is a very annoying bug! Any help would be greatly appreciated! EDIT: Speed stuff // Constants for controling horizontal movement private const float MoveAcceleration = 13000.0f; private const float MaxMoveSpeed = 1750.0f; private const float GroundDragFactor = 0.48f; private const float AirDragFactor = 0.58f; // Constants for controlling vertical movement private const float MaxJumpTime = 0.35f; private const float JumpLaunchVelocity = -3500.0f; private const float GravityAcceleration = 3400.0f; private const float MaxFallSpeed = 550.0f; private const float JumpControlPower = 0.14f;

    Read the article

  • How can I implement a database TableView like thing in C++?

    - by Industrial-antidepressant
    How can I implement a TableView like thing in C++? I want to emulating a tiny relation database like thing in C++. I have data tables, and I want to transform it somehow, so I need a TableView like class. I want filtering, sorting, freely add and remove items and transforming (ex. view as UPPERCASE and so on). The whole thing is inside a GUI application, so datatables and views are attached to a GUI (or HTML or something). So how can I identify an item in the view? How can I signal it when the table is changed? Is there some design pattern for this? Here is a simple table, and a simple data item: #include <string> #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/random_access_index.hpp> using boost::multi_index_container; using namespace boost::multi_index; struct Data { Data() {} int id; std::string name; }; struct row{}; struct id{}; struct name{}; typedef boost::multi_index_container< Data, indexed_by< random_access<tag<row> >, ordered_unique<tag<id>, member<Data, int, &Data::id> >, ordered_unique<tag<name>, member<Data, std::string, &Data::name> > > > TDataTable; class DataTable { public: typedef Data item_type; typedef TDataTable::value_type value_type; typedef TDataTable::const_reference const_reference; typedef TDataTable::index<row>::type TRowIndex; typedef TDataTable::index<id>::type TIdIndex; typedef TDataTable::index<name>::type TNameIndex; typedef TRowIndex::iterator iterator; DataTable() : row_index(rule_table.get<row>()), id_index(rule_table.get<id>()), name_index(rule_table.get<name>()), row_index_writeable(rule_table.get<row>()) { } TDataTable::const_reference operator[](TDataTable::size_type n) const { return rule_table[n]; } std::pair<iterator,bool> push_back(const value_type& x) { return row_index_writeable.push_back(x); } iterator erase(iterator position) { return row_index_writeable.erase(position); } bool replace(iterator position,const value_type& x) { return row_index_writeable.replace(position, x); } template<typename InputIterator> void rearrange(InputIterator first) { return row_index_writeable.rearrange(first); } void print_table() const; unsigned size() const { return row_index.size(); } TDataTable rule_table; const TRowIndex& row_index; const TIdIndex& id_index; const TNameIndex& name_index; private: TRowIndex& row_index_writeable; }; class DataTableView { DataTableView(const DataTable& source_table) {} // How can I implement this? // I want filtering, sorting, signaling upper GUI layer, and sorting, and ... }; int main() { Data data1; data1.id = 1; data1.name = "name1"; Data data2; data2.id = 2; data2.name = "name2"; DataTable table; table.push_back(data1); DataTable::iterator it1 = table.row_index.iterator_to(table[0]); table.erase(it1); table.push_back(data1); Data new_data(table[0]); new_data.name = "new_name"; table.replace(table.row_index.iterator_to(table[0]), new_data); for (unsigned i = 0; i < table.size(); ++i) std::cout << table[i].name << std::endl; #if 0 // using scenarios: DataTableView table_view(table); table_view.fill_from_source(); // synchronization with source table_view.remove(data_item1); // remove item from view table_view.add(data_item2); // add item from source table table_view.filter(filterfunc); // filtering table_view.sort(sortfunc); // sorting // modifying from source_able, hot to signal the table_view? // FYI: Table view is atteched to a GUI item table.erase(data); table.replace(data); #endif return 0; }

    Read the article

  • Determining the angle to fire a shot when target and shooter moves, and bullet moves with shooter velocity added in

    - by Azaral
    I saw this question: Predicting enemy position in order to have an object lead its target and followed the link in the answer to stack overflow. In the stack overflow page I used the 2nd answer, the one that is a large mathematical derivation. My situation is a little different though. My first question though is will the answer provided in the stack overflow page even work to begin with, assuming the original circumstances of moving target and stationary shooter. My situation is a little different than that situation. My target moves, the shooter moves, and the bullets from the shooter start off with the velocities in x and y added to the bullets' x and y velocities. If you are sliding to the right, the bullets will remain in front of you as you move so as long as your velocity remains constant. What I'm trying to do is to get the enemy to be able to determine where they need to shoot in order to hit the player. Unless the player and enemy is stationary, the velocity from the ship adding to the velocity of the bullets will cause a miss. I'd rather like to prevent that. I used the formula in the stack overflow answer and did what I thought were the appropriate adjustments. I've been banging at this for the last four hours and I just can't make it click. It is probably something really simple and boneheaded that I am missing (that seems to be a lot of my problems lately). Here is the solution presented from the stack overflow answer: It boils down to solving a quadratic equation of the form: a * sqr(x) + b * x + c == 0 Note that by sqr I mean square, as opposed to square root. Use the following values: a := sqr(target.velocityX) + sqr(target.velocityY) - sqr(projectile_speed) b := 2 * (target.velocityX * (target.startX - cannon.X) + target.velocityY * (target.startY - cannon.Y)) c := sqr(target.startX - cannon.X) + sqr(target.startY - cannon.Y) Now we can look at the discriminant to determine if we have a possible solution. disc := sqr(b) - 4 * a * c If the discriminant is less than 0, forget about hitting your target -- your projectile can never get there in time. Otherwise, look at two candidate solutions: t1 := (-b + sqrt(disc)) / (2 * a) t2 := (-b - sqrt(disc)) / (2 * a) Note that if disc == 0 then t1 and t2 are equal. If there are no other considerations such as intervening obstacles, simply choose the smaller positive value. (Negative t values would require firing backward in time to use!) Substitute the chosen t value back into the target's position equations to get the coordinates of the leading point you should be aiming at: aim.X := t * target.velocityX + target.startX aim.Y := t * target.velocityY + target.startY Here is my code, after being corrected by Sam Hocevar (thank you again for your help!). It still doesn't work. For some reason it never enters the section of code inside the if(disc = 0) (obviously because it is always less than zero but...). However, if I plug the numbers from my game log on the enemy and player positions and velocities it outputs a valid firing solution. I have looked at the code side by side a couple of times now and I can't find any differences. There has got to be something simple I'm missing here. If someone else could look at this code and determine what is going on here I'd appreciate it. I know it's not going through that section because if it were, shouldShoot would become true and the enemy would be blasting away at the player. This section calls the function in question, CalculateShootHeading() if(shouldMove) { UseEngines(); } x += xVelocity; y += yVelocity; CalculateShootHeading(); if(shouldShoot) { ShootWeapons(); } UpdateWeapons(); This is CalculateShootHeading(). This is inside the enemy class so x and y are the enemy's x and y and the same with velocity. One output from my game log gives Player X = 2108, Player Y = -180.956, Player X velocity = 10.9949, Player Y Velocity = -6.26017, Enemy X = 1988.31, Enemy Y = -339.051, Enemy X velocity = 1.81666, Enemy Y velocity = -9.67762, 0 enemy projectiles. The output from the console tester is Bullet position = 2210.49, -239.313 and Player Position = 2210.49, -239.313. This doesn't make any sense. The only thing that could be different is the code or the input into my function in the game and I've checked that and I don't think that it is wrong as it's updated before this and never changed. float const bulletSpeed = 30.f; float const dx = playerX - x; float const dy = playerY - y; float const vx = playerXVelocity - xVelocity; float const vy = playerYVelocity - yVelocity; float const a = vx * vx + vy * vy - bulletSpeed * bulletSpeed; float const b = 2.f * (vx * dx + vy * dy); float const c = dx * dx + dy * dy; float const disc = b * b - 4.f * a * c; shouldShoot = false; if (disc >= 0.f) { float t0 = (-b - std::sqrt(disc)) / (2.f * a); float t1 = (-b + std::sqrt(disc)) / (2.f * a); if (t0 < 0.f || (t1 < t0 && t1 >= 0.f)) { t0 = t1; } if (t0 >= 0.f) { float shootx = vx + dx / t0; float shooty = vy + dy / t0; heading = std::atan2(shooty, shootx) * RAD2DEGREE; } shouldShoot = true; }

    Read the article

  • FLTK Images (Using Cmake)

    - by Cenoc
    I'm trying to load and manipulate a jpeg file using FLTK compiled using cmake... but I get the following errors: 2LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_read_scanlines referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_start_decompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_calc_output_dimensions referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_read_header referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_stdio_src referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_CreateDecompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_destroy_decompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) 2fltkimages.lib(Fl_JPEG_Image.obj) : error LNK2019: unresolved external symbol _jpeg_finish_decompress referenced in function "public: __thiscall Fl_JPEG_Image::Fl_JPEG_Image(char const *)" (??0Fl_JPEG_Image@@QAE@PBD@Z) I hate these linking errors..... can anyone help? Thank you in advance.

    Read the article

  • With PascalMock how do I mock a method with an untyped out parameter and an open array parameter?

    - by Oliver Giesen
    I'm currently in the process of getting started with unit testing and mocking for good and I stumbled over the following method that I can't seem to fabricate a working mock implementation for: function GetInstance(const AIID: TGUID; out AInstance; const AArgs: array of const; const AContextID: TImplContextID = CID_DEFAULT): Boolean; (TImplContextID is just an alias for Integer) I thought it would have to look something like this: function TImplementationProviderMock.GetInstance( const AIID: TGUID; out AInstance; const AArgs: array of const; const AContextID: TImplContextID): Boolean; begin Result := AddCall('GetInstance') .WithParams([@AIID, AContextID]) .ReturnsOutParams([AInstance]) .ReturnValue; end; But the compiler complains about the .ReturnsOutParams([AInstance]) saying "Bad argument type in variable type array constructor.". Also I haven't found a way to specify the open array parameter AArgs at all. Also, is using the @-notation for the TGUID-typed parameter the right way to go? Is it possible to mock this method with the current version of PascalMock at all?

    Read the article

  • Emulating Dynamic Dispatch in C++ based on Template Parameters

    - by Jon Purdy
    This is heavily simplified for the sake of the question. Say I have a hierarchy: struct Base { virtual int precision() const = 0; }; template<int Precision> struct Derived : public Base { typedef Traits<Precision>::Type Type; Derived(Type data) : value(data) {} virtual int precision() const { return Precision; } Type value; }; I want a function like: Base* function(const Base& a, const Base& b); Where the specific type of the result of the function is the same type as whichever of first and second has the greater Precision; something like the following pseudocode: template<class T> T* operation(const T& a, const T& b) { return new T(a.value + b.value); } Base* function(const Base& a, const Base& b) { if (a.precision() > b.precision()) return operation((A&)a, A(b.value)); else if (a.precision() < b.precision()) return operation(B(a.value), (B&)b); else return operation((A&)a, (A&)b); } Where A and B are the specific types of a and b, respectively. I want f to operate independently of how many instantiations of Derived there are. I'd like to avoid a massive table of typeid() comparisons, though RTTI is fine in answers. Any ideas?

    Read the article

  • Artifacts when trying to draw background grid without anti-aliasing in a QGraphicsScene

    - by estan
    Hi folks, I'm trying to draw a background grid in the drawBackground() function of my QGraphicsScene subclass: void Scene::drawBackground(QPainter *painter, const QRectF &rect) { const int gridSize = 50; const int realLeft = static_cast<int>(std::floor(rect.left())); const int realRight = static_cast<int>(std::ceil(rect.right())); const int realTop = static_cast<int>(std::floor(rect.top())); const int realBottom = static_cast<int>(std::ceil(rect.bottom())); // Draw grid. const int firstLeftGridLine = realLeft - (realLeft % gridSize); const int firstTopGridLine = realTop - (realTop % gridSize); QVarLengthArray<QLine, 100> lines; for (qreal x = firstLeftGridLine; x <= realRight; x += gridSize) lines.append(QLine(x, realTop, x, realBottom)); for (qreal y = firstTopGridLine; y <= realBottom; y += gridSize) lines.append(QLine(realLeft, y, realRight, y)); //painter->setRenderHint(QPainter::Antialiasing); painter->setPen(QPen(QColor(220, 220, 220), 0.0)); painter->drawLines(lines.data(), lines.size()); // Draw axes. painter->setPen(QPen(Qt::lightGray, 0.0)); painter->drawLine(0, realTop, 0, realBottom); painter->drawLine(realLeft, 0, realRight, 0); } However, unless I turn on anti-aliasing, moving items around will sometimes leave artifacts in the grid (areas where it's not drawn). It seems it mostly happens at low zoom levels, when the view is zoomed out a bit. Any ideas what I might be doing wrong here? I'd really don't want to turn anti-aliasing on since the lines are strictly horizontal and vertical, and I'd like them to be as crisp as possible. Any help is much appriciated, Regards, Elvis

    Read the article

  • C++ function overloading and dynamic binding compile problem

    - by Olorin
    #include <iostream> using namespace std; class A { public: virtual void foo(void) const { cout << "A::foo(void)" << endl; } virtual void foo(int i) const { cout << i << endl; } virtual ~A() {} }; class B : public A { public: void foo(int i) const { this->foo(); cout << i << endl; } }; class C : public B { public: void foo(void) const { cout << "C::foo(void)" << endl; } }; int main(int argc, char ** argv) { C test; test.foo(45); return 0; } The above code does not compile with: $>g++ test.cpp -o test.exe test.cpp: In member function 'virtual void B::foo(int) const': test.cpp:17: error: no matching function for call to 'B::foo() const' test.cpp:17: note: candidates are: virtual void B::foo(int) const test.cpp: In function 'int main(int, char**)': test.cpp:31: error: no matching function for call to 'C::foo(int)' test.cpp:23: note: candidates are: virtual void C::foo() const It compiles if method "foo(void)" is changed to "goo(void)". Why is this so? Is it possible to compile the code without changing the method name of "foo(void)"? Thanks.

    Read the article

  • Is it a bug???????????????/

    - by Knowing me knowing you
    I'm using VS2010 Ultimate. Having code: //file IntSet.h #include "stdafx.h" #pragma once /*Class representing set of integers*/ template<class T> class IntSet { private: T** myData_; std::size_t mySize_; std::size_t myIndex_; public: #pragma region ctor/dtor explicit IntSet(); virtual ~IntSet(); #pragma endregion #pragma region publicInterface IntSet makeUnion(const IntSet&)const; IntSet makeIntersection(const IntSet&)const; IntSet makeSymmetricDifference(const IntSet&)const; void insert(const T&); #pragma endregion }; //file IntSet_impl.h #include "StdAfx.h" #include "IntSet.h" #pragma region ctor/dtor template<class T> IntSet<T>::IntSet():myData_(nullptr), mySize_(0), myIndex_(0) { } template<class T> IntSet<T>::~IntSet() { } #pragma endregion #pragma region publicInterface template<class T> void IntSet<T>::insert(const T& obj) {/*IF I SET A BREAKPOINT HERE AND AFTER THAT I CHANGE SOMETHING IN THE BODY I'M GETTING MSG SAYING THAT THE BREAKPOINT WILL NOT CURRENTLY BE HIT, AFTER I REBUILD THE BREAKPOINT IS VALID AGAIN*/ /*Check if we are initialized*/ if (mySize_ == 0) { mySize_ = 1; myData_ = new T*[mySize_]; } /*Check if we have place to insert obj in.*/ if (myIndex_ < mySize_) { myData_[myIndex_++] = new T(obj); return; } /*We didn't have enough place...*/ T** tmp = new T*[mySize_];//for copying old to temporary basket std::copy(&myData_[0],&myData_[mySize_],&tmp[0]); delete myData_; auto oldSize = mySize_; mySize_ *= 2; myData_ = new T*[mySize_]; std::copy(&tmp[0],&tmp[oldSize],&myData_[0]); myData_[myIndex_] = new T(obj); ++myIndex_; } #pragma endregion Thanks.

    Read the article

  • C++ Virtual Methods for Class-Specific Attributes or External Structure

    - by acanaday
    I have a set of classes which are all derived from a common base class. I want to use these classes polymorphically. The interface defines a set of getter methods whose return values are constant across a given derived class, but vary from one derived class to another. e.g.: enum AVal { A_VAL_ONE, A_VAL_TWO, A_VAL_THREE }; enum BVal { B_VAL_ONE, B_VAL_TWO, B_VAL_THREE }; class Base { //... virtual AVal getAVal() const = 0; virtual BVal getBVal() const = 0; //... }; class One : public Base { //... AVal getAVal() const { return A_VAL_ONE }; BVal getBVal() const { return B_VAL_ONE }; //... }; class Two : public Base { //... AVal getAVal() const { return A_VAL_TWO }; BVal getBVal() const { return B_VAL_TWO }; //... }; etc. Is this a common way of doing things? If performance is an important consideration, would I be better off pulling the attributes out into an external structure, e.g.: struct Vals { AVal a_val; VBal b_val; }; storing a Vals* in each instance, and rewriting Base as follows? class Base { //... public: AVal getAVal() const { return _vals->a_val; }; BVal getBVal() const { return _vals->b_val; }; //... private: Vals* _vals; }; Is the extra dereference essentially the same as the vtable lookup? What is the established idiom for this type of situation? Are both of these solutions dumb? Any insights are greatly appreciated

    Read the article

  • How string accepting interface should look like?

    - by ybungalobill
    Hello, This is a follow up of this question. Suppose I write a C++ interface that accepts or returns a const string. I can use a const char* zero-terminated string: void f(const char* str); // (1) The other way would be to use an std::string: void f(const string& str); // (2) It's also possible to write an overload and accept both: void f(const char* str); // (3) void f(const string& str); Or even a template in conjunction with boost string algorithms: template<class Range> void f(const Range& str); // (4) My thoughts are: (1) is not C++ish and may be less efficient when subsequent operations may need to know the string length. (2) is bad because now f("long very long C string"); invokes a construction of std::string which involves a heap allocation. If f uses that string just to pass it to some low-level interface that expects a C-string (like fopen) then it is just a waste of resources. (3) causes code duplication. Although one f can call the other depending on what is the most efficient implementation. However we can't overload based on return type, like in case of std::exception::what() that returns a const char*. (4) doesn't work with separate compilation and may cause even larger code bloat. Choosing between (1) and (2) based on what's needed by the implementation is, well, leaking an implementation detail to the interface. The question is: what is the preffered way? Is there any single guideline I can follow? What's your experience?

    Read the article

  • how to define a field of view for the entire map for shadow?

    - by Mehdi Bugnard
    I recently added "Shadow Mapping" in my XNA games to include shadows. I followed the nice and famous tutorial from "Riemers" : http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Shadow_map.php . This code work nice and I can see my source of light and shadow. But the problem is that my light source does not match the field of view that I created. I want the light covers the entire map of my game. I don't know why , but the light only affect 2-3 cubes of my map. ScreenShot: (the emission of light illuminates only 2-3 blocks and not the full map) Here is my code i create the fieldOfView for LightviewProjection Matrix: Vector3 lightDir = new Vector3(10, 52, 10); lightPos = new Vector3(10, 52, 10); Matrix lightsView = Matrix.CreateLookAt(lightPos, new Vector3(105, 50, 105), new Vector3(0, 1, 0)); Matrix lightsProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1f, 20f, 1000f); lightsViewProjectionMatrix = lightsView * lightsProjection; As you can see , my nearPlane and FarPlane are set to 20f and 100f . So i don't know why the light stop after 2 cubes. it's should be bigger Here is set the value to my custom effect HLSL in the shader file /* SHADOW VALUE */ effectWorld.Parameters["LightDirection"].SetValue(lightDir); effectWorld.Parameters["xLightsWorldViewProjection"].SetValue(Matrix.Identity * .lightsViewProjectionMatrix); effectWorld.Parameters["xWorldViewProjection"].SetValue(Matrix.Identity * arcadia.camera.View * arcadia.camera.Projection); effectWorld.Parameters["xLightPower"].SetValue(1f); effectWorld.Parameters["xAmbient"].SetValue(0.3f); Here is my custom HLSL shader effect file "*.fx" // This sample uses a simple Lambert lighting model. float3 LightDirection = normalize(float3(-1, -1, -1)); float3 DiffuseLight = 1.25; float3 AmbientLight = 0.25; uniform const float3 DiffuseColor = 1; uniform const float Alpha = 1; uniform const float3 EmissiveColor = 0; uniform const float3 SpecularColor = 1; uniform const float SpecularPower = 16; uniform const float3 EyePosition; // FOG attribut uniform const float FogEnabled ; uniform const float FogStart ; uniform const float FogEnd ; uniform const float3 FogColor ; float3 cameraPos : CAMERAPOS; texture Texture; sampler Sampler = sampler_state { Texture = (Texture); magfilter = LINEAR; minfilter = LINEAR; mipfilter = LINEAR; AddressU = mirror; AddressV = mirror; }; texture xShadowMap; sampler ShadowMapSampler = sampler_state { Texture = <xShadowMap>; magfilter = LINEAR; minfilter = LINEAR; mipfilter = LINEAR; AddressU = clamp; AddressV = clamp; }; /* *************** */ /* SHADOW MAP CODE */ /* *************** */ struct SMapVertexToPixel { float4 Position : POSITION; float4 Position2D : TEXCOORD0; }; struct SMapPixelToFrame { float4 Color : COLOR0; }; struct SSceneVertexToPixel { float4 Position : POSITION; float4 Pos2DAsSeenByLight : TEXCOORD0; float2 TexCoords : TEXCOORD1; float3 Normal : TEXCOORD2; float4 Position3D : TEXCOORD3; }; struct SScenePixelToFrame { float4 Color : COLOR0; }; float DotProduct(float3 lightPos, float3 pos3D, float3 normal) { float3 lightDir = normalize(pos3D - lightPos); return dot(-lightDir, normal); } SSceneVertexToPixel ShadowedSceneVertexShader(float4 inPos : POSITION, float2 inTexCoords : TEXCOORD0, float3 inNormal : NORMAL) { SSceneVertexToPixel Output = (SSceneVertexToPixel)0; Output.Position = mul(inPos, xWorldViewProjection); Output.Pos2DAsSeenByLight = mul(inPos, xLightsWorldViewProjection); Output.Normal = normalize(mul(inNormal, (float3x3)World)); Output.Position3D = mul(inPos, World); Output.TexCoords = inTexCoords; return Output; } SScenePixelToFrame ShadowedScenePixelShader(SSceneVertexToPixel PSIn) { SScenePixelToFrame Output = (SScenePixelToFrame)0; float2 ProjectedTexCoords; ProjectedTexCoords[0] = PSIn.Pos2DAsSeenByLight.x / PSIn.Pos2DAsSeenByLight.w / 2.0f + 0.5f; ProjectedTexCoords[1] = -PSIn.Pos2DAsSeenByLight.y / PSIn.Pos2DAsSeenByLight.w / 2.0f + 0.5f; float diffuseLightingFactor = 0; if ((saturate(ProjectedTexCoords).x == ProjectedTexCoords.x) && (saturate(ProjectedTexCoords).y == ProjectedTexCoords.y)) { float depthStoredInShadowMap = tex2D(ShadowMapSampler, ProjectedTexCoords).r; float realDistance = PSIn.Pos2DAsSeenByLight.z / PSIn.Pos2DAsSeenByLight.w; if ((realDistance - 1.0f / 100.0f) <= depthStoredInShadowMap) { diffuseLightingFactor = DotProduct(xLightPos, PSIn.Position3D, PSIn.Normal); diffuseLightingFactor = saturate(diffuseLightingFactor); diffuseLightingFactor *= xLightPower; } } float4 baseColor = tex2D(Sampler, PSIn.TexCoords); Output.Color = baseColor*(diffuseLightingFactor + xAmbient); return Output; } SMapVertexToPixel ShadowMapVertexShader(float4 inPos : POSITION) { SMapVertexToPixel Output = (SMapVertexToPixel)0; Output.Position = mul(inPos, xLightsWorldViewProjection); Output.Position2D = Output.Position; return Output; } SMapPixelToFrame ShadowMapPixelShader(SMapVertexToPixel PSIn) { SMapPixelToFrame Output = (SMapPixelToFrame)0; Output.Color = PSIn.Position2D.z / PSIn.Position2D.w; return Output; } /* ******************* */ /* END SHADOW MAP CODE */ /* ******************* */ / For rendering without instancing. technique ShadowMap { pass Pass0 { VertexShader = compile vs_2_0 ShadowMapVertexShader(); PixelShader = compile ps_2_0 ShadowMapPixelShader(); } } technique ShadowedScene { /* pass Pass0 { VertexShader = compile vs_2_0 VSBasicTx(); PixelShader = compile ps_2_0 PSBasicTx(); } */ pass Pass1 { VertexShader = compile vs_2_0 ShadowedSceneVertexShader(); PixelShader = compile ps_2_0 ShadowedScenePixelShader(); } } technique SimpleFog { pass Pass0 { VertexShader = compile vs_2_0 VSBasicTx(); PixelShader = compile ps_2_0 PSBasicTx(); } } I edited my fx file , for show you only information and functions about the shadow ;-)

    Read the article

  • Need help with BOOST_FOREACH/compiler bug

    - by Jacek Lawrynowicz
    I know that boost or compiler should be last to blame, but I can't see another explanation here. I'm using msvc 2008 SP1 and boost 1.43. In the following code snippet execution never leaves third BOOST_FOREACH loop typedef Graph<unsigned, unsigned>::VertexIterator Iter; Graph<unsigned, unsigned> g; g.createVertex(0x66); // works fine Iter it = g.getVertices().first, end = g.getVertices().second; for(; it != end; ++it) ; // fine std::pair<Iter, Iter> p = g.getVertices(); BOOST_FOREACH(unsigned handle, p) ; // fine unsigned vertex_count = 0; BOOST_FOREACH(unsigned handle, g.getVertices()) vertex_count++; // oops, infinite loop vertex_count = 0; BOOST_FOREACH(unsigned handle, g.getVertices()) vertex_count++; vertex_count = 0; BOOST_FOREACH(unsigned handle, g.getVertices()) vertex_count++; // ... last block repeated 7 times Iterator code: class Iterator : public boost::iterator_facade<Iterator, unsigned const, boost::bidirectional_traversal_tag> { public: Iterator() : list(NULL), handle(INVALID_ELEMENT_HANDLE) {} explicit Iterator(const VectorElementsList &list, unsigned handle = INVALID_ELEMENT_HANDLE) : list(&list), handle(handle) {} friend std::ostream& operator<<(std::ostream &s, const Iterator &it) { s << "[list: " << it.list <<", handle: " << it.handle << "]"; return s; } private: friend class boost::iterator_core_access; void increment() { handle = list->getNext(handle); } void decrement() { handle = list->getPrev(handle); } unsigned const& dereference() const { return handle; } bool equal(Iterator const& other) const { return handle == other.handle && list == other.list; } const VectorElementsList<T> *list; unsigned handle; }; Some ASM fun: vertex_count = 0; BOOST_FOREACH(unsigned handle, g.getVertices()) // initialization 013E1369 mov edi,dword ptr [___defaultmatherr+8 (13E5034h)] // end iterator handle: 0xFFFFFFFF 013E136F mov ebp,dword ptr [esp+0ACh] // begin iterator handle: 0x0 013E1376 lea esi,[esp+0A8h] // begin iterator list pointer 013E137D mov ebx,esi 013E137F nop // forever loop begin 013E1380 cmp ebp,edi 013E1382 jne main+238h (13E1388h) 013E1384 cmp ebx,esi 013E1386 je main+244h (13E1394h) 013E1388 lea eax,[esp+18h] 013E138C push eax // here iterator is incremented in ram 013E138D call boost::iterator_facade<detail::VectorElementsList<Graph<unsigned int,unsigned int>::VertexWrapper>::Iterator,unsigned int const ,boost::bidirectional_traversal_tag,unsigned int const &,int>::operator++ (13E18E0h) 013E1392 jmp main+230h (13E1380h) vertex_count++; // forever loop end It's easy to see that iterator handle is cached in EBP and it never gets incremented despite of a call to iterator operator++() function. I've replaced Itarator implmentation with one deriving from std::iterator and the issue persisted, so this is not iterator_facade fault. This problem exists only on msvc 2008 SP1 x86 and amd64 release builds. Debug builds on msvc 2008 and debug/release builds on msvc 2010 and gcc 4.4 (linux) works fine. Furthermore the BOOST_FOREACH block must be repeaded exacly 10 times. If it's repeaded 9 times, it's all OK. I guess that due to BOOST_FOREACH use of template trickery (const auto_any), compiler assumes that iterator handle is constant and never reads its real value again. I would be very happy to hear that my code is wrong, correct it and move on with BOOST_FOREACH, which I'm very found of (as opposed to BOOST_FOREVER :). May be related to: http://stackoverflow.com/questions/1275852/why-does-boost-foreach-not-work-sometimes-with-c-strings

    Read the article

  • Linker errors between multiple projects in Visual C++

    - by rlbond
    Hi, I have a solution with multiple projects. I have a "main" project, which acts as a menu and from there, the user can access any of the other projects. On this main project, I get linker errors for every function called. How do I avoid these linker errors? I set the project dependencies already in the "Project Dependencies..." dialog. Thanks EDIT -- I did as suggested and added the output folder to the linker's additional directories. Now, however, I get a million errors as follows: 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_ios ::setstate(int,bool)" (?setstate@?$basic_ios@DU?$char_traits@D@std@@@std@@QAEXH_N@Z) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::ios_base::width(int)" (?width@ios_base@std@@QAEHH@Z) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::basic_streambuf ::sputn(char const *,int)" (?sputn@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEHPBDH@Z) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: static bool __cdecl std::char_traits::eq_int_type(int const &,int const &)" (?eq_int_type@?$char_traits@D@std@@SA_NABH0@Z) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: static int __cdecl std::char_traits::eof(void)" (?eof@?$char_traits@D@std@@SAHXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::basic_streambuf ::sputc(char)" (?sputc@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEHD@Z) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::basic_streambuf * __thiscall std::basic_ios ::rdbuf(void)const " (?rdbuf@?$basic_ios@DU?$char_traits@D@std@@@std@@QBEPAV?$basic_streambuf@DU?$char_traits@D@std@@@2@XZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: char __thiscall std::basic_ios ::fill(void)const " (?fill@?$basic_ios@DU?$char_traits@D@std@@@std@@QBEDXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::ios_base::flags(void)const " (?flags@ios_base@std@@QBEHXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: int __thiscall std::ios_base::width(void)const " (?width@ios_base@std@@QBEHXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: static unsigned int __cdecl std::char_traits::length(char const *)" (?length@?$char_traits@D@std@@SAIPBD@Z) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::basic_ostream & __thiscall std::basic_ostream ::flush(void)" (?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV12@XZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::basic_ostream * __thiscall std::basic_ios ::tie(void)const " (?tie@?$basic_ios@DU?$char_traits@D@std@@@std@@QBEPAV?$basic_ostream@DU?$char_traits@D@std@@@2@XZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: bool __thiscall std::ios_base::good(void)const " (?good@ios_base@std@@QBE_NXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_ostream ::_Osfx(void)" (?_Osfx@?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEXXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_streambuf ::_Lock(void)" (?_Lock@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEXXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: void __thiscall std::basic_streambuf ::_Unlock(void)" (?_Unlock@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QAEXXZ) already defined in panels.lib(panel_main.obj) 3msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: class std::locale::facet * __thiscall std::locale::facet::_Decref(void)" (?_Decref@facet@locale@std@@QAEPAV123@XZ) already defined in panels.lib(panel_main.obj) 3libcpmtd.lib(ios.obj) : error LNK2005: "private: static void __cdecl std::ios_base::_Ios_base_dtor(class std::ios_base *)" (?_Ios_base_dtor@ios_base@std@@CAXPAV12@@Z) already defined in msvcprtd.lib(MSVCP90D.dll) 3libcpmtd.lib(ios.obj) : error LNK2005: "public: static void __cdecl std::ios_base::_Addstd(class std::ios_base *)" (?_Addstd@ios_base@std@@SAXPAV12@@Z) already defined in msvcprtd.lib(MSVCP90D.dll) 3libcpmtd.lib(locale0.obj) : error LNK2005: "void __cdecl _AtModuleExit(void (__cdecl*)(void))" (?_AtModuleExit@@YAXP6AXXZ@Z) already defined in msvcprtd.lib(locale0_implib.obj) 3libcpmtd.lib(locale0.obj) : error LNK2005: __Fac_tidy already defined in msvcprtd.lib(locale0_implib.obj) 3libcpmtd.lib(locale0.obj) : error LNK2005: "private: static void __cdecl std::locale::facet::facet_Register(class std::locale::facet *)" (?facet_Register@facet@locale@std@@CAXPAV123@@Z) already defined in msvcprtd.lib(locale0_implib.obj) 3libcpmtd.lib(locale0.obj) : error LNK2005: "private: static class std::locale::_Locimp * __cdecl std::locale::_Getgloballocale(void)" (?_Getgloballocale@locale@std@@CAPAV_Locimp@12@XZ) already defined in msvcprtd.lib(MSVCP90D.dll) 3libcpmtd.lib(locale0.obj) : error LNK2005: "private: static class std::locale::_Locimp * __cdecl std::locale::_Init(void)" (?_Init@locale@std@@CAPAV_Locimp@12@XZ) already defined in msvcprtd.lib(MSVCP90D.dll) 3libcpmtd.lib(locale0.obj) : error LNK2005: "public: static void __cdecl std::_Locinfo::_Locinfo_ctor(class std::_Locinfo *,class std::basic_string,class std::allocator const &)" (?_Locinfo_ctor@_Locinfo@std@@SAXPAV12@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z) already defined in msvcprtd.lib(MSVCP90D.dll) 3libcpmtd.lib(locale0.obj) : error LNK2005: "public: static void __cdecl std::_Locinfo::_Locinfo_dtor(class std::_Locinfo *)" (?_Locinfo_dtor@_Locinfo@std@@SAXPAV12@@Z) already defined in msvcprtd.lib(MSVCP90D.dll) 3libcpmtd.lib(xlock.obj) : error LNK2005: "public: __thiscall std::_Lockit::_Lockit(int)" (??0_Lockit@std@@QAE@H@Z) already defined in msvcprtd.lib(MSVCP90D.dll) 3libcpmtd.lib(xlock.obj) : error LNK2005: "public: __thiscall std::_Lockit::~_Lockit(void)" (??1_Lockit@std@@QAE@XZ) already defined in msvcprtd.lib(MSVCP90D.dll)

    Read the article

  • How does void QTableWidget::setItemPrototype ( const QTableWidgetItem * item ) clones objects?

    - by chappar
    QTableWidget::setItemPrototype says following. "The table widget will use the item prototype clone function when it needs to create a new table item. For example when the user is editing in an empty cell. This is useful when you have a QTableWidgetItem subclass and want to make sure that QTableWidget creates instances of your subclass." How does this actually work as you can pass any of the QTableWidgetItem subclass pointer to setItemPrototype and at run time there is no way you can get the size of an object having just pointer to it?

    Read the article

  • Is there a way that I can hard code a const XmlNameTable to be reused by all of my XmlTextReader(s)?

    - by highone
    Before I continue I would just like to say I know that "Premature optimization is the root of all evil." However this program is only a hobby project and I enjoy trying to find ways to optimize it. That being said, I was reading an article on improving xml performance and it recommended sharing "the XmlNameTable class that is used to store element and attribute names across multiple XML documents of the same type to improve performance." I wasn't able to find any information about doing this in my googling, so it is likely that this is either not possible, a no-no, or a stupid question, but what's the harm in asking?

    Read the article

  • Help with Boost Grammar

    - by Decmanc04
    I have been using the following win32 console code to try to parse a B Machine Grammar embedded within C++ using Boost Spirit grammar template. I am a relatively new Boost user. The code compiles, but when I run the .exe file produced by VC++2008, the program partially parses the input file. I believe the problem is with my grammar definition or the functions attached as semantic atctions. The code is given below: // BIFAnalyser.cpp : Defines the entry point for the console application. // // /*============================================================================= Copyright (c) Temitope Jos Onunkun 2010 http://www.dcs.kcl.ac.uk/pg/onun/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // // B Machine parser using the Boost "Grammar" and "Semantic Actions". // // // //////////////////////////////////////////////////////////////////////////// #include <boost/spirit/core.hpp> #include <boost/tokenizer.hpp> #include <iostream> #include <string> #include <fstream> #include <vector> #include <utility> /////////////////////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; /////////////////////////////////////////////////////////////////////////////////////////// // // Semantic actions // //////////////////////////////////////////////////////////////////////////// vector<string> strVect; namespace { //semantic action function on individual lexeme void do_noint(char const* str, char const* end) { string s(str, end); if(atoi(str)) { ; } else { strVect.push_back(s); cout << "PUSH(" << s << ')' << endl; } } //semantic action function on addition of lexemes void do_add(char const*, char const*) { cout << "ADD" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; } //semantic action function on subtraction of lexemes void do_subt(char const*, char const*) { cout << "SUBTRACT" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; } //semantic action function on multiplication of lexemes void do_mult(char const*, char const*) { cout << "\nMULTIPLY" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; cout << "\n"; } //semantic action function on division of lexemes void do_div(char const*, char const*) { cout << "\nDIVIDE" << endl; for(vector<string>::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) cout << *vi << " "; } //semantic action function on simple substitution void do_sSubst(char const* str, char const* end) { string s(str, end); //use boost tokenizer to break down tokens typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; boost::char_separator<char> sep("-+/*:=()"); // default char separator Tokenizer tok(s, sep); Tokenizer::iterator tok_iter = tok.begin(); pair<string, string > dependency; //create a pair object for dependencies //save first variable token in simple substitution dependency.first = *tok.begin(); //create a vector object to store all tokens vector<string> dx; // for( ; tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } vector<string> d_hat; //stores set of dependency pairs string dep; //pairs variables as string object for(int unsigned i=1; i < dx.size()-1; i++) { dependency.second = dx.at(i); dep = dependency.first + "|->" + dependency.second + " "; d_hat.push_back(dep); } cout << "PUSH(" << s << ')' << endl; for(int unsigned i=0; i < d_hat.size(); i++) cout <<"\n...\n" << d_hat.at(i) << " "; cout << "\nSIMPLE SUBSTITUTION\n"; } //semantic action function on multiple substitution void do_mSubst(char const* str, char const* end) { string s(str, end); //use boost tokenizer to break down tokens typedef boost::tokenizer<boost::char_separator<char> > Tok; boost::char_separator<char> sep("-+/*:=()"); // default char separator Tok tok(s, sep); Tok::iterator tok_iter = tok.begin(); // string start = *tok.begin(); vector<string> mx; for( ; tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { mx.push_back(*tok_iter ); } mx.push_back("END\n"); //add a marker "end" for(unsigned int i=0; i<mx.size(); i++) { // if(mx.at(i) == "END" || mx.at(i) == "||" ) // break; // else if( mx.at(i) == "||") // do_sSubst(str, end); // else // { // do_sSubst(str, end); // } cout << "\nTokens ... " << mx.at(i) << " "; } cout << "PUSH(" << s << ')' << endl; cout << "MULTIPLE SUBSTITUTION\n"; } } //////////////////////////////////////////////////////////////////////////// // // Simple Substitution Grammar // //////////////////////////////////////////////////////////////////////////// // Simple substitution grammar parser with integer values removed struct Substitution : public grammar<Substitution> { template <typename ScannerT> struct definition { definition(Substitution const& ) { multi_subst = (simple_subst [&do_mSubst] >> +( str_p("||") >> simple_subst [&do_mSubst]) ) ; simple_subst = (Identifier >> str_p(":=") >> expression)[&do_sSubst] ; Identifier = alpha_p >> +alnum_p//[do_noint] ; expression = term >> *( ('+' >> term)[&do_add] | ('-' >> term)[&do_subt] ) ; term = factor >> *( ('*' >> factor)[&do_mult] | ('/' >> factor)[&do_div] ) ; factor = lexeme_d[( (alpha_p >> +alnum_p) | +digit_p)[&do_noint]] | '(' >> expression >> ')' | ('+' >> factor) ; } rule<ScannerT> expression, term, factor, Identifier, simple_subst, multi_subst ; rule<ScannerT> const& start() const { return multi_subst; } }; }; //////////////////////////////////////////////////////////////////////////// // // Main program // //////////////////////////////////////////////////////////////////////////// int main() { cout << "************************************************************\n\n"; cout << "\t\t...Machine Parser...\n\n"; cout << "************************************************************\n\n"; // cout << "Type an expression...or [q or Q] to quit\n\n"; //prompt for file name to be input cout << "Please enter a filename...or [q or Q] to quit:\n\n "; char strFilename[256]; //file name store as a string object cin >> strFilename; ifstream inFile(strFilename); // opens file object for reading //output file for truncated machine (operations only) Substitution elementary_subst; // Simple substitution parser object string str, next; // inFile.open(strFilename); while (inFile >> str) { getline(cin, next); str += next; if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; parse_info<> info = parse(str.c_str(), elementary_subst, space_p); if (info.full) { cout << "\n-------------------------\n"; cout << "Parsing succeeded\n"; cout << "\n-------------------------\n"; } else { cout << "\n-------------------------\n"; cout << "Parsing failed\n"; cout << "stopped at: \": " << info.stop << "\"\n"; cout << "\n-------------------------\n"; } } cout << "Please enter a filename...or [q or Q] to quit\n"; cin >> strFilename; return 0; } The contents of the file I tried to parse, which I named "mf7.txt" is given below: debt:=(LoanRequest+outstandingLoan1)*20 || newDebt := loanammount-paidammount The output when I execute the program is: ************************************************************ ...Machine Parser... ************************************************************ Please enter a filename...or [q or Q] to quit: c:\tplat\mf7.txt PUSH(LoanRequest) PUSH(outstandingLoan1) ADD LoanRequest outstandingLoan1 MULTIPLY LoanRequest outstandingLoan1 PUSH(debt:=(LoanRequest+outstandingLoan1)*20) ... debt|->LoanRequest ... debt|->outstandingLoan1 SIMPLE SUBSTITUTION Tokens ... debt Tokens ... LoanRequest Tokens ... outstandingLoan1 Tokens ... 20 Tokens ... END PUSH(debt:=(LoanRequest+outstandingLoan1)*20) MULTIPLE SUBSTITUTION ------------------------- Parsing failedstopped at: ": " ------------------------- My intention is to capture only the variables in the file, which I managed to do up to the "||" string. Clearly, the program is not parsing beyond the "||" string in the input file. I will appreciate assistance to fix the grammar. SOS, please.

    Read the article

  • Which is the better way to avoid magic string keys? Using string const keys in a class or using enumeration?

    - by user596314
    My idea is to avoid magic string keys in my Asp.Net MVC application. To do so, I want to create string constant keys to be shared in the application. For example, I can write TempData[MyClass.Message] or TempData[MyEnum.Message.ToString()] instead of TempData["Message"]. public class MyClass { public const string Message = "Message"; } and public enum MyEnum { Message, Others } My questions are: Which is the better way to avoid magic string keys? Using string const keys in a class or using enumeration together with ToString()?

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >