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 |
|---|---|---|---|---|
3,578,083 | 3,578,247 | What is the best way to use a HashMap in C++? | I know that STL has a HashMap API, but I cannot find any good and thorough documentation with good examples regarding this.
Any good examples will be appreciated.
| The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. ... |
3,578,173 | 3,578,204 | C++ Singleton design question | I have a requirement to have a only a single instance of a class at any given point of time. Singleton is the obvious candidate.
But I have some other conditions that are not typical of a Singleton.
The lifetime of the singleton is not the lifetime of the program. This object has to be created every time I enter a par... | If you create an instance every time you enter a given state and destroy it every time you leave that state, it would make more sense to have the instance be owned by whatever is managing state transitions (or some other entity that is aware of the state transitions).
For example, you could have a smart pointer to an... |
3,578,444 | 3,578,496 | Passing type of template function to template class used within it? | I am trying to build a template function. Inside templated classes are used and I would like to pass the template type of the function to those classes. So I have:
template <class T>
T find_bottleneck (ListGraph &g, CrossRefMap<ListGraph, Edge, T> &weight, Node &s, Node &t) {
// Check if theres a single edge left... | It's just a missing typename.
typename CrossRefMap<ListGraph, Edge, T>::ValueIt
typename is the answer to at least 50% of all C++-template-related questions :-) It tells the compiler that what follows is always a type, regardless of the template parameters (ValueIt could for example be a int instead of a typedef for a... |
3,578,594 | 3,579,306 | Help with Pointer Arithmetic | I've been studying C++ for a test and I am currently stuck with pointer arithmetic.
The basic problem is the following:
int numColumns = 3;
int numRows = 4;
int a[numRows][numColumns];
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
a[2][0] = 7;
a[2][1] = 8;
a[2][2] = 9;
a[3][0] = 10;... | int array[3][5] is NOT an abstraction (in the C++ language) for int array[3*5]. The standard says that a 2 dimensional array (and N-dimensional arrays in general) are arrays of arrays. That array[3][5] is an array of three elements, where each element is an array containing 5 elements (integers in this case). C++'s ... |
3,578,728 | 3,578,753 | file rewriting with boost? | I would like to avoid using CreateFileMapping/MapViewOfFile to rewrite part of a file. Does boost provide this functionality?
| Memory-Mapped Files
|
3,579,061 | 3,601,762 | How can I create a odbc layer on top of existing business data? | I want to expose our internal bussiness data through odbc driver. One of the propitary product that i found is DataDirect OpenAccess. I want to use SQL to query live data from our data source. Writing my own SQLEngine will take ages but i need something like following diagram. We intend to use it on live data so export... | Given the requirements you describe, I don't see any choice but for you to develop an odbc driver that knows how to talk to your lisp engine. This will be a non-trivial task.
However, since you mention open source, you may be able to get a running start by looking at one of the the open source odbc drivers such as i... |
3,579,122 | 3,579,149 | What to pass to this function? | I have the following problem:
//A.h
class A
{
//...
// this is the important part, i have to call this in the proper way
// in A::SetNewValue(), but i don't know how to do that
protected:
void SetValue(const int* i);
//...
public:
// ??
void SetNewValue(const int* p);
}
the cpp:
//A.cpp
//??
... | SetValue takes a pointer just like SetNewValue so you can pass the pointer value straight through:
void A::SetNewValue(const int* p)
{
SetValue(p);
}
I also fixed the missing void return type in your function definition.
You should be able to call it with a pointer to int or const int because you can always ad... |
3,579,156 | 3,579,180 | How do I use a C++ library from C# and .NET? | My question is closely related to how a DLL exports C++ classes and generic methods (wrt C++ language features without a C# parallel).
I believe you can call functions inside an extern "C" block from C# by just referencing the DLL and using DLLImport. But can you instantiate a templated C++ type? What if the C++ typ... | The sane way to do it is to use managed c++ to access unmanaged c++ and compile into an assembly.
|
3,579,189 | 3,579,243 | How to find the error of G++ optimize C++ code? | Today, I encounter a strange problem. My c++ code can work under debug mode.
using g++ -g to compile the code. However, when I use g++ -O to optimize the code. It will stuck somewhere. It seems there is dead looping. Does anybody know how to find this kind of error? When I debug the code with DDD debuger, it works fi... | Why is it that at the beginning of the loop you typecasted the solSize to int int solSize=int(curSol_.size()); but didn't do that in the while loop solSize=curSol_.size();. You might want to investigate the values in the debug and the optimized version.
Also, there seem to be places in the code where there are floats ... |
3,579,361 | 3,579,404 | How does sizeof know the size of the operand array? | This may be a stupid question but how does the sizeof operator know the size of an array operand when you don't pass in the amount of elements in the array. I know it doesn't return the total elements in the array but the size in bytes, but to get that it still has to know when the array ends. Just curious as to how ... | sizeof is interpreted at compile time, and the compiler knows how the array was declared (and thus how much space it takes up). Calling sizeof on a dynamically-allocated array will likely not do what you want, because (as you mention) the end point of the array is not specified.
|
3,579,408 | 3,579,438 | import C# form into c++ | Is there a way to import a C# windows form and user control into C++.NET? I'm using VS2008 and have VS2010 installed as well.
| If you have a .NET assembly or control in an assembly it doesn't matter wheter you code and use it from managed C++, C# or VB.NET or any other .NET language, that's one of the reasons why .NET was invented: be language independent.
To use it: simply reference the .NET assembly in the new project.
|
3,579,557 | 3,579,684 | counting characters (again!) | Suppose I would like to count characters in some mFile like this:
while((c = getc(mFile)) != EOF){
chars[c]++;
}
If I try to show them:
for(int f=0;f<256;f++) {
if(isprint(f) && chars[f]>0)
cout << (char)f << " " << (int)chars[f] << endl;
}
All characters print fine. But if I do
cout << "... | Based on your answer to my comment, I'd say the problem is likely to be that char is signed on your platform, and you have more than 127 spaces in your input file, so chars[32] is wrapping and becoming negative.
Why not use a more appropriately-sized type for your counters?
|
3,579,604 | 3,579,637 | C++: Using and returning character arrays from functions, return type or reference? | C++: Using and returning character arrays from functions, return type or reference?
I'm trying to create a null terminated string outside of a function, then run a function which will assign some data to it. For example, char abc [80] is created in main. input() is then run, which will return user input to abc. I fi... | Just use standard strings. The insanity of using arrays of constant width has caused at least the company I work four many hundreds of thousands of dollars in development time. The correct answer to you question may be frustrating to you but it really is, "DON'T DO THAT!!!"
|
3,579,656 | 3,580,031 | Question about unions and heap allocated memory | I was trying to use a union to so I could update the fields in one thread and then read allfields in another thread. In the actual system, I have mutexes to make sure everything is safe. The problem is with fieldB, before I had to change it fieldB was declared like field A and C. However, due to a third party driver, f... | I don't think you can declare fieldB as a pointer and get the desired behavior (assuming I am understanding the question correctly). For the union to make sense as you are using it, you need to declare it as an array in the union.
I was kind of curious if it would be possible to overload the new operator for the class... |
3,579,732 | 3,631,749 | Process Memory Map (Linux Windows) | Can someone please point me to some documentation on the virtual memory maps used for Linux and Windows. By that I mean what virtual addresses, code, writable static data, the stack and the heap (along with other kernel bits) will normally be placed in, in a typical process?
| Probably the best way to get the process memory map on Linux is to look at the /proc//maps file. One can clearly see that for each executable or shared object there are separate sections for executable, const static data, and writable static data. Each one of these sections exists in its own memory page which allows Li... |
3,579,765 | 3,688,941 | How to properly hide methods and properties from intellisense | Would anyone know how to properly hide classes, methods and properties from intellisense while preserving the ability to call them; and so they do not appear in interop assemblies that are generated from a type library?
I'm writing API hooks for automated testing we don't want exposed to consumers yet. This appears to ... | It appears Visual Studio 2008 and 2010 now ignore the 'hidden' attribute, making otherwise hidden interfaces browseable.
It appears the interop assembly must be modified by adorning the following over classes, methods and properties that are intended to exist but not be browseable:
[System.ComponentModel.EditorBrowsabl... |
3,579,796 | 3,579,818 | find nearest location from original point | Suppose we have the following problem - we want to read a set of (x, y) coordinates and a name, then sort them in order, by increasing the distance from the origin (0, 0). Here is an algorithm which use simplest bubble sort:
#include<iostream>
#include <algorithm>
using namespace std;
struct point{
... | The STL sort function std::sort can take a user-defined comparison function (or function object) as an optional third argument. So if you have your items in e.g.:
vector<point> points;
You can sort them by calling:
sort(points.begin(), points.end(), my_comp);
where my_comp() is a function with the following prototyp... |
3,579,941 | 3,581,390 | Handling ATL/ActiveX events from within JavaScript | I have an ATL ActiveX control that raises three events (Connected, Authenticated, Disconnected) which need to be handled in IE/JavaScript. So far as I can tell, I'm doing everything right, specifically:
(1) I've told ATL to implement the IProviderClassInfo2 interface, as described here.
(2) I've implemented connection... | I figured it out by looking at the Circ sample project that comes with VS2010. Turns out that (at least in my case) the ATL event wizard didn't update the IDL for the dispatch interface. Life was good once I updated the dispinterface section of the IDL file from this:
dispinterface _IMyControlEvents
{
properties:... |
3,580,328 | 3,580,364 | What is the best way to create a HashMap of String to Vector of Strings in C++? | Criteria, don't want creating copies of objects all over the place.
Should be fast, memory efficient and should not create leaks.
Should be threadsafe.
Ideally I would want to store pointers to vectors in the HashMap, but I am worried about memory leaks that way.
Is this the best way?
std::map<std::string, std::auto_pt... | You're prohibited from storing an auto_ptr in any standard container. §23.1/3: "The type of objects stored in these components must meet the requirements of CopyConstructible
types (20.1.3), and the additional requirements of Assignable types." std::auto_ptr doesn't meet that requirement.
|
3,580,389 | 3,580,429 | C++ / C# differences with float and double | We are converting a C++ math library to C#. The library mixes the use of floats and doubles (casting between them sometimes) and we are trying to do the same, in order to get the exact same results in C# that we had in C++ but it is proving to be very difficult if not impossible.
I think the problem is one or more of t... | C++ allows the program to retain a higher precision for temporary results than the type of the subexpressions would imply. One thing that can happen is that intermediate expressions (or an unspecified subset of them) are computed as extended 80-bit floats.
I would be surprised on the other hand if this applied to C#, b... |
3,580,407 | 3,580,472 | Add to part of image in OpenGL instead of full redraw? | I have a simulation that uses OpenGL for drawing. While it is running, I would like to plot some things on top of my simulation in real time, but every iteration I only want to add few lines to that graph, instead of always re-drawing it from scratch (that would be too costly).
How could I create some surface to which ... |
How could I create some surface to which I can always add, that does not get erased, and how could I overlay it on top of my simulation?
Render to texture using any technique. Then blit the texture on screen. If you don't want it to get erased, don't erase it.
See "Simple Framebuffer Object" demo from NVidia for more... |
3,580,457 | 3,580,462 | STL name for the "map" functional programming function | I would like to be able to write something like
char f(char);
vector<char> bar;
vector<char> foo = map(f, bar);
The transform function appears to be similar, but it will not autogenerate the size of the resultant collection.
| You can use std::back_inserter in <iterator>, although providing the size in front is more efficient. For example:
string str = "hello world!", result;
transform(str.begin(), str.end(), back_inserter(result), ::toupper);
// result == "HELLO WORLD!"
|
3,580,525 | 3,581,320 | Which of these is faster? | I was wondering if it was faster to render a single quad the size of the window with a texture the size of a window than to draw the bitmap directly to the window using double buffering coupled with the platform specific way of drawing to a window.
| The initial setup for textures tends to be relatively slow, but once that's done the drawing is quite fast -- in a typical case where graphics memory is available, it'll upload the texture to the memory on the graphics cards during initial setup, and after that, all the drawing will happen from there. At the same time,... |
3,580,621 | 3,580,724 | creating input stream manipulator | As an exercise, I'm trying to create a input stream manipulator that will suck up characters and put them in a string until it encounters a specific character or until it reaches eof. The idea came from Bruce Eckel's 'Thinking in c++' page 249.
Here's the code I have so far:
#include <string>
#include <iostream>
#incl... | This line:
SIU.S->append(&N);
appends the character as a char *. The append function is expecting a null terminated string, so it keeps reading from &N, (&N)+1... until it sees a zero byte.
You can either make up a small null terminated char array and pass that in, or you can use the an alternate append function that ... |
3,580,714 | 3,580,999 | assignin sockaddr to another changes the addr? | While trying the following the address in the second sockaddr changes:
/*Stuff*/
sockaddr add1, add2;
recvfrom(/*socket*/, /*buffer*/, /*count*/, /*flag*/, &add1, /*fromlen*/);
add2 = add1; //The sa_data - part changes O_o...
/*Stuff*/
Anyone knows why?...
EDIT: 1.I changed the sockaddr to sockaddr_storage which de... | How is fromlen being set when you call recvfrom()? If fromlen > sizeof(add1), you are possibly writing over add2 by accident.
Beej's Guide suggests that you use local variables of type struct sockaddr_storage, which is guaranteed to be big enough to hold any of the struct sockaddr_foos in use.
|
3,580,789 | 3,580,876 | WCHAR wszFoo[CONSTANT_BAR] = {0}; <-- What does {0} mean? | WCHAR wszFoo[CONSTANT_BAR] = {0};
I've never seen something like {0} used in C++ as part of the language. And I have no idea how to search for a question like this online. What is it?
| $8.5.1/7 -
"If there are fewer initializers in
the list than there are members in the
aggregate, then each member not
explicitly initialized shall be
value-initialized (8.5)."
All this means, is that there is an explict request to initialize first element to 0. Since initializers are not specified for the re... |
3,580,955 | 3,580,971 | Filling an array passed as a parameter with objects | I have a function similar to this:
void foo(obj ary[], int arysize) {
for (int i = 0; i < arysize; i++)
ary[i] = obj(i, "abc");
}
And I call it like this:
obj array[5];
foo(array, 5);
It's supposed to populate the array with my objects. However, when it returns, the objects are garbage. It works with val... | That should work fine. I'd look into the assignment operator for your class.
|
3,581,194 | 3,581,255 | Project ideas to become good at C++ | I want to get into C++ team at work. Their job is to write CGIs in C++ (mainly but not limited to). I know basic C++. Reading the list at C++ book guide question on SO, I've got three books from a friend (I actually had the first one).
The C++ Programming Language - Bjarne Stroustrup - for reference
C++ Templates The ... | Let me add to your list of reading material; the C++ FAQ Lite is absolutely the best resource for learning the ins and outs of C++. It is useful both as a reference for old timers and as an introduction to beginners. I would strongly recommend reading as much of it as you possibly can, and try small examples that demon... |
3,581,450 | 4,328,029 | Is doxygen the (de facto) standard documentation syntax specification? | We all have the good habit of documenting our code, right?
Nowadays, in-code documentation itself has a syntax. It's almost like a programming language onto itself. The questions are:
What (How many) documentation syntax specifications exist?
Is there a standard documentation syntax?
Who is defining this standar... |
What (How many) documentation syntax specifications exist?
Almost every medium software development organization seems to have their own. Often they are included under the umbrella of "coding style guidelines".
Is there a standard documentation syntax?
There are a few standards that I am aware of which have some ... |
3,581,586 | 3,581,628 | modifying small part of an existing file | I looked at boost's mapped_file, and CreateFileMapping/MapViewOfFile, but they seem overly complicated to use.
Anything simpler I can use to overwrite a few bytes here and there in an existing file? Performance is not a very high consideration.
| You can use the standard C library directly. fopen then fseek to where you want to write stuff. Or, if you want to be fancy, you can also try mmap.
|
3,581,619 | 3,582,260 | How to achieve pushbutton type effect using bitmaps | Hello there I have a issue related to the usage of the bitmap enabled Dialog window.I have created a keyboard type layout and i wish to get the input through keyboard also.When i use the mouse I am able to get the button(s) pressed and also all the buttons are working fine - the other images DEFAULT,SELECTED,DISABLED .... | As far as I understand, you have a series of buttons that simulate a computer keyboard layout. whenever the user presses a key on the keyboard, you need to simulate a button click in your dialog box. You have provided bitmaps for each state of each button.
To do this, I would process the WM_KEYDOWN and WM_KEYUP message... |
3,581,902 | 3,581,919 | Why does this code compile? | Last night, being too tired, I wrote this strange line:
::TerminateThread(::TerminateThread, 0);
To my surprise, the compiler does not complain (It even run...)
Since TerminateThread() is defined as
BOOL WINAPI TerminateThread(HANDLE hThread, DWORD dwExitCode);
I'm no sure why I am able to compile it.
Any explanation... | HANDLE is a pointer to void, and Microsoft's compiler allows implicitly converting a function pointer to a pointer to void.
This tripped me up many times, especially with the heap functions:
HeapAlloc (GetProcessHeap, 0, size); // oops, should be GetProcessHeap()
|
3,581,931 | 3,587,837 | Trying to compile libdwarf, gives undefined errors | I'm trying to build the libdwarf api under windows but I'm receiving the following compile errors.
in dwarf_elf_access.c
undefined type Elf32_Ehdr,
undefined symbol EI_CLASS
undefined symbol ELFCLASS64
undefined symbol ELFDATA2LSB
...
I did a search through all the header files and source files and I couldn't find the... | It seems you need to link the libelf library too (the dwarf library uses it).
|
3,581,981 | 3,582,101 | Overloading the C++ indexing subscript operator [] in a manner that allows for responses to updates | Consider the task of writing an indexable class which automatically synchronizes its state with some external data-store (e.g. a file). In order to do this the class would need to be made aware of changes to the indexed value which might occur. Unfortunately the usual approach to overloading operator[] does not allow f... | From the operator[] you can only really tell access.
Even if the external entity uses the non cost version this does not mean that a write will take place rather that it could take place.
As such What you need to do is return an object that can detect modification.
The best way to do this is to wrap the object with a ... |
3,582,039 | 3,582,163 | Parse and remove part of a QString | I want to parse some kind (or pure) XML code from a QString.
My QString is like:
<a>cat</a>My cat is very nice.
I want to obtain 2 strings:
cat, and My Cat is very nice.
I think a XML parser is not maybe necessary, but in the future I will have more tags in the same string so it's also a very interesting point.
| In Qt you have the QRegExp class that can help you to parse your QString.
According to Documentation example:
QRegExp rxlen("^<a>(.*)</a>(.*)$");
int pos = rxlen.indexIn("<a>cat</a>My cat is very nice.");
QStringList list
if (pos > -1) {
list << = rxlen.cap(1); // "cat"
list << = rxlen.cap(2); // "My cat ... |
3,582,386 | 3,582,460 | How to use Model for QCombobox | I want to use QCombobox as a the Combobox of Swing in Java. So i need to use Model for holding my object. How can i hold my object in QCombobox. (I think that I should hold data in Model because QCombobox was designed according to MVC Pattern ... )
Any help will be appreciated.
| Depending on what you want to display with your QComboBox, you'll need to write your own model, inheriting QAbstractListModel, reimplementing rowCount()and data().
Then, use QComboBox::setModel() to make the QComboBox display it.
If you just want to display strings, you can use a QStringListModel, provided with Qt.
|
3,582,457 | 3,582,483 | Unable to watch variable values in Visual studio with compiler optimization set to Maximize speed(/O2) | I am using working on a c++ application in Visual studio 2008
I have built my project with Maximize speed(/o2) (From Properties -> configuration properties -> c/c++ -> optimization -> optimization)
Unable to watch the variable values while debugging the code. Pls help.
| This is normal. Once you activate optimizations, the compiler pretty much ignores all your variable requests and tries to do what it thinks is best.
There's a reason why the debug builds have no optimizations enabled :)
Edit: You might have some luck with enabling or disabling optimizations for specific bits of code. ... |
3,582,479 | 3,583,359 | How to remove 'ImageList_Read' : inconsistent dll linkage warning? | When I build my Visual C++ Solution ( 2005), I get the following warnings
1> c:\winddk\7000.0.winmain_win7beta.081212-1400\inc\api\commctrl.h(678) : see previous definition of 'ImageList_Read'
1>e:\xml parse\development\gui\h\wtl4mfc.h(6) : warning C4273: 'ImageList_Write' : inconsistent dll linkage
1> c:... | That warning comes from having two declarations that have different __declspec. I expect WINCOMMCTRLAPI hides a __declspec attribute.
To fix it, first check that you need to get both of those declarations included - perhaps different source files are picking up different include paths erroneously? Or directly includin... |
3,582,509 | 3,582,551 | Why does integer overflow cause errors with C++ iostreams? | Ok, so I have some problems with C++ iostreams that feels very odd, but it is probably defined behaviour, considering this happens with both MSVC++ and G++.
Say I have this program:
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
cout << a << endl;
cin >> a;
cout << a << endl;
... | iostreams is designed to detect errors and enter an error state. You get the same result from integer overflow as from entering a non-numeric string.
Cast cin (or any stream) to bool or check cin.rdstate() to determine if an error has occurred.
Call cin.clear() and cin.ignore() to flush out the error. It will pick up a... |
3,582,608 | 3,582,733 | How to correctly implement custom iterators and const_iterators? | I have a custom container class for which I'd like to write the iterator and const_iterator classes.
I never did this before and I failed to find an appropriate how-to. What are the guidelines regarding iterator creation, and what should I be aware of ?
I'd also like to avoid code duplication (I feel that const_iterato... |
Choose type of iterator which fits your container: input, output, forward etc.
Use base iterator classes from standard library. For example, std::iterator with random_access_iterator_tag.These base classes define all type definitions required by STL and do other work.
To avoid code duplication iterator class should be... |
3,582,624 | 3,583,138 | Registry problem - deleting key/values with C++ | The following piece of code seems to unreliably execute and after and undeterministic time it will fail with error code 234 at the RegEnumValue function.
I have not written this code, I am merely trying to debug it. I know there is an issue with doing RegEnumValue and then deleting keys in the while loop.
I am tryin... | There are some errors in your code:
The 4-th parameter of RegEnumValue (the namesize) is in-out parameter. So you have to reset namesize to sizeof(name)/sizeof(name[0]) (in case of the usage char type it is just sizeof(name)) inside the while loop before every call of RegEnumValue. It's the main error in your progra... |
3,582,635 | 3,584,922 | Port unmanaged C++ project to C# | I need to port a C/C++ unmanaged project (VS 2008) to C# (preferably .net 3.5).
Are there any conversion-helping
tools; let's say something
translating the code syntax and
asking you verifications/modifications for each
problematic point (I guess I'm dreaming...)
Where can I find some useful howtos or artic... | It will cost you far more to convert it than to wrap it and pay a freelancer (like me) to help you out by changing the C++ code for you every few months (or every few years) when you need to make a change. There are some mechanical approaches but the bigger issue is that you can never really be sure that the new C# cod... |
3,582,660 | 3,582,672 | How portable is code using wmemset()? | Currently our code uses a for-loop for filling a buffer holding a Unicode string with some Unicode character value (of type wchar_t). There's wmemset() function in Visual C++ using which we could replace a loop with a single function call in that code. However we're concerned about portability - we'd like to leave code... | It's mentioned in the C++ standard cwchar (Table 48) at least and hence should be pretty standard. So I guess it should not hurt portability
|
3,582,690 | 3,597,844 | Getting GLE=5 (Access Denied ) Error While creating Named Pipe | I have tried creating a named pipe but getting GLE 5 (access denied Error)
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include "iostream.h"
//#define PIPE_ACCESS_DUPLEX 0x00000003
//#define PIPE_ACCESS_INBOUND 0x00000001
//#define PIPE_ACCESS_OUTBOUND 0x00000002
#define BUFSIZE 512
... | Well I tried around a lot of things with my programme but was not able to find out why the creation is failed.
I was working on VC++ 6.0 . Then I started my Visual Studio 2008 and created a C++ project. Pasted the Code . Compiled. Got the error :
Error 1 fatal error C1083: Cannot open include file: 'iostream.h': No... |
3,582,869 | 3,583,242 | Searching good Debugger for C++ | i was wondering if there was a good debugger you can recommend for C++.
thanks for helping
| i recommend emacs + gdb. best combination ever.
http://www.cs.cmu.edu/~gilpin/tutorial/
|
3,582,870 | 3,582,997 | Factorizing a number | I've got a number which is less than 500,000,000 and I want to factorize it in an efficient way. What algorithm do you suggest? Note: I have a time limit of 0.01 sec!
I've just written this C++ code but it's absolutely awful!
void factorize(int x,vector<doubly> &factors)
{
for(int i=2;i<=x;i++)
{
if(x%i==0... | As you might know, factorization is a hard problem. You might also know that you only have to test divisibility with primes. A small, but well known hint: You only have to test up to the square root of n. I leave the reasoning to you.
Look at the sieve of Eratosthenes. And maybe you find a hint in these questions and a... |
3,583,026 | 3,583,123 | Implement complex number's class in C++ | Here I am trying to implement a class for complex numbers using books and the Internet. Here is the code:
#include <iostream>
#include <ostream>
using namespace std;
class Complex{
private:
float re,im;
public:
Complex(float x,float y){
re=x;
im=y;
}
fl... | #include <iostream>
// ...
Complex s(3.45,23.12);
std::cout << s;
See this answer for why I think using namespace std; is a bad idea.
Also, I suppose implementing a class for complex numbers is an exercise? Because the standard library already has one.
|
3,583,566 | 3,583,696 | How to fill std::vector with data from another vector that meets some criteria | I have a vector of points, and I need to get those which are at a distance less than a value from a given point.
I could do it with a simple loop, but is there a better way to do it?
Thanks in advance
| Use std::remove_copy_if:
#include <algorithm>
#include <vector>
#include <iostream>
#include <functional>
#include <iterator>
int main() {
std::vector<int> v;
v.push_back(3);
v.push_back(2);
v.push_back(6);
v.push_back(10);
v.push_back(5);
v.push_back(2);
std::vector<int> v2;
std::... |
3,583,746 | 4,421,722 | C++ - change the cursor in an X Window | I thought this would be easy to find, but a google search has been very unhelpful. Is there a simple api to change the mouse cursor in your X window? (I know in windows you can just call "SetCursor")
| #include <X11/cursorfont.h>
/* ... */
Cursor c;
c = XCreateFontCursor(dpy, XC_xterm);
XDefineCursor(dpy, w, c);
Where dpy is your display, w is your window and XC_xterm is a constant defining the shape of your cursor. Here's a list of available cursor shape, along with images.
|
3,583,887 | 3,584,117 | Is there a C/C++ library that allows you to find out whether a set of expressions are mutually exclusive? | I'm writing a compiler for a dataflow programming language I have designed. One of the features that I really like about it is that you can express the following:
x <- a + 1 if b > 3;
x <- a - 1 if b <= 3;
Which implies something like:
x <- a - 1 + 2*(b>3);
In order to pull this off though the compiler needs to know th... | I think you need a small set of simple rules that tell you whether two expressions are equal, or are totally different.
Let's start with the easiest ones: b>3 and b<=3
Checking whether they're equal is easy: b>3 and b>3 are equal, b>3 and b<=3 clearly aren't.
To see whether they are completely different, we would have ... |
3,584,019 | 3,584,749 | Rotate Text by 90 degrees with GDI | I want to draw text to a GDI Surface and rotate this text by 90 degrees counter clockwise. I would prefer to use DrawText to draw the text because it supports carriage return. I tried to use a font with lfEscapement (see the code below) but the line is not rotated - one line gets rendered over the other. Is there any p... | lf.lfEscapement = 90;
That should be 900 to get the text vertical, units are 0.1 degrees.
Your plan to let DrawText take care of the line breaks is going to fall flat I'm afraid. I could not convince it to align the text properly. It aligns on the last line, not the first. Some code to play with:
wchar_t* ms... |
3,584,246 | 3,584,284 | Static properties in C++ | With pseudo code like this:
class FooBar {
public:
int property;
static int m_static;
}
FooBar instance1 = new FooBar();
FooBar instance2 = new FooBar();
If I set property of instance1, it would obviously not effect the second one. However, if I set the static property instead, the change should propagate to ... | A static member is essentially a global variable bound to a class (not an instance!). Global variables are not thread-local, hence change to that variable will be reflected in all threads.
(BTW, C++98 does not have the concept of threads. In C++0x you can make it thread-local (by §9.4.2/1) with
static thread_local int ... |
3,584,385 | 3,585,613 | Friend access to protected nested class | I have the following C++ code:
class A {
protected:
struct Nested {
int x;
};
};
class B: public A {
friend class C;
};
class C {
void m1() {
B::Nested n; // or A::Nested
}
};
Compiling this snippet with g++ 4.4, it does not make a difference whether I use B::Nested or A::Nested in m1. Clang accep... | According to the Standard, GCC is correct and Clang is wrong. It says at 11.2/4
A member m is accessible when named in class N if
m as a member of N is protected, and the reference occurs in a member or friend of class N, or in a member or friend of a class P derived from N, where m as a member of P is private or pro... |
3,584,544 | 3,585,007 | Drawing sprites on D3D device | I have a hooked DirectX used in C++ code that draws text and sprite. I tested it and it drew well onto 2D application. However, when I tried it with 3D application (some complex game actually), only text was visible. From that I deduced the sprite is not being overdrawn by something else, hence the text would be too. I... | Firstly, the easiest way to render sprites to a D3D device is ID3DXSprite.
Secondly, i think there's a typo and you meant to set COLOROP to MODULATE, not ALPHAOP.
However, i think in both cases you would only end up with an invisible output if your alpha was 0. Could it be that the texture you're using is fully transpa... |
3,584,610 | 3,584,952 | Why always 6 parameters are shown for functions in a callstack generated on Solaris? | Why do the functions displayed in a callstack generated in Solaris always contain 6 parameters?
In most of the cases, the original function will not be having 6 parameters at all. Sometimes I also find, the parameter values displayed are not matching the order in function declaration.
Any pointers or links for underst... | I believe, depending on your version of Solaris (64 bit?), that the calling convention specifies the first 6 parameters of a function be passed by registers. Even if they're not being used, your debugger may just be showing the contents of these 6 registers.
Edit: from http://publib.boulder.ibm.com/httpserv/ihsdiag/get... |
3,585,002 | 3,585,045 | Learning C++, questions about environment | I am asking this here because I think my last question was more than one question so creating another question seemed appropriate. However, you can close it if it does not adhere to the SO policies.
In this comment on my last question , I was given a nice advice by Michael Aaron Safyan (at least I liked it):
Once you... | When it comes to C++ development there are two major camps: MSVC, and gcc. Porting a project between them is not always easy, so since Xcode is gcc-based as long as you stick to gcc projects (typical filenames to look for are configure and Makefile) you should not have a problem.
|
3,585,033 | 3,585,066 | Size of struct with a single element | Given
struct S {
SomeType single_element_in_the_struct;
};
Is it always true that
sizeof(struct S) == sizeof(SomeType)
Or it may be implementation dependent?
| This will usually be the case, but it's not guaranteed.
Any struct may have unnamed padding bytes at the end of the struct, but these are usually used for alignment purposes, which isn't a concern if you only have a single element.
|
3,585,069 | 3,585,104 | Weird linker error with static std::map | Why do I get linker error when I try to compile this in Visual Studio 2008
#include <stdafx.h>
#include <iostream>
#include <map>
#include <string>
class MyClass
{
public:
MyClass () { };
virtual ~MyClass() {};
static std::string niceString (std::map<int, int> mappp) { _myMap = mappp; return "nice string"; };
pri... | You've declared the static member _myMap, but not defined it. Add this line just above int main():
std::map<int, int> MyClass::_myMap;
Think of it like a function that has been declared but not defined in any .cpp file - you get a linker error if you use it.
|
3,585,144 | 3,599,028 | warning C4673: throwing 'ex::traced_error<EX>' the following types will not be considered at the catch site | MSVC 10 and MSVC 9 are both generating a level 4 warning message when compiling my exception framework, although the behavior of the program seems correct. The exception framework is rather large & complex, but I have managed to boil it down to its essence. This is a complete program you can compile & run in VS10
#i... | The issue is indirectly about the multiple virtual inheritance from std::exception. The compiler gets confused because of it, but forgets to tell you why. :-/
James McNellis is right: the compiler promises to mention a type, but it doesn't. Try without the template:
#include <stdexcept>
class Base: virtual public std:... |
3,585,174 | 3,585,231 | c++ program to watch directory for alterations | I am looking for a way to make a program in C or C++ that detects if there was any files altered, renamed, moved or deleted in a specified directory for Linux systems. Is there a way to do that?
| You want inotify (and its man page.)
|
3,585,341 | 3,585,398 | How to profile the memory consumption by a set of C++ classes? | I am trying to figure out the memory consumption by my (C++) program using gprof. The program does not have a gui, it is entirely cli based.
Now, I am new to gprof, so I read a few tutorials, that taught me how to run gprof and spot time consumption.
However, I need to find out the memory consumption by a specific set ... | Trivial.
template<typename T> class Counter {
static int count = 0;
Counter() { count++; }
Counter(const Counter&) { count++; }
Counter& operator=(const Counter&) {}
~Counter() { count--; }
};
class A : Counter<A> {
static int GetConsumedBytes() {
return sizeof(A) * count;
}
};
If t... |
3,585,486 | 3,585,580 | Confused about testing an interface implementing method in C++.. how can I test this? | Please, consider the following (I'm sorry for the amount of code; but this is the minimal example I could think of...):
class SomeDataThingy
{
};
struct IFileSystemProvider
{
virtual ~IFileSystemProvider() {}
//OS pure virtual methods
}
struct DirectFileSystemProvider
{
//Simply redirects the pure virtual... | Can you modify the constructor of SomeFilter? If so, you can inject IFileSystemProvider that way.
class SomeFilter : public IFilter
{
public:
SomeFilter(const IFileSystemProvider& fs = DirectFileSystemProvider())
: fs(fs)
{
}
private:
int Matches(const SomeDataThingy& subject) const
{
... |
3,585,517 | 3,594,869 | bi-directional communication using socketpair: hangs reading output from child process | I'm trying to use a socketpair to have a parent process provide input to a child process that execs a different program (e.g., grep) and then read the resulting output. The program hangs in the while loop that reads the output from the program that the child execs.. The child dupes stdin and stdout on to its end of the... | Your code hangs as grep's output may be less than 80 bytes and you are issuing a blocking read on sp[0]. The proper way of doing this is by marking both sockets as non-blocking and selecting() over both of them.
You also forgot to close(sp[0]) before you wait(), which will leave your child process waiting for input.
|
3,585,774 | 3,586,082 | How to pass data from a QDialog? | In Qt, what is the most elegant way to pass data from a QDialog subclass to the component that started the dialog in the cases where you need to pass down something more complex than a boolean or an integer return code?
I'm thinking emit a custom signal from the accept() slot but is there something else?
| QDialog has its own message loop and since it stops your application workflow, I usually use the following scheme:
MyQDialog dialog(this);
dialog.setFoo("blah blah blah");
if(dialog.exec() == QDialog::Accepted){
// You can access everything you need in dialog object
QString bar = dialog.getFoo();
}
|
3,586,003 | 3,596,684 | unsigned char* image to Python | I was able to generate python bindings for a camera library using SWIG and I am able to capture and save image using the library's inbuilt functions.
I am trying to obtain data from the camera into Python Image Library format, the library provides functions to return camera data as unsigned char* .
Does anyone know h... | Okay Guys, so finally after a long fight (maybe because am a newbie in python), I solved it.
I wrote a data structure that could be understood by python and converted the unsigned char* image to that structure. After writing the interface for the custom data structure, I was able to get the image into Python Image Libr... |
3,586,300 | 3,586,352 | How to create overloading functions in Visual-C++ library (.net)? | So what I want is to create 3 functions with same names but taking difrent arguments (one will take 2 and others one lats say System::String). (I will compile tham into .net library from visual-C++, create a c# project, connect my lib to it and want to be able to see in my library one function name which would have 3 o... |
ref class SampleClass
{
public:
SampleClass(){}
void Set(int value){}
void Set(String^ value){}
void Set(int value1, String^ value2){}
...
};
Build this as .NET Class library, and add reference to it in C# client project.
|
3,586,373 | 3,586,575 | Compile C++ code for AIX on Ubuntu? | Question in one sentence: How can I compile code for AIX using G++ on Ubuntu? (Assuming it is possible)
I hope that it is as simple as adding an option to the make file to specify target processor. I am a novice when it comes to most things compiler related.
Thank you in advance.
| What you are looking for is a cross-compiling toolchain.
A toolchain includes a cross-compiler (a compiler that runs on the current platform but builds the binary code to run on another, on your case, AIX), the C or C++ library, and some other interesting tools.
I have successfully used buildroot in the past, which is... |
3,586,410 | 3,589,581 | How to understand the design and code flow of any product quickly? | I have switched to a new company and I am working on a product that has a huge code base without documentation. I want to quickly get acquainted with the design and the code flow of the product so that I may become a productive member ASAP
Slowly and steadily one does gets to understand the code, but what should be the... | I'm a contract engineer, and this situation is routine several times per year—for the last few decades.
I find it quite helpful to first run the application and play with it—before looking at any code:
What the heck does it do? If necessary, read the user documentation.
What happens with extreme values?
What if I lea... |
3,586,467 | 3,586,496 | Template specialization: non-inline function definition issue | The following code compiles properly.
#include <string>
template <typename T, typename U>
class Container
{
private:
T value1;
U value2;
public:
Container(){}
void doSomething(T val1, U val2);
};
template<typename T, typename U>
void Container<typename T, typename U>::doSomething(T val1, U val2)
{
... | You are not explicitly specializing a member function. But you are defining the member function of an explicit (class template-) specialization. That's different, and you need to define it like
inline void Container<char,std::string>::doSomething(char val1, std::string val2)
{
; // Some other implementation
}
Not... |
3,586,472 | 3,586,696 | unhandlex exceptions when using new after implementing a setup project in visual studio 2010 | I have my little client application which - when started - creates some user defined objects on the heap via "new"
pHistory = new CHistory;
This was no problem and everything ran fine until yesterday.
I wanted to deploy my application and did decide to use a "Setup Project" from Visual Studio 2010. http://msdn.microso... | My newbie fix to this problem is to create a new solution and insert every file from the old one to this new one.
It works fine, now...
But I am still not sure what caused this problem... I am still believing in the cause due to the setup project... but the other answerers told me it is not the cause :/...
|
3,586,738 | 3,586,859 | WS_CLIPCHILDREN does not work when in fullscreen | I have a main window created with :
if (!fullscreen)
{
wStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN;
wExStyle = WS_EX_TOPMOST;
}
else
{
wStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN;
wExStyle = WS_EX_TOPMOST;
}
I have also a child window created runti... | WS_POPUP cannot be used with WS_CHILD. Not positive that's the cause though.
|
3,586,798 | 3,587,194 | Coin flipping game: Optimization problem | There is a rectangular grid of coins, with heads being represented by the value 1 and tails being represented by the value 0. You represent this using a 2D integer array table (between 1 to 10 rows/columns, inclusive).
In each move, you choose any single cell (R, C) in the grid (R-th row, C-th column) and flip the coin... | I think a greedy algorithm suffices, with one step per coin.
Every move flips a rectangular subset of the board. Some coins are included in more subsets than others: the coin at (0,0) upper-left is in every subset, and the coin at lower-right is in only one subset, namely the one which includes every coin.
So, choosing... |
3,586,923 | 3,586,969 | counting unicode characters in c++ | How do you count unicode characters in a UTF-8 file in C++? Perhaps if someone would be so kind to show me a "stand alone" method, or alternatively, a short example using http://icu-project.org/index.html.
EDIT: An important caveat is that I need to build counts of each character, so it's not like I'm counting the tota... | In UTF-8, a non-leading byte always has the top two bits set to 10, so just ignore all such bytes. If you don't mind extra complexity, you can do more than that (to skip ahead across non-leading bytes based on the bit pattern of a leading byte) but in reality, it's unlikely to make much difference except for short stri... |
3,587,275 | 3,587,310 | Which operator delete? | Is there a difference between:
operator delete(some_pointer);
and
delete some_pointer;
and if so what is the difference and where one should use one and where the other version of this operator?
Thanks.
| Ironically, the delete operator and operator delete() are not the same thing.
delete some_pointer; calls the destructor of the object pointed to by some_pointer, and then calls operator delete() to free the memory.
You do not normally call operator delete() directly, because if you do, the object's destructor will no... |
3,587,474 | 3,587,889 | MSXML4 and setting the encoding string | I using MSXML4 to generate a XML.
I'm trying to set the encoding value to UTF-8.
Here is my code:
const _bstr_t k_XML_Tag_Name ("xml");
const _bstr_t k_Processing_Tag_Name ("version=\"1.0\" encoding=\"utf-8\"");
MSXML2::IXMLDOMProcessingInstructionPtr pProccessingInstruction = m_pXmlDoc->createProcessingInstruction... | When you save the xml to a file you should see the <?xml version="1.0" encoding="UTF-8"?> declaration. However, according to this article, when you use the XML property of the document the declaration returned does not contain the encoding, which seems to be by design. Is this the behavior you are encountering? The art... |
3,588,154 | 3,588,205 | How usable is Qt without its preprocessing step? | I think it's unreasonable for a library to require preprocessing of my source code with a special tool. That said, several people have recommended the Qt library to me for cross platform GUI development.
How usable is Qt without the preprocessing step?
EDIT: Okay people, I'm not meaning this question as a rip on Qt -- ... | Qt doesn't require the use of moc just to use it, it requires that usage if you create a subclass of QObject, and to declare signals and slots in your custom classes.
It's not unreasonable, moc provides features that C++ doesn't have, signals/slots, introspection, etc.
So, to do something minimally advanced, you WILL h... |
3,588,372 | 3,588,396 | binary '*' : no global operator found which takes type 'statistician' (or there is no acceptable conversion) | I am trying to overload my operators its really just a class that holds arithmetic functions and a sequence of array variables.
But when i am overloading my (*) multiplication operator i get this error:
binary '*' : no global operator found which takes type 'statistician'
(or there is no acceptable conversion)
T... | Declare a namespace scope operator*, so that you can also have a convertible operand on the left hand side that is not of type statistician.
statistician operator*(const statistician &left, const statistician &right) {
// ...
}
Needless to say that you should remove the in-class one then, and you need a converting ... |
3,588,431 | 3,588,527 | C++: how do I convert a string into a float where the starting char can change? | I have this kinda of input:
x4.9
x.25
C400
What is the best way to drop the first char and convert to float?
| You can use sscanf(), eg:
#include <stdio.h>
float f;
char *str = "x4.9";
if( sscanf(str, "%*c%f", &f) == 1 )
{
// use f as needed ...
}
|
3,588,467 | 3,588,492 | How to detect a C++ identifier string? | E.g:
isValidCppIdentifier("_foo") // returns true
isValidCppIdentifier("9bar") // returns false
isValidCppIdentifier("var'") // returns false
I wrote some quick code but it fails:
my regex is "[a-zA-Z_$][a-zA-Z0-9_$]*"
and I simply do regex.IsMatch(inputString).
Thanks..
| It should work with some added anchoring:
"^[a-zA-Z_][a-zA-Z0-9_]*$"
If you really need to support ludicrous identifiers using Unicode, feel free to read one of the various versions of the standard and add all the ranges into your regexp (for example, pages 713 and 714 of http://www-d0.fnal.gov/~dladams/cxx_standard.p... |
3,588,525 | 3,588,530 | How do you understand a large chunk of code? | I am a fresh college grad student that just started my job. In my ramp up period, I need to learn a lot of product code. There are some design docs but they do not help much.
Can you provide some general techniques to browse and understand huge product code (specifically C++)?
| Run it through doxygen. This will generate html documentation which will be helpful even if the code does not have proper doxygen-style comments.
Another good advice is to look through the unit tests, if there are any. If there are no unit tests, a good way to understand the code is to write your own unit tests. The... |
3,588,526 | 3,590,126 | How to turn off beeping when pressing ENTER on a single-line EDIT control under Windows CE? | I'm developing an application targeted to a POCKET PC 2003 (Windows CE 4.2) device using C++ and native WINAPI (i.e. no MFC or the like). In it I have a single-line edit control which part of the main window (not a dialog); hence the normal behaviour of Windows when pressing ENTER is to do nothing but beep.
I've subcla... | After spewing all messages to a log file, I finally managed to figure out which message was causing the beeping - WM_CHAR with wParam set to VK_RETURN. Stopping that message from being forwarded to the edit control stopped the beeping. ^^
The final code now reads:
LRESULT CALLBACK Gui::ItemIdInputProc( HWND hwnd, UINT... |
3,588,544 | 3,588,578 | What is the problem with this piece of C++ queue implementation? | I'm trying to write a linked queue in C++, but I'm failing so far. I've created 2 files by now: my main.cpp and box.h. When trying to use my box, I receive the following message:
Description Resource Path Location Type
conversion from ‘Box*’ to
non-scalar type ‘Box’
requested main.cpp /QueueApplic... | The problem is with this line
Box<int> newBox = new Box<int>();
The new operator returns a pointer to a Box object created on the heap. The pointer will be of type Box<int>*. The left side of that expression declares a Box object. You can't directly assign a pointer-to-X to an X. You should probably just omit the new ... |
3,588,848 | 3,589,166 | Transforming verticies with center point and scale factor? | My application is a vector drawing application. It works with OpenGL. I will be modifying it to instead use the Cairo 2D graphics library. The issue is with zooming. With openGL camera and scale factor sort of work like this:
float scalediv = Current_Scene().camera.ScaleFactor / 2.0f;
float cameraX = GetCameraX();
f... | I think Cairo can do what you want ... see http://cairographics.org/matrix_transform/ . Does that solve your problem, and if not, why ?
|
3,588,858 | 3,588,865 | Why some projects choose the extension for source files .cc in c++? | Any reason for that, what is .cc for?
| C++ is the ultimate language of choice and flexibility and C++ developers like to be different. The .cc extension is just one of the many that people choose for header and source files. Some others I've seen.
No extension: Popular with header files
.h
.hpp
.cpp
.cc
.c
.C (explicit capital on case sensitive file sys... |
3,588,876 | 3,598,365 | Make Windows let me map 1 GB of virtual memory | I am using CreateFileMapping and MapViewOfFile to try and map an almost 1 GB file. I was having some problems with extending the file so I thought that I would try using CreateFileMapping with a 1 GB size. That is larger than the actual file, but it works well on smaller files.
It seems that I can get almost to a 1 GB ... | This is a long shot, but it could be that something small is mapped near 0x40000000 (maybe a DLL?), and since the kernel cannot find a contiguous VA space that is the size you want (i.e. you've got enough, but it's split up), it fails. If you want to map in gigantic files, it's much easier on a modern architecture - as... |
3,589,064 | 3,589,077 | C++ pattern to prohibit instantiation of a class outside a certain scope? | I have a System class that can return a pointer to an Editor class. The Editor class is instantiated within the System class and passed pointers to System's private variables. The Editor class essentially acts as an alternative interface to System's internal data structures.
My question:
Does a design pattern exist th... | You could make Editor's constructor private which would keep others from instantiating it and then making System a friend will allow it to access the constructor.
class System {
public:
System() : editor_(new Editor()) { ... }
private:
Editor* editor_;
}
class Editor {
friend class System;
Editor() { ... |
3,589,131 | 3,589,239 | Trying to use a while statement to validate user input C++ | I am new to C++ and am in a class. I am trying to finish the first project and so far I have everything working correctly, however, I need the user to input a number to select their level, and would like to validate that it is a number, and that the number isn't too large.
while(levelChoose > 10 || isalpha(levelChoose... | This is an annoying problem with cin (and istreams in general). cin is type safe so if you give it the wrong type it will fail. As you said a really large number or non-number input it gets stuck in an infinite loop. This is because those are incompatible with whatever type levelChoose may be. cin fails but the buf... |
3,589,204 | 3,589,283 | Multiple namespace declaration in C++ | Is it legal to replace something like this:
namespace foo {
namespace bar {
baz();
}
}
with something like this:
namespace foo::bar {
baz();
}
?
| You can combine namespaces into one name and use the new name (i.e. Foobar).
namespace Foo { namespace Bar {
void some_func() {
printf("Hello World.");
}
}}
namespace Foobar = Foo::Bar;
int main()
{
Foobar::some_func();
}
|
3,589,422 | 3,589,446 | Using OpenGL glutDisplayFunc within class | I've created a C++ class (myPixmap) to encapsulate the work performed by the OpenGL GLUT toolkit. The display() member function of the class contains most of the code required to set up GLUT.
void myPixmap::display()
{
// open an OpenGL window if it hasn't already been opened
if (!openedWindow)
{
... | The problem is that a pointer to an instance bound member function has to include the this pointer. OpenGL is a C API, and knows nothing about this pointers. You'll have to use a static member function (which doesn't require an instance, and thus no this), and set some static data members (to access the instance) in ... |
3,589,452 | 3,590,939 | what to use libharu c++ or i text java | i need to create pdf creation server and i don't know what is the best tools to chose
java itext engine or c++ libharu , programming is not the problem c++ and java is the same to me .
but i need something that will be fast so c++ libharu is good but iText i know its more rebust and complete .
are those assumption true... | If it's a server, I'd go with java, it will be easier to deploy to the server.
|
3,589,511 | 3,589,593 | Should a library use an interface that uses smart pointers? | I'm starting to write a library and considering its interface. Previous libraries I've written all use raw pointers (both internally and in its interface), and now I want to try the smart pointer library that comes with VS2010.
Should the interface use smart pointers? (Possibly forcing the library users to use smart p... | It is imposable to answer those question without understanding a lot more about your design principles and how you expect the library to be used.
So I can only answer based on my experience and how I like my libraries to be used.
Yes.
Yes. Don't do it.
Its probably not a good idea to mix them (though I have never ... |
3,589,517 | 3,589,583 | Cairo Matrix equivillant of GlOrtho Matrix? | Given that I do something like this:
void glOrtho( GLdouble left,
GLdouble right,
GLdouble bottom,
GLdouble top,
GLdouble nearVal,
GLdouble farVal);
and the result is: http://www.opengl.org/sdk/docs/man/xhtml/glOrtho.xmlw could I achieve a matrix like this:
http://cairogra... | I don't know Cairo so I'll delete my answer if a better one comes.
According to the docs of Cairo:
x_new = xx * x + xy * y + x0;
y_new = yx * x + yy * y + y0;
When you use OpenGL, the formula is like: (m being the matrix)
x_new = m(1,1) * x + m(1,2) * y + m(1,3) * z + m(1,4)
y_new = m(2,1) * x + m(2,2) * y + m(2,3) * ... |
3,589,663 | 3,589,690 | Why no unsigned floating point types? |
Possible Duplicate:
Why doesn't C have unsigned floats?
The question is probably very basic and probably answered many time earlier, but I want to understand why C++ does not have unsigned floating point types, even though floating point literals can be signed or unsigned.
$3.9.1/8- "There are three floating
poin... | Unsigned integer types have two important properties that differentiate them from signed integer types: "shifted" range (no negative subrange, but positive subrange twice as wide) and modulo arithmetic. For integer types these properties are important enough to justify the existence of unsigned types.
With floating-typ... |
3,589,716 | 3,589,774 | Level Order Traversal of a Binary Tree | void traverse(Node* root)
{
queue<Node*> q;
Node* temp_node= root;
while(temp_node)
{
cout<<temp_node->value<<endl;
if(temp_node->left)
q.push(temp_node->left);
if(temp_node->right)
q.push(temp_node->right);
if(!q.empty())
{
... | void traverse(Node* root)
{
queue<Node*> q;
if (root) {
q.push(root);
}
while (!q.empty())
{
const Node * const temp_node = q.front();
q.pop();
cout<<temp_node->value<<"\n";
if (temp_node->left) {
q.push(temp_node->left);
}
if (te... |
3,589,830 | 3,589,851 | C++: Best way to destruct static stuff | When I have a class containing static stuff, how can I free the memory at the end of the application the best way?
Foo.h
class GLUtesselator;
class Foo
{
private:
static GLUtesselator *tess;
public:
Foo();
virtual ~Foo();
}
Foo.cpp
#include "Foo.h"
#include <GL/glu.h>
GLUtesselator *Foo::tess = gluNewTe... | Simple. Don't make the static member a pointer.
Then it will be correctly constructed and destructed.
Foo.h
#include <GL/glu.h>
class Foo
{
private:
static GLUtesselator tess;
public:
Foo();
virtual ~Foo();
};
Foo.cpp
//
GLUtesselator Foo::tess;
If you have to use the gluN... |
3,589,936 | 7,214,192 | C++ URLencode library (Unicode capable)? | I need a library that can URLencode a string/char array.
Now, I can hex encode an ASCII array like here:
http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029
But I need something that works with Unicode.
Note: On Linux AND on Windows !
CURL has a quite nice:
char *encodedURL = curl_easy_escape(handle,WEBPAGE_URL,... | If I read the quest correctly and you want to do this yourself, without using curl I think I have a solution (sssuming UTF-8) and I think this is a conformant and portable way of URL encoding query strings:
#include <boost/function_output_iterator.hpp>
#include <boost/bind.hpp>
#include <algorithm>
#include <sstream>
#... |
3,590,020 | 3,590,030 | circular dependency(?) in C++ | My initial suspicion was that there was a circular dependency in my code and went through Resolve header include circular dependencies. But this hasn't resolved my compilation errors. Here is the code with 3 classes - A, G & N.
//A.h
#ifndef A_H_
#define A_H_
class com::xxxx::test::G;
namespace com { namespace xxxx ... | The forward declaration
class com::xxxx::test::G;
is illegal. Members of a namespace must be declared within it.
namespace com { namespace xxxx { namespace test {
class G;
Also, as Kenny says, namespaces aren't used like this in C++. Unless your project is distributed as a library or is of reasonably large size ... |
3,590,089 | 3,590,117 | Which is Android/Java corresponding method to the C#/C++ method GetTickCount()? | I wanna know a corresponding method in Android/Java that is like the GetTickCount method in C#/C++?
| For Android it is SystemClock.uptimeMillis().
Please note that uptimeMillis() does not include time spent in deep sleep. You may need SystemClock.elapsedRealtime() for total time after boot.
|
3,590,336 | 3,590,467 | C++: What script can I use to test my Apache and FastCGI set up? | I asked at serverfault: How to set up apache with fastcgi and a simple test script? I have been having real difficulties for a couple of weeks trying to understand how to set up my machine so that I can test my C++ application with Apache/FastCGI.
I tried with the simplest "Hello World" type of script. The only reply... | There are some examples of scripts on the FastCGI website .
|
3,590,515 | 3,590,608 | Can member function arguments be of the same class type? | //node.h
class node
{
public:
void sort(node n);
};
I didn't try the code yet . But It's interesting to know if is this a valid case and Why ?
Edit :
This leads me to another question :
Can I declare FOO inside a member function like this ?
//FOO.h
Class FOO
{
public:
void sort(int n) ;
... | Having now established that your question is solely related to passing node by value in a member (rather than passing node* or node&) the answer is still yes. You can even define the body of the member within the class is you so wish.
As to why, think of things from the compiler's point of view. As it parses the class ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.