question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,971,275
2,989,974
Word automation - SaveAs
I try to write a simple MFC - Word Automation to save for every 1 minute. I follow this article : http://www.codeproject.com/KB/office/MSOfficeAuto.aspx And this is what Im trying to implement , I'm new to COM so I think there's problem here: my VBA is generated by Word 2010: ActiveDocument.SaveAs2 FileName:="1.docx", FileFormat:=wdFormatXMLDocument _ , LockComments:=False, Password:="", AddToRecentFiles:=True, _ WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _ SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _ False, CompatibilityMode:=14 And my code to implement VBA code above : { COleVariant varName(L"b.docx"); COleVariant varFormat(L"wdFormatXMLDocument"); COleVariant varLockCmt((BYTE)0); COleVariant varPass(L""); COleVariant varReadOnly((BYTE)0); COleVariant varEmbedFont((BYTE)0); COleVariant varSaveNativePicFormat((BYTE)0); COleVariant varForms((BYTE)0); COleVariant varAOCE((BYTE)0); VARIANT x; x.vt = VT_I4; x.lVal = 14; COleVariant varCompability(&x);; VARIANT result; VariantInit(&result); _hr=OLEMethod( DISPATCH_METHOD, &result, pDocApp, L"SaveAs2",10, varName.Detach(),varFormat.Detach(),varLockCmt.Detach(),varPass.Detach(),varReadOnly.Detach(), varEmbedFont.Detach(),varSaveNativePicFormat.Detach(),varForms.Detach(),varAOCE.Detach(),varCompability.Detach() ); } I get no error from this one, but it doesn't work.
The VBA syntax uses named parameters where the order and count of the parameters do not matter. However, when calling from C++ you need to pass the required number of parameters in the right order. SaveAs2 is defined as: void SaveAs2( ref Object FileName, ref Object FileFormat, ref Object LockComments, ref Object Password, ref Object AddToRecentFiles, ref Object WritePassword, ref Object ReadOnlyRecommended, ref Object EmbedTrueTypeFonts, ref Object SaveNativePictureFormat, ref Object SaveFormsData, ref Object SaveAsAOCELetter, ref Object Encoding, ref Object InsertLineBreaks, ref Object AllowSubstitutions, ref Object LineEnding, ref Object AddBiDiMarks, ref Object CompatibilityMode ) So, it has 17 parameters which means you should specify them all if you are going to pass CompatibilityMode, which was specified as 10th parameter in your example (that corressponds to SaveFormsData). If you do not need all the parameters, or just for testing, you can try a simpler code: _hr = OLEMethod(DISPATCH_METHOD, &result, pDocApp, L"SaveAs2", 2, varName.Detach(), varFormat.Detach()); If you need the rest of the parameters, you need to pass all the parameters up to the parameter you need set. In that case, you can pass COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); for the parameters you do not like to set. Edit - Test Code This works for me: CoInitialize(NULL); CLSID clsid; IDispatch *pWApp; HRESULT hr = CLSIDFromProgID(L"Word.Application", &clsid); hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void **)&pWApp); hr = OLEMethod(DISPATCH_PROPERTYPUT, NULL, pWApp, L"Visible", 1, COleVariant((long)1)); VARIANT result; VariantInit(&result); hr = OLEMethod(DISPATCH_PROPERTYGET, &result, pWApp, L"Documents", 0); IDispatch *pDocs = result.pdispVal; VARIANT result2; VariantInit(&result2); hr = OLEMethod(DISPATCH_METHOD, &result2, pDocs, L"Open", 1, COleVariant(L"D:\\Archive\\t1.docx")); IDispatch *pDoc = result2.pdispVal; VARIANT result3; VariantInit(&result3); hr = OLEMethod(DISPATCH_METHOD, &result3, pDoc, L"SaveAs2", 1, COleVariant(L"D:\\Archive\\t2.docx")); CoUninitialize();
2,971,386
2,987,731
How do I write a std::codecvt facet?
How do I write a std::codecvt facet? I'd like to write ones that go from UTF-16 to UTF-8, which go from UTF-16 to the systems current code page (windows, so CP_ACP), and to the system's OEM codepage (windows, so CP_OEM). Cross-platform is preferred, but MSVC on Windows is fine too. Are there any kinds of tutorials or anything of that nature on how to correctly use this class?
I've written one based on iconv. It can be used on windows or on any POSIX OS. (You will need to link with iconv obviously). Enjoy The answer for the "how to" question is to follow the codecvt reference. I was not able to find any better instructions in the Internet two years ago. Important notices theoretically there is no need for such work. codecvt_byname should be enough on any standard supporting platform. But in reality there are some compilers that don't support or badly support this class. There is also a difference in interfaces of codecvt_byname on different compilers. my working example is implemented with state template parameter of codecvt. Always use standard mbstate type there as this is the only way to use your codecvt with standard iostream classes. std::mbstate_t type can't be used as a pointer on 64bit platforms in a cross-platform way. stateless conversions work for short strings, but may fail if you try to convert a data chunk greater that streambuf internal buffer size (UTF is essentially stateful encoding)
2,971,518
2,971,566
Polygon Chain - Conversion to non-crossing while preserving shape?
I have polygon chains similar to the following... ...given the chain in the image, how would I go about calculating a chain that defines the same shape but without crossing paths? Specifically, in the case of the image's input chain, the result I want looks like this: A1, A2, Intersect between A2 and A3, Intersect between A3 and A4, A4, A5, Intersect between A3 and A4, A3, Intersect between A3 and A2, A6 I'm looking for an algorithm to accomplish this for any chain, but I'm not sure what I'm trying to do is even called, which makes searching for a solution tricky. If there's a name for what I'm trying to do it would be of great help to know it. Thank you for any assistance!
Here's a simple algorithm: for each line segment in the chain: Identify any segments which cross this segment If crossings > 0 Follow the branch to the right, if this doesn't lead back to the current intersection follow the branch to the left go to the next line segment If following a branch doesn't lead back to that intersection before getting to the end of the chain that means you have skipped a loop, so you need to choose the other branch. For your example, running this algorithm would produce Start at segment A1-A2 No intersections, goto next Segment A2-A3 Intersection A2-A3/A6-A5 choose right path and store the current intersection somewhere Segment A6-A5 Intersection A6-A5/A4-A3 choose right path and store intersection Segment A3-A4 A4-A5 A5-A6 Back at intersection A6-A5/A4-A3, go right again to be back on A4-A3 A3-A2 Back at intersection A2-A3/A6-A5, go right again Finish
2,971,670
2,971,689
Member access syntaxes for pointer to a structure
#include <iostream> typedef struct _person { std::string name; unsigned int age; }Person; int main() { Person *pMe = new Person; pMe->age = 10; pMe->name = "Larson"; std::cout << "Me " << (*pMe).age << " " << (*pMe).name.c_str() << std::endl; return 0; } Consider the above code. The members of the structures can be referenced in two ways. Eg., pMe->age or (*pMe).age. Is this just a syntactic difference or is there any functional difference available in these two approaches?
This is just a syntactic difference and the reason for the difference can be found here Because the syntax for access to structs and class members through a pointer is awkward, C++ offers a second member selection operator (->) for doing member selection from pointers. Hence both lines are equivalent. The -> operator is not only easier to type, but is also much less prone to error because there are no precedence issues to worry about. Consequently, when doing member access through a pointer, always use the -> operator.
2,971,730
2,971,803
Is there a way find out which second event will happen in MFC
I stumbled upon a curious problem with MFC. I have a Dialog where I check every Edit field on ON_EN_KILLFOCUS if it's valid. If validation doesn't go through I set focus back and show error message. This would be fine, if only I would close the dialog. I mean if I leave wrongly entered field and press close button or X, then ON_EN_KILLFOCUS is invoked first, after other handling events, because message appears and focus goes back to the field. So my question: Is there a way to find out in ON_EN_KILLFOCUS which event will be after it? If yes then I can check if its close event and then close dialog, not returning my focus to wrongly entered Edit field. Any help would be so much help!
In general, you cannot know what event comes after the focus changed event. However, it is possible to solve this, you change the conditions when the validation logic is fired - validate an edit control when focus is lost and the focus is lost to another edit control By checking that the focus is lost to another control, you are saying to the user, "don't move on to this component - you haven't filled out the current one correctly yet!". It captures the user's intent better than validating on any focus change. It will also not run validation when the user clicks Close or the system X button, or any other button. Of course, you will need add explicit validation when the OK button is clicked. Not only is this fairly simple to code (check that the new focus window is a child of the dialog and is an input component - you can determine it's an input component by looking at the Window Class name of the window. EDIT for edit boxes.) This also deals with cases where the user shifts focus for other reasons, such as a System Message Box, or other focus grabbing event. Since the focus is not moving to one of your other edit controls, then validation is not run, and the focus is not forced back to your application, which could be quite annoying for some people!
2,971,782
2,971,794
Why does this program hang?
I have the following code which is seems to be lead to the infinite loop: struct X { void my_func( int ) { std::cout << "Converted to int" << std::endl; } }; struct X2 : X { void my_func( char value ) { my_func(value); } }; What is the problem with it?
The second bit is infinitely recursive: struct X2 : X { void my_func( char value ) { my_func(value); } //calls itself over and over again }; Prefix my_func with the name of the base class and you will be OK struct X2 : X { void my_func( char value ) { X::my_func(value); } }; EDIT Just realised that base class my_func's signature is different. C++ compiler resolves the function overload statically, that means it will pick the function that best matches the type of the argument, that's why it calls the char overload. For example: char cChar = 'a'; myfunc(cChar); void myfunc(char a){} //<-- this one is called void myfunc(int a){} int iInt = 1; myfunc(iInt); void myfunc(char a){} void myfunc(int a){} //<-- this one is called Thanks Charles Bailey. The above code does not apply in this case as X2's my_func hides base class's my_func. This leaves the only solution to qualify the function with the class name.
2,971,845
2,974,272
Learning C++ from AS3
I'm a decent AS3 programmer. I work in games, and that is my reason for programming. While there is much I can accomplish with Adobe AIR, my understanding at this point is that learning C++ is probably a good direction to take. I would learn a lot of valuable lower level programming if I needed it down the road, and I would have an easier time learning other C oriented languages. I see a lot of information for people looking to learn AS3 who know C++, but not the other way around. Why C++? Cross platform compatibility is important to me, so I'm not particularly interested in C# or Objective-C at this junction. I'm also aware of Haxe, and while I love the concept, after doing some research I'm worried about investing a lot of time into something so recent with limited learning resources and documentation. I'm looking for advice and resources (books, articles) related to this topic. Thanks in advance!
About Haxe: I personally see no risk in using it. I completely switched to Haxe from AS3 about 9 months ago, and I feel it was a very good decision. AS3 has completely stalled since its release. Sure, the player API has grown, but the language itself hasn't evolved, except for the introduction of typed vectors. While I feel that your general concern towards Haxe is unjustified, I have to point out, that Haxe/CPP is a different beast. Although the project is very promissing and ambitious, it does have its problems. Many cool Haxe features are translated into C++ with serious overhead (although in performance critical situations you can simply avoid them). Also the resulting code is really not nice to read, debugging is not really obvious (you can debug the code, but you than have to fix the problem in the original Haxe source) and there is no canonical way of using the Haxe output from C++ in a decent way. And the C++ platform is known to have minor quirks, although it has become reasonably stable. The question is now, what exactly you're trying to achieve learning C++. Haxe/CPP is a decent way to use a high level language getting about the same performance as C++, while staying even more cross platform. IMHO, from an AS3 point of view, the most interesting thing about C++ is its low level access and the templates, both of which are very powerful aspects. To me, AS3 is basically a poor man's Java, except for the mostly unused dynamic and functional traits. Thus, if you are determined to learn C++, I would suggest, you try learning C++ from Java.
2,971,918
2,971,927
Unable to run native C++ application on different machine
I wrote a simple 'Hello, world' application in C++ using Visual Studio 2008. I am able to run the app successfully on my local machine. BUt when I copy the exe onto another machine and run, it does not run. It gives the error that 'Application has failed to start because application configuration is incorrect'. The another system does not have Visual Studio installed. What could be the problem? Thanks, Rakesh.
Probably the CRT DLL is missing. Compile your app using static CRT - /MT (/MTd for debug). More info. In Visual studio go to Project properties > C/C++ > Code Generation > Runtime Library.
2,972,020
2,972,065
C++ warning: suggest parentheses around arithmetic in operand of |
I have a code like A = B|C|D|E; Throwing the warning "suggest parentheses around arithmetic in operand of |" Expecting that expression needs high priority paranthesis for operators, tried the following ways: A=(B|C)|(D|E); one more as : A=(((B|C)|D)|E); Still the same warning persists. Please help me in resolving this. Thanks, Sujatha B, C,D are enums and E is an integer.
You have some arithmetic operator in your expression that isn't really simply B, or that isn't really simply C, etc. The compiler is suggesting that you parenthesize whichever expression so that readers will see that you wrote what you meant. If you don't parenthesize, everyone has to remember exactly what the priorities are, and they have to figure out if you remembered when you wrote it. Try this: (B)|(C)|(D)|(E).
2,972,146
2,972,393
What sorting method to use: quicksort, bucket sort, radix, ... for tiny data pairs? (c++)
I need to optimize some code that sorts a vector<pair<int, float >>a where the pairs needs to be sorted on the float value. The vector will have an length between 0 and 5. I've been googling and reading up on sorting methods in C++ but cannot find any benchmarks on sorting tiny data sets. For the system it's important be as fast as possible as it's used for a real time blob tracking system. Kind regards, Pollux
First, premature optimization is the root of all evil. That is, first benchmark your code and make sure the sorting is the one that's actually taking the most time. If another part of your performance-critical code is taking 80% of the execution time, you will get drastic performance improvements optimizing that first. Considering you have 5 elements, the point is pretty much moot. Any algorithm you use (except bogosort :D) should have a pretty much constant execution time, unless you run the algorithm a few hundred times per second, or more. Second, provided you still want to optimize the search, if you know for sure you always will have 5 elements, the optimal method is by hard-coding the comparations (It can be proven mathematically that this method is optimal, providing a minimal number of executed operations in the worst case scenario - we had this as a laboratory application in university). The same applies if you have less than five elements, but the algorithm becomes prohibitive to write and execute if you have more than seven elements - the logic is convoluted to write and follow so your code will become difficult to maintain. Let me know if you need help with writing the optimal hard-coded algorithm itself (though I think you should find the implementation and theory online). If you do not always have five numbers (or for some reason want to avoid the hardcoded comparisions algorithm), use the sort provided by the library. This page concludes that the stl sort is optimal in terms of time (not only number of executed operations). I do not know what implementation was used for search.
2,972,160
2,972,409
how to auto enable a signal on my programme window open
i am using QT4 for my c++ programme i want to enable a SIGNAL automatically when my window is open so please tell me how do i enable a SIGNAL when my programme window open. i am new to QT so please give a detail description. Thanks
Overwrite QWidget::showEvent() (see QT documentation)
2,972,166
2,977,389
Qt QPainter error when rotating an ellipse using horizontalSlider
I have to create a simple box which rotates an ellipse and some text depending upon value from horizontalSlider/spinBox. The widget has to be resizable, And size of the ellipse has to change depending upon that. For now only the ellipse is being painted. The text painting will be added if this works. The problem is that if the window after resize exceeds the original window size, the painting is weird. window.h: #ifndef WINDOW_H #define WINDOW_H #include <QtGui> #include "ui_form.h" class Window : public QWidget, private Ui::Form { Q_OBJECT public: Window(QWidget *parent = 0); public slots: void rotateEllip(int angle); void rotateText(int angle); protected: void paintEvent(QPaintEvent *event); }; #endif // WINDOW_H window.cpp: #include "window.h" qreal textAngle = 0.0; qreal ellipAngle = 0.0; Window::Window(QWidget *parent) : QWidget(parent) { setupUi(this); connect(spinBox_ellipse,SIGNAL(valueChanged(int)),this,SLOT(rotateEllip(int))); connect(horizontalSlider_ellipse,SIGNAL(valueChanged(int)),this,SLOT(rotateEllip(int))); connect(spinBox_text,SIGNAL(valueChanged(int)),this,SLOT(rotateText(int))); connect(horizontalSlider_text,SIGNAL(valueChanged(int)),this,SLOT(rotateText(int))); } void Window::rotateEllip(int angle) { ellipAngle = (qreal) angle; Window::Window(this); } void Window::rotateText(int angle) { textAngle = (qreal) angle; Window::Window(this); } void Window::paintEvent(QPaintEvent *event) { QPen pen(Qt::black,2,Qt::SolidLine); QPoint center(0,0); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); /* Drawing ellipse*/ painter.eraseRect(10,10,frame_ellipse->width(),frame_ellipse->height()); painter.translate(frame_ellipse->width()/2+10,frame_ellipse->height()/2+10); painter.rotate(ellipAngle); if (frame_ellipse->width() > frame_ellipse->height()) painter.drawEllipse(center,(frame_ellipse->height()/4)-5,(frame_ellipse->height()/2)-10); else if (frame_ellipse->width() <= frame_ellipse->height() ) painter.drawEllipse(center,(frame_ellipse->width()/2)-10,(frame_ellipse->width()/4)-5); painter.rotate(-ellipAngle); painter.translate(-frame_ellipse->width()/2+10,-frame_ellipse->height()/2+10); } main.cpp is normal window.show() calling.
My guess is the call to constructor creates a temporary widget object and messes up the drawing.
2,972,800
2,972,917
Windows context menu for multiple files [C++]
I want to create a context menu that support multiple files. I read through SO and understand that either you must use DDE or shell extension (something to do with creating and registering COM object). However all the sourcecodes I found are in C#. I then decided to go with COM object. I found 1 in C++ that uses COM but it's dated 2006, so I just don't know if it's outdated. http://www.codeproject.com/KB/shell/shellextguide1.aspx Can anyone shed me some light on this? And is there any good and new article out there covering this issue? Or if anyone has some something similar before using DDE and IPC?
It should work fine, the underlying mechanic hasn't changed in the last 4 years. Take a look at the comments at the bottom of the article, people are using it without problems. (There is also a link to a VS 2008 template for multiple-files)
2,973,085
2,973,139
MFC: Deleting dynamically created CWnd objects
Lets say in a dialog, we dynamically create a variable number of CWnds... like creating a and registering a CButton every time the user does something/ Some pseudo-code... class CMyDlg : public CDialog { vector<CWnd *> windows; void onClick() { CButton *pButton = new CButton(...); //do other stuff like position it here windows.push_back(pButton); } } Do I need to explicitly delete them or will MFC do it? If I have to, would it be in the destructor as normal, or are there any special things to avoid breaking MFC... making sure I don't delete the objects while the HWNDs are still in use for example?
CButton *pButton = new CButton(...); These are C++ objects, which needs to be deleted explicitly. (Where as Main frame windows and Views are self destructed). You can refer the detailed answer ( by me) Destroying Window Objects
2,973,087
2,973,205
Convert C++/MFC from visual studio.net 2002 to visual studio 2010
We will convert a number of programs written in C++ and MFC in Visual Studio.NET 2002 to Visual Studio 2010. What problems can we expect to encounter? What changes are there in the libraries that are worth knowing?
MFC has had a number of breaking changes over those releases. All the changes are documented on MSDN, and usually they're pretty straightforward - function signature changes and the like (which can often be fixed simply by inspecting the compiler error message and working out what it wants instead).
2,973,301
2,973,322
What is a possible workaround for object slicing in c++?
This is the code: #include <string> #include <vector> #include <iostream> using namespace std; class A { public: virtual const string f() const { return "A"; } }; class B : public A { public: const string f() const { return "B"; } }; int main(int ac, char** av) { vector<A> v; v.push_back(B()); cout << v.at(0).f() << endl; return 0; } Expected result is B, but it's A. As I understand object slicing is taking place. How to avoid it? Shall I store pointers in vector instead of object instances? Is this the only choice?
You need to store pointers. If these refer to dynamically allocated objects, use smart pointers.
2,973,304
2,973,803
How to load COM DLL at runtime
I have a VB6 COM DLL. I want to use it from C++. I know how to register it, generate a tlb file from the DLL, and #import it in C++. I'd like however, to load and use DLLs like this dynamically, at runtime, without knowing them in advance. Is this possible? Thanks,
Yes, but you need to get the question clearer. Sometimes, you do know the COM interface upfront, just not the implementation. In that case, you can create a dummy implementation of the interface and #import that. At runtime, you'd still register the real component, get an object from it (via CoCreateInstance probably) and store that in an appropriate smart pointer. With VB6, it's a bit less direct. This adds a level of indirection. Read up on IDispatch. You need to get that known interface to describe an unknown interface. That way, the unknown interface can be obtained at runtime.
2,973,467
2,973,710
How to tell if a MFC Dialog has been created/initialized?
I have an OnMove handler in my dialog class, which does some stuff with control objects (i.e a CButton). I'm finding this handler gets called before the dialog OnInitDialog method is called, and hence when I try to call methods on the child controls, I get ASSERTS in debug as the controls don't yet exist... they are created in OnInitDialog. There's two things I'd like to be able to check: How do I tell the dialog has been initialized? How do I check an individual CWnd control object's window has been created? In both cases I'm looking for class members or method call results that can be used.
Set a flag in OnInitDialog Use your dialog's m_hWnd: if ( ::IsWindow(m_Ctrl.m_hWnd) ) { ... }
2,973,914
2,973,932
Will destructor be called?
If I create a vector of vector of vector, if I clear the first vector, or the first vector gets deleted, will all the child vectors call the destructor and free the memory or will it cause a memory leak? Thanks
If you have: vector <vector <vector <int> > > > v; v.clear(); then destructors will be called suitably for all the subvectors.
2,973,917
2,974,001
c++ global functions and OOP?
In C++ one can have a 'GLOBAL FUNCTION', which means it does not belong to any class. I wondered if that isn't just a violation of the basic principles of OOP? What would be the difference with using a global function or function that is static in a class? I'm thinking the latter is more OOP oriented. But I may be wrong however... Does it not make it harder when writing a multithreaded applicaton?
A static function inside a class is as OO as a global function inside a module. The thing is in JAVA, you don't have the choice. In C++, you can encapsulate your global functions inside namespaces, you don't need a dummy class to do this. This way you have modularity. So of course you can put functions outside namespaces this way you have really global functions. But that's not very different from a JAVA kitchen sink class with a bunch of static functions. It's also bad code, but can be just ok for small projects :) Also in C++ you have a lot of choices to have "global" function that actually are linked to a class, as operator functions, that may be for instance friends of a class. EDIT As for multithreading, you have to worry about global variables, not functions.
2,973,964
2,974,112
Conversion between different template instantiation of the same template
I am trying to write an operator which converts between the differnt types of the same implementation. This is the sample code: template <class T = int> class A { public: A() : m_a(0){} template <class U> operator A<U>() { A<U> u; u.m_a = m_a; return u; } private: int m_a; }; int main(void) { A<int> a; A<double> b = a; return 0; } However, it gives the following error for line u.m_a = m_a;. Error 2 error C2248: 'A::m_a' : cannot access private member declared in class 'A' d:\VC++\Vs8Console\Vs8Console\Vs8Console.cpp 30 Vs8Console I understand the error is because A<U> is a totally different type from A<T>. Is there any simple way of solving this (may be using a friend?) other than providing setter and getter methods? I am using Visual studio 2008 if it matters.
VC10 accepts this: template <class T = int> class A { public: template< typename U> friend class A; A() : m_a(0){} template <class U> operator A<U>() { A<U> u; u.m_a = m_a; return u; } private: int m_a; };
2,973,976
2,974,015
Inheritance and method overloading
Why C++ compiler gives this error? Why i can access lol() from B, but can not access rofl() [without parameters]. Where is the catch? class A { public: void lol(void) {} void rofl(void) { return rofl(0);} virtual void rofl(int x) {} }; class B : public A { public: virtual void rofl(int x) {} }; int _tmain(int argc, _TCHAR* argv[]) { A a; a.lol(); a.rofl(1); a.rofl(); B b; b.lol(); b.rofl(1); b.rofl(); //ERROR -> B::rofl function does not take 0 arguments return 0; }
The B::rofl(int) 'hides' the A::rofl(). In order to have A's rofl overloads, you should declare B to be using A::rofl;. class B : public A { public: using A::rofl; ... }; This is a wise move of C++: it warns you that you probably also need to override the A::rofl() method in B. Either you do that, or you explicitly declare that you use A's other overloads.
2,973,987
2,974,039
Type or Vector for representing points\positions
I have a series of points\positions that won't change. Should I represent as Vector of ints or as a new type? My preference at the moment is to go with vector: doSomething(myVec[0], myVec[1] ); doSomethingElse(myVec[2], myVec[3] ); as opposed to: doSomething( myType.getPos1(), myType.getPos2() ); doSomethingElse( myType.getPos3(), myType.getPos4() ); Any thoughts or ideas? Thanks
Since you're using stl, I'd use vector< pair<int,int> > (or vector< pair<double,double> > if the points aren't integer). It works great for points. So then you could do something like this: vector< pair<int,int> > points; points.push_back(make_pair(1,2)); points.push_back(make_pair(2,2));
2,974,250
2,974,865
WMI with Qt examples and info
Where can I find more information on and examples of using WMI with Qt? I have no prior experience with WMI.
Microsoft have an overview of how to work with WMI from C++. I would start with that and then implement a user interface on top with QT. WMI exposes a COM interface so you should get familiar with that if you have not used it before. Don Box's Essential COM is one of the better books on the subject. The Code Project site also has some related information. It is generally a good site for C++ programming on Windows. Are you trying to create a cross-platform app, or do you just target Windows?
2,974,470
2,974,501
Efficiency of the STL priority_queue
I have an application (C++) that I think would be well served by an STL priority_queue. The documentation says: Priority_queue is a container adaptor, meaning that it is implemented on top of some underlying container type. By default that underlying type is vector, but a different type may be selected explicitly. and Priority queues are a standard concept, and can be implemented in many different ways; this implementation uses heaps. I had previously assumed that top() is O(1), and that push() would be a O(logn) (the two reasons I chose the priority_queue in the first place) - but the documentation neither confirms nor denies this assumption. Digging deeper, the docs for the Sequence concept say: The complexities of single-element insert and erase are sequence dependent. The priority_queue uses a vector (by default) as a heap, which: ... supports random access to elements, constant time insertion and removal of elements at the end, and linear time insertion and removal of elements at the beginning or in the middle. I'm inferring that, using the default priority_queue, top() is O(1) and push() is O(n). Question 1: Is this correct? (top() access is O(1) and push() is O(n)?) Question 2: Would I be able to achieve O(logn) efficiency on push() if I used a set (or multiset) instead of a vector for the implementation of the priority_queue? What would the consequences be of doing this? What other operations would suffer as a consequence? N.B.: I'm worried about time efficiency here, not space.
The priority queue adaptor uses the standard library heap algorithms to build and access the queue - it's the complexity of those algorithms you should be looking up in the documentation. The top() operation is obviously O(1) but presumably you want to pop() the heap after calling it which (according to Josuttis) is O(2*log(N)) and push() is O(log(N)) - same source. And from the C++ Standard, 25.6.3.1, push_heap : Complexity: At most log(last - first) comparisons. and pop_heap: Complexity: At most 2 * log(last - first) comparisons.
2,974,643
2,974,659
Reading in 4 bytes at a time
I have a big file full of integers that I'm loading in. I've just started using C++, and I'm trying out the filestream stuff. From everything I've read, it appears I can only read in bytes, So I've had to set up a char array, and then cast it as a int pointer. Is there a way I can read in 4 bytes at a time, and eliminate the need for the char array? const int HRSIZE = 129951336; //The size of the table char bhr[HRSIZE]; //The table int *dwhr; int main() { ifstream fstr; /* load the handranks.dat file */ std::cout << "Loading table.dat...\n"; fstr.open("table.dat"); fstr.read(bhr, HRSIZE); fstr.close(); dwhr = (int *) bhr; }
To read a single integer, pass in the address of the integer to the read function and ensure you only read sizeof int bytes. int myint; //... fstr.read(reinterpret_cast<char*>(&myint), sizeof(int)); You may also need to open the file in binary mode fstr.open("table.dat", std::ios::binary);
2,974,676
2,974,690
Should a programmer have mastery over C++
I was wondering if it is necessary for programmers to have expertise on at least 1 programming language? Programming languages like C#, java, VB.Net etc change every year or two. Should a programmer have mastery over C++, which is a stable language and rarely undergoes changes? I am a C# developer and using it for about 7 years now, I still don't have mastery on it. EDIT I think my question is being misunderstood. I am not against changes or evolution. I love the new features and abstraction provided by languages such as C#, VB, Java. And I keep waiting for new features if it makes a programmers life easy. But this fact also make this languages very difficult to master. They are continuously evolving. Languages like C++ have slow evolution cycle. So given this scenario, Is it helpful to be master of C++? This is what my original question meant. Note:- Based on the answers by friends below, I have understood that languages and framework are tools for expressing the concepts. Also it might be a good idea to express the concepts in different programming languages.
Programming languages like C#, java, VB.Net etc change every year or two. They don't "change" but evolve. Your knowledge and experience are not lost. Should a programmer have mastery over C++, which is a stable language and rarely undergoes changes? Programming is all about new and change. If you don't like it, consider another profession. I am a C# developer and using it for about 7 years now, I still don't have mastery on it. If you were to achieve mastery, the life would become boring and maybe even pointless. Maybe it's not the target but the road that matters? EDIT: After reading your comments I feel that you misattribute the volume of the .NET class library to the complexity of the C# language itself. Don't mix them. The C# language is relatively simple, it's easy to "master". What you're mentioning as useful methods of the char datatype are just helper methods from the .NET library. It's one of the assets of the platform. It's what makes .NET developers so productive, because they don't have to waste hours digging for third-party libraries to make basic operations for them: XML, imaging, networking, databases and more it's all available directly from the .NET library. Naturally, its sheer size might frighten you and provide an impression of it's being endless. It ain't! Just use what you need and leave the rest be.
2,974,771
2,976,043
Force OpenGL to keep contents in memory?
I'm using OpenGL to render polygons. I notice that if I minimize the program then start using it again, it will be very slow for a few seconds. (I'm guessing its reuploading my display lists to the card). How can I prevent this because it's a bit annoying. I want it to always have the contents. Thanks
When you minimize a program under Windows, it does the equivalent of SetProcessWorkingSetSize(current_process, -1,-1);. This tells the virtual memory manager that all the memory occupied by that program is eligible for being paged out. The only way I know of to prevent this is to prevent the user from minimizing the program in the first place (e.g., use DeleteMenu to remove the "minimize" item from its system menu). Note that this isn't a matter of your program's drawing data being removed from the graphics card -- it's a matter of all its data (and quite possibly code) being removed from memory entirely. Of course, if you have enough memory and a lightly enough loaded system, it won't be removed immediately -- it's just marked as being available, so if the system needs memory for something else, it will be (some of) the first to get used.
2,974,780
2,975,997
Visual C++ Compiler allows dependent-name as a type without "typename"?
Today one of my friends told me that the following code compiles well on his Visual Studio 2008: #include <vector> struct A { static int const const_iterator = 100; }; int i; template <typename T> void PrintAll(const T & obj) { T::const_iterator *i; } int main() { std::vector<int> v; A a; PrintAll(a); PrintAll(v); return 0; } I usually use g++, and it always refuse to pass the second PrintAll() call. As I know, for this problem, g++ is doing the standard way translating a template. So, is my knowledge wrong, or is it a extension of VS2008?
This is not an extension at all. VC++ never implemented the two phases interpretation properly: At the point of definition, parse the template and determine all non-dependent names At the point of instantiation, check that the template produces valid code VC++ never implemented the first phase... it's inconvenient since it means not only that it accepts code that is non-compliant but also that it produces an altogether different code in some situations. void foo(int) { std::cout << "int" << std::endl; } template <class T> void tfoo() { foo(2.0); } void foo(double) { std::cout << "double" << std::endl; } int main(int argc, char* argv[]) { tfoo<Dummy>(); } With this code: compliant compilers will print "int", because it was the only definition available at the point of definition of the template and the resolution of foo does not depend on T. VC++ will print "double", because it never bothered with phase 1 It might seem stupid as far as differences go, but if you think about the number of includes you have in a large program, there is a risk that someone will introduce an overload after your template code... and BAM :/
2,974,803
2,977,230
Does Qt have resource system limits?
My Qt application depends on Oracle DLLs to start. As it's linked statically for the most part (except for these DLLs), I'd like to embed the DLLs and the EXE into a launcher that would behave like a fully static application (one exe, no DLLs to take along). The launcher would extract the included files in a temp directory, launch the software, and clean up when done. I've tried to embed the EXE and the Oracle DLLs (around 30 MB) in the launcher using Qt resource system, but the compiler (MSVC 2005) fails with fatal error C1001: An internal error has occurred in the compiler. Is there a size limit for resources included with Qt's resource system (or do I abuse it by including such large files in my executable)?
Limit comes from compiler, as error says it is INTERNAL compiler error. So compiller couldn't handle it. You could try to walkaround it, by splitting bigger files in to small parts and manualy put them together in your code. I'm not sure if it will work, but it is worth trying.
2,974,855
2,974,907
How to create a function with return type map<>?
Fairly straightforward question. I have a map that I wish to initialize by calling a function like so: map<string, int> myMap; myMap = initMap( &myMap ); map<string, int> initMap( map<string, int> *theMap ) { /* do stuff... */ However, the compiler is moaning. What's the solution to this? EDIT 1: I'm sorry, but I screwed up. The code was correctly written with *theMap, but when I posted the question, I failed to notice that I had omitted the *. So to answer the comment, the error message I get is: 1>Roman_Numerals.cpp(21): error C2143: syntax error : missing ';' before '<' which is thrown at map<char, int> initMap( map<char, int> *numerals ); using VC++ 2010 Express and the same error again when I define the function.
Either do: map<string, int> myMap; initMap( myMap ); void initMap( map<string, int>& theMap ) { /* do stuff in theMap */ } or do: map<string, int> myMap; myMap = initMap( ); map<string, int> initMap() { map<string, int> theMap; /* do stuff in theMap */ return theMap; } i.e. let the function initialise the map you give it, or take the map the function gives you. You're doing both (without a return statement too!) I'd go for the first option.
2,974,908
2,974,993
Error can not open source file "..."
I'm using VS2010 (downloaded via dreamspark) and although I can open the #include file by right clicking on it and pressing on Open Document, it complains "Error can not open source file "..."" which seems rather absurd. I'm using Qwt with Qt this time around and I'm specifically having the problem for: #include <qwt_counter.h> #include <qwt_plot.h> (And I am using the "<>"); not sure how to make those appear properly in the code above. Thanks in advance.
As Neil indicated, try using quotes instead of the <> characters around the filename. When using the quotes, MSVC will look in the same directory as the file the #include is in for the specified file, then if it's not found there will look in the directories specified by the include path. When the filename is surrounded by <> characters, the current file's directory isn't looked at - the compiler goes right to the include path. See http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx for details. Note that this is an implementation dependent behavior - it might not apply to other compilers. If that doesn't help, make sure that your include path contains the directory that the file is located in by setting the "Include Directories" property appropriately: http://msdn.microsoft.com/en-us/library/t9az1d21.aspx Finally, you might be using a makefile project (I'm not sure how common it is for Qt projects to continue to use qmake when built from VS) , in which case you'll need to perform whatever configuration is necessary in the make file(s) or parameters passed on the command line that invokes the makefiles.
2,975,040
2,975,128
C++ Refactoring Precompiled Header
Unfortunately on a project here at work, someone had the great idea to put every header every single file from pretty big project into the precompiled header. This means any change to any header in the project has to recompile the entire project, and all cpp files taking way too long. Is there any decent C++ refactoring tool which could automatically put the needed includes in the appropriate cpp files? I really don't want to do this manually with hundreds of different files.
There are very few decent C++ refactoring tools because parsing C++ code is hard (and therefore also slow). You'll probably have to write such a tool yourself, possibly with some assistance from GCC-XML.
2,975,052
3,041,224
c++ project using c# assemblies: how to speedup compile time?
I've got a mixed c++/c# project. The original project is c++ and has been extended using c# assemblies. In the beginning this was ok, but since the c# part is growing I experience a big problem growing: Compile time of the c++ part becomes a problem. Why? Simple: every time I change something in a c# project, the c++ compiler is not sure if this is important (meaning, it is unable to know if I changed part of the interface or only internal implementation) and does recompile the whole c++ project. This is a becoming a huge problem since I need to use the c++ part to test the c# part, and right now I'll have to wait several minutes for every little code change. I need to find a way I do not need to recompile the whole c++ program, but only the parts which depend on the c# assembly or nothing, if the interface of the c# assembly was unchanged. Is there any way to achieve this? [Update] I'm using Visual Studio 2010 Premium.
You could extract interfaces from your C# classes and put those interfaces into a separate C# project. Since these interfaces will not change each and every time an implementation (in your original C# project) changes the C++ projects do not need a rebuild.
2,975,100
2,975,158
C++ Constructor Parameters Question
I'm learning C++. I have a simple class named GameContext: class GameContext { public: GameContext(World world); virtual ~GameContext(); }; To initialize a GameContext object, I need a World object. Should the GameContext constructur take a pointer to a World object (World*), the address to a World object (&World) or a reference to a World object (World)? What is the const keyword when used near a parameter? For example: GameContext(const World &world) Thanks.
First, teminology: You're right that a World * would be a pointer to a World object. A World &, however, would be a reference to a World object. A World would be a copy of the World object, not a reference to it. The const (used primarily with a pointer or reference, as in World const &world or World const *world) means that you're getting a reference/pointer to a const object -- in other words, you're not allowed to modify the original object to which it refers/points. For small objects, you usually want to pass a copy. For large objects, you'll typically want to pass a const reference. There are exceptions to this, but that's a reasonable rule of thumb to use until you've learned enough more to know when to break the rules (so to speak). Just based on the name, I'd guess your World object is probably large enough that you probably want to pass it by const reference, so your ctor should look like: GameContext(World const &world);
2,975,275
2,975,421
How large does a collection have to be for std::map<k,v> to outpace a sorted std::vector<std::pair<k,v> >?
How large does a collection have to be for std::map to outpace a sorted std::vector >? I've got a system where I need several thousand associative containers, and std::map seems to carry a lot of overhead in terms of CPU cache. I've heard somewhere that for small collections std::vector can be faster -- but I'm wondering where that line is.... EDIT: I'm talking about 5 items or fewer at a time in a given structure. I'm concerned most with execution time, not storage space. I know that questions like this are inherently platform-specific, but I'm looking for a "rule of thumb" to use. Billy3
It's not really a question of size, but of usage. A sorted vector works well when the usage pattern is that you read the data, then you do lookups in the data. A map works well when the usage pattern involves a more or less arbitrary mixture of modifying the data (adding or deleting items) and doing queries on the data. The reason for this is fairly simple: a map has higher overhead on an individual lookup (thanks to using linked nodes instead of a monolithic block of storage). An insertion or deletion that maintains order, however, has a complexity of only O(lg N). An insertion or deletion that maintains order in a vector has a complexity of O(N) instead. There are, of course, various hybrid structures that can be helpful to consider as well. For example, even when data is being updated dynamically, you often start with a big bunch of data, and make a relatively small number of changes at a time to it. In this case, you can load your data into memory into a sorted vector, and keep the (small number of) added objects in a separate vector. Since that second vector is normally quite small, you simply don't bother with sorting it. When/if it gets too big, you sort it and merge it with the main data set. Edit2: (in response to edit in question). If you're talking about 5 items or fewer, you're probably best off ignoring all of the above. Just leave the data unsorted, and do a linear search. For a collection this small, there's effectively almost no difference between a linear search and a binary search. For a linear search you expect to scan half the items on average, giving ~2.5 comparisons. For a binary search you're talking about log2 N, which (if my math is working this time of the morning) works out to ~2.3 -- too small a difference to care about or notice (in fact, a binary search has enough overhead that it could very easily end up slower).
2,975,304
2,975,438
Undefined reference to XOpenDisplay in a Qt project
Now I am feeling quite stupid. I am trying to do some stuff with xlib in Qt Creator. My code: #include <QtCore/QCoreApplication> #include <X11/Xlib.h> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Display *display = XOpenDisplay(NULL); return 0; } Just one line of code and gives me: /main.cpp:8: undefined reference to `XOpenDisplay' It is defined in Xlib.h as extern Display *XOpenDisplay( _Xconst char* /* display_name */ ); I feel I am missing something very basic.
I've figured it out. Adding -lX11 to the the Makefile solved this issue.
2,975,330
2,975,401
How do you indent preprocessor statements?
When there are many preprocessor statements and many #ifdef cascades, it's hard to get an overview since normally they are not indented. e.g. #ifdef __WIN32__ #include <pansen_win32> #else #include <..> #ifdef SOMEOTHER stmts #endif maybe stmts #endif When I consider also indenting those preprocessor statements, I fear of getting confused with the general indentation level. So how do you solve this in a beautiful way?
Just because preprocessing directives are "normally" not indented is not a good reason not to indent them: #ifdef __WIN32__ #include <pansen_win32> #else #include <..> #ifdef SOMEOTHER stmts #endif maybe stmts #endif If you frequently have multiple levels of nesting of preprocessing directives, you should rework them to make them simpler.
2,975,385
2,975,787
Why does my data not seem to be aligned?
I'm trying to figure out how to best pre-calculate some sin and cosine values, store them in aligned blocks, and then use them later for SSE calculations: At the beginning of my program, I create an object with member: static __m128 *m_sincos; then I initialize that member in the constructor: m_sincos = (__m128*) _aligned_malloc(Bins*sizeof(__m128), 16); for (int t=0; t<Bins; t++) m_sincos[t] = _mm_set_ps(cos(t), sin(t), sin(t), cos(t)); When I go to use m_sincos, I run into three problems: -The data does not seem to be aligned movaps xmm0, m_sincos[t] //crashes movups xmm0, m_sincos[t] //does not crash -The variables do not seem to be correct movaps result, xmm0 // returns values that are not what is in m_sincos[t] //Although, putting a watch on m_sincos[t] displays the correct values -What really confuses me is that this makes everything work (but is too slow): __m128 _sincos = m_sincos[t]; movaps xmm0, _sincos movaps result, xmm0
m_sincos[t] is a C expression. In an assembly instruction, however, (__asm?), it's interpreted as an x86 addressing mode, with a completely different result. For example, VS2008 SP1 compiles: movaps xmm0, m_sincos[t] into: (see the disassembly window when the app crashes in debug mode) movaps xmm0, xmmword ptr [t] That interpretation attempts to copy a 128-bit value stored at the address of the variable t into xmm0. t, however, is a 32-bit value at a likely unaligned address. Executing the instruction is likely to cause an alignment failure, and would get you incorrect results at the odd case where t's address is aligned. You could fix this by using an appropriate x86 addressing mode. Here's the slow but clear version: __asm mov eax, m_sincos ; eax <- m_sincos __asm mov ebx, dword ptr t __asm shl ebx, 4 ; ebx <- t * 16 ; each array element is 16-bytes (128 bit) long __asm movaps xmm0, xmmword ptr [eax+ebx] ; xmm0 <- m_sincos[t] Sidenote: When I put this in a complete program, something odd occurs: #include <math.h> #include <tchar.h> #include <xmmintrin.h> int main() { static __m128 *m_sincos; int Bins = 4; m_sincos = (__m128*) _aligned_malloc(Bins*sizeof(__m128), 16); for (int t=0; t<Bins; t++) { m_sincos[t] = _mm_set_ps(cos((float) t), sin((float) t), sin((float) t), cos((float) t)); __asm movaps xmm0, m_sincos[t]; __asm mov eax, m_sincos __asm mov ebx, t __asm shl ebx, 4 __asm movaps xmm0, [eax+ebx]; } return 0; } When you run this, if you keep an eye on the registers window, you might notice something odd. Although the results are correct, xmm0 is getting the correct value before the movaps instruction is executed. How does that happen? A look at the generated assembly code shows that _mm_set_ps() loads the sin/cos results into xmm0, then saves it to the memory address of m_sincos[t]. But the value remains there in xmm0 too. _mm_set_ps is an 'intrinsic', not a function call; it does not attempt to restore the values of registers it uses after it's done. If there's a lesson to take from this, it might be that when using the SSE intrinsic functions, use them throughout, so the compiler can optimize things for you. Otherwise, if you're using inline assembly, use that throughout too.
2,975,542
2,975,583
Integer Types in file formats
I am currently trying to learn some more in depth stuff of file formats. I have a spec for a 3D file format (U3D in this case) and I want to try to implement that. Nothing serious, just for the learning effect. My problem starts very early with the types, that need to be defined. I have to define different integers (8Bit, 16bit, 32bit unsigned and signed) and these then need to be converted to hex before writing that to a file. How do I define these types, since I can not just create an I16 i.e.? Another problem for me is how to convert that I16 to a hex number with 8 digits (i.e. 0001 0001).
Hex is just a representation of a number. Whether you interpret the number as binary, decimal, hex, octal etc is up to you. In C++ you have support for decimal, hex, and octal representations, but they are all stored in the same way. Example: int x = 0x1; int y = 1; assert(x == y); Likely the file format wants you to store the files in normal binary format. I don't think the file format wants the hex numbers as a readable text string. If it does though then you could use std::hex to do the conversion for you. (Example: file << hex << number;) If the file format talks about writing more than a 1 byte type to file then be careful of the Endianness of your architecture. Which means do you store the most significant byte of the multi byte type first or last. It is very common in file format specifications to show you how the binary should look for a given part of the file. Don't confuse this though with actually storing binary digits as strings. Likewise they will sometimes give a shortcut for this by specifying in hex how it should look. Again most of the time they don't actually mean text strings. The smallest addressable unit in C++ is a char which is 1 byte. If you want to set bits within that byte you need to use bitwise operators like & and |. There are many tutorials on bitwise operators so I won't go into detail here.
2,975,831
2,975,844
Is leaked memory freed up when the program exits?
If I programmed — without knowing it — a memory leak, and the application terminates, is the leaked memory freed?
Yes, a "memory leak" is simply memory that a process no longer has a reference to, and thus can no longer free. The OS still keeps track of all the memory allocated to a process, and will free it when that process terminates. In the vast majority of cases the OS will free the memory - as is the case with normal "flavors" of Windows, Linux, Solaris, etc. However it is important to note that in specialized environments such as various Real-Time Operating Systems the memory may not be freed when the program is terminated.
2,976,058
2,976,097
C++: Can I get out of the bounds of my app's memory with a pointer?
If I have some stupid code like this: int nBlah = 123; int* pnBlah = &nBlah; pnBlah += 80000; *pnBlah = 65; Can I change another app's memory? You have explained me this is evil, I know. But I was just interested. And this isn't something to simply try. I don't know what would happen. Thanks
In C++ terms, this is undefined behavior. What will actually happen depends on many factors, but most importantly it depends on the operating system (OS) you are using. On modern memory-managed OS's, your application will be terminated with a "segmentation fault" (the actual term is OS-dependent) for attempting to access memory outside of your process address space. Some OS's however don't have this protection, and you can willy-nilly poke and destroy things that belong to other programs. This is also usually the case if your code is inside kernel space, e.g. in a device driver.
2,976,076
2,976,127
C++: synchronize 5 consumers to 1 producer (multithreaded)
I have five consumers and one producer. The five consumers each output different data, from the one producer, for ~10ms. During those 10ms the producer prepares the parameters for the next output. When the output parameters are set, I want to set a flag instructing the consumers to begin the next output. I only want the producer to produce when the consumers are outputting the data. I am unsure how to synchronize the five consumers and the single producer. I currently have two flags, runFlag and doneFlag. When a consumer reads the new data I want to set runFlag to true so the calculations begin, and I want to set doneFlag to false, as the calculations have not completed. However, if I set doneFlag to false in one consumer it may be false in another consumer before that consumer can check the flag. I hope my question is specific enough. Please let me know if there's anything else I can provide. Also, I'm just looking for a general idea of how to proceed. I know there are multiple ways to do this, but I'm unsure which method will work the best. Thanks!
You will need 2 events and an integer reference count. When producer has produced some thing it: initiates read_count = 0; sets event readme. starts to wait on event completed; Consumers wait on event readme. After doing their work they ATOMICALLY increment read_count. If the read_count reaches the number of consumers, 5 in your case, then it sets the completed event. Thus producer can continue and the cycle repeats itself.
2,976,246
2,976,265
C++: How do applications like Cheat Engine and ArtMoney work?
After asking this question (C++: Can I get out of the bounds of my app’s memory with a pointer?), I decided to accept it isn't possible to modify other app's memory with pointers (with a modern OS). But if this isn't possible, how do programs like ArtMoney and CheatEngine work? Thanks
Check these functions: ReadProcessmemory WriteProcessmemory
2,976,274
2,976,423
adjust bitmap image brightness/contrast using c++
adjust image brightness/contrast using c++ without using any other 3rd party library or dependancy
Image brightness is here - use the mean of the RGB values and shift them. Contrast is here with other languages solutions available as well. Edit in case the above links die: The answer given by Jerry Coffin below covers the same topic and has links that still live. But, to adjust brightness, you add a constant value to each for the R,G,B fields of an image. Make sure to use saturated math - don't allow values to go below 0 or above the maximum allowed in your bit-depth (8-bits for 24-bit color) RGB_struct color = GetPixelColor(x, y); size_t newRed = truncate(color.red + brightAdjust); size_t newGreen = truncate(color.green + brightAdjust); size_t newBlue = truncate(color.blue + brightAdjust); For contrast, I have taken and slightly modified code from this website: float factor = (259.0 * (contrast + 255.0)) / (255.0 * (259.0 - contrast)); RGB_struct color = GetPixelColor(x, y); size_t newRed = truncate((size_t)(factor * (color.red - 128) + 128)); size_t newGreen = truncate((size_t)(factor * (color.green - 128) + 128)); size_t newBlue = truncate((size_t)(factor * (color.blue - 128) + 128)); Where truncate(int value) makes sure the value stays between 0 and 255 for 8-bit color. Note that many CPUs have intrinsic functions to do this in a single cycle. size_t truncate(size_t value) { if(value < 0) return 0; if(value > 255) return 255; return value; }
2,976,296
2,976,304
C++ dynamic array of matrices (from scythe statistical library)
I am trying to use the scythe statistical library (found here: http://scythe.wustl.edu/). I can initialize a matrix just fine with: Matrix<double> A(2, 2, false); But I would like to have a dynamic array of such matrices. Does anyone have any hints? Do I use vector? If so how? Many thanks!
A std::vector would be an excellent choice, especially if you don't know until runtime how many matrices you need. For example, std::vector<Matrix<double> > vectorOfMatrices; vectorOfMatrices.push_back(Matrix<double>(2, 2, false)); // etc.
2,976,396
2,976,443
Compile and link errors
Are there strategies or methods to identify whether a particular piece of code or program will generate a link error or a compile error.
You mention in your comments "if you don't have access to a compiler". Well if you have access to the web you have access to a compiler: Ideon Codepad's online compiler/parser Comeau's "try it out" web-based compiler (thanks commenters for the updates) This will just help you with compiling what's in the web form though, linking and producing an executable is another story...
2,976,477
2,976,483
Difference between iostream and iostream.h
What is the difference between iostream and iostream.h?
iostream.h is deprecated by those compilers that provide it, iostream is part of the C++ standard. To clarify explicitly there is no mention of iostream.h at all in the current C++ standard (INCITS ISO IEC 14882 2003). Edit: As @Jerry mentioned, not only does the current standard not mention it, but no standard for C++ mentions it.
2,976,489
6,210,386
IShellLink::SetIconLocation translates my icon path into %Program Files% which is WRONG
Does anyone know how to correct for this behavior? Currently, when our installer installs our application, it obtains an IShellLink, then loads it up with the data necessary for our shortcut icon (in the start menu & desktop), and then uses IPersistFile::Save to write out the shortcut. The problem is that the path specified for the icon, via IShellLink::SetIconLocation, is transformed into using %ProgramFiles%... which... for x64, is WRONG. I've noticed that lots of other 32 bit software has this failing under x64 - but then I assumed that they were using %ProgamFiles% themselves, as a literal element in their .lnk creation code. However, it appears to be that IShellLink is forcing this bug into existence, and I don't have a work-around (or perhaps that the link property editor in the shell is responsible for the problem and the underlying link is okay). A few Google searches have turned up nothing... has anyone else encountered this or know of an article / example of how to force x64 windows to not muck this up? Clarifying example: hr = m_shell_link->SetIconLocation("C:\\Program Files (x86)\\Acme\\Prog.exe", 0); Will result in a shortcut which has the correct icon, but when you press "Change icon" in the shortcut properties page, will report "Windows can't find the file %ProgramFiles%\Acme\Prog.exe.")
Convert the name into a short filename, and it will only convert the drive letter, yet keep the correct path. PWCHAR pIcon = L"C:\\Program Files (x86)\\Myfoo\\Bar.exe"; DWORD dwLen = GetShortPathName(pIcon, NULL, 0); PWCHAR pShort = NULL; if (dwLen) { pShort = new WCHAR[dwLen]; dwLen = GetShortPathName(pIcon, pShort, dwLen); if (!dwLen) { delete [] pShort; pShort = NULL; } } if (NULL == pShort) { psl->SetIconLocation(pIcon,iTmp); } else { psl->SetIconLocation(pShort,iTmp); } delete [] pShort;
2,976,654
2,976,839
gethostbyname creates a thread?
I am working in C++ with VS2008 and Win7. While examining a program I was following the threads created, and it seems that gethostbyname() creates a thread for itself. Could you explain why? On msdn is says: "The memory for the hostent structure returned by the gethostbyname function is allocated internally by the Winsock DLL from thread local storage. " Does this memory fool visual studio into thinking it is a thread? EDIT: It seems that from this link, and also from my observations that this also happens with the Connect function. I guess this is normal behavior. The code below is from msdn [gethostbyname page] and it exhibits the same behavior. int main(int argc, char **argv) { //----------------------------------------- // Declare and initialize variables WSADATA wsaData; int iResult; DWORD dwError; int i = 0; struct hostent *remoteHost; char *host_name; struct in_addr addr; char **pAlias; // Validate the parameters if (argc != 2) { printf("usage: %s hostname\n", argv[0]); printf(" to return the IP addresses for the host\n"); printf(" %s www.contoso.com\n", argv[0]); printf(" or\n"); printf(" %s IPv4string\n", argv[0]); printf(" to return an IPv4 binary address for an IPv4string\n"); printf(" %s 127.0.0.1\n", argv[0]); return 1; } // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } host_name = argv[1]; printf("Calling gethostbyname with %s\n", host_name); remoteHost = gethostbyname(host_name); if (remoteHost == NULL) { dwError = WSAGetLastError(); if (dwError != 0) { if (dwError == WSAHOST_NOT_FOUND) { printf("Host not found\n"); return 1; } else if (dwError == WSANO_DATA) { printf("No data record found\n"); return 1; } else { printf("Function failed with error: %ld\n", dwError); return 1; } } } else { printf("Function returned:\n"); printf("\tOfficial name: %s\n", remoteHost->h_name); for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) { printf("\tAlternate name #%d: %s\n", ++i, *pAlias); } printf("\tAddress type: "); switch (remoteHost->h_addrtype) { case AF_INET: printf("AF_INET\n"); break; case AF_NETBIOS: printf("AF_NETBIOS\n"); break; default: printf(" %d\n", remoteHost->h_addrtype); break; } printf("\tAddress length: %d\n", remoteHost->h_length); i = 0; if (remoteHost->h_addrtype == AF_INET) { while (remoteHost->h_addr_list[i] != 0) { addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++]; printf("\tIP Address #%d: %s\n", i, inet_ntoa(addr)); } } else if (remoteHost->h_addrtype == AF_NETBIOS) { printf("NETBIOS address was returned\n"); } } return 0; }
AFAIK, gethostbyname blocks. WinSock often creates some helper threads though.
2,976,671
2,976,678
Exposing a std::list as read only
I have a class that contains, among other things, an std::list. I want to expose this list but only in such a way that the structure and the data it contains are read only, but still can be used with iterators. The way I've got it 'working' atm is to return a copy of the list. This leave my class 'safe' but of course does nothing to stop the caller from modifying their copy of the list and not getting the right data. Is there a better way?
Why not return a const std::list& instead?
2,976,790
2,976,878
Redirect a TCP connection
I have something like a proxy server (written in java) running between my clients and the actual video server (made in c++). Everything the clients send goes through this proxy and is then redirected to the server. It is working fine, but I have some issues and think it would be better if I could make this proxy server only to listen to the clients requests and then somehow tell the server that a request has been made from the client side, and that it is supposed to create a connection with the client directly. Basically in the TCP level what I want to happen is something like this: 1- whenever a client sends a SYN to my proxy, the proxy just sends a message to the real server telling the ip and port of the client. 2- The server would then send the corresponding SYN-ACK to the specified client creating a direct connection between client and server. The proxy would then be just relaying the initial requests (but not the later data transfer) to the actual server. I just don't know if that is possible. Thank you very much Nelson R. Perez
You don't have control of TCP handshake in userland like that. This is what firewalls/routers do but it all happens in the kernel. Take a look at the firewalling software for your platform - you might not even have to code anything.
2,977,007
2,977,045
Public Data members vs Getters, Setters
I am currently working in Qt and so C++. I am having classes that has private data members and public member functions. I have public getters and setters for the data members available in the class. Now my question is, if we have getters and setters for data members in our classes then what's the point in making those data members as private? I agree having private data members in Base classes sounds logical. But besides that, having private members and so do their getters and setters doesn't seem to be of a logical one for me. Or instead can we make all variables as public so that no need for getters and setters at all? Is it a good practice to have those? I know having private members ensure data abstraction but having getters and setters actually lets access to those variables quite easily. Any pointers regarding this are welcome.
Neither. You should have methods that do things. If one of those things happens to correspond with a specific internal variable that's great but there should be nothing that telegraphs this to the users of your class. Private data is private so you can replace the implementation whenever you wish (and can do full rebuilds but that's a different issue). Once you let the Genie out of the bottle you will find it impossible to push it back in. EDIT: Following a comment I made to another answer. My point here is that you are asking the wrong question. There is no best practice with regard to using getters/setters or having public members. There is only what is best for your specific object and how it models some specific real world thing (or imaginary thing perhaps in the case of game). Personally getters/setters are the lesser of two evils. Because once you start making getters/setters, people stop designing objects with a critical eye toward what data should be visible and what data should not. With public members it is even worse because the tendency becomes to make everything public. Instead, examine what the object does and what it means for something to be that object. Then create methods that provide a natural interface into that object. It that natural interface involves exposing some internal properties using getters and setters so be it. But the important part is that you thought about it ahead of time and created the getters/setters for a design justified reason.
2,977,077
2,977,201
C++ boost mpl vector
I understand that the following code won't work, as i is a runtime parameter and not a compile time parameter. But i want to know, whether there is a way to achieve the same. i have a list of classes and i need to call a template function, with each of these classes. void GucTable::refreshSessionParams() { typedef boost::mpl::vector< SessionXactDetails, SessionSchemaInfo > SessionParams; for( int i = 0; i < boost::mpl::size<SessionParams>::value; ++i ) boost::mpl::at<SessionParams, i>::type* sparam = g_getSessionParam< boost::mpl::at<SessionParams, i>::type >(); sparam->updateFromGucTable(this); } } Can someone suggest me a easy and elegant way to perform the same? i need to iterate through the mpl::vector and use the type to call a global function and then use that parameter to do some run-time operations. Thanks in advance, Gokul. Working code typedef boost::mpl::vector< SessionXactDetails, SessionSchemaInfo > SessionParams; class GucSessionIterator { private: GucTable& m_table; public: GucSessionIterator(GucTable& table) :m_table(table) { } template< typename U > void operator()(const U& ) { g_getSessionParam<U>()->updateFromGucTable(m_table); } }; void GucTable::refreshSessionParams() { boost::mpl::for_each< SessionParams >( GucSessionIterator(*this) ); return; }
I only used MPL for a collection of types for BOOST_AUTO_TEST_CASE_TEMPLATE, so my knowledge is quite limited. However, I'd guess you could use for_each to iterate through an MPL sequence.
2,977,174
8,539,875
Is there a C++11 syntax file for vim?
In particular, the display of initialization lists is really bad: vector<int> v({1,2,3}); will highlight the curly braces in red (denoting an error).
There is now a C++11 script from http://www.vim.org/scripts/script.php?script_id=3797, which no longer mark the braces inside parenthesis as error.
2,977,982
2,977,992
C++ struct definition
Possible Duplicate: What does ‘unsigned temp:3’ means I just found this code in a book (was used in an example) typedef struct { unsigned int A:1; unsigned int B:1; unsigned int C:1; } Stage; What is the meaning of this structure definition? (the A:1;)
Those are C bitfields. In compliant compilers, the combination of A B and C do not occupy more than one int. A, B, and C occupy one bit each in the integer.
2,977,983
2,978,011
does VS express conflict with professional?
I just recently installed VS 2008 Professional on my computer and I already have C++ and C# express on my computer. But for some strange reason I can not find the executable for VS professional 2008. when I go into program files and look under visual studios 2008. All i see is a bunch of tools but no vs 2008 exe
Strange... have you check the directory C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe?
2,978,096
2,978,327
Using * Width & Precision Specifiers With boost::format
I am trying to use width and precision specifiers with boost::format, like this: #include <boost\format.hpp> #include <string> int main() { int n = 5; std::string s = (boost::format("%*.*s") % (n*2) % (n*2) % "Hello").str(); return 0; } But this doesn't work because boost::format doesn't support the * specifier. Boost throws an exception when parsing the string. Is there a way to accomplish the same goal, preferably using a drop-in replacement?
Try this: #include <boost/format.hpp> #include <iomanip> using namespace std; using namespace boost; int main() { int n = 5; string s = (format("%s") % io::group(setw(n*2), setprecision(n*2), "Hello")).str(); return 0; } group() lets you encapsulate one or more io manipulators with a parameter.
2,978,118
2,978,377
Data parallel libraries in C/C++
I have a C# prototype that is heavily data parallel, and I've had extremely successful order of magnitude speed ups using the Parallel.For construct in .NETv4. Now I need to write the program in native code, and I'm wondering what my options are. I would prefer something somewhat portable across various operating systems and compilers, but if push comes to shove, I can go with something Windows/VC++. I've looked at OpenMP, which looks interesting, but I have no idea whether this is looked upon as a good solution by other programmers. I'd also love suggestions for other portable libraries I can look at.
If you're using Parallel.For in .Net 4.0, you should also look at the Parallel Pattern Library in VS2010 for C++; many things are similar and it is library based. If you need to run on another platform besides Windows the PPL is also implemented in Intel's Thread Building Blocks which has an open source version. Regarding the other comment on similarities / differences vs. .Net 4.0, the parallel loops in the PPL (parallel_for, parallel_for_each, parallel_invoke) are virtually identical to the .Net 4.0 loops. The task model is slightly different, but should be straightforward.
2,978,259
2,981,617
Programmatically create static arrays at compile time in C++
One can define a static array at compile time as follows: const std::size_t size = 5; unsigned int list[size] = { 1, 2, 3, 4, 5 }; Question 1 - Is it possible by using various kinds of metaprogramming techniques to assign these values "programmatically" at compile time? Question 2 - Assuming all the values in the array are to be the same barr a few, is it possible to selectively assign values at compile time in a programmatic manner? eg: const std::size_t size = 7; unsigned int list[size] = { 0, 0, 2, 3, 0, 0, 0 }; Solutions using C++0x are welcome The array may be quite large, few hundred elements long The array for now will only consist of POD types It can also be assumed the size of the array will be known beforehand, in a static compile-time compliant manner. Solutions must be in C++ (no script, no macros, no pp or code generator based solutions pls) UPDATE: Georg Fritzsche's solution is amazing, needs a little work to get it compiling on msvc and intel compilers, but nonetheless a very interesting approach to the problem.
The closest you can get is using C++0x features to initialize local or member arrays of templates from a variadic template argument list. This is of course limited by the maximum template instantiation depth and wether that actually makes a notable difference in your case would have to be measured. Example: template<unsigned... args> struct ArrayHolder { static const unsigned data[sizeof...(args)]; }; template<unsigned... args> const unsigned ArrayHolder<args...>::data[sizeof...(args)] = { args... }; template<size_t N, template<size_t> class F, unsigned... args> struct generate_array_impl { typedef typename generate_array_impl<N-1, F, F<N>::value, args...>::result result; }; template<template<size_t> class F, unsigned... args> struct generate_array_impl<0, F, args...> { typedef ArrayHolder<F<0>::value, args...> result; }; template<size_t N, template<size_t> class F> struct generate_array { typedef typename generate_array_impl<N-1, F>::result result; }; Usage for your 1..5 case: template<size_t index> struct MetaFunc { enum { value = index + 1 }; }; void test() { const size_t count = 5; typedef generate_array<count, MetaFunc>::result A; for (size_t i=0; i<count; ++i) std::cout << A::data[i] << "\n"; }
2,978,315
2,978,575
C++ - Where to store a global counter?
The diagram http://www.freeimagehosting.net/uploads/2fd3f4161c.png Here's the Minimalist-UML diagram of an app I've been working on. It's supposed to simulate the management of a bunch of sensors relating to different measurements. Please ignore the House class, the diagram is outdated... However, I have trouble. Each sensor (sound, contact, heat, pressure, gas - All of these inherit from sensor) has an unique ID, starting at 0 for the first one and ending at the total number of sensors - 1. For good practices' sake, where shall I store the total number of sensors, so the classes I'm using for input/output of files (saving and loading) and insertion of new sensors can access and increment that counter? Thank you for your time!
One option would be to create a static function in your Sensor class that increments and returns a static counter variable. The constructor for Sensor could call this function to get an ID. // header file class Sensor { ... protected: static int getId() { return id++; } private: static int id; int myId; }; // .cpp file int Sensor::id = 0; Sensor::Sensor(...) : myId(getId()) ... {} I'm ignoring threading and persistence issues here. But hopefully this gives you a better idea.
2,978,488
2,978,603
select() hanging indefinitely
I have an application that runs on embedded linux (older kernel, 2.6.18). I'm using Live555. Occasionally when the camera is heavily loaded, my RTSP server (built using Live555) will hang indefinitely--no amount of connecting or cajoling seems to get it to snap out of it, short of resetting the application. I narrowed the hang down to this code: static int blockUntilReadable(UsageEnvironment& env, int socket, struct timeval* timeout) { int result = -1; do { fd_set rd_set; FD_ZERO(&rd_set); if (socket < 0) break; FD_SET((unsigned) socket, &rd_set); const unsigned numFds = socket+1; result = select(numFds, &rd_set, NULL, NULL, timeout); <--HANG timeout is, of course, a NULL pointer which indicates it should block until one of the sockets is readable. Problem is: it doesn't matter if I connect to the RTSP server--it simply blocks indefinitely. I did a netstat -an, and it always outputs something like: Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:5222 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:5800 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:5000 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:5802 0.0.0.0:* LISTEN tcp 21 0 0.0.0.0:554 0.0.0.0:* LISTEN When it's in a failed state, I always see 21 on the Recv-Q, which is "The count of bytes not copied by the user program connected to this socket." Does anyone have any idea what might be going south, or how I could troubleshoot this issue?
That code looks pretty solid. I'm a little curious as to why you're casting to unsigned int, but it shouldn't hurt anything. Some thoughts: It's not hanging where you think it is. Hopefully you've double/triple checked this. (Check it again?) Your netstat interpretation is wrong. That part, as the man page notes, is for "Established" sockets - yours is a listener, which is the next sentence: "Listening: Since Kernel 2.6.18 this column contains the current syn backlog." That looks like a huge backlog... Which leads me to think you're not accept()-ing, perhaps because you're stuck in select(). That is the select() on your listening socket right? Last, double check that you're calling select() on the right socket. ie, print out that socket arg, and see if it is what it should be. Essentially, verify: 1) it's is hanging in select() and 2) the arguments to select are correct. I suspect one of those two are not true.
2,978,689
2,978,713
Playing sounds over the microphone in c++
I am making a program in C++ for Windows XP that requires sound to be played so that any program that is currently recording the microphone can hear it, but it will not come out of the speakers. There seems to be no "real" way of doing it, but it is possible to go into "sndvol32 -R" and set the Wave out mix or similar as the current input device. Then you can turn the master volume to 0, play the sound, turn it back up, and reset the input device to the microphone. Is there a way of doing this transparently, or setting the current input device using functions, so that you dont have to see sndvol32 pop up? Thanks
Doing this would require a complicated kernel-level driver. Fortunately for you, someone has already done this (it's not free, but it's a fantastic program).
2,978,844
2,978,882
Struct containing a Map in a Map? (C++/STL)
I was wondering if it was possible to create a struct containing a number of variables and a map in a map. What I have at the moment: typedef std::map<std::string,double> lawVariables; struct ObjectCustomData { std::string objectType; bool global_lock; std::map<std::string, lawVariables> lawData; }; This struct is then passed on to another function as a single data block for that object. The structure setup is as follows: Each object has a data block that contains: its ObjectType, a bool for a lock, and a varying number of "laws" that could look like this: law1 -> var_a = 39.3; -> var_g = 8.1; law8 -> var_r = 83.1; -> var_y = 913.3; -> var_a = 9.81; Firstly, I'm unsure whether I should be using a Map within a Map and secondly even if this would be valid, I'm unsure how to fill it with data and how to recall it afterwards. I looked at maps because then I can search (on a name) if a certain object has a certain law, and if that law has certain variables. (sorry for the first messy post appearance, hope this is better :) )
I was wondering if it was possible to create a struct containing a number of variables and a map in a map Yes. It is possible to have Map as value inside another map. If you are particular about the order of insertion and the entries are less for inner map then your data structure can looks like: typedef std::vector<std::pair<std::string,double> > lawVariables; struct ObjectCustomData { std::string objectType; bool global_lock; std::map<std::string, lawVariables> lawData; }; EDIT: I saw your edit now. If lookup is your primary requirement then go for map. Example: typedef std::map<std::string,double> lawVariables; struct ObjectCustomData { std::string objectType; bool global_lock; std::map<std::string, lawVariables> lawData; }; void test(ObjectCustomData& data) { lawVariables& variable = data.lawData["law_1"]; variable["var_a"] = 39.3; }
2,979,165
3,063,297
Fober et al Lock-Free FIFO Queue: multiple consumers and producers?
I was wondering if the fifo queue presented in Fober et al's paper http://nedko.arnaudov.name/soft/L17_Fober.pdf was a multiple consumer and produce fifo queue. If not, which is the best documented multiple consumer and producer FIFO queue? Thanks
yes. read section '3.1 Linearizability' the pop operation assumes that concurrent dequeue might happen. This means that multiple threads will be able to consume the queue.
2,979,195
2,979,234
How can I search PDF?
Im doing a small project in C++ in LINUX PLATFORM.i need to search 10 or more PDF files and find required data.how can i do so?. i will make my question more clear with following eg Suppose i have ten text books all about c++ and i need info about the topic array. How i can search the pdf and find data?
Read this pdftotext If you actually want to write code to do then you'll probably have to learn of to navigate the internals of a PDF file. There have been some answers on how to do that for example one pointing to this article which on the 2nd page has the code in C for a basic PDF parser xtractpro
2,979,222
2,979,228
How to use a object whose copy constructor and copy assignment is private?
In reading TCPL, I got a problem, as the title refered, and then 'private' class is: class Unique_handle { private: Unique_handle& operator=(const Unique_handle &rhs); Unique_handle(const Unique_handle &rhs); public: //... }; the using code is: struct Y { //... Unique_handle obj; }; and I want to execute such operations: int main() { Y y1; Y y2 = y1; } although, these code are come from TCPL, but I still can not got the solution... Can anybody help me, appreciate.
As its name suggests, the Unique_handle isn't meant to be copied. Its implementation ensures it by disabling the copy constructor and copy assignment operator. One solution for multiple instances having access to a Unique_handle is holding a pointer to it, and copying the pointer. Then multiple instances of Y point to the same unique handle. Take care, however, to manage resources properly in this case.
2,979,384
2,979,401
Purpose of Header guards
In C++ what is the purpose of header guard in C++ program. From net i found that is for preventing including files again and again but how do header guard guarantee this.
The guard header (or more conventionally "include guard") is to prevent problems if header file is included more than once; e.g. #ifndef MARKER #define MARKER // declarations #endif The first time this file is #include-ed, the MARKER preprocessor symbol will be undefined, so the preprocessor will define the symbol, and the following declarations will included in the source code seen by the compiler. On subsequent #include's, the MARKER symbol will be defined, and hence everything within the #ifnde / #endif will be removed by the preprocessor. For this to work properly, the MARKER symbol needs to be different for each header file that might possibly be #include-ed. The reason this kind of thing is necessary is that it is illegal in C / C++ to define a type or function with the same name more than once in a compilation unit. The guard allows you to #include a header file without worrying if has already been included. Without the guard, multiple inclusions of the same header file would lead to unwanted redeclarations and compilation errors. This is particularly helpful when header files need to #include other header files. In short, it doesn't prevent you from #include-ing a file again and again. Rather, it allows you to do this without causing compilation errors.
2,979,386
2,979,503
MultiOS "Jet Database" for C++/Qt?
Hopefully I can articulate this well: I'm porting an application I made years ago from VB6 (I know, I know!) to C++/Qt. In my original application, one thing I liked was that I didn't need an actual SQL server running, I could just use MS Access .mdb files. I was wondering if something similar exists for Qt that will work on multiple OSes - a database stored in a file, pretty much, but that I can still run SQL queries with. Not sure if something like this exists or not, but any help appreciated, thanks!
I second the comment by "Mosg". Have a look at SQLite.
2,979,392
2,979,430
Why C/C++ have memory issue?
I have read lots of programmers saying and writing when programming in C/C++ there are lots of issue related to memory. I am planning to learn to program in C/C++. I have beginner knowledge of C/C++ and I want to see some short sample why C/C++ can have issues with memory management. Please Provide some samples.
There are many ways you can corrupt or leak memory in C or C++. These errors are some of the most difficult to diagnose, because they are often not easily reproducible. For example, it is simple to fail to free memory you have allocated. For example, this will do a "double free", trying to free a twice and failing to free b: char *a = malloc(128*sizeof(char)); char *b = malloc(128*sizeof(char)); b = a; free(a); free(b); // will not free the pointer to the original allocated memory. An example buffer overrun, which corrupts arbitrary memory follows. It is a buffer overrun because you do not know how long str is. If it is longer than 256 bytes, then it will write those bytes somewhere in memory, possible overwriting your code, possibly not. void somefunc(char *str) { char buff[256]; strcpy(buff, str); }
2,979,523
2,979,573
How to test if a string has a certain unicode char?
Supose you have a command line executable that receives arguments. This executalbe is widechar ready and you want to test if one of this arguments starts with an HYPHEN case in which its an option: command -o foo how you could test it inside your code if you don't know the charset been used by the host? Should be not possible to a given console to produce the same HYPHEN representation by another char in the widechar forest? (in such case it would be a wild char :P) int _tmain(int argc, _TCHAR* argv[]) { std::wstring inputFile(argv[1]); if(inputFile->c_str() <is an HYPHEN>) { _tprintf(_T("First argument cannot be an option")); } }
In your case, Windows will deliver the command line as a UTF-16 string so you shouldn't need to worry about character sets. Just check (inputFile->c_str()[0] == L'-') and you should be good to go. Of course UTF-16 is a variable-length encoding but the hyphen character is represented by a single wide-char value.
2,979,525
2,979,557
Boost threading/mutexs, why does this work?
Code: #include <iostream> #include "stdafx.h" #include <boost/thread.hpp> #include <boost/thread/mutex.hpp> using namespace std; boost::mutex mut; double results[10]; void doubler(int x) { //boost::mutex::scoped_lock lck(mut); results[x] = x*2; } int _tmain(int argc, _TCHAR* argv[]) { boost::thread_group thds; for (int x = 10; x>0; x--) { boost::thread *Thread = new boost::thread(&doubler, x); thds.add_thread(Thread); } thds.join_all(); for (int x = 0; x<10; x++) { cout << results[x] << endl; } return 0; } Output: 0 2 4 6 8 10 12 14 16 18 Press any key to continue . . . So...my question is why does this work(as far as i can tell, i ran it about 20 times), producing the above output, even with the locking commented out? I thought the general idea was: in each thread: calculate 2*x copy results to CPU register(s) store calculation in correct part of array copy results back to main(shared) memory I would think that under all but perfect conditions this would result in some part of the results array having 0 values. Is it only copying the required double of the array to a cpu register? Or is it just too short of a calculation to get preempted before it writes the result back to ram? Thanks.
The assignment has an lvalue of type double on the left and that lvalue is the only object being accessed by a thread. Since each thread accesses a different object, there is no data race. Note that subscripting an array does not constitute an access.
2,979,584
2,979,638
How can I use STL sort in c++ to sort some values in the class?
I have a class named Graph, in this class I have a member named V, it is a vector. I have a struct named Edge, and a list of Edges. like below: struct Edge{ int u; int v; Edge(int u,int v){ this->u=u; this->v=v; } }; struct Vertex{ int d; int f; . . . } class Graph{ vector < Vertex > V; . . . int edgeCmp(Edge* x,Edge* y){ return ( V[x->v].d < V[y->v].d )?1:0; } void someFunction(){ list<Edge> backEdges; backEdges.sort(&Graph::edgeCmp); } } But it doesn't work!! may someone help me to do such a thing? I get this error: Error 3 error C2064: term does not evaluate to a function taking 2 arguments c:\program files\microsoft visual studio 9.0\vc\include\xutility 346 It can't understand I'm calling the function which takes 2 arguments. I don't know why.
You can't use a member function as the comparator. A member function needs the this pointer which cannot be passed from sort. Instead, you have to create a function object to include the extra info, like: class Graph{ vector < Vertex > V; struct EdgeComparer { const vector<Vertex>& V; EdgeComparer(const vector<Vertex>& vertices) : V(vertices) {} bool operator() (const Edge& a, const Edge& b) const { return V[a.v].d < V[b.v].d; } }; ... EdgeComparer ec (V); backEdges.sort(ec); Note that, since you have a list of Edge, not Edge*, the input arguments of the comparator should not be Edge*. I have changed those to const Edge&.
2,979,673
2,979,689
How do you use C++0x raw strings with GCC 4.5?
This page says that GCC 4.5 has C++ raw string literals: http://gcc.gnu.org/projects/cxx0x.html But when I try to use the syntax from this page: http://www2.research.att.com/~bs/C++0xFAQ.html#raw-strings #include <iostream> #include <string> using namespace std; int main() { string s = R"[\w\\\w]"; } I get this error: /opt/local/bin/g++-mp-4.5 -std=gnu++0x -O3 rawstr.cc -o rawstr rawstr.cc:9:19: error: invalid character '\' in raw string delimiter rawstr.cc:9:5: error: stray 'R' in program What is the right syntax for raw strings?
Try R"(\w\\\w)"; The delimiters […] were changed to (…) in n3077.
2,979,954
2,979,973
Parametrised and Conversion Constructors
Is there any difference between parametrised constructor and conversion constructor. If so what is it?
A parameterised constructor is (presumably) any constructor that takes one or more parameters. A conversion constructor is a constructor that can be called with a single parameter and is not declared explicit. struct A { A(); // not parameterised or conversion A( int x, int y ); // paramterised, not conversion A( int x ); // conversion explicit A( float z ); // not conversion; }; Conversion constructors can be used by the compiler. Given: void f( A a ) { } the compiler can call this function as: f( 42 ); using the conversion constructor to convert 42 into an object of type A.
2,980,219
2,980,228
Achieving C# "readonly" behavior in C++
this is my first question on stack overflow, so be gentle. Let me first explain the exact behavior I would like to see. If you are familiar with C# then you know that declaring a variable as "readonly" allows a programmer to assign some value to that variable exactly once. Further attempts to modify the variable will result in an error. What I am after: I want to make sure that any and all single-ton classes I define can be predictably instantiated exactly once in my program (more details at the bottom). My approach to realizing my goal is to use extern to declare a global reference to the single-ton (which I will later instantiate at a time I choose. What I have sort of looks like this, namespace Global { extern Singleton& mainInstance; // not defined yet, but it will be later! } int main() { // now that the program has started, go ahead and create the singleton object Singleton& Global::mainInstance = Singleton::GetInstance(); // invalid use of qualified name Global::mainInstance = Singleton::GetInstance(); // doesn't work either :( } class Singleton { /* Some details ommited */ public: Singleton& GetInstance() { static Singleton instance; // exists once for the whole program return instance; } } However this does not really work, and I don't know where to go from here. Some details about what I'm up against: I'm concerned about threading as I am working on code that will deal with game logic while communicating with several third-party processes and other processes I will create. Eventually I would have to implement some kind of synchronization so multiple threads could access the information in the Singleton class without worry. Because I don't know what kinds of optimizations I might like to do, or exactly what threading entails (never done a real project using it), I was thinking that being able to predictably control when Singletons were instantiated would be a Good Thing. Imagine if Process A creates Process B, where B contains several Singletons distributed against multiple files and/or libraries. It could be a real nightmare if I can not reliably ensure the order these singleton objects are instantiated (because they could depend on each other, and calling methods on a NULL object is generally a Bad Thing). If I were in C# I would just use the readonly keyword, but is there any way I can implement this (compiler supported) behavior in C++? Is this even a good idea? Thanks for any feedback. Edit If I was locked in to following the code example above, the selected answer would be the easiest way to do what I needed. I decided to change the pattern away from singleton though, even though I only plan to ever make one of these EntryPoint objects. class EntryPoint { /* Intentionally defined this way to discourage creation */ EntryPoint(const EntryPoint &); // undefined & private EntryPoint& operator=(const EntryPoint &); // undefined & private // public EntryPoint() { /* All of the action is performed here! */ } /* Other supporting functions */ } // The easier to understand main function! int main() { EntryPoint * ep = new EntryPoint(); // transfer control to the entrypoint delete ep; } One of the reasons I was thinking I would need all these singletons is I plan to create a larger architecture that would support modular plugin-type applications. I also wanted more error-checking and memory protection to minimize memory leaks. I was happy to find that the cross-platform Qt (http://qt.nokia.com/) offers a guarded pointer and other cool features.
Why not just use Singleton::GetInstance directly? Why do you need to store it in a (readonly) global? This solves dependency issues as well.
2,980,240
2,983,544
How to get the Drive letter and Mount Path - MSDN
I get the devices list from the system using SetupDiGetClassDevs Function - MSDN. Also i can able to get the vendor id and product id from the devices. But i cant able to get the drive letter and the mount path For Example if i plug the usb drive means , i have to get the drive letter like "G:/" Please help me to get the drive letter and mount path for the devices if (SetupDiEnumDeviceInterfaces(hDevInfo, NULL,&GUID_DEVINTERFACE_USB_DEVICE,i,&Interface_Info)) { wprintf(L"\tDeviccvcvcveInstanceId : %d\n", i); pspdidd->cbSize = sizeof(*pspdidd); SP_DEVICE_INTERFACE_DETAIL_DATA *pDetData = NULL; DWORD dwDetDataSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA) + 256; pDetData = (SP_DEVICE_INTERFACE_DETAIL_DATA*) malloc (dwDetDataSize); pDetData->cbSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA); SetupDiGetDeviceInterfaceDetail(hDevInfo,&Interface_Info,pDetData,dwDetDataSize, NULL,&DeviceInfoData); qDebug ()<<QString::fromWCharArray( pDetData->DevicePath ); }
You can use QueryDosDevice function (see http://msdn.microsoft.com/en-us/library/aa365461(VS.85).aspx). See http://msdn.microsoft.com/en-us/library/cc542456(VS.85).aspx for an code example.
2,980,253
2,980,276
how to convert utf-8 to ASCII in c++?
i am getting response from server in utf-8 but not able to read that. how to convert utf-8 to ASCII in c++?
First note that ASCII is a 7-bit format. There are 8-bit encodings, if you are after one of these (such as ISO 8859-1) you'll need to be more specific. To convert an ASCII string to UTF-8, do nothing: they are the same. So if your UTF-8 string is composed only of ASCII characters, then it is already an ASCII string, and no conversion is necessary. If the UTF-8 string contains non-ASCII characters (anything with accents or non-Latin characters), there is no way to convert it to ASCII. (You may be able to convert it to one of the ISO encodings perhaps.) There are ways to strip the accents from Latin characters to get at least some resemblance in ASCII. Alternatively if you just want to delete the non-ASCII characters, simply delete all bytes with values >= 128 from the utf-8 string.
2,980,385
3,006,182
How to get only USB devices not all the devices in the system
Grretings to all, I get devices list from the system. but i am not sure that if i want to get only the usb devices currently in the system means , What class i must specify in the below code ( DWORD Flags ) hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, 0, // Enumerator 0, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE );
Consider using EnumerateHostController(). Examples www.intel.com/intelpress/usb/examples/DUSBVC.PDF github.com/Microsoft/Windows-driver-samples/blob/master/usb/usbview/enum.c Additional info and a detailed discussion here.
2,980,386
2,980,471
base destructor called twice after derived object?
hey there, why is the base destructor called twice at the end of this program? #include <iostream> using namespace std; class B{ public: B(){ cout << "BC" << endl; x = 0; } virtual ~B(){ cout << "BD" << endl; } void f(){ cout << "BF" << endl; } virtual void g(){ cout << "BG" << endl; } private: int x; }; class D: public B{ public: D(){ cout << "dc" << endl; y = 0; } virtual ~D(){ cout << "dd" << endl; } void f(){ cout << "df" << endl; } virtual void g(){ cout << "dg" << endl; } private: int y; }; int main(){ B b, * bp = &b; D d, * dp = &d; bp->f(); bp->g(); bp = dp; bp->f(); bp->g(); }
Destructors are called in order, as if they were unwinding the effects of the corresponding constructors. So, first the destructors of the derived objects, then the destructors of the base objects. And making the destructors virtual doesn't have any impact on calling / not calling the base class destructor. Also to mention, your example could be simplified this way (this code also results in calling the base destructor twice and the derived destructor once): struct A { ~A() { // ... } }; struct B: A { ~B() { // ... } }; int main() { A a; B b; }
2,980,581
2,987,560
Help with WinAPI scroll bars
Right now I have a window with horizontal ad vertical scrollbars. I use these parameters to initialize it. //Set OGL Frame scroll bar SCROLLINFO inf; inf.cbSize = sizeof(SCROLLINFO); inf.fMask = SIF_PAGE | SIF_POS; inf.nPage = 20; inf.nPos = 30; It creates them in the center and I like their size, but when I scroll I multiply by 50 which creates chopiness. How could I add more resolution to the bars and still keep the same thumb size. Is there a way I can calculate the size and position of the bar based on the above parameters? Thanks
Right, here's my solution even though one is already accepted. Everytime I have issues with the windows controls I use Controlspy to experiment with them. Controlspy also lists all the different messages that can be sent to the different controls. Find one that is similar to what you are trying to do and check that specific message on MSDN.
2,980,778
2,980,872
Boost singleton trouble
I have some class which uses boost singleton. It calls some function from own c++ library. This library is written in make file as dependence. Now I have another singleton class and it should call first singleton class. After this code I got linkers error about undefined references for functions which are used in first singleton. When I remove calling first singleton class from second the errors remove. Maybe there is something wrong? class First : public boost::singleton<First> { void temp() { /* Calling function from own library */ } }; class Second : public boost:singleton<Second> { const First &someInstance() const { return First::get_const_instance(); } }; End errors: In function `First::temp()': undefined reference to `Ogre::WindowEventUtilities::messagePump()' undefined reference to `Ogre::Root::renderOneFrame()' Yes, there is calling Ogre's functions from temp one.
These errors indicate you're not linking correctly with Ogre. If they disappear when Second isn't referencing First, that's because First is not being referenced/used anywhere else. Did you try using First in your code to check whether the errors remain?
2,980,790
2,981,896
Make function declarations based on function definitions
I've written a .cpp file with a number of functions in it, and now need to declare them in the header file. It occurred to me that I could grep the file for the class name, and get the declarations that way, and it would've worked well enough, too, had the complete function declaration before the definition -- return code, name, and parameters (but not function body) -- been on one line. It seems to me that this is something that would be generally useful, and must've been solved a number of times. I am happy to edit the output and not worried about edge cases; anything that gives me results that are right 95% of the time would be great. So, if, for example, my .cpp file had: i2cstatus_t NXTI2CDevice::writeRegisters( uint8_t start_register, // start of the register range uint8_t bytes_to_write, // number of bytes to write uint8_t* buffer = 0) // optional user-supplied buffer { ... } and a number of other similar functions, getting this back: i2cstatus_t NXTI2CDevice::writeRegisters( uint8_t start_register, // start of the register range uint8_t bytes_to_write, // number of bytes to write uint8_t* buffer = 0) for inclusion in the header file, after a little editing, would be fine. Getting this back: i2cstatus_t writeRegisters( uint8_t start_register, uint8_t bytes_to_write, uint8_t* buffer); or this: i2cstatus_t writeRegisters(uint8_t start_register, uint8_t bytes_to_write, uint8_t* buffer); would be even better.
I compiled exuberant ctags version 5.8. This command gets me what I want: /usr/local/bin/ctags -x --c-kinds=f $SOURCE | awk -v OFS=" " '$1=$1' | cut -d " " -f 5- | sed -e 's/[A-Za-z]*:://g' | sed -e 's/)$/);/' where you substitute the filename you are interested in in place of $SOURCE. Note that the ctags command by itself gives a reasonable output, and you can throw in a -u flag if you want the output in the order it appears in the file, instead of in alphabetical order.
2,980,822
2,980,921
why it is up to the compiler to decide what value to assign when assigning an out-of-range value to a variable
in C++ Primer 4th edition 2.1.1, it says "when assigning an out-of-range value to a signed type, it is up to the compiler to decide what value to assign". I can't understand it. I mean, if you have code like "char 5 = 299", the compiler will generate asm code like "mov BYTE PTR _sc$[ebp], 43"(VC) or "movb $43, -2(%ebp)"(gcc+mingw), it IS decided by the compiler. but what if we assign a value that is given by the user input? like, via command line? and the asm code generated will be "movb %al, -1(%ebp)"(gcc+mingw) and " mov cl, BYTE PTR _i$[ebp] mov BYTE PTR _sc$[ebp], cl "(VC), so now how can compiler decide what will happen? I think now it is decided by the CPU. Can you give me a clear explanation?
It is up to the compiler whether or not to let it be decided by the CPU. :) The C++ standard specifies how your program should behave. The compiler ensures that this behavior is achieved. if you do something that is not specified by the standard, then the compiler can do anything it likes. It can produce an error message, send an email to your grandmother or hack your bank account. Or it can generate code anyway, and yes, then it's up to the CPU what happens next. But the point is that the CPU is not responsible for ensuring that your program behaves as specified by the C++ standard. The compiler is. And so, it is up to the compiler how any deviation from the standard should be handled (even if it will often choose to do nothing special, that is still the compiler's decision)
2,980,823
2,981,056
Frame skipping with OpenGL and WinAPI?
Here is my situation. I'm creating a drawing application using OpenGL and WinAPI. My OpenGL frame has scrollbars which renders the screen and modifies GlTranslatef when it gets a scroll message. The problem is wen I get too many shapes the scrollbar is less responsive since it cannot rerender it each and every time it gets a scroll message. How could I make it so the scrollbar has priority. I want it to skip drawing if it would compromise the smoothness of the scrolling. I thought of doing rendering on a separate thread but I was told all UI things should stay on the same thread. Thanks
You can measure the runtime of your draw routine. When it is greater than a threshold you decide, you should either throttle the updates or draw less (if you can).
2,980,909
3,027,026
Is it possible to catch media stream URL of flash player using NPAPI functions?
I'm trying to make a video download panel for Chrome likes Real Player's one ( a DLL plugin ).. My question is : "Is it possible to use NPAPI functions such as NPP_NewStream, NPP_StreamAsFile, NPP_DestroyStream... to catch the media stream URL of flash-player ? " If not, then what part of NPAPI do I have to use ?
Using the NPAPI you can't magically spy on other components in the browser, the stream functions are for dealing with streams for your own plugin instance. If the Flash player gives you access to the URL using scripting functions however, you can use the scripting extensions to get it similar to how you'd retrieve it using JavaScript.
2,980,917
2,981,185
C++ - Is it possible to implement memory leak testing in a unit test?
I'm trying to implement unit testing for my code and I'm having a hard time doing it. Ideally I would like to test some classes not only for good functionality but also for proper memory allocation/deallocation. I wonder if this check can be done using a unit testing framework. I am using Visual Assert btw. I would love to see some sample code , if possible !
You can use the debug functionality right into dev studio to perform leak checking - as long as your unit tests' run using the debug c-runtime. A simple example would look something like this: #include <crtdbg.h> struct CrtCheckMemory { _CrtMemState state1; _CrtMemState state2; _CrtMemState state3; CrtCheckMemory() { _CrtMemCheckpoint(&state1); } ~CrtCheckMemory() { _CrtMemCheckpoint(&state2); // using google test you can just do this. EXPECT_EQ(0,_CrtMemDifference( &state3, &state1, &state2)); // else just do this to dump the leaked blocks to stdout. if( _CrtMemDifference( &state3, &state1, &state2) ) _CrtMemDumpStatistics( &state3 ); } }; And to use it in a unit test: UNIT_TEST(blah) { CrtCheckMemory check; // TODO: add the unit test here } Some unit test frameworks make their own allocations - Google's for example allocates blocks when a unit test fails, so any test block that has a fail for any other reason always also has a false positive "leak".
2,980,920
2,982,227
Strict pointer aliasing: any solution for a specific problem?
I have a problem caused by breaking strict pointer aliasing rule. I have a type T that comes from a template and some integral type Int of the same size (as with sizeof). My code essentially does the following: T x = some_other_t; if (*reinterpret_cast <Int*> (&x) == 0) ... Because T is some arbitary (other than the size restriction) type that could have a constructor, I cannot make a union of T and Int. (This is allowed only in C++0x only and isn't even supported by GCC yet). Is there any way I could rewrite the above pseudocode to preserve functionality and avoid breaking strict aliasing rule? Note that this is a template, I cannot control T or value of some_other_t; the assignment and subsequent comparison do happen inside the templated code. (For the record, the above code started breaking on GCC 4.5 if T contains any bit fields.)
static inline int is_T_0(const T *ob) { int p; memcpy(&p, ob, sizeof(int)); return p == 0; } void myfunc(void) { T x = some_other_t; if (is_T_0(&x)) ... On my system, GCC optimizes away both is_T_0() and memcpy(), resulting in just a few assembly instructions in myfunc().
2,981,247
2,981,261
C++, Qt - How do I get rid of dll dependencies?
I have compiled my Qt application and now have the following question - now my built project requires QtCore4.dll and QtGui4.dll to be located at the same folder where the .exe file is. (I built my project using MSVS2008 with Qt addon) Q: Is there any way to combine my final application with these .dll files so that they make one large .exe-file? (I simply don't want to have another bunch of dll files with my release - app) Thank you.
You need to build and link to Qt statically. Edit: Here's an updated link to at least similar information.
2,981,303
2,981,328
Generate set/get methods for a c++ class
Is there any tool that generates set and get methods for a class automatically. Just I create classes very frequently and would like to have a tool which for each class-member wil generate the following functions automatically: Member_Type getMemberName() const; //in header file Member_Type getMemberName() const //in source file { return member; } void setMemberName(const Member_Type & val); //in header void setMemberName(const Member_Type & val) //in source file { member = val; } I have met a macro like this but did not like the idea: #define GETSETVAR(type, name) \ private: \ type name; \ public: \ const type& get##name##() const { return name; } \ void set##name##(const type& newval) { name = newval; } May be someone knows how to do that with MS Visual Studio, or eny other tool?
Not the tool actually, but you could use Encapsulate Method in Visual Assist X, for example, which makes getter / setter methods for some private class member. Sure, many of tools that work similiar as VAX do have the same methods. Also, if you have to do this action for a huge amount of classes, you could implement your own command-line tool and lauch it for every source file that you have.
2,981,349
2,981,363
C++: Question about freeing memory
On Learn C++, they wrote this to free memory: int *pnValue = new int; // dynamically allocate an integer *pnValue = 7; // assign 7 to this integer delete pnValue; pnValue = 0; My question is: "Is the last statement needed to free the memory correctly, completly?" I thought that the pointer *pnValue was still on the stack and new doesn't make any sense to the pointer. And if it is on the stack it will be cleaned up when the application leaves the scope (where the pointer is declared in), isn't it?
Setting a pointer to NULL (or zero) after deleting it is not necessary. However it is good practice. For one thing, you won't be able to access some random data if you later dereference the pointer. Additionally, you'll often find code with the following: if(ptr) { delete ptr; ptr = NULL; } So setting the pointer to NULL will ensure it won't be deleted twice. Finally, you might find code like this: void foo(bar *ptr) { if(!ptr) throw Exception(); // or return, or do some other error checking // ... } And you'd probably want that safety check to be hit.
2,981,386
2,981,400
#define usage in C/C++
I need to write such a define in C/C++ #define scanf( fscanf(inf, in order to replace each scanf( with fscanf(inf, literary But I do not know how... Thanks
You want to use a Variadic macro. In your case, I believe you want: #define scanf(...) fscanf(inf,__VA_ARGS__)
2,981,569
2,981,638
boost::function & boost::lambda - call site invocation & accessing _1 and _2 as the type
Sorry for the confusing title. Let me explain via code: #include <string> #include <boost\function.hpp> #include <boost\lambda\lambda.hpp> #include <iostream> int main() { using namespace boost::lambda; boost::function<std::string(std::string, std::string)> f = _1.append(_2); std::string s = f("Hello", "There"); std::cout << s; return 0; } I'm trying to use function to create a function that uses the labda expressions to create a new return value, and invoke that function at the call site, s = f("Hello", "There"); When I compile this, I get: 1>------ Build started: Project: hacks, Configuration: Debug x64 ------ 1>Compiling... 1>main.cpp 1>.\main.cpp(11) : error C2039: 'append' : is not a member of 'boost::lambda::lambda_functor<T>' 1> with 1> [ 1> T=boost::lambda::placeholder<1> 1> ] Using MSVC 9. My fundamental understanding of function and lambdas may be lacking. The tutorials and docs did not help so far this morning. How do I do what I'm trying to do?
You need: boost::function<std::string(std::string, std::string)> f = boost::bind(&std::string::append, _1, _2);
2,981,593
2,981,600
Does the following indicate a bad design?
I was wondering whether you think the following code usually indicates a bad design ... class X { public: ... private: Y y; }; Class Y { public: Y( X& value ){ x = value; }; private: X& x; } (i.e. there is some sort of cyclic dependency between the classes X and Y).
No, I don't think it is bad design. It looks like a parent-child relationship (which is 1-to-1) where the child has a pointer back to the parent. The main reason for such a design is if someone could get a reference to Y without coming through X. If all access to Y are done only through X, such a reference is more questionable. As Billy ONeal points out, one example could be an iterator that needs to be able to reference the collection it belongs to. This could make it possible to have an iterator into an array that doesn't need to be invalidated when the array is resized, as it would check the array's current buffer address and current size on each access. Another example could be an OrderLine class (your X) which holds a reference to the item and a quantity count etc. It also has an optional member of type DigitalLicense (your Y). DigitalLicense contains a large encrypted description of the license, so it's only included in those OrderLines that corresponds to a product with a digital license. On construction, a reference to the DigitalLicense is also put in a separate map, keyed on the license id. It is now possible to look up a DigitalLicense based on the license id in the map. Then the back reference is used to go from the DigitalLicense to the OrderLine. If the OrderLine has a similar back reference it is possible to get back to the Order as well.
2,981,621
2,981,629
How to draw to screen in c++?
How would I draw something on the screen ? not the console window but the entire screen, preferably with the console minimised. Also, would it show up on a printscreen ? What I want to do is create something like a layer on top of the screen that only me and my aplication are aware of yet still be able to use aplications as usual. Here's an example: Let's say I want 2 yellow squares 5 by 5 pixels in size appearing in the center of the screen on top of all the other applications, unclickable and invisible to a printscreen. [Edit] I forgot to mention that I'm using Visual Studio 2010 on Windows XP.
in windows you can use the GetDC-function. just a minimalistic example: #include <Windows.h> #include <iostream> void drawRect(){ HDC screenDC = ::GetDC(0); ::Rectangle(screenDC, 200, 200, 300, 300); ::ReleaseDC(0, screenDC); } int main(void){ char c; std::cin >> c; if (c == 'd') drawRect(); std::cin >> c; return 0; } but since Windows Vista it is very slow
2,981,724
2,982,247
boost::function & boost::lambda again
Follow-up to post: Using * Width & Precision Specifiers With boost::format I'm trying to use boost::function to create a function that uses lambdas to format a string with boost::format. Ultimately what I'm trying to achieve is using width & precision specifiers for strings with format. boost::format does not support the use of the * width & precision specifiers, as indicated in the docs: Width or precision set to asterisk (*) are used by printf to read this field from an argument. e.g. printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec); This class does not support this mechanism for now. so such precision or width fields are quietly ignored by the parsing. so I'm trying to find other ways to accomplish the same goal. Here is what I have so far, which isn't working: #include <string> #include <boost\function.hpp> #include <boost\lambda\lambda.hpp> #include <iostream> #include <boost\format.hpp> #include <iomanip> #include <boost\bind.hpp> int main() { using namespace boost::lambda; using namespace std; boost::function<std::string(int, std::string)> f = (boost::format("%s") % boost::io::group(setw(_1*2), setprecision(_2*2), _3)).str(); std::string s = (boost::format("%s") % f(15, "Hello")).str(); return 0; } This generates many compiler errors: 1>------ Build started: Project: hacks, Configuration: Debug x64 ------ 1>Compiling... 1>main.cpp 1>.\main.cpp(15) : error C2872: '_1' : ambiguous symbol 1> could be 'D:\Program Files (x86)\boost\boost_1_42\boost/lambda/core.hpp(69) : boost::lambda::placeholder1_type &boost::lambda::`anonymous-namespace'::_1' 1> or 'D:\Program Files (x86)\boost\boost_1_42\boost/bind/placeholders.hpp(43) : boost::arg<I> `anonymous-namespace'::_1' 1> with 1> [ 1> I=1 1> ] 1>.\main.cpp(15) : error C2664: 'std::setw' : cannot convert parameter 1 from 'boost::lambda::placeholder1_type' to 'std::streamsize' 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 1>.\main.cpp(15) : error C2872: '_2' : ambiguous symbol 1> could be 'D:\Program Files (x86)\boost\boost_1_42\boost/lambda/core.hpp(70) : boost::lambda::placeholder2_type &boost::lambda::`anonymous-namespace'::_2' 1> or 'D:\Program Files (x86)\boost\boost_1_42\boost/bind/placeholders.hpp(44) : boost::arg<I> `anonymous-namespace'::_2' 1> with 1> [ 1> I=2 1> ] 1>.\main.cpp(15) : error C2664: 'std::setprecision' : cannot convert parameter 1 from 'boost::lambda::placeholder2_type' to 'std::streamsize' 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 1>.\main.cpp(15) : error C2872: '_3' : ambiguous symbol 1> could be 'D:\Program Files (x86)\boost\boost_1_42\boost/lambda/core.hpp(71) : boost::lambda::placeholder3_type &boost::lambda::`anonymous-namespace'::_3' 1> or 'D:\Program Files (x86)\boost\boost_1_42\boost/bind/placeholders.hpp(45) : boost::arg<I> `anonymous-namespace'::_3' 1> with 1> [ 1> I=3 1> ] 1>.\main.cpp(15) : error C2660: 'boost::io::group' : function does not take 3 arguments 1>.\main.cpp(15) : error C2228: left of '.str' must have class/struct/union 1>Build log was saved at "file://c:\Users\john\Documents\Visual Studio 2005\Projects\hacks\x64\Debug\BuildLog.htm" 1>hacks - 7 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== My fundamental understanding of boost's lambdas and functions is probably lacking. How can I get this to work?
I think that, for this case, you would want to use boost.bind instead of boost.lambda. Part of the problem is that boost::io::group is a function template that takes and returns a variable number of objects, making it difficult to create the appropriate signature for the function<> declaration. I would create a string formatting function with a simple signature and then use boost.bind to create a specific formatting functor from that. i.e. #include <string> #include <iomanip> #include <boost/function.hpp> #include <boost/format.hpp> #include <boost/bind.hpp> using namespace boost; using namespace std; string fmt_str(const string& s, int w, int p) { return (format("%s") % io::group(setw(w), setprecision(p), s)).str(); } int main() { function<string (int, string)> f = bind(fmt_str, _2, _1, _1); string s = f(15, "Hello"); return 0; }
2,981,827
2,981,867
Strict pointer aliasing: is access through a 'volatile' pointer/reference a solution?
On the heels of a specific problem, a self-answer and comments to it, I'd like to understand if it is a proper solution, workaround/hack or just plain wrong. Specifically, I rewrote code: T x = ...; if (*reinterpret_cast <int*> (&x) == 0) ... As: T x = ...; if (*reinterpret_cast <volatile int*> (&x) == 0) ... with a volatile qualifier to the pointer. Let's just assume that treating T as int in my situation makes sense. Does this accessing through a volatile reference solve pointer aliasing problem? For a reference, from specification: [ Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. See 1.9 for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. — end note ] EDIT: The above code did solve my problem at least on GCC 4.5.
Volatile can't help you avoid undefined behaviour here. So, if it works for you with GCC it's luck. Let's assume T is a POD. Then, the proper way to do this is T x = …; int i; memcpy(&i,&x,sizeof i); if (i==0) … There! No strict aliasing problem and no memory alignment problem. GCC even handles memcpy as an intrinsic function (no function call is inserted in this case).
2,981,911
2,982,051
Drawing N-width lines?
Given a series of points, how could I calculate the vector for that line 5 pixels away? Ex: Given: \ \ \ How could I find the vector for \ \ \ \ \ \ The ones on the right. I'm trying to figure out how programs like Flash can make thick outlines. Thanks
A thick line is a polygon. (Let's forget about antialiasing for now) picture http://img39.imageshack.us/img39/863/linezi.png start = line start = vector(x1, y1) end = line end = vector(x2, y2) dir = line direction = end - start = vector(x2-x1, y2-y1) ndir = normalized direction = dir*1.0/length(dir) perp = perpendicular to direction = vector(dir.x, -dir.y) nperp = normalized perpendicular = perp*1.0/length(perp) perpoffset = nperp*w*0.5 diroffset = ndir*w*0.5 (You can easily remove one normalization and calculate one of the offsets by taking perpendicular from the other) p0, p1, p2, p3 = polygon points: p0 = start + perpoffset - diroffset p1 = start - perpoffset - diroffset p2 = end + perpoffset + diroffset p3 = end - perpoffset + diroffset P.S. You're the last person I ever going to explain this stuff to. Things like these should be understood on intuitive level.
2,981,928
2,981,961
How do I get the size of the boost buffer
I am trying to make an asynchronised server in visual studio and I use boost::asio::async_read(m_socket, boost::asio::buffer(m_buffer), boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error)); to get the buffer to be put in m_buffer boost::array<char, 256> m_buffer; but how do I get the size of this thing, m_buffer? size() didn't work, end() didn't work.. Any help would be fantastic. Thanks in advance.
boost::array has a constant size. If you want to print it as a null-terminated string, use .data() to get a const char*. If you just want to find the position of the \0, use std::find. int size = find(array.begin(), array.end(), '\0') - array.begin();
2,982,158
2,982,165
c++ function overloading, making fwrite/fread act like PHP versions
I'm used to the PHP fwrite/fread parameter orders, and i want to make them the same in C++ too. I want it to work with char and string types, and also any data type i put in it (only if length is defined). I am total noob on c++, this is what i made so far: Edit: fixed the std::string &buf size_t fwrite(FILE *fp, const std::string &buf, const size_t len = SIZE_MAX){ if(len == SIZE_MAX){ return fwrite(buf.c_str(), 1, buf.length(), fp); }else{ return fwrite(buf.c_str(), 1, len, fp); } } size_t fwrite(FILE *fp, const void *buf, const size_t len = SIZE_MAX){ if(len == SIZE_MAX){ return fwrite((const char *)buf, 1, strlen((const char *)buf), fp); }else{ return fwrite(buf, 1, len, fp); } } Should this work just fine? And how should this be done if i wanted to do it the absolutely best possible way?
If you want to write to a file in the best possible way, you should use std::iostreams. Dealing with the length of the buffer manually is a recipe for problems. Also, the top overload should take a const std::string&, not const std::string. However, I don't see any actual bugs.