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 |
|---|---|---|---|---|
4,532,703 | 4,532,737 | How to download source code of url that has no file extension? | As of right now I'm using this code below to download files to get there source code:
NSString *stringUrl = @"http://example.com/hello/goodbye.html";
NSURL *finalURL = [NSURL URLWithString:[stringUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
self.source = [NSString stringWithContentsOfURL:f... | It should work just as if there was a file defined. The GET url is merely a request to the webserver. The server is allowed to return whatever content of the "file" it wants to.
In other words: the complexity of handling the strange URLs like that need not be a part of your downloading code (so long as you process redi... |
4,532,866 | 4,532,922 | Returning const 'this' pointer | if this is a const pointer to class's object how can you return a const pointer from non-const return type?
Class T
{
public:
T* func(){return this;}
};
| Firstly, this is not a "const pointer". Where did you get that strange idea? Pointer this has scalar type and is not an lvalue, meaning that it can't possibly be "const" or "non-const". Pointer this is an rvalue and it is non-modifiable.
Secondly, the code in your question is valid regardless of whether the pointer inv... |
4,532,885 | 4,542,874 | Calculate spherical polygon area? | I have used "Girard's Theorem" to calculate the area of spherical polygon with great circle edges, as stated in a previous answer.
In most cases, it works fine, but I encounters a negative area case. The coordinate (lon/lat) of those vertices in counterclockwise are (radian):
5.240747351 1.016447132
5.268216612 1.06786... | I have figured it out! The problematic interior angle is not ~179 but ~181, due to the value range of "acos" is [0, PI]. So some judgement should be conducted for each angle (whether the calculated angle is interior or exterior).
|
4,532,953 | 4,533,004 | Mixed declaration in a for loop | I want to write a for loop as shown below; in the initialization section, I want to declare variables of different types:
for (int loop=0, long result = 1; loop <= 10 ; loop++, result *= 2 )
{
cout << "2^"<<loop<<"=" << result<<endl;
}
But it is giving error, means it's not allowed. Any solution fo... | Don't write code like this. It is speed-bump code, somebody will read this some day and go Whoa! and lose 5 minutes of his life trying to figure out why you did this. That's 5 minutes he'll never get back, you'll owe him for no good reason.
If constricting the scope of result is really that important then use an extr... |
4,533,063 | 4,533,102 | How does ifstream's eof() work? | #include <iostream>
#include <fstream>
int main() {
std::fstream inf( "ex.txt", std::ios::in );
while( !inf.eof() ) {
std::cout << inf.get() << "\n";
}
inf.close();
inf.clear();
inf.open( "ex.txt", std::ios::in );
char c;
while( inf >> c ) {
std::cout << c << "\n";
}... | -1 is get's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof)
The EOF flag is only set once a read tries to read past th... |
4,533,126 | 4,533,178 | Get pointer to member function from within member function in C++ | Currently in the program I am attempting to write I need to be able to get a pointer to a member function within a member function of the same class. The pointer needs to be passed to a function as a void (*)(). Example:
//CallFunc takes a void (*)() argument
class testClass {
public:
void ... | To take pointer to member function you need following syntax:
callFunc(&testClass::aFunc1);
But note, that to invoke member function you need have class instance. So callFunc needs 2 parameters (I'm using template but you can change it to testClass):
template <class T>
void callFunc(T*inst, void (T::*member)())
{
... |
4,533,188 | 4,533,197 | How does the "return value" of operator >> of istream class work? | I tried to understand the statement:
int main() {
fstream inf( "ex.txt", ios::in );
char c;
while( inf >> c ) {
cout << c << ", ";
}
return 0;
}
What does ( inf >> c ) return in the while loop above? I downloaded the gcc source code and tried to play around w... | To return a self ref you just return *this. You don't actually declare an internal self reference. You can have reference members, but you must initialize them in the constructor initializer list: class Foo { Foo(int& some_int_ref) :my_ref_member(some_int_ref)
istream has another overload to determine its boolean va... |
4,533,258 | 4,533,315 | Is there a portable alternative to relational comparison of pointers in C++? | I lack industry experience with the language. But in my spare time I have encountered a couple of places where I need to compare pointers, preferably with behavior defined by the standard.
First case, if I decide to use ordered binary tree as a container in my application (and not hash table) and I want equality to be ... | I'm not quite sure what you're asking for (i.e., what exactly are you trying to accomplish?), but I think this is what you want to know:
The relational functors greater, greater_equal, less, and less_equal defined in <functional> yield total ordering for any pointer type, even if the built-in relational operators do no... |
4,533,264 | 4,533,444 | Access-specifiers are not foolproof? | If I've a class like this,
class Sample
{
private:
int X;
};
Then we cannot access X from outside, so this is illegal,
Sample s;
s.X = 10; // error - private access
But we can make it accessible without editing the class! All we need to do is this,
#define private public //note this define!
class Samp... |
But we can make it accessible without editing the class! All we need to do is this,
Technically, all you've shown is that "we can turn a legal program into Undefined Behavior" without editing one specific class.
That's hardly news. You can also turn it into undefined behavior just by adding a line such as this to the... |
4,533,414 | 4,533,463 | Add Website to the Internet Explorer Trusted Site in Win32 | I am writing an application which adds configured url to the trusted site settings in Internet explorer. I am writing an Win32 application, so i can't use interop services. Can anyone please help to sort this issue?
Thanks in advance.
Best Regards,
Rajesh
| You have to use Internet Security Manager Object over COM.
|
4,533,429 | 4,536,666 | Macro to an other macro with arguments from first macro | I'm trying to make this macro work:
#define InitProperty(Name, Type) DefineMethods ( ##Name.Mode, Type, Name )
Now this doesn't seem to be working this gets me:
DefineMethodsLenght.Mode(caller, Lenght)
instead of
DefineMethods(Lenght.Mode, caller, Lenght);
What's going on here; isn't this possible?
| Well, the title of your question implies that there are TWO macros involved, but your example only shows one macro. So I'll go ahead and guess that you have:
#define InitProperty(Name, Type) DefineMethods ( Name.Mode, Type, Name )
#define DefineMethods(Name, Type, Arg) DefineMethods##Name( Type, Arg )
Now if you inv... |
4,533,482 | 4,533,503 | Storing member function pointers of derived classes in map | I am trying to implement a factory for two classes Circle, Square both of which inherits from Shape.
class Shape {
public:
virtual static
Shape * getInstance() = 0;
};
class Circle : public Shape {
public:
static const std::string type;
Shape * getInstance() {
return new Circle;
... | Okay I got the mistake.
1) shouldn't declare - virtual static Shape * getInstance() = 0; - in Shape class.
2) getInstance() should be static in all other classes.
Here is the complete implementation
class Shape {
public:
virtual
std::string getType() = 0;
};
class Circle : public Shape {
public:
static cons... |
4,533,534 | 4,533,553 | Use format strings that contain %1, %2 etc. instead of %d, %s etc. - Linux, C++ | As a follow-up of this question (Message compiler replacement in Linux gcc), I have the following problem:
When using MC.exe on Windows for compiling and generating messages, within the C++ code I call FormatMessage, which retrieves the message and uses the va_list *Arguments parameter to send the varied message argume... | First of all functions like printf support positioned format:
printf("%2$s, %1$d", salary, name);
For C++, beside the C solution there is a boost::format library:
std::cout << boost::format("%2%, %1%") % salary % name;
Also if you are moving software to Linux I would suggest use "different" approach for localization:... |
4,533,546 | 4,533,557 | Is there an equivalent way to do CString::GetBuffer in std::string? | Many Windows API, such as GetModuleFileName, etc... write output to char* buffer. But it is more convenient to use std::string. Is there a way to have them write to std::string (or std::wstring)'s buffer directly?
Sorry for my poor English. I'm not a native English speaker. -_-
Taworn T.
| If you're using C++0x, then the following is guaranteed to work:
std::string s;
s.resize(max_length);
size_t actual_length = SomeApiCall(&s[0], max_length);
s.resize(actual_length);
Before C++0x the std::string contents is not guaranteed to be consecutive in memory, so the code is not reliable in theory; in practice i... |
4,533,652 | 4,534,720 | How to split string using istringstream with other delimiter than whitespace? | The following trick using istringstream to split a string with white spaces.
int main() {
string sentence("Cpp is fun");
istringstream in(sentence);
vector<string> vec = vector<string>(istream_iterator<string>(in), istream_iterator<string>());
return 0;
}
Is there a similar trick to split a string with... | Generally speaking the istringstream approach is slow/inefficient and requires at least as much memory as the string itself (what happens when you have a very large string?). The C++ String Toolkit Library (StrTk) has the following solution to your problem:
#include <string>
#include <vector>
#include <deque>
#include ... |
4,533,758 | 4,533,801 | Absence of typeof operator in C++03? | I'm just wondering how boost have implemented BOOST_TYPEOF (in C++03) which seems to be a very useful tool. Anyone has any idea?
Also, I'm thinking C++03 itself could have provided typeof operator, especially when it already has sizeof(expr) which must be knowing the type of the expr also, otherwise how else could it t... | It just uses compiler magics. Like, GCC's __typeof__. For compilers that don't provide such magic, it provides an emulation that can detect the type of some expressions, but fails with completely unknown types.
A possible implementation could be to have a list of functions that accept an expression of a given type, an... |
4,534,048 | 4,534,298 | ::GetPrivateProfileString read whole section of INI file | I'm modifying existing C++ application and moving out some values that are currently hard coded.
I'm doing this with one class that will "manage" this whole thing and hold map<CString, CString> of the values from the INI file.
Right now I have to read each value separately using ::GetPrivateProfileString function - ca... | You don't need to read the file manually but it helps to read the manual for GetPrivateProfileString:
lpKeyName [in] : The name of the key
whose associated string is to be
retrieved. If this parameter is NULL,
all key names in the section specified
by the lpAppName parameter are copied
to the buffer specifie... |
4,534,208 | 4,534,426 | How does a template class inherit another template class? | I have a "SquareMatrix" template class which inherits "Matrix" template class, like below:
SquareMatrix.h:
#ifndef SQUAREMATRIX_H
#define SQUAREMATRIX_H
#include "Matrix.h"
template <class T> class SquareMatrix : public Matrix<T>
{
public:
T GetDeterminant();
};
template <class T> ... | IntelliSense is not a compiler, it's a completion tool. It doesn't compile the whole program, hence it can't really understand everything. It also works on the fly as you modify your code. Therefore it may get lost when you use templates, multiple includes with different defines, change something that has dependencies,... |
4,534,296 | 4,537,904 | What are the advantages of C++/CLI (formerly "Managed C++") over standard C++? | The closest question I found in SO was this one, but the answers were really referring to advantages of C++/CLI over C#.
I need to understand the advantages of C++/CLI over standard C++.
| One thing I haven't seen mentioned in the answers yet (probably because it's more of a disadvantage, but it's a relevant consideration) is that C++/CLI tends to get second-class treatment. Microsoft used to push it as pretty much a replacement for C++. they wanted native developers to switch to .NET, and the way to do ... |
4,534,313 | 4,534,320 | What is the difference between "template <class T>" and "template <typename T>"? |
Possible Duplicate:
Use 'class' or 'typename' for template parameters?
I see two different template class declarations:
template <class T> class SampleClass1
{
// ...
};
and
template <typename T> class SampleClass2
{
// ...
};
What is the difference between these two codes?
EDIT: I corrected the wrong ke... | If by
template <typedef T> class SampleClass2
you mean
template <typename T> class SampleClass2
then there is no difference. The use of class and typename (in the context of a template parameter that refers to a type) is interchangeable.
The reason that both keywords are allowed here is historical. See this article... |
4,534,679 | 4,534,706 | Memory Management with returning char* function | Today, without much thought, I wrote a simple function return to a char* based on a switch statement of given enum values. This, however, made me wonder how I could release that memory. What I did was something like this:
char* func()
{
char* retval = new char[20];
// Switch blah blah - will always return some ... | You could write such functions in pair, like
Xyz* CreateXyz();
void DestroyXyz(Xyz *xyz);
Abc* NewAbc();
void DeleteAbc(Abc *abc);
Or you simply can transfer the responsibilty of deleting Xyz/Abc to the clients, i.e ones who call the function must also do delete on the returned object after using it.
Whatever you c... |
4,534,766 | 4,534,808 | Basic data alignment question | I've been playing around to see how my computer works under the hood. What I'm interested in is seeing is what happens on the stack inside a function. To do this I've written the following toy program:
#include <stdio.h>
void __cdecl Test1(char a, unsigned long long b, char c)
{
char c1;
unsigned long long b1;... | Memory layout of POD structs is pretty much specified and guaranteed by language rules + type alignment/size requirements on your platform.
Implementation has free hands with the local variables and function parameters. It is most likely that it puts some of these into stack only because you use unary & operator to ta... |
4,534,830 | 4,534,837 | C++/Size of a 2d vector | How do I find the size of a 2 dimensional vector? So far I have the following code which doesn't compile.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < vector <int> > v2d;
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 5; y++)
{
v2d.push_... | To get the size of v2d, simply use v2d.size().
For size of each vector inside v2d, use v2d[k].size().
Note: for getting the whole size of v2d, sum up the size of each individual vector, as each vector has its own size.
|
4,534,906 | 4,534,977 | what does stack and heap overflow exploit means | what does this stack and heap over flow exploit mean
| An example of Stack-based exploitation: (implementation defined or possibly undefined, nevertheless interesting!)
Just look at the output:
http://www.ideone.com/A3vlY
Also note the runtime-error!
I'm particularly trying to do this:
By overwriting the return address in a stack frame. Once the function
returns, execu... |
4,534,907 | 4,534,921 | __stdcall typedef g++ problem | This code compiles (as I would expect):
typedef void __stdcall (*Func)();
struct A {
static void __stdcall f() { }
};
int main() {
Func p = A::f;
}
But this one:
struct A {
typedef void __stdcall (*Func)();
static void __stdcall f() { }
};
int main() {
A::Func p = A::f;
}
fails with not-very-he... | The syntax is void(__stdcall *)(), not void __stdcall (*)().
|
4,535,027 | 4,535,097 | How to know the type of an object in a list? | I want to know the type of object (or type) I have in my list so I wrote this:
void **list; //list of references
list = new void * [2];
Foo foo = Foo();
const char *not_table [] = {"tf", "ft", 0 };
list[0] = &foo;
list[1] = not_table;
if (dynamic_cast<LogicProcessor*>(list[0])) { //ERROR here ;(
printf("Foo was f... | You shall use a boost::variant or boost::any to accomplish this purpose. dynamic_cast only works when the source and target types are linked by inheritance. Also, using void*s is terrible, terrible style in the overwhelming majority of code, as it's completely unsafe.
Actually, reading your code, I just suggest that yo... |
4,535,050 | 4,535,141 | How to create a va_list on GCC? | I'm trying to convert some code so that it compiles on gcc too (right now, it compiles only on MSVC).
The code I'm stuck at is in a pseudo-formatting function that accepts as input a format string and zero or more arguments (const char *format, ...). It will then process some of the placeholders consuming some of the a... | I'm a bit lost. Why do you need a new dynamically-generated va_list? Why not just reuse the old one?
I believe vsnprintf() uses a current va_list object (if you can call it that). So you are free to va_start(), use the arguments you want via va_arg(), then pass the remaining arguments via the va_list to vsnprintf(),... |
4,535,199 | 4,535,221 | Program terminates after rc.d script starts it (Arch Linux) | Hey guys,
I have written a program to act as a keyboard backlight controller for my MacBook Pro that runs Arch, just like there is natively in OS X. The program itself works great, but the rc.d script I provide with the Arch program package, doesn't seem to open the program correctly ... or so I think.
The source to th... | If you read the source code for mbpkbdbacklightctl.cpp you will see these lines:
95 std::string the_display = ":0.0";
96 Display *x11_display = XOpenDisplay(the_display.c_str());
97 if(x11_display != NULL) {
So it will fail if there is no active X server, this means that you have to start this script after X sessio... |
4,535,227 | 14,448,783 | gtkmm application with Gio file monitors | I need to monitor multiple directories for changes. I'm using Gtk::Main, calling Gio::Init, and adding directory monitors exactly as the documentation suggests. However, the callback is never called, for any directory. Do I need another loop solely for the monitors, and if so, how would I use it in conjunction with Gtk... | I had the same problem in Vala and here is the complete solution.
As pointed out by Andrea Azzarone, you can use the Gtk::Main loop.
However, pay attention to your Gio::FileMonitor reference. At the end of the function, it is destroyed so that the callback won't be called if you don't keep a reference to the Gio::FileM... |
4,535,763 | 4,535,811 | How am I accessing the cpp standard library without placing '#include' statements? | I've been teaching myself cpp sporadically from 'accelerated C++' and recently I noticed that when I forgot my #include <algorithm> statement, my code (which includes transform and find_if) compiled and ran successfully anyways. After this, I tried removing all standard header include statements altogether and found th... | Standard library headers are allowed to include other standard library headers. So if you e.g. #include <string>; your implementation is allowed (but not required to) include every other standard library header there is, including <algorithm>. In your case, that probably happened, but it's nothing you should rely on.
|
4,535,824 | 4,535,836 | Windows Procedure If Else statement doesn't work for message | I am currently trying to make a GUI for some software and I'm having problems with some static controls. In my windows procedure I have the WM_CTLCOLORSTATIC message for when the static controls are to be drawn. Inside the message, I have an IF ELSE statement where it compares the handles of a window to the one that ... | Here's your problem.
if (hwnd = ANNwindow->settingsborder)
should be
if (hwnd == ANNwindow->settingsborder)
// ^^
and the same for the else if statement.
You're assigning the contents of ANNwindow->settingsborder to your hwnd, an operation that virtually always returns true instead of doing an equality test.
|
4,535,825 | 4,535,852 | error: switch quantity not an integer | I have researched my issue all over StackOverflow and multi-google links, and I am still confused. I figured the best thing for me is ask...
Im creating a simple command line calculator. Here is my code so far:
const std::string Calculator::SIN("sin");
const std::string Calculator::COS("cos");
const std::string Ca... | In switch, the expression must be of "an integral type or of a class type for which there is an unambiguous conversion to integral type" (quoting VS2008 docs).
A string class doesn't have "unambiguous conversion to integral type", like a char does.
As a work-around:
Create a map<string, int> and switch on the value of... |
4,535,993 | 4,536,041 | When will C++0x be released, and when will it be the de-facto standard? | I read that C++0x is likely to be officially released during march 2010, and that it will become an ISO standard for the end of 2011.
Is this really the most likely scenario, or does it risk to be postponed again and again?
I'm also wondering when will it become the de-facto standard: when will anyone (including the mo... | For better or worse, anything about a "de facto standard" is subjective on at least two fronts. One is when a compiler includes enough C++0x features to qualify as implementing C++0x, and the second is when use of those became "accepted". Most C++ compilers already include at least a few significant C++0x features, and... |
4,536,095 | 4,536,188 | Unary minus and signed-to-unsigned conversion | Is this always technically correct:
unsigned abs(int n)
{
if (n >= 0) {
return n;
} else {
return -n;
}
}
It seems to me that here if -INT_MIN > INT_MAX, the "-n" expression could overflow when n == INT_MIN, since -INT_MIN is outside the bounds. But on my compiler this seems to work ok... i... | If you want to avoid the overflow, you should first cast n to an unsigned int and then apply the unary minus to it.
unsigned abs(int n) {
if (n >= 0)
return n;
return -((unsigned)n);
}
In your original code the negation happens before the type conversion, so the behavior is undefined if n < -INT_MAX.
When nega... |
4,536,226 | 4,536,391 | How to make Qt support HTML 5 database? | I am using Qt 4.7.1 and embedded a webview in my app. But I got the following error when trying to visit http://webkit.org/demos/sticky-notes/ to test the HTML 5 database feature
Failed to open the database on disk. This is probably because the version
was bad or there is not enough space left in this domain's quota
... | Check QWebSettings documentation.
In particular, you have to use setAttribute to enable QWebSettings::OfflineStorageDatabaseEnabled and point out the local storage location using setOfflineStoragePath (e.g. QDesktopServices::DataLocation).
You might want to do it per-page, but as an example, doing it globally can be do... |
4,536,246 | 4,536,325 | CMake basic project setup | I'm new to CMake and re-learning C++, so I hope these are appropriate questions. I have a project in directory /projects/A and some .h files in /projects/include/open-source-project-1 that the A project depends on.
Sample Hierarchy:
/projects
/CMakeLists.txt
/A
/CMakeLists.txt
/a.cpp
/B
/CMakeLists.t... | Your top-level CMakeLists.txt file is not needed unless all of the projects are directly inter-related somehow or have otherwise unresolvable dependencies. Unrelated projects should not include each other, nor do they need a parent list file.
If A and B are separate projects, ./A/CMakeLists.txt and ./B/CMakeLists.txt ... |
4,536,336 | 4,536,361 | What's the best way to return a subset of a list | I have a list of tasks. A task is defined by a name, a due date (and time) and a duration.
My TaskManager class handles a std::list<Task> sorted by due date. It has to provide a way to get the tasks due on a specific day.
An example : I have task 1 due on Monday 6 am, task 2 due on Monday 9 am, task 3 due on Tuesday 7 ... | instead of using a std::list, consider using a std::set or std::map, which can keep the items in a sorted order without additional effort. Then you can find the items due on a particular date using std::set::lower_bound or std::map::lower_bound.
|
4,536,405 | 4,536,516 | How to find the size of Flash and RAM used by a firmware? | How can I find the size of Flash (ROM) and RAM used by the Firmware? The firmware is implemented using C++. Also I have Keil microvision4; will it be helpful to find the ROM and RAM size?
Or do I need to look at the MAP(.M51) file of the firmware to find the memory sizes?
Or just telling the size of hex files(.hex) fil... | A few comments:
The size of the hex file doesn't provide a great deal of information. For example: it won't provide any RAM usage. It may not even tell you the size of the image as it resides on the device (are you writing to NOR and NAND flash? What are the flash block sizes, etc.)
The map file is a good tool for ... |
4,536,552 | 4,536,576 | Passing a specific array element using pointer reference | I am having problem with passing a pointer by reference.
This is the method
void set_range(double **measu)
{
if ((*measu)[0] < 0) //or i is used for a loop
return ;
}
int main()
{
double *mes;
set_range(&mes[1]);
}
I have allocated memory and required values are set. But this program give... | Change your function to take a double* instead of a double**, eg:
void set_range(double *measu)
{
if (*measu < 0) //or i is used for a loop
return;
}
int main()
{
double *mes;
...
set_range(&mes[1]);
}
Alternatively, use a real reference instead:
void set_range(double &measu)
{
if (measu < 0) //or i is ... |
4,536,596 | 4,536,670 | tool to generate C++ wrapper over java class | From what I understand, SWIG is to wrap C++/C to make it appear in Java, and javah is to implement certain java functions in C++ ( aka native functions ).
Is there a tool which can create a C++ wrapper over a java class, so that the caller. of this c++
wrapper doesn't have to worry about java, for example
Input Java ... | Options include, the following, in ascending order of expense to you.
Hand-written JNI code written by clients of your Java class.
Hand-written, JNI-driven wrappers written by you for clients of your class.
JACE-generated wrappers. JACE is a free tool. Last version was in 2008; not sure if development is continuing.... |
4,536,741 | 4,536,759 | How to access a child class function | class base{}
class child : public base{
**dummyfunction();**
}
now I am calling a function in which I am passing a child class object.
**child ob;**
function(**ob**);//calling a function
//function body
function(**base *object**)
{
**//here I want to access the function of child class. How can I do it???**
... | What you required is downcasting.
you can acheive by making the dummyFunction as virtual in base class and then overriding this function in child class this solution would not require downcasting
otherwise you can use the method described in the below post but this is not safe to downcast
Downcasting Method
|
4,536,816 | 4,539,501 | Application Distribution | I have a SDL app that compiles fine, and the images show up, but only if they are in the correct folder with the binary next to them, if the images are moved they wont show up next time the application is run. How can I make a complete binary that will allow me to compile the images as well as the code, so that I can d... | I suggest making a .deb file. If you really seriously want to distribute anything for Ubuntu, you will have to get comfortable with dpkg sooner or later.
Now there is a Right Way to create packages, described in the Debian New Maintainer's Guide.
And then there's the dirty hippie way. For that you just need (a) a direc... |
4,536,832 | 4,536,868 | Prevent strings stored in memory from being read by other programs | Some programs like ProcessExplorer are able to read strings in memory (for example, my error message written in the code could be displayed easily, even though it is compiled already).
Imagine if I have a password string "123456" allocated sequentially in memory. What if hackers are able to get hold of the password ty... | I believe you are confusing two things. The strings ProcessExplorer is finding are also able to be found by the "strings" command in Unix. It just dumps all the stored strings in an executable not the current memory.
Unless you compiled a User password into your program, the memory allocated to store the data shouldn't... |
4,536,896 | 4,536,927 | IBM XL C/C++ Compiler: check compiler mode using preprocessor directive | I am trying to compile a sample c++ file test.cpp using IBM xlC compiler on AIX system. The file should be compiled in both 32-bit and 64-bit modes. I am using following commands to compile them in both modes:
xlC test.cpp (default compiler mode is 32-bit)
xlC -q64 test.cpp
Under test.cpp, I have to printf("Using 32-bi... | in XLC, if you are using the -q64 flag, the macro __64BIT__ is defined.
Straight from IBM XL C/C++'s documentation:
If the compiler is invoked in 64-bit mode, the __64BIT__ preprocessor macro is defined.
|
4,537,169 | 4,537,212 | Use templates as a members when not all the details are known | Is it possible to specifiy a template as a member but not know all the details? Or rather how can I work around this.
Example doesn't work but might show you what I'm trying to achieve.
template<typename T>
struct Foo {
///blah...
};
struct Bar {
Foo* m_foo;
};
Bar in this case is a base class, and depending ... | You can either make Bar a template class as well so it can pass that template argument along to Foo, or else you can make all the Foo<T> variations inherit from a common interface (in C++, an interface is just an abstract class with no implementation, all members are pure virtual functions) and then Bar can point to th... |
4,537,377 | 4,538,309 | Add extra include/lib paths to MinGW | I would like to add some extra include/lib directories besides the default ones for MinGW to search upon compilation. The reason for this is because the hard drive I currently have MinGW installed into is nearly full and so I had to install Qt into my second one instead. Thus, how can I have MinGW include the Qt files ... | You can set environment variables CPLUS_INCLUDE_PATH for include directories and LIBRARY_PATH for library directories. More information can be found in Environment Variables Affecting GCC
|
4,537,390 | 4,537,453 | Compiling ANSI C++ code on Mac OS X | I'm struggling to compile and run a program on Mac OS X, which is written using ANSI/ISO C++ (Windows). Source code
I've tried to compile using g++, and by importing the files and compiling using Xcode.
If i try to compile using g++ (command line), I get a couple of warning, which are easy to fix,:
e.g. warning: form... |
In stopwatch.cpp change the include at line 49 from strstream.h to sstream.
In stopwatch.cpp line 50 change the include from fstream.h to fstream.
In qsort.h change the declaration of Qsort() so the second and third parameters are unsigned long rather than size_t.
In qsort.cpp change the definition of Qsort() so the s... |
4,537,452 | 4,537,536 | Skinning WinAPI Controls | If you've ever seen an application in the Adobe Creative Suite 5 (CS5), you may have noticed that it doesn't look like the native Windows GUI.. They have modified it to have a different look to it.
Where would someone begin to make an application that has a custom skin? CS5 uses the Adobe Source library for it's widget... | Use QT and QML. It doesn't have a steep learning curve. You define your GUI with JavaScript and add lots of effects and enjoy using PNGs in every single thing you can imagine. Then you do your application logic with C++. In fact you can do some fairly advanced things other than UI with QML but it's better to seperate c... |
4,537,556 | 4,537,587 | Deallocating vector of pointers, but memory still in use | I have no idea what's wrong with the following code! I am deleting all pointers, but when I use the "top" command to watch the memory, I can see that still lots of memory is allocated to the program. Am I missing something here to free the memory?
#include <iostream>
#include <vector>
using namespace std;
int main()
... | There is no leak in this code (Assuming there are no exceptions being thrown after allcoation and before deallocation). The reason why that you are not seeing memory coming down is that the CRT may not release the memory you delete immediately back to the process. It might keep it for future use. However, it is guarant... |
4,537,581 | 4,537,661 | populating an std::[container] from a function by passing an output iterator | I want to populate a container from inside a function by passing an output iterator as this is the most efficient way to do it as I understand. e.g.
template <typename OutputIterator>
void getInts(OutputIterator it)
{
for (int i = 0; i < 5; ++i)
*it++ = i;
}
(Is returning a std::list costly?)
But how can I enf... | You can use boost::enable_if in conjunction with std:iterator_traits :
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>
template <typename OutputIterator>
typename boost::enable_if<
boost::is_same<
int, /* replace by your type here */
typename std::iterator_traits<Out... |
4,537,586 | 4,537,877 | How do I implement a method selector kind of pattern in C++? | Here is the scenario:
void quicksort(void *data, size_t size);
void mergesort(void *data, size_t size);
void heapsort(void *data, size_t size);
size_t binary_search(void *data, size_t size, size_t key)
{
// Usual binary search implementation
// ...
return 0; // just a placeholder
}
I want user to specify... | Specific notes to your question:
Don't mix sort and search.
First, a linear search is O(N), whereas sort_and_search is O(N log N) at best, i.e. a linear search would be faster. Binary search is a good choice of algoreithm only if you search many times over already-sorted data.
Second, you noticed yourself that the cal... |
4,537,753 | 4,554,760 | When should I use _mm_sfence _mm_lfence and _mm_mfence | I read the "Intel Optimization guide Guide For Intel Architecture".
However, I still have no idea about when should I use
_mm_sfence()
_mm_lfence()
_mm_mfence()
Could anyone explain when these should be used when writing multi-threaded code?
| Caveat: I'm no expert in this. I'm still trying to learn this myself. But since no one has replied in the past two days, it seems experts on memory fence instructions are not plentiful. So here's my understanding ...
Intel is a weakly-ordered memory system. That means your program may execute
array[idx+1] = something... |
4,537,930 | 4,580,940 | Removing a character from a string | i have a string. I want to delete the last character of the string if it is a space.
i tried the following code,
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
but my g++ compiler gives me an error saying:
error: no matching function for call to ‘remove_if(__gnu_cxx::__normal_iterator<char*,
std::ba... | The first problem is that isspace has multiple overloads in the C++ Standard Library. The initial fix is to provide an explicit type for the function so that the compiler knows which function to take the address of:
#include <string>
#include <algorithm>
#include <cctype>
int main()
{
std::string str = "lol hi inni... |
4,538,239 | 4,538,286 | Overloading operator [] | I have a task to write a class matrix in C++ and there is a condition, to override the operator [] for matrix so if I have a matrix with name Matrix with this "Matrix[0][0]" I must take it's first element, on it's first line. I have represented the matrix with two dimensional dynamic array and templates (T **matrix). C... | i assume matrix is a member variable of type T** of Matrix.
template< class T >
T* operator []( Matrix<T>& m, unsigned int row )
{
// maybe remember rows and assert(row<rows);
return m.matrix[ row ];
}
Now you may write something like
Matrix<T> m(50,9999);
m[42][1337];
to access element 1337 in row 42.
|
4,538,339 | 4,538,351 | How to make this jpeg compression faster | I am using OpenCV to compress binary images from a camera:
vector<int> p;
p.push_back(CV_IMWRITE_JPEG_QUALITY);
p.push_back(75); // JPG quality
vector<unsigned char> jpegBuf;
cv::imencode(".jpg", fIplImageHeader, jpegBuf, p);
The code above compresses a binary RGB image stored in fIplImageHeader to a JPEG image. F... | Try using libjpeg-turbo instead of libjpeg, it has MMX & SSE optimizations.
|
4,538,522 | 4,538,580 | PacMan Movement isn't smooth | I am moving pacman in a line using simple for loop but the pacman blinks or may be its the whole screen updating and blinking. How can i make it more smooth?
Edit:
I am currently using C++ Turbo and its built in graphics library. BUt i tend to use SDL later (using image tiles over a 2D array (grid)).
| There are many techniques you can use for smooth transition between frames. Probably the simplest is double buffering where the construction of a frame is done outside of the viewable video memory, then the whole block of memory is switched to the new frame location (usually with page flipping, a fast hardware switch, ... |
4,538,586 | 4,538,786 | How to compress a buffer with zlib? | There is a usage example at the zlib website: http://www.zlib.net/zlib_how.html
However in the example they are compressing a file. I would like to compress a binary data stored in a buffer in memory. I don't want to save the compressed buffer to disk either.
Basically here is my buffer:
fIplImageHeader->imageData = (c... | This is an example to pack a buffer with zlib and save the compressed contents in a vector.
void compress_memory(void *in_data, size_t in_data_size, std::vector<uint8_t> &out_data)
{
std::vector<uint8_t> buffer;
const size_t BUFSIZE = 128 * 1024;
uint8_t temp_buffer[BUFSIZE];
z_stream strm;
strm.zalloc = 0;
str... |
4,538,672 | 4,782,340 | Slow building of a Symbian Qt Project in Qt Creator. Takes over 20 minutes | I'm trying to build a moderately sized Symbian Qt project (around 100 files) using the latest released Nokia Qt SDK (Qt 4.6.3 and Qt Mobility 1.0.2).
The build for the simulator finishes in under 3 minutes, but when I build for the device, the build takes well over 20 minutes! I can forget trying to debug on the device... | I solved the slow compilation problem as indicated by this thread
http://discussion.forum.nokia.com/forum/showthread.php?196650-Selective-compiling&p=720040&viewfull=1#post720040
I added
SYMBIANBUILD_DEPENDENCYOFF = 1
to the project environment variables (or it could be added to Windows environment variables), and the... |
4,538,975 | 4,538,988 | Template function to return template type | I have the following function but my compiler (VS2003) says that the assignement T = .... is illegal. Can someone clarify what I've done wrong? The type of value is a boost::variant. node is a struct.
template <typename T>
T find_attribute(const std::string& attribute)
{
std::vector<boost::shared_p... | You should declare a variable:
if ((*att_iter).key.compare(attribute) == 0) {
T temp = (*att_iter).value; //T : Illegal use of this type as an expression.
return temp;
}
|
4,538,987 | 4,539,154 | C++ LoadLibrary() from the current path | I'm a .net developer mostly, doing something small in C++ so im having a little trouble.
I'm loading another C++ dll using hInst = LoadLibrary(TEXT("mydll.dll")); and I came to realize that this looks for the dll I'm trying to load in 'C:\' or in 'system32'.
Can someone show me how to load the dll from the current dire... | The process current directory can be acquired using the function GetCurrentDirectory():
TCHAR bufCurrentDirectory[MAX_PATH + 1] = { 0 };
DWORD dwNumCharacters = ::GetCurrentDirectory(MAX_PATH, bufCurrentDirectory);
if(dwNumCharacters == 0) error();
Now the path to the process's current directory is in bufCurrentDirect... |
4,539,187 | 4,539,229 | Insert text into the textbox of another application | How do I, using C# or C++, insert text into the textbox of another application?
I did this a long time ago and seemed to remember something about using the applications HWND. But since that change for every instance of the application I feel that I fon't remember the complete story. Do I somehow get a list of running a... | Use FindWindowEx() to find the handle (HWND) and then send the WM_SETTEXT message using SendMessage()
When using FindWindowEx you will need to first find the main window handle by using its class name. Then you will need to find the handle of whatever container the textbox is in, calling FindWindowEx, passing the handl... |
4,539,228 | 4,539,245 | Static Linking Problem in Qt with SQLite | I'm having a static linking problem in my C++ app. I'm hoping you can help. Code for header and source below.
#ifndef PRACTICARDSDB_H
#define PRACTICARDSDB_H
#include "cardset.h"
#include "card.h"
#include "filter.h"
class PractiCardsDB
{
public:
PractiCardsDB();
static void resetAll();
static void resetDa... | When you define a static member function separately from the declaration, you do not have to use the static modifier.
bool PractiCardsDB::createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("EnglishSpanish");
if (!db.open())
{
return false;
}
r... |
4,539,328 | 5,368,386 | How check if file have been changed via other process? | I have two processes (firsts source in perl, seconds source in c++) and both of them use same file. One of them writes to the file line by line, and another reads from file if new line is appended to it. For second process to know that file is modified the first proces flush - es after each apendence. But second proces... | It seems that stat64 doesn't change it's st_mtime member when file is flushed. Instead the st_size changes. So I can use st_size to detect if file was changed.
|
4,539,406 | 6,363,678 | Nonstatic member as a default argument of a nonstatic member function | struct X
{
X():mem(42){}
void f(int param = mem) //ERROR
{
//do something
}
private:
int mem;
};
Can anyone give me just one reason as to why this is illegal in C++?! That is to say, I know that it is an error, I know what the error means, I just can't understand why would this be illegal!
| Your code (simplified):
struct X
{
int mem;
void f(int param = mem); //ERROR
};
You want to use a non-static member data as default value for a parameter of a member function. The first question which comes to mind is this : which specific instance of the class the default value mem belongs to?
X x1 = {100}; //... |
4,539,476 | 4,539,544 | add two dll's to msvc 2010 application | I'm trying to use libcurl library in my application.
when i start my application, it asks for libcurl.dll and zlib1.dll
to exist in the same folder. when i add them everything works fine but i want to include
them to the executable.
how can i statically add both dll's to the application?
| You cannot statically link dlls into an executable. The purpose of dynamic libraries is to be loaded dynamically during runtime from an external image (dll file). You should check whether curl and zlib provide proper static libraries and link against them instead of lib stubs for the dlls.
Consider that linking against... |
4,539,563 | 4,539,588 | brace-enclosed initializer list | assuming I have an object similar to this one:
struct MenuDef
{
int titleResourceId;
struct MenuItemDef {
char* name;
int value;
SomeFunctionPtr someFactory;
} menuItems[10];
};
That is initialized like this:
const MenuDef m = {
1,
{
... | I believe it is safe according to 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).
As a reminder :
To value-initialize an object of type
T means:
if T is a class type (clause 9) with... |
4,539,573 | 4,539,585 | boost::variant conversion to type | I have the following variant from the boost lib:
typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
Now I want to get a value from a variable declared as 'value' in a struct node, so I thought I could work generic and call the function as such: find_attribute<long>(a... | You have to use boost::get<type>(variant) to get the value from a variant.
|
4,539,640 | 4,539,673 | c++ validate number and stop infinity loop | I'm doing a console app, I'm passing an integer to the app and it works ok, but if I pass a letter, it goes crazy,
int opt=0;
std::cout<<"Pick lang:"<<'\n';
std::cout<<"1.[es-ES]:"<<'\n';
std::cout<<"2.[en-US]:"<<'\n';
std::cin >> opt;
while(opt<1 || opt>2)
{
std::cout<<"\nERROR!"<<'\n';
std::cout<<"Pick la... | After performing cin >> extraction, you want to check if the cin stream is still good or not. If you expect cin to extract a number but it gets something else instead, eg. like a letter, then the stream will be set to a bad state and that's why you see it 'going crazy'.
What you have to do is after input, check if cin ... |
4,539,876 | 4,540,330 | Is it possible to program for Windows Phone 7 in standard C++ only? | I know that the recommended language for Windows Phone 7 development is C#.
However, for various reasons, I very much prefer continuing to program in standard C++, if possible.
Is it possible to program for Windows Phone 7 in standard C++ only?
If the answer is yes, what tools and resources do I need to accomplish that... | EDIT, finally: for WP7 it won't ever be, but for Windows Phone 8 - yes you can. Native apps, C/C++, iOS/Android portability and code sharing, DirectX. You'll need Visual Studio 2012 and Windows 8 for WP8 development, though. VS2010 is not getting the requisite SDK. To run the emulator, you'll need a 64-bit physical Win... |
4,539,995 | 4,540,150 | weirdest bug ever - int definition causes sigsegv. stack overflow? | I'm using the BSPlib and when adding a simple definition of "int i" on the function running on multiple threads (along with many other) I get a message like "Process 2 caught SIGNAL 11 Segmantation fault ". it's important to note that I checked alot and without it I don't get the segmentation fault and with it I get it... | Your declaration/initialization of the table variable is incorrect. You are initializing it as an array of arrays (i.e. as n+1 distinct memory blocks), whereas you are telling bsplib that it is a a contiguous memory block of n*n ints. You either need to change your allocation or the registration.
As a consequence, bspl... |
4,540,138 | 4,540,253 | How to implement escape Sequence in SDL | I'm trying to use the STL library inside the SDL. but it gives me the error
"undeclared identifier"
Is there any way I can use "\n"or even cout<<endl;
Can the function SDL_WarpMousewhich places the mouse cursor on a desired location on screen help me with this. Because I want to put a tile on the next line sequence.
I ... | cout and endl are in the std namespace and must be qualified:
std::cout << std::endl;
Alternatively, you can use a using declaration:
using std::cout;
using std::endl;
cout << endl;
|
4,540,499 | 4,540,549 | When CPP line splicing is undone within C++0x raw strings, is a conforming implementation required to preserve the original newline sequence? | The latest draft of C++0x, n3126, says:
Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines.
...
Within the r-char-sequence of a raw string literal, any transformations performed in
phases 1 and 2 (trigraphs, un... | Translation phase 1 starts with
Physical source file characters are
mapped, in an implementation-defined
manner, to the basic source character
set (introducing newline characters
for end-of-line indicators) if
necessary. Trigraph
sequences (2.3) are replaced [...]
I'd interpret the requirement "any transf... |
4,540,852 | 4,540,886 | clone a wchar_t* in c++ | I want to clone a path that is held in a var named szPath to a new wchar_t.
szPath is of the type wchar_t *. so i tried doing something like:
szPathNew = *szPath;
but this is referring to the same place in memory.
what should i do? i want to deep clone it.
| Do this,
wchar_t clone[260];
wcscpy(clone,szPath);
Or, if you want to allocate memory yourself,
wchar_t *clone = new wchar_t[wcslen(szPath)+1];
wcscpy(clone,szPath);
//use it
delete []clone;
Check out : strcpy, wcscpy, _mbscpy at MSDN
However, if your implementation doesn't necessarily require raw pointers/array, the... |
4,540,932 | 4,544,361 | IWebPreferences for each WebView | I am trying to disable image auto loading of some WebViews while I keep others enabled. However when I disable it for a WebView, all webviews stop loading image. Below is code I use:
IWebPreferences *prefs = NULL;
webView->preferences(&prefs);
prefs->setLoadsImagesAutomatically(false);
prefs->Release();
What is the pr... | Just use different identifier for each webview using initWithIdentifier
|
4,541,130 | 4,541,290 | Definitions of sqrt, sin, cos, pow etc. in cmath | Are there any definitions of functions like sqrt(), sin(), cos(), tan(), log(), exp() (these from math.h/cmath) available ?
I just wanted to know how do they work.
| This is an interesting question, but reading sources of efficient libraries won't get you very far unless you happen to know the method used.
Here are some pointers to help you understand the classical methods. My information is by no means accurate. The following methods are only the classical ones, particular impleme... |
4,541,157 | 4,541,252 | Why neither constructor nor assignment operator executed when declaring object? | The test program is
#include <iostream>
using namespace std;
class A
{public:
A (): I(0) {cout << "default construcot" << endl; };
explicit A (int i): I(i) {cout << "another construcot" << endl; };
A (const A& a): I(a.I) {cout << "copy constructor" << endl; }
A& operator = (const A& a)
... |
Why
The standard allows the compiler to optimize away the copy construction. Not this is NOT an assignment as it is part of the declaration (so if the optimization was not done it would result in a temporary object and then a copy construction of the temporary into a).
Is there a way to force execution of assignment... |
4,541,345 | 4,541,362 | why use c++ Typedef? | My understanding of typedef is to give a declaration an alias.
Such the declaration for int will now be referred to as Integer. But why? Why would someone use typedef? What's the more advantageous reason?
typedef int Integer;
Integer blamo = 50;
cout << blamo << endl;
| that isn't a good example because Integer and int don't have any different meaning. But imagine something like,
typedef int BlamoType;
Now, in the future when 'blamo' becomes a 64-bit integer, you can just change this typedef, and all other code stays the same.
Another reason for typedef is to shorten type names. For ... |
4,541,399 | 4,543,424 | Grabbing events on specific keys with X11 on Linux | I'm writing a program in C++ to implement the keyboard backlight feature from OS X on MacBook Pro's running a Linux distro. So far, it turns the backlight on, on boot and if no keyboard and mouse events are registered for 20 seconds, it will turn it back off, and of course turn it on yet again when an event is register... | The normal way to do this is with XGrabKey(). It uses keycodes, but you wouldn't hardcode the keycode, you'd get it with XKeysymToKeycode(). To be more correct you'd also want to redo the grab when you get a MappingNotify (XMappingEvent). (Note, MappingNotify, not MapNotify.) If there isn't a keysym for these keys - th... |
4,541,423 | 4,541,450 | C++ int & long marshalling in C# | I'm currently porting a proprietary dll (an API) to C#, and I have some problems when marshalling some of the used data types.
For example the API header file defines the following types:
typedef unsigned int tINT; /* natural unsigned */
typedef signed int tINTs; /* natural signed */
typedef unsigned int tLONG; /... | Try to Marshal it as an IntPtr. IntPtr is 4 bytes on a 32bit system and 8 bytes on a 64bit system in .Net.
|
4,541,457 | 4,541,523 | Determining where a type is defined | I am working on a rather large code base that has a bit of the #ifdef magic going on. I'm looking at one file and trying to determine where a type is defined. Unfortunately, it includes many file, which include many files, which include many files, etc. some of which define macros that affect which definitions you mi... | With complicated defines and dependencies this feature doesn't always work in Visual Studio either.
Solution: ask your compiler to dump the code after it was preprocessed, ask it to print #line and #file directives too. Search through the resulted file for your type, then look at the closest #file directive to see wher... |
4,541,556 | 4,541,707 | Pushing an array into a vector | I've a 2d array, say A[2][3]={{1,2,3},{4,5,6}}; and I want to push it into a 2D vector(vector of vectors). I know you can use two for loops to push the elements one by on on to the first vector and then push that into the another vector which makes it 2d vector but I was wondering if there is any way in C++ to do this ... | The new C++0x standard defines initializer_lists which allows you to:
vector<vector<int>> myvector = {{1,2,3},{4,5,6}};
gcc 4.3+ and some other compilers have partial C++0x support.
for gcc 4.3+ you could enable c++0x support by adding the flag -std=c++0x
Its not the best way to have your static data represented like ... |
4,541,717 | 4,541,761 | Non-Type parameters for templates |
Possible Duplicate:
What does template <unsigned int N> mean?
Hi ! Are non-type template parameters and constants same ? Do the following code work because template parameter cannot be modified ? If can be modified, the compiler should have thrown error while declaring array "a[T]". Is my understanding correct ?
tem... | Yeah, kind of. Thing is every time you instantiate a template the compiler will generate specific code for that specific type parametrization. So for instance, in your example if you have foo<3> and foo<5> the compiler will generate code for two separate functions one where T=3 and one where T=5
So yeah, it works becau... |
4,542,067 | 4,889,285 | Qt and variadic functions | OK, before lecturing me on the use of C-style variadic functions in C++...everything else has turned out to require nothing short of rewriting the Qt MOC.
What I'd like to know is whether or not you can have a "slot" in a Qt object that takes an arbitrary amount/type of arguments. The thing is that I really want to be... | Apparently people keep thinking this question is still in need of answer because several weeks after I asked it and then answered it myself, people are still posting their responses. So I guess I have to make it explicitly an answer instead of both in the question itself and the first comment for it:
You can't use a v... |
4,542,100 | 4,542,643 | C++, Inheriting template nested class | Trying to get tensor_ref<A>::result visible in tensor_view.
template<class A, class Range, class = void>
struct tensor_view
: detail::tensor_ref<A>,
const_tensor_view<A, Range, tensor_view<A, Range> >
{
using detail::tensor_ref<A>::result;
...
template<class A>
struct tensor_ref<A, typename same_rank<A,N>:... | This doesn't work and it isn't intended to make it work for any further revision of C++.
So you cannot have that using declaration - use the ordinary tensor_view::template result way when using it, instead.
|
4,542,354 | 4,542,377 | C++ print out a binary search tree | Got nothing better to do this Christmas holiday, so I decided to try out making a binary search tree. I'm stuck with the print function. How should the logic behind it work? Since the tree is already inserting it in a somewhat sorted order, and I want to print the tree from smallest values to the biggest.
So I need to ... | You can use recursion (pseudocode):
prin-tree(node):
print-tree(left-subnode) if exists
print(node-value)
print-tree(right-subnode) if exists
...
print(root-of-tree)
|
4,542,521 | 4,542,530 | How do you convert LPCWSTR to const char *? | How do you convert LPCWSTR to const char *?
Thanks
| Use the WideCharToMultiByte function.
Note that LPCWSTR is the same as const wchar_t *, so if you're dealing with wide character data throughout your application, you may not need to convert it at all.
|
4,542,626 | 4,542,689 | Documenting Macro Functions in C++ with Doxygen | How do I document a macro function in C++ using Doxygen, and refer to it in the documentation of my non-Evil code?
More specifically, I have some regular class called "Message" defined in Message.H that users can inherit from to define their own messages. In another file ("MessageHelpers.H") I have a crazy macro like t... | See http://www.doxygen.nl/manual/index.html
The section "Special Commands" lists the \def command, and the section "Automatic link generation" describes what you want to link to the macro.
Use \def to document a macro separate from the declaration.
Use #MACRO(params) to auto-link to said macro definition.
|
4,542,726 | 4,542,733 | get function ptr to member function of instanced class? | class gfx {
void resize(int x, int y);
}
gfx g;
can i cast g.resize to a 'void (*)(int, int)' somehow?
| No. gfx::resize is of type void(gfx::*)(int, int). You can't meaningfully convert it to type void(*)(int, int) because you can only call it as a member function on an object of type gfx.
A member function can only be called on an instance of the class, so given your gfx g;, you can call g.resize(), but you can't just ... |
4,542,789 | 4,542,813 | C++: non-temporary const reference | I need to write a class whose constructor takes a constant reference to a object and stores it locally.
In order to avoid most common mistakes I can foresee, I'd like to only accept references to non-temporary (ie: references to lvalues).
How can I write a function that takes constant references to non-temporary only?
... | If you are going to store a reference and need to use it after the constructor has completed, it's probably best for the constructor to take a pointer:
struct C {
C(const X* p) : p_(p) { }
const X* p_;
};
This way, it's pretty much guaranteed that you won't have a pointer to a temporary (unless X does somethi... |
4,542,900 | 4,543,050 | Win32 -- Object cleanup and global variables | I've got a question about global variables and object cleanup in c++.
For example, look at the code here;
case WM_PAINT:
paintText(&hWnd);
break;
void paintText(HWND* hWnd) {
PAINTSTRUCT ps;
HBRUSH hbruzh = CreateSolidBrush(RGB(0,0,0));
HDC hdz = BeginPaint(*hWnd,&ps);
char s1[] = "Na... | 1.- You should delete all object for which you create a HANDLE. If the object was created by using a WIN32 function it should be released by using another WIN32 function. PAINTSTRUCT is a variable created on the Stack so it will be deleted when the functions scope ends.
2.- There is a rule that says: declare a variable... |
4,542,944 | 4,543,044 | Qt how do I wait/know when a QMainWindow is closed? | How do I know when a QMainWindow is closed ? So I can update a list in another window...
It would be perfect to be able to wait until it closes.
account.h:
class account : public QMainWindow
{
//...
accounts.h
class accounts : public QMainWindow
{
//...
public:
account accWin;
//...
accounts.cpp
//...
void account... | You could override QWidget::closeEvent(QCloseEvent*) for your QMainWindow and do your list updating there. closeEvent will be called when your window receives a close request (i.e. while it is still visible).
Alternatively, you could hook up to your window's QObject::destroyed(QObject*) signal.
|
4,543,497 | 4,543,632 | symbolic computation | Does anyone know a good approach/libs for doing algebraic computations in C++?
I have an application being developed in c++ which needs to do algebraic computation. For now I built a C++ parser that accepts expressions in form of strings like "5 + (2 - MYFUNC(3))" which get tokenized into structs and then converted in... | Have a look on Bison and Flex Parser. The basic idea here is that a grammar file would be written and converted into C code which can be integrated into you application. Any book on Flex and Bison (http://www.amazon.com/Flex-Bison-Text-Processing-Tools/dp/0596155972) is good enough for initial reading.
May be this help... |
4,543,537 | 4,543,566 | In C++, should I almost always use virtual inheritance? | I see from this entry that virtual inheritance adds sizeof(pointer) to an object's memory footprint. Other than that, are there any drawbacks to me just using virtual inheritance by default, and conventional inheritance only when needed? It seems like it'd lead to more future-proof class design, but maybe I'm missing s... | The drawbacks are that
All classes will have to initialize all its virtual bases all the time (e.g. if A is virtual base of B, and C derives from B, it also have to initialize A itself).
You have to use more expensive dynamic_cast everywhere you use a static_cast (may or may not be the issue, depending on your system ... |
4,543,552 | 4,543,586 | Is it safe for me to manage memory of a dll class if I call new and delete? | If my DLL has the implementation of one of my classes, if I do new and delete on it is that okay? When is the problem regarding DLLs and who allocates what?
What if that class calls new?
class InDLL {
A* something;
InDLL()
{
something = new A;
}
};
...
//me
InDLL dll = new InD... | The one important rule is that whoever allocates memory is responsible for freeing that memory, using the same allocator. There are no restrictions on how the memory must be allocated (it can be allocated by the main executable, by your DLL, or by some other DLL), but once it's allocated, the same module must free it.... |
4,543,670 | 4,543,673 | Question of using static_cast on "this" pointer in a derived object to base class | this is an example taken from Effective C++ 3ed, it says that if the static_cast is used this way, the base part of the object is copied, and the call is invoked from that part. I wanted to understand what is happening under the hood, will anyone help?
class Window { // base class
public... | This:
static_cast<Window>(*this).onResize();
is effectively the same as this:
{
Window w = *this;
w.onResize();
} // w.~Window() is called to destroy 'w'
The first line creates a copy of the Window base class subobject of the SpecialWindow object pointed to by this. The second line calls onResize() on that... |
4,543,675 | 4,543,778 | Problem with converting IP addresses in C++ | I need to find the IP address of my node in my code. Currently, I have this line:this line:
IPv4Address addr = nb_ipv4->GetAddress (maininterface , 0);
In this line, I expect to get the IP address for my main interface, but instead I see this error:
error:conversion from 'ns3::Ipv4InterfaceAddress' to non-scalar type... | I think that must be tagged as C++, and (if it is The ns-3 network simulator) you must do this:
IPv4Address addr = nb_ipv4->GetAddress(maininterface).GetLocal();
|
4,543,682 | 4,544,714 | What are the basics of networking for a 3D game in C++? | In a few weeks I'm thinking of helping a project finish a pretty major aspect of a C++ world with 3D characters: networking. I will help with the server's transfer of information from/to clients. I already know C++ well enough. I just need to know what specifically I should know to do this and resources from which I co... | as RageD said, it's a big difference in networking between different types of games. A FPS server typically sends complete game state to all clients regularly (e.g. 60Hz) over UDP. Other game types can use TCP (tuned a bit like TCP_NODELAY and forcing immediate ACK packets) or reliable UDP (raknet lib or others). Netwo... |
4,544,162 | 4,544,573 | Make tabs movable in Qt | I want to make an application in Qt where the tabs in the QTabBar can be "undocked" so they will become a floating window, or can be dragged into another QTabBar and "transfer" into that QTabBar. My aim is to let the user completely customize the interface by dragging modules around into each other.
If you have ever us... | Take a look to the Qt Main Window Demo it uses QDockWidget rather than QTabBar's.
This example should be included the QTDIR/demos/ folder of your Qt installation.
You will see that there are no tabs in the window, but try to drag some dock and drop it over another dock an you will see that a tabbar is created. Also the... |
4,544,234 | 4,567,919 | Calling pthread_cond_signal without locking mutex | I read somewhere that we should lock the mutex before calling pthread_cond_signal and unlock the mutex after calling it:
The pthread_cond_signal() routine is
used to signal (or wake up) another
thread which is waiting on the
condition variable. It should be
called after mutex is locked, and must
unlock mutex in order ... | If you do not lock the mutex in the codepath that changes the condition and signals, you can lose wakeups. Consider this pair of processes:
Process A:
pthread_mutex_lock(&mutex);
while (condition == FALSE)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
Process B (incorrect):
condition = TRUE;
pth... |
4,544,237 | 4,547,065 | How to access the accelerometer of a Windows Mobile device? | I've successfully ported my Qt-based C++ application to my girlfriend's Windows Mobile device. (A Samsung Omnia 2.)
However, it seems that the Qt Mobility Sensors API is not supported on Windows Mobile, so the application's specific features that would require the accelerometer are not working.
The question is, how to ... | If your Omnia 2 has WM 6.5 Update you may use the unified sensor API here
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.