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 |
|---|---|---|---|---|
6,947,078 | 6,947,907 | C++ get appdata path of other users | In my program I have been using SHGetFolderPath to get the AppData path. However I need to get the AppData path of the other users on the computer. The only way I can think to do it is to get the path for the current user, and then replace the current user's name with the other users names. I don't know how to get a li... | For your situation I would recommend the following:
Continue to store configuration files in AppData, but store it in CSIDL_COMMON_APPDATA (SHGetFolderPath). This AppData is shared with all users. Your setup program (or an administrator user) can set up a folder in this location named after your program that gives "... |
6,947,322 | 6,947,401 | bitsets in C++ using VS2010 | I can't figure out if I'm doing anything wrong here, hopefully someone here can enlighten me.
I have a class Flags, this is an extremely simplified version but I declare a bitset
class Flags
{
private:
//List of 8 bits
std::bitset<8> _P;
public:
Flags();
}
On my constructor I initialise it as
Flags::Flags(... | It's a bug in VC according to http://connect.microsoft.com/VisualStudio/feedback/details/532897/problems-constructing-a-bitset-from-an-unsigned-long-in-the-vc-rc
Also note that identifiers starting with _ and a capital letter are reserved for the implementation and illegal to use in your program.
EDIT: According to the... |
6,947,400 | 6,947,578 | Counte elements (size) of array of objects | I am doing this learning/practicing with arrays of objects and array of pointers to objects and I'm very confused about how to get dynamic arrays sizes.
I've got this:
private:
Client ** arr_client;
public:
static string members [];
then populated the array arr_client with tokenized data from the following ... | First, I applaud you for trying to learn the fundamentals before adopting an advanced tool like vector.
There's no clean and reliable way to do what you ask. People usually remember the size of an array in a separate variable, like this:
unsigned int num_strings=3;
static string members[num_strings];
If you really wa... |
6,947,612 | 6,953,958 | Generating m distinct random numbers in the range [0..n-1] | I have two methods of generating m distinct random numbers in the range [0..n-1]
Method 1:
//C++-ish pseudocode
int result[m];
for(i = 0; i < m; ++i)
{
int r;
do
{
r = rand()%n;
}while(r is found in result array at indices from 0 to i)
result[i] = r;
}
Method 2:
//C++-ish pseudocode
int arr[n];... | Pure mathematics:
Let's calculate the quantity of rand() function calls in both cases and compare the results:
Case 1:
let's see the mathematical expectation of calls on step i = k, when you already have k numbers chosen. The probability to get a number with one rand() call is equal to p = (n-k)/n. We need to know the ... |
6,947,654 | 6,947,780 | c++ const on a collection | I was surprised when the declaration:
const std::map<double, Foo*> myCollection;
would not allow me to call non-const methods on Foo*. I thought the const applied to the collection itself (i.e., no items could be added or removed). I would think the way to convey item const would be:
std::map<double, Foo const*> myC... | You must be doing something wrong -- operator[] on std::map is not declared const, so it cannot be used to access elements of the map. The reason it's not const is because if the key isn't present in the map, it gets added to the map with a default-constructed value, and doing so modifies the map.
Instead, use the fin... |
6,947,783 | 6,948,592 | bitsets in C++ using VS2010 (another) | I just asked another question about bitsets which turns out to be a bug in VS2010
bitsets in C++ using VS2010
However upon changing the constructor I used for the bitset I've run into another problem (as described in the edit of the other question)
When using the default constructor for a bitset, it isn't being initial... | Solved it
I have this array (note the index)
void (MPU::*_STY[0x94])(BIT_8 ** pSource, const BIT_8 args[]); // STY
This is in my assignment list (note the index)
_STY[0x94] = &MPU::ZeroPageX_SourceOnly;
I think I just learnt my lesson
|
6,947,805 | 6,947,828 | block non-specialized template c++ | Is it possible to somehow forbid using templated function for types for which specialization was not explicitly written. I mean something like that
template <typename T>
void foo(){}
template <>
void foo<int>(){}
int main(int argc, char* argv[]){
foo<int>(); //ok
foo<char>(); //Wrong - no specialized version ... | Sure: just don't define it and you'll get a linker error if you try to use it:
template <typename T>
void foo(); // not defined
template <>
void foo<int>() { }
Alternatively, you can use some variation of a static assert to give a "nicer" compile-time error. Here is an example using the C++0x static_assert. Note t... |
6,948,438 | 6,948,531 | stacktrace and functions in namespaces | I am trying to get a backtrace at some point of the execution of my (c++) program.
for that I am using backtrace and backtrace_symbols. Something along this lines:
std::string stacktrace( unsigned int frames_to_skip )
{
std::string str;
void* stack_addrs[50];
int trace_size = backtrace( stack_addrs, 50 );
... | Your problem may be the functions you are using. Your max_depth in backtrace(..) is set to 16. That may be too low. At any rate...
This blog post on C++ stack traces with GCC explains how you should be performing stack traces. In sum,
#include <execinfo.h>
void print_trace(FILE *out, const char *file, int line)
{
c... |
6,948,887 | 6,948,943 | Using a namespace only inside one specific class file | This is a rather simple question more or less considering syntax semantics.
I've got a class inside a namespace, which uses a lot of classes out of another namespace:
namespace SomeNamespace
{
class MyClass
{
//...
//These types of namespace uses occur alot around here:
void DoSomething(const a... | This does what you want. Both namespaces are accessible to MyClass. using namespace is bad practice in headers though.
namespace SomeNamespace {
namespace other {
using namespace anothernamespace;
class MyClass {
};
}}
namespace SomeNamepace {
typedef other::MyClass MyClass;
}
You really should prefer speci... |
6,949,077 | 6,952,751 | Only one material applied to multiple objects | It turns out I was just being an idiot; this code works fine, it's just the data that was incorrect
N.B. If any of @datenwolf's comments or answers don't make sense, it's because I've started this question again; it's difficult to phrase.
I'm writing an OpenGL Wavefont object loader. I can load and display the model, a... | I assume the loop of the first snippet is within, or gets called by model_draw. But it would help if I knew the context of that render loop (the function in which the render loop is).
So there are two basic mistakes, not directly related to rendering a specific model, but about transformation setup.
You call gluLookAt ... |
6,949,150 | 6,949,288 | Why a segmentation fault for changing a non-const char*? | With this code, I get a segmentation fault:
char* inputStr = "abcde";
*(inputStr+1)='f';
If the code was:
const char* inputStr = "abcde";
*(inputStr+1)='f';
I will get compile error for "assigning read-only location".
However, for the first case, there is no compile error; just the segmentation fault when... | Here is what the standard says about string literals in section [2.13.4/2]:
A string literal that does not begin with u, U, or L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n const char”, where n is the size of the string as defined below; i... |
6,949,306 | 6,949,514 | Can std::find function use for our own classes? | I have set of classes. Each class is inherited from another class. The relationship is as follows. (I am just posting how one class inherited from another class, just to get idea for all of you)
class LineNumberList : public MyVector <LineNumber > //top class
class MyVector : public std::vector <Type>
class LineNumber ... | "I tried with standard find function, but it doesn’t work." Works for me:
#include <vector>
#include <iostream>
#include <algorithm>
class ElementNumber {
protected:
int number;
public:
ElementNumber(int p) :number(p) {}
bool operator==(const ElementNumber&e) { return number == e.number; }
};
class Li... |
6,949,360 | 6,952,853 | MFC share one static label on all the views of the application | I am working on a C++ MFC application. I am wondering if I can make a Static label or button that can exist in all the Views of the application without re-writing code.
I want this label to appear on almost all the views of the application and update dynamically depending on the user actions.
Thanks in advance.
| I think the easiest way to do what you want would be to create a base class view with the button or label created programmatically (rather than using the resource editor) as member variables. Then inherit all your other views from that base class and you'll still have the button/label to show, hide or update as necess... |
6,949,560 | 6,949,816 | Hooking sendto() causes crash depending on code ordering | I'm using a DLL-injector to inject a dll which goes into the IAT and replaces the system call sendto() with my own.
This is the replace method.
void replaceFunction(DWORD f, DWORD nf)
{
// Base address.
HMODULE hMod = GetModuleHandle(NULL);
// DOS Header.
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)hMod;
// NT ... | Your calling convention is incorrect. The default calling convention for C++ is __cdecl, but sendto's calling convention is __stdcall. Change the calling convention of my_sendto to __stdcall to fix the crash.
|
6,949,611 | 6,949,670 | Question about variables with combination of extern and const | I googled const + extern on the internet, but it seems there isn't really a good answer for my question.
const alone means internal linkage, but if I want to share a const variable among compilation units. Is extern the best choice?
Common solution would be:
//g.h
extern const int MAX;
// g.c
extern const int MAX = 3... | if you want to be able to use your constant at compile time (i.e. size an array by it, without using VLA) it has to be known at compile time, i.e. it cannot have external linkage.
However, you could just declare your constant in your header file, and make it available to anyone including it. Still, that won't have the ... |
6,949,777 | 6,949,801 | Dynamic Structure in C++ | struct testing
{
char lastname[20];
};
testing *pt = new testing;
pt->lastname = "McLove";
and I got
56 C:\Users\Daniel\Documents\Untitled2.cpp incompatible types in
assignment of 'const char[7]' to 'char[20]'
Why ?
Thanks in advance.
| Because compile time arrays are constant. In your struct testing, you have an array of 20 chars, and you're trying to assign a pointer ("McLove", a compile time string, e.g., a const char*) to an array (a char[]), which won't work.
To copy the data "McLove" into the array, you need to use strncpy:
strncpy(pt->lastname,... |
6,949,986 | 6,949,993 | C++ std::map Intristic Type Initialization Using [] Operator | What a title, suppose I have a map like this:
std::map<int, int> m;
and if I write the following
cout<<m[4];
What will be the result (0, uninitialized, compiler specific)?
Does the same applies for pointers (i.e. std::map)?
EDIT:
To clarify, in this question I am seeking for standard behavior.
Thanks in advance,... | The value will be what the default constructor for the type creates, because new spots are filled using T(). For int, this is 0. You can see this for yourself:
#include <iostream>
using namespace std;
int main() {
cout << int() << endl; // prints 0
}
Initializing a type like with empty parentheses like this is c... |
6,950,055 | 6,950,099 | c++ exception safety | Exceptional C++ mentions the following code
template <class T> class Stack
{
public:
Stack();
~Stack();
/*...*/
private:
T* v_; // ptr to a memory area big
size_t vsize_; // enough for 'vsize_' T's
size_t vused_; // # of T's actually in use
};
template<cl... | Quoting the C++03 standard, §5.3.4/8:
A new-expression obtains storage for the object by calling an allocation function. If the new-expression terminates by throwing an exception, it may release storage by calling a deallocation function. If the allocated type is a non-array type, the allocation function’s name is ope... |
6,950,335 | 6,950,341 | ordered version of unordered_map? | In my following program I'm currently using unordered_map just because I wanted O(1) search/insert time. But now I wanted the items to be ordered. Sorting it every time is very inefficient. What are my alternatives ? I read that hash_map does the job but the articles i read are very confusing or rather complicated for ... | Just use a regular std::map. Note this means you need ordering instead of hashing.
An unordered_map is a hash_map, by the way. "Unordered" just captures the conceptual difference rather than the implementation difference, so it's a better name.
|
6,950,353 | 6,950,610 | Random Access in multimap's value, or should I just use map of vector | I was wondering, is there any way to perform random access in multimap's values.
#include <map>
#include <vector>
#include <string>
int main() {
std::map<std::string, std::vector<std::string>> m0;
m0["Food"].push_back("Ice Cream");
m0["Food"].push_back("Pizza");
// Random access to Pizza. Nice!
p... | std::multimap<>'s iterators are strictly bidirectional (§23.3.2/1), so no, random-access between values with the same key is not possible.
|
6,950,381 | 6,950,488 | Is there anything special I need to do to use C code in my C++ program? | Note: I am using g++ version 4.3.4 to compile my C++ code.
So far, whenever I've wanted to use C style language elements in my code it seems that I can just include the C stuff mixed in and alongside my C++.
I know C++ is mostly backwards compatible with C... so I guess my questions are these:
What parts of C are not... | Picking out a couple of questions:
"What is the proper way to have C and C++ code in the same .cpp file?"
"Can I continue to use g++ to compile my hybrid code?"
If you want to mix C-style C++ in the same file as regular C++, just go ahead and do it. You can trust the compiler to pick up any issues - they will be minima... |
6,950,406 | 6,950,485 | Explain this algorithm (Compare points in SURF algorithm) | I need to know if this algorithm is a known one:
void getMatches(IpVec &ipts1, IpVec &ipts2, IpPairVec &matches, float ratio) {
float dist, d1, d2;
Ipoint *match;
matches.clear();
for (unsigned int i = 0; i < ipts1.size(); i++) {
d1 = d2 = FLT_MAX;
for (unsigned int j = 0; j < ipts2.s... | You've asked a lot of questions and I don't think I can answer all of them, but here are answers to as much of your question as I can.
This is most certainly a nearest-neighbor algorithm where the goal is to find the two closest points to each point in the first vector and then check whether the ratio of their distanc... |
6,950,587 | 6,950,848 | How to extract/create a JointDef based off a b2Joint instantiation | I'm trying to serialize a b2World, and due to Box2D's many private objects that are used, made, and deleted internally, the issue becomes much more complicated. I decided that i should use these internal objects get() functions to get the data i need, and create a "b2Definition" object based off it at save time, and us... | I did a lot of this recently to make an export/import utility to serialize a Box2D world to JSON and then load it again. You may find the source code useful - check out http://www.iforce2d.net/b2djson Scroll towards the bottom and you can see the source code, look at the function b2dJson::b2j(b2Joint* joint)
It's not c... |
6,950,630 | 6,950,676 | C++ Analogue for WPF | So I've fooled around with WPF a bit recently, and I must say that I really like the idea. I love the framework as a whole, from the GUI to the plumbing.
However, as much as I love managed land, I love my native code just as much. So I'm wondering what sort of libraries exists for C++ which capture the essence of vario... |
There isn't really anything like this. Not cross-platform at any rate. Direct2D works reasonably well, but is obviously Windows-only. And NVIDIA recently dropped this "path" extension of OpenGL that is similar in basic functionality, but it is NVIDIA-only (and not available on Mac OSX). Cairo has an OpenGL backend, bu... |
6,950,826 | 6,951,066 | Qt Button Handling Advice | I have come to the point where I am tired of how I am handling user input in Qt (namely QPushButton presses) and I am looking for advice on the best method in which to handle these events.
Below is an example of what I am currently doing:
MyClass.h
class MyClass : public QMainWindow
{
Q_OBJECT
public:
...
... | You are actually using the standard way of handling button presses in Qt. The only other way that I'm aware of is by having MyClass be an event filter for the buttons, that seems like overkill in this case.
The only change I would make to your code is to put the signal -> slot connections in MyClass itself. In this exa... |
6,950,977 | 6,960,912 | Tesseract - change language file location | I am making an AIR project, which will need some OCR capabilities, so i decided to use tesseract (now i try to get it working on Windows).
My problem is, that can not change the location of the language file - it always tries to look in my Tesseract installation directory (program files (x86)\Tesseract-OCR\tessdata\m... | I have solved the problem by rewriting the source code of Tesseract (im using SVN 597). As nguyenq said, Tesseract tries to look for the data at the path set by the TESSDATA_PREFIX environment variable. If this is not found, then it does some trickery i dont understand :) .
So if anyone needs a portable version of Tess... |
6,951,044 | 6,951,579 | Difference in Compiler Behaviour in case of VIRTUAL Functions in C# and C++. This i was asked in a Interview | How does the Virtual Differs in C++ and c#? basically i wanted to know is there any difference in the way Vtable is represented in C# and c++? Also is there any difference in the way the compiler creates the V Table in C# and c++?
Basically the interviewer wanted to know how does the compiler behaviour differrs for vi... | (1) In C# one can choose to override a virtual function from base class. Both base and derived methods can have same syntax, but derived method can participate in polymorphism only if it uses the keyword override before it. See this answer for more details.
In C++, if provided the same syntax method in derived class as... |
6,951,161 | 6,951,203 | Downloading multiple files with libcurl in C++ | I am currently trying to make an updater for my software project. I need it to be able to download multiple files, I don't mind if they download in sync or one after each other, whatever is easier (file size is not an issue). I followed the example from the libcurl webpage and a few other resources and came up with thi... |
Why not put this in a function and call it twice?
Your syntax for the arrays is all wrong, plus all the variables inside the loop are local, which means they are destroyed after each loop iteration.
What Conspicuous Compiler said. That's what's causing your program to freeze; it's stuck in an infinite loop because i i... |
6,951,639 | 6,951,655 | C++ Fstream Only Prints One Word | This is a very strange issue. I'm trying to print a large text file, it's a Wikipedia entry. It happens to be the page on Velocity. So, when I tell it to print the file, it prints "In", when it should print "In physics, velocity is etc, etc etc".
Here's the code I'm using to print out:
#include <iostream>
#include <fs... | wiki >> wikiRead;
The default delimiter for stream is space, so when the stream encounters a space, it simply stops reading, that is why it reads only one word.
If you want the stream to read all words, the you've to use a loop as:
char* wikiRead = new char[1024]; //must allocate some memory!
while(wiki >> wikiRead)
{... |
6,951,938 | 6,952,077 | libgmp-10.dll is missing | I recently installed MinGW on my 64-bit Windows 7 computer and when I attempt to compile the most basic of c++ programs, for example
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World" << endl;
return 0;
}
I get the error that "The program can't start because libgmp-10.dll is missing f... | Have you tried adding C:\MinGW\bin as a System variable Path (not PATH) in Settings->System Properties->Environment Variables?
I saw this solution on this page: Missing libgmp-10.dll
|
6,952,000 | 6,952,048 | Object oriented code,in non-object oriented language | Is this statement true??
Writing object oriented code, even in non-object oriented language.
Can anybody site an example.. or provide some links...
| Yes, you can do that, You can simulate OOP concepts like Inheritance and Polymorphism in a procedural language like c.
Since you ask for a Code Example, Here is one:
To simulate Inheritance all you need is the first member of a structure be an instance of the superclass, and then you can cast around pointers to base an... |
6,952,227 | 6,952,319 | Why does this code give segmentation fault? | I wrote a small example to test my understanding of pointers and memory, however I was sure this would work but then it gave seg fault... Any idea what I am doing wrong? Add: I ran this code with other code.
#include <iostream>
using namespace std;
struct Card {
int a;
Card(int a) : a(a) { }
};
int main() {
... | char ** cArray;
cArray is an unintialized pointer to pointer. You cannot de-reference it.
*(cArray + i) = "string";
|
6,952,305 | 6,952,332 | Is this a proper use of the logical "and" operator? | I'm looking at someone's code and they did:
if ( myNum > (num1 && num2 && num3) )
... with the intent of executing code when myNum is greater than num1, num2, and num3. Will this work?
edit: Thanks guys. I didn't think it would work, but I'm no expert, so I thought I'd ask people who are.
| No - certainly not in C# or Java, at least. You want:
if ((myName > num1) && (myNum > num2) && (myNum > num3))
(It's possible that you don't need the brackets here - I can never remember operator precedence.)
It wouldn't work as written in Java or C# as && is an operator on Boolean operands, with a Boolean result. It'... |
6,952,335 | 6,952,471 | Inspecting memory values | I have source code for a project that inspects a game's memory values. The thing I don't understand is this: How did the author so precisely determined the type and location of these values? For example, here's a struct he defined:
typedef struct {
UInt16 times_used; // 0x0
UInt16 token; // 0x2
SInt16 previ... | I hope I get this straight:
You look at 0x3bc2060 and the next 0x8b8 bytes/octets.
To reverse engineer a struct like this it is crucial to observe the program using this struct by filling it with values for the different fields in it.
Then you can deduce from many dumps starting at 0x3bc2060 and the following 0x8b8 by... |
6,952,399 | 6,952,515 | What is MVC and how to write MVC framework |
Possible Duplicates:
MVC approach with C++
What's the best way to learn mvc in PHP?
I have a heard a lot about mvc frameworks. I even tried to look for it on google and wikipedia. But still it is not clear to me.
Also, I want to know how can I implement it on my own, as by doing myself would make things more clear ... | MVC stands for Model View Controller, is a "style" of programming, it consists in dividing the classes ( Model ) that will make operations, the template/graphics (View) and the Controller. It helps writing good code because the View and the Model are separate, so you can write reusable code. The Controller makes the Mo... |
6,952,486 | 6,952,583 | Recommended way to insert elements into map |
Possible Duplicate:
In STL maps, is it better to use map::insert than []?
I was wondering, when I insert element into map, what is the recommended way. Should I
map[key] = value;
or
map.insert(std::pair<key_type, value_type>(key, value));
I did the following quick test:
#include <map>
#include <string>
#include <i... |
insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
operator[] needs the default constructor because the map... |
6,952,645 | 6,952,781 | getting seg fault while reading from a binary file that is created by the same code | I have written this code to make a binary file of float numbers, but I get a segmentation fault error at the end. It writes 9000 float numbers to the file but when reading it only reads 4096 of them. When I run the executable file a few times the number of bytes it reads switches between 4096, 8192 and 9000. but I have... | There is an error in your code. There is no need to take address of pointers.
//out.write((char *) &realRef, length*sizeof(float));
out.write((char *) realRef, length*sizeof(float));
//in.read((char *) &readTest, size);
in.read((char *) readTest, size);
|
6,952,820 | 6,952,887 | binary buffers for communication, c++ | If I need a binary buffer object,
like that used for TCP/UDP communication,
what would I base it on, in c++ ?
vector<unsigned char> ?
std::string ? -- std::string can hold 0-bytes, contrary to popular belief, so it can be used to hold binary data
new char[] ?
malloc() ?
Did anybody see std::vector used for binary buf... | A binary buffer can be just seen as a piece of memory that you reserve for storing some unstructured information.
In this sense, using new char[] and malloc are perfectly equivalent, IMO, in that they give you a piece of memory and a pointer to it.
Using std::vector is a different matter; aside from the cost, which I d... |
6,952,886 | 6,953,019 | Need to write specific lines of a text into a new text | I have numerical text data lines ranging between 1mb - 150 mb in size, i need to write lines of numbers related to heights, for example: heights=4 , new text must include lines: 1,5,9,13,17,21.... consequentially.
i have been trying to find a way to do this for a while now, tried using a list instead of vector which ... | You need to use seekg to set the position at the beginning of the file, once you have read it (you have read it once, to count the lines (which I don't think you actually need, as this size is never used, at least in this piece of code)
And what is the point if the inner while? On each loop, you have
int i=1;
myfile_... |
6,953,060 | 6,953,233 | Avoid Flickering on a dialog that moves its controls on resize | I have a popup dialog( CDialog ) that handles WM_CTLCOLOR message to color itself. It is having some controls (like bitmap buttons) that draws themselves using OwnerDraw. It is also having a control that displays an image with size that takes up to 70% of the dialog.
When user re-sizes the dialog, some of the controls ... | It will probably work, but you should try solutions that don't alter your control hierarchy before, because it has other subtle consequences (focus, tab order, message notifications, etc).
Try one or all of the following:
Use BeginDeferWindowPos/DeferWindowPos/EndDeferWindowPos functions to move the children.
Set the ... |
6,953,128 | 6,953,152 | Need iterator when using ranged-based for loops | Currently, I can only do ranged based loops with this:
for (auto& value : values)
But sometimes I need an iterator to the value, instead of a reference (For whatever reason). Is there any method without having to go through the whole vector comparing values?
| Use the old for loop as:
for (auto it = values.begin(); it != values.end(); ++it )
{
auto & value = *it;
//...
}
With this, you've value as well as iterator it. Use whatever you want to use.
EDIT:
Although I wouldn't recommended this, but if you want to use range-based for loop (yeah, For whatever reas... |
6,953,248 | 6,953,372 | Static, nonmember or static nonmember function? | Every time I have some functionality which is in the direction of "utility", I end up wondering which option is the best. For instance, printing message structs (own or external), some encoding/decoding code or simply a few useful conversion functions in the context I'm working.
The options I think about are:
1) Static... | The difference between options 2 and 3 is that in the second case, the function will be internal to the translation unit. If the function is only defined in the cpp this should be the option (which is roughly equivalent to an unnamed namespace --which is a fourth option to consider, again roughly equivalent to 3).
If t... |
6,953,319 | 6,953,443 | CreateThread failure on a longterm run | I'm writing a program in C++ using WINAPI to monitor certain directory for new files arriving, and send them in certain order. The files are derived from a live video stream, so there are 2 files in a unit - audio file and video file, and units should be sent in sequence. a. k. a. (1.mp3, 1.avi); (2.mp3, 2.avi)... Arc... | Using TerminateThread is a bad idea in many ways. In your case, it makes your program fail because it doesn't release the memory for the thread stack. Failure comes when your program has consumed all available virtual memory and CreateThread() cannot reserve enough memory for another thread. Only ever use TerminateT... |
6,953,405 | 7,280,264 | How to remove a child node from an XML file in C++ using Xerces-C? | root = doc->getDocumentElement();
child=root->getLastChild();
DOMNode* removedElement = root->removeChild(child);
removedElement->release();
The child is getting newline character as a node if the XML file is like this:
<root>
<child1> </child1>
<child2> text </child2>
</r... | Found the answer myself.
The understanding of DOM is different. The children of <root> in this case are the text nodes of root, child1, text node of child1, child2, text node of child2.
So the number of children of root is 5. But generally, as per XML notations, we thought they are 2.
So here when I try to remove the l... |
6,953,622 | 6,954,058 | questions about using NSURLConnection to download files and show the progress | I am trying to download files using NSURLConnection and show the download progress.
But I have some limitations and would like to ask if there's any way to solve this.
my file needs to be compiled in cpp file.
for example, I have written this interface to use NSURLConnection
@interface DownloadUtil : NSObject
<NSURLP... |
My first question is that if there's any way to use NSURLConnection in cpp.
There should be no problem with having an Objective-C pointer as a C++ class member. My guess is that you are actually including the header file where you declare PatchDownload in some other cpp file. Could you check this and if necessary sho... |
6,953,807 | 6,953,920 | identifying mouse double click or two single clicks based on coordinates | I'm sending mouseclicks to an ActiveX control in C++ one after the other (I'm using AutoDesk Design Review (a CAD system) and sending the clicks to draw an arc).
The only problem I'm having is that if two of the clicks are near each other it registers as a double click.
Is there a value in Windows which determines if ... | The Windows API does provide a way to determine the double-click time and the double-click rectangle:
GetDoubleClickTime() to get the double-click time.
GetSystemMetrics() with the SM_CXDOUBLECLK index to get the rectangle width.
GetSystemMetrics() with the SM_CYDOUBLECLK index to get the rectangle height.
According ... |
6,953,864 | 6,995,410 | Building libphp5.so for embedding in C/C++ | I've been trying to build and link libphp5.so using the --enable-embed configure option, on OSX. This doesn't complete successfully, failing primarily because of object files not being found during the linking stage.
There are reports that the --enable-embed option has been broken on OSX for a long time.
Has anybody ha... | I finally managed to do this after lots of failed attempts. Here is a configure string that will build the libphp5.a library on OSX for PHP 5.3.6:
./configure --enable-embed=static --disable-libxml --disable-dom --disable-simplexml --disable-xml --disable-xmlreader --disable-xmlwriter --without-pear --without-iconv
Th... |
6,953,969 | 6,954,070 | Can static_assert check if a type is a vector? | Can static_assert check if a type is a vector? IE, an int would raise the assertion, whereas a vector<int> would not.
I'm thinking of something along the lines of:
static_assert(decltype(T) == std::vector, "Some error")
| Yes. Consider the following meta function:
#include <stdio.h>
#include <vector>
template <class N>
struct is_vector { static const int value = 0; };
template <class N, class A>
struct is_vector<std::vector<N, A> > { static const int value = 1; };
int main()
{
printf("is_vector<int>: %d\n", is_vector<int>::value);... |
6,954,133 | 6,954,521 | When should I start to learn Qt? | I've been learning C++ for a month, and prior to that, C, just elementary C. Can I jump right in and learn Qt or should I spend more time on C++?
| I would always recommend learning C++ before learning and using Qt. Because you already had a little experience (a little because 1 month is a little) you can slowly go for Qt.
Just make sure that you're comfortable with using C++. The more confident you are in that language, the more you can concentrate on the Qt part... |
6,954,284 | 6,954,692 | Why prefer template-based static assert over typedef-based static assert? | There're two widely used implementations of static assert for versions of C++ that don't have built-in static_assert.
The first one is used in Boost and uses a template and a specialization of that template:
template <bool> struct static_assert;
template <> struct static_assert<true> {}; // only true is defined
#define... | I've generally used the second, or some variant of it, in my own code.
In practice, the Boost variant has the advantage that it can be used
anywhere an expression may appear, and not just at statement level. It
has the disadvantage that it can only be used where an expression may
appear, and thus not at namespace scop... |
6,954,377 | 6,954,419 | Is it OK to inject a specialization into the std namespace? | In this article on defining your own extensions to ::std::error_code the author recommends this code:
namespace std
{
template <>
struct is_error_code_enum<http_error>
: public true_type {};
}
in order to enable conversions from your own error constants to the system error type.
Is this reasonable? It always m... | Yep, specializations (for user-defined types) of existing std types are the only thing you're allowed to put in the std namespace, as long as the specialization meets the requirements for the original template.
See 17.6.4.2.1 in the C++0x draft.
New types, function overloads and anything else, of course, is forbidden. ... |
6,954,436 | 6,954,615 | sorting and extracting elements from the vector | Problem:
I have a class CPerson whose member variables are Age and Marks. I have created a vector of persons and populated with the objects. Now i want to extract only the persons who have scored 100 marks.
My Approach:
I tried to sort the vector based on marks and then looped through the vector to find the first posi... | It sounds like you need the remove_copy_if function, which could be better named as copy_if_not. Unfortunately, the copy_if function is missing from STL.
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
typedef int CPerson;
bool HasNotScoredHundred(const CPerson & pe... |
6,954,490 | 6,954,540 | How often should I call srand() in a C++ application? | I have a C++ application which calls rand() in various places. Do I need to initialize srand() regularly to ensure that rand() is reasonably random, or is it enough to call it once when the app starts?
| If you have only a single thread, seed once. If you reseed often, you might actually break some of the statistical properties of the random numbers. If you have multiple threads, don't use rand at all, but rather something threadsafe like drand48_r, which lets you maintain a per-thread state (so you can seed once per t... |
6,954,560 | 8,140,786 | boost::program_options : how to add a program description text | I would like that a text is printed before the description of the allowed options when I print my options_description. Something like :
This program counts from 1 to 10. <--- this is what is missing
Generic options:
-h [ --help ] Produce help message.
-v [ --version ] Show program name/version banner and... | The options_description class is for describing the options, not the program. The Program_options library isn't really intended for general-purpose documentation.
I suppose you could abuse the label:
po::options_description options(
"This program counts from 1 to 10.\n\nGeneric options");
|
6,954,571 | 6,954,611 | Breaking up a LPARAM variable & looking at groups of bits | I know that a LPARAM variable has certain bits set(inside it) that identify information such as long key presses & etc. when I receive a WM_KEYDOWN event.
So I am trying to break up a LPARAM variable & look at groups of individual bit values & groups of bits & that value(for eg looking at the 16th to the 24th bit & the... | In general, you use bitwise-AND to check if a certain bit is set:
unsigned int flags; // some flags
if (flags & 0x01) { } // bit 0 is set
if (flags & 0x02) { } // bit 1 is set
if (flags & 0x04) { } // bit 2 is set
...
if (flags & (1U << n)) { } // bit n is set
However, don't rely on the physical bit values. Instead,... |
6,954,749 | 6,954,808 | debug assertion failed using sprintf in c++ | I keep getting the "debug assertion failed" error when i debug my code
It seems to fail at the sprintf line in the function below:
void GetReference(int side)
{
for (int j=0; j<exposeNumber; j++)
{
image = cvQueryFrame(capture); // get the first frame of video
sprintf(fileName, "RefImage%i",... | fileName MUST be big enough. And a char*. And not NULL. For example:
char fileName[1024];
or
char* fileName = new char[ 1024 ];
//..
delete[] fileName;
Or something smaller here. As I see, I guess 32 or 64 would be big enough.
I'm pretty sure the assertion fails because of NULL (or 0, which is the same here) pointer ... |
6,954,820 | 6,955,634 | Two-way asynchronous communication in C++ | I'm trying to implement two-way asynchronous communication in C++. I'd like to be able to specify the IP address and port number on two machines and be able to get the machines to communicate with each other.
I've looked at Boost::asio and have implemented the following so far:
#include <cstdlib>
#include <iostream>
#i... | I've not used Boost.ASIO, but searching for "boost asio ip address" and "boost asio gethostbyname" yielded this stuff:
http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/reference/ip__address.html
http://www.boost.org/doc/libs/1_42_0/doc/html/boost_asio/reference/ip__tcp/resolver.html
The resolver has a resolve m... |
6,954,853 | 6,954,913 | C++ Binary file read issue | I was making a function to read a file containing some dumped data (sequence of 1 byte values). As the dumped values were 1 byte each, I read them as chars. I opened the file in binary mode, read the data as chars and did a casting into int (so I get the ascii codes). But the data read isn't correct (compared in a hex-... | I think, you might have to use unsigned char and unsigned int to get correct results. In your code, the bytes you read are interpreted as signed values. I assume you did not intend that.
|
6,954,906 | 6,955,332 | Does C++11 allow vector<const T>? | Container requirements have changed from C++03 to C++11. While C++03 had blanket requirements (e.g. copy constructibility and assignability for vector), C++11 defines fine-grained requirements on each container operation (section 23.2).
As a result, you can e.g. store a type that is copy-constructible but not assignabl... | No, I believe the allocator requirements say that T can be a "non-const, non-reference object type".
You wouldn't be able to do much with a vector of constant objects. And a const vector<T> would be almost the same anyway.
Many years later this quick-and-dirty answer still seems to be attracting comments and votes. No... |
6,954,921 | 6,954,946 | What is C# Equivalent to C++ STL fill method | In C++, we can set a range of values of an array(and other similar containers) using fill.
For example,
fill(number, number+n,10);
The above code will set the first n values of the array number with the value 10.
What is the closest C# equivalent to this.
| There's no equivalent method but there are many ways to write similar code
Methods from the Linq-to-Objects classes can create sequences that you can use to initialize lists but this is very different from how things in C++ actually occur.
new List<char>(Enumerable.Repeat('A', 10));
new List<int>(Enumerable.Range(1, 10... |
6,954,948 | 6,959,424 | how much time does it take to make a call to opencl? | I'm currently implementing an algorithm that does allot of linear algebra on small matrices and vectors. the code is fast but I'm wondering if it would make sense to implement it on a gpgpu instead of the cpu.
I'm able to store most of the matrices and vectors in the gpu memory as a preprocessing step, and have profil... | It is hard to determine the exact "overhead" of calling OpenCL, because operations on the GPU can be done in parallel with whatever else is running on the CPU.
Depending on your application, you can, for example, do a transfer of a chunk of data to the GPU from your application and in paralell do some preprocessing in ... |
6,954,949 | 6,955,251 | How to check if the iterator is initialized? | If I use a default constructor for an iterator, how to check if it was assigned later on?
For pointers, I could do this :
int *p = NULL;
/// some code
if ( NULL == p ) {
// do stuff
}
How do I do the above for iterators?
Is it possible at all?
#include <iostream>
#include <list>
int main ()
{
std::list<int>::... | I managed to find this in the current standard (c++03 ). 24.1 p 5 tells :
Just as a regular pointer to an array guarantees that there is a
pointer value pointing past the last element of the array, so for any
iterator type there is an iterator value that points past the last
element of a corresponding containe... |
6,955,014 | 14,294,264 | NURBS Library supporting trivariate NURBS | Does anyone know a free (as in free beer) C, C++ or even FORTRAN library that supports operations not only NURBS curves and surfaces but also Volumes (i.e. trivariate NURBS)?
I know about open nurbs, but as far as I know it does not support NURBS volumes (feel free to correct me on that, since my experiences with that... | IRIT modelling environment supports trivatiate spline volumes.
It is free, but only for non commercial uses. You can contact the developer and ask about the commercial licencing terms.
|
6,955,023 | 6,955,199 | c++ namespace best practice dilemma | I'm finding that what I've considered "best practice" for use namespace in c++ is hurting the readability of my code, and making me question how to use them well.
My program consists of a few different modules which are mostly built into libraries that the "main" application uses. Each library uses it's own namespace, ... | I have been in this situation before. It is often the case that a lot of template functions/classes in your headers are really "implementation", although by the nature of templates in C++ you are forced to put them in a header file. Thus, I just put everything in some "detail" or "implementation" namespace, where I can... |
6,955,114 | 6,955,200 | Is C notably faster than C++ | As far as I understand all scripting languages and core scientific programs are usually written in C; this renders the implementation messy yet in a way straight to the point.
I understand these people would like to max their performance but is there a real difference between using C strings and C structures to using C... | C++ is often used for scientific programs. The popularity of C may be waning in that domain. Fortran remains popular as a "low-level" language.
In C++, "you only pay for what you use." So there is nothing that would make it any slower than C. In particular for scientific programs, expression templates make it possible ... |
6,955,336 | 6,955,403 | C++ const reference member extending lifetime of object | This is related to a question posted yesterday.
class A
{
public:
mutable int x;
A()
{
static int i = 0;
x = i;
i++;
std::cout << " A()" << std::endl;
}
~A()
{
std::cout << "~A()" << std::endl;
}
void foo() const
{
x = 1;
};
};
class B... | This is undefined behavior, so there is no language standard explanation.
However, the destructor of A doesn't do anything to the memory area where x is stored, so if you look there later the value might just still be there. Or if you try to write to the address, the address is still there. You are just not allowed to ... |
6,955,365 | 6,955,542 | Combine c++ and javascript development in Eclipse | I am new to Eclipse IDE, but now I need it to develop apps for webOS.
Help me please with the next questions:
I have downloaded the Eclipse IDE for JavaScript Web development. How can I find it's version information?
Can I use one instance of Eclipse IDE for JavaScript and C++ development at the same time? (if yes the... |
Usually Versioninformation can be found under Help->About Eclipse
I do not know about this exact setup but I have Java/C++/PHP in one Eclipse install.
I installed the java version and then Help->Install New Software where I choose -all sites- as source and then searched for the compontent I wanted and installed it.
Af... |
6,955,427 | 6,955,491 | c++ lambda expression help | I'm a bit new to c++0x, can anyone explain to me why the following fail to compile:
void memory_leak_report()
{
std::cout.flags(std::ios::showbase);
std::for_each(allocation_records.begin(), allocation_records.end(),
[] (const struct memory_leak_report& rec) {
std::cout <... | First, In C++, you don't need to (and it's usually considered bad style) put struct in front of uses of a struct. Just const memory_leak_report& would do fine.
Second, you tell us how the struct memory_allocation_record is defined, but the lambda takes a memory_leak_report as its parameter, which, as far as I can see, ... |
6,955,550 | 6,956,314 | Remember the last selected item of a combobox | I have a dialog in a MFC project that contains a combobox with the following items: blue, black, yellow. When I start the dialog the combobox has the blue item selected. If I change to yellow, close the dialog and open the dialog again, I want the selected item to be yellow and not blue.
Any idee how can I remember th... | In your dialog class, have a static member and always set it to the last color used in the combo box. Since the member is static, it will persist even if you change the actual dialog object
|
6,955,562 | 6,955,590 | C++: function with vector of any derived class on input | Let's have the following simple function (the body of my function is more complicated but for the sake of simplicity):
unsigned VctSize(const vector< Base_class > vct) {
return vct.size()
}
How can I make the function accept vectors of derived classes of Base_class on input?
And can I make the function accept vect... | This will accept vectors of any type
template <class T>
unsigned VecSize(const vector<T>& vct)
{
return vct.size();
}
In order to accept only vectors of derived classes, you can use boost::enable_if
template<class T>
typename enable_if<is_base_and_derived<BaseClass, T>, unsigned>::type
VecSize(const vector<T>& vc... |
6,955,578 | 6,956,176 | Subtraction and Intersection of two vectors of pointers in C++ | I've two vectors having pointers to my custom class object.
The pointers in these two vectors don't point to the same object, but the values stored in the objects are same.
My custom class structure is:
Class Item
{
string ItemId;
string ItemDescription;
float ItemPrice;
}
The first vector(V1) is having n ... | Here is example of how to do it using STL set_intersection and set_difference to get what you wanted:
class Item
{
public:
Item(int i):ItemId(i){}
int ItemId;
string ItemDescription;
float ItemPrice;
bool operator<(const Item& rhs)
{
return ItemId < rhs.ItemId;
}
bool operator==(const ... |
6,955,752 | 6,956,550 | Is there an equivalent readline().split() python function in C++? | Essentially, the
int main( int argc, char** argv )
does exactly that (or to a very close extent). I was wondering if I could replicate the functionality of the int main( ... ) with other functions as well. For example, say I have a
readline();
function that reads a line from a file. I would like to know how many arg... | boost::split
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "word1 word2 word3", boost::is_any_of(", "));
|
6,955,909 | 6,984,542 | What means "Unrecognized storage class 111 for .text symbol `._XXXXXXXXX"? | I get this error message many times when trying to do objdump of my executable or shared library compiled on AIX 5.3. For any other executable on this machine it works fine.
This executable also crashes at runtime (at string assignment).
I'm not sure if it matters, but during the linking I have few warnings like:
ld: 0... | You were actually right john, thanks a lot!
There was a "static initialization order fiasco" problem with my code.
After replacing all suspicious global objects with function calls problem seems to be solved.
So I changed:
CFoo g_F;
into:
CFoo& GetF() {
static CFoo F;
return F;
}
And it's fine now. For this part ... |
6,955,985 | 6,956,105 | How to act as a microphone using DirectShow or something else on windows? | I have googled for a while to find how to create a virtual mic on windows. But I find nothing.
I want to write a program acting as a microphone which can be used in Skype when there is no mic on my computer. So that I can play music from audio files to my friends.
Is it realizable? Can I do it in C++?
If so, Can I d... | Maybe something like this is what you want?
http://software.muzychenko.net/eng/vac.htm
Also a related question on super user.
https://superuser.com/questions/190093/how-to-play-mp3-files-into-the-microphone-input
|
6,956,170 | 6,956,490 | How to implement a shared buffer? | I've got one program which creates 3 worker programs. The preferable method of communication in my situation would be through a memory buffer which all four programs may access.
Is there a way to pass a pointer, reference or any kind of handler to the child processes?
Update
The three child programs are transforming ... | Your question is platform dependent, therefore :
for Windows : Named Shared Memory
for linux : mmap or POSIX shared memory access
general case : boost::interprocess
|
6,956,296 | 6,956,405 | branching based on two boolean variables | Suppose I have two boolean variables, and I want to do completely different things based on their values. What is the cleanest way to achieve this?
Variant 1:
if (a && b)
{
// ...
}
else if (a && !b)
{
// ...
}
else if (!a && b)
{
// ...
}
else
{
// ...
}
Variant 2:
if (a)
{
if (b)
{
/... | The first variant is the clearest and most readable, but it can be adjusted:
if (a && b) {
// ...
} else if (a) { // no need to test !b here - b==true would be the first case
// ...
} else if (b) { //no need to test !a here - that would be the first case
// ...
} else { // !a&&!b - the last remaining
//... |
6,956,533 | 6,956,993 | Template specification compile error in g++ | I have a container object that is templatized. I am trying to make a specialized constructor for float versions. Problem is, when the compiler attempts to compile the second object that uses the float version, I get a multiple definition of error.
NOTES: The entire class in in the h file. The file is wrapped with a def... | Specializations still must abide by the one-definition rule just like any other non-template method. Either mark it inline or define the method body in a source file (not your header).
|
6,956,623 | 6,957,968 | method pointer and inheritance // kind of strategy pattern (C++) | In my design, there is a class which reads information from file. The read info represents a job (for simplicity, it's an integer, which is "job id"). The file reader class can accept objects which can handle such a job. Now my idea was, to make an Interface, e.g. "IJobHandler" which has a pure virtual function "DoJob(... | Here's a complete example:
class IAcceptable;
class DelegateBase
{
public:
virtual void Call() = 0;
};
template <class Class> class Delegate: public DelegateBase
{
public:
typedef void (Class::*Function)();
Delegate(Class* object, Function f): func(f) {}
virtual void Call() { (object->*func)(); ... |
6,956,785 | 6,956,856 | Error Including QGeoPositionInfo | I am new to Qt ,
I have been given this task where i should use GPS
so to use to GPS ,i only did this one line of code
#include <QGeoPositionInfo>
and the following error appeared
In file included from ..\Project\mainwindow.cpp:3:
..\Project\/form.h:7:28: error: QGeoPositionInfo: No such file or directory
how can i... | QGeoPositionInfo is part of Qt Mobility, which is an extension to Qt.
|
6,956,836 | 6,956,979 | Library for stock options calculations | I am writing some financial analysis software and need to do some calculations concerning stock options. I need to calculate the current value of a short position if it were closed by selling, by getting exercised, or by expiration. However, I do not have a good method to test if my calculations are accurate. Ideall... | I suggest you check out if QuantLib can help you.
|
6,957,061 | 6,957,093 | why do I need to link a lib file to my project? | I am creating a project that uses a DLL. To build my project, I need to include a header file, and a lib file. Why do I need to include the respective lib file? shouldn't the header file declare all the needed information and then at runtime load any needed library/dll?
Thanks
| In many other languages, the equivalent of the header file is all you need. But the common C linkers on Windows have always used import libraries, C++ linkers followed suit, and it's probably too late to change.
As a thought experiment, one could imagine syntax like this:
__declspec(dllimport, "kernel32") void __stdcal... |
6,957,238 | 6,957,383 | Can the conditional operator lead to less efficient code? | Can ?: lead to less efficient code compared to if/else when returning an object?
Foo if_else()
{
if (bla)
return Foo();
else
return something_convertible_to_Foo;
}
If bla is false, the returned Foo is directly constructed from something_convertible_to_Foo.
Foo question_mark_colon()
{
return... | A temporary Foo has to be constructed either way, and both cases are a clear candidate for RVO, so I don't see any reason to believe the compiler would fail to produce identical output in this case. As always, actually compiling the code and looking at the output is the best course of action.
|
6,957,368 | 9,598,599 | Retrieving the status of another user from libpurple (the IM library underpinning Pidgin) | I'm trying to pull the current status of another person on a SIMPLE network (Microsoft Office Communicator). I'm using libpurple, built a c++ wrapper around libpurple, and I can send/receive IMs with other users on the SIMPLE network. What I still need is to get the current status of other users
Here's my current att... | For some reason, calling this from the signed-on signal doesn't work.
Calling it from the buddy-signed-on signal works for me. Of course, in that case it will be called once for each signed-on buddy ...
sample function to be called from the "buddy-signed-on" signal:
static void buddy_signed_on(PurpleBuddy *buddy) {
GS... |
6,957,419 | 6,957,581 | Syntax for specializing function templates in C++ | Suppose I have a function template where the type parameter is used as a return type only:
template <typename T>
T foo()
{
return whatever;
}
Then what is the correct syntax to specialize that function template? Both of the following seem to work:
template <>
std::string foo()
{
return whatever;
}
template <>... | The compiler will deduce the correct template specialization based on informations provided (here, the function return type).
So these syntaxes have exactly the same behaviour, one being more explicit than the other.
|
6,957,606 | 6,958,444 | Use a C++ function in Java | I have a C++ project with some .cpp and .h files. One of these .cpp has a function with this signature:
int** verts(int L, int W, int l, int w)
I'd like to use this function in a Java project. Yes, I could rewrite it in Java, but it's a very very articulated function. It would be great calling this function (and obtain... | You can write a library which contains this function, and wraps it with
a JNI wrapper, but it's not trivial. The most important question is
what the int** really represent, and how they are managed: whether and
how you have to delete them, and how you want to represent them in Java.
Just guessing, I suspect that the ... |
6,957,738 | 6,957,849 | Wrapper design pattern | Say I have a class:
class B;
class A{
public:
A();
virtual B foo();
}
defined in a 3rd party component. I want to wrap classes A and B, resulting myA and myB.
Now, I shouldn't be able to access class A and class B from the outside, but rather have the same functionality for myA and myB. foo() could be called f... | I don't understand why you prefer to do this with inheritance instead of encapsulation. Generally speaking, extending the class you're wrapping is the "wrong" way to implement the wrapper pattern, especially since you generally want to redefine the interface in the process. In class myA, you'll have a field of type A t... |
6,957,929 | 6,958,759 | boost bind class function pointer | class Foo
{
double f1( int x, std::string s1 );
double f2( int x, SomeClass s2 );
}
I want to be able to bind Foo.f1's s1 without an instance of foo to create in essense
typedef double (Foo::* MyFooFunc)( int )
MyFooFunc func1 = boost::bind( &Foo::f1, _1, _2, "some string" );
MyFooFunc func2 = boost::bind( ... | typedef double (Foo::* MyFooFunc)( int );
MyFooFunc func1 = boost::bind( &Foo::f1, _1, _2, "some string" );
The result of boost::bind is not a pointer to member, so func1 cannot be initialized as such on the second line. The result of boost::bind is an unspecified type (which will depend on the parameters). If you're... |
6,957,943 | 6,958,211 | How to add new row to existing QTableWidget? | My app is phonebook(educational purposes). When user opens application, QTableWidged is filled with data loaded from .xml file. When user add new phone number, I would like to append this number to QTableWidget, but previously I setRowCount to current value, and now it is one row to little. How can I solve this problem... | Doing something like this should work:
tableWidget->insertRow( tableWidget->rowCount() );
This will append a row to the end of your table. You can use the insertRow() function to insert new rows into the middle of your table as well.
|
6,958,130 | 6,958,216 | Accessing private member variables from a templated class assignment operator | I have a container class that is templatized. I am overloading the assignment operator such that derived types can also be assigned.
My problem is, when the type is not the same, I cannot access the private members of the container class. What is the best approach to gaining access? The member variables cannot be made ... | Since you want to access private members of template class instantiated with different types, you've to make other templates as friend of the template class as:
template <class T>
class Container
{
template<class U>
friend class Container;
};
Note that if T and U are different types, then Container<T> an... |
6,958,520 | 6,958,566 | Difference between &(*similarObject) and similarObject? Are they not same? | Can someone please explain this to me
dynamic_cast<SomeObject *>( &(*similarObject) );
What is the point of doing the address of a dereferenced pointer? Wouldn’t the pointer itself just be the address of it?
| It may be that the type of similarObject has overloaded operator* and so it returns something whose address you're passing to dynamic_cast.
&(*x) and x may not be always the same thing. For example, think of iterator:
std::map<int, int>::iterator it = v.begin();
Then it and &(*it) are two different thing:
The type of... |
6,958,685 | 6,958,939 | Calling a Objective C function from C++ Code | I googled around and I find a million results to this subject. But none of the pages helps me. I think that I have a very common problem. I'm playing around with audio programming especially working with audio queues. The purpose of my program does not matter for explaining the problem. But in a nutshell: I get an erro... | self only exists in Objective-C methods and that is a C style function. You need to pass self from an Objective-C method to the inUserData when you set up the callback, then cast it back to the correct type.
//This is an example for using AudioQueueNewInput
//Call this in an Objective-C method passing self to inUserDat... |
6,958,844 | 6,958,895 | Accessing functions of a class that implement an Interface that are not part of the Interface | I am writing an application in c++.
I have an interface defined with various functions:
class ITest
{
public:
virtual void x()=0;
virtual void y()=0;
}
I then have a class that implements this interface, along with additional functions:
class NewClass: public ITest
{
public:
virtual void x();
v... | NewClass* p = dynamic_cast<NewClass*>(pTest);
if(p==0)
{
//error!!! pTest's dynamic type wasn't NewClass*
}
else
{
p->z();
}
Instead of dynamic_cast, you can use static_cast. But if pTest's dynamic type is not actually NewClass* you'll get undefined behavior.
|
6,958,972 | 6,959,089 | Modifying text in the terminal | Is it possible to modify text I printed to the terminal without clearing the screen?
For instance, if I'm showing progress of something in percentage, can I modify that percentage without having to clear the screen and printing again? I'm looking for a cross-platform way, if there is one.
Talking C++.
thanks
| There are a number of ways to do this, and depending on how much effort you want to put into it, you can do a lot of cool things with ascii text in a terminal window.
Advanced: ncurses library
Easier: ansi escape characters with printf or cout
Easiest: As others have said, simply use \r for a carriage return without a... |
6,959,023 | 11,340,114 | C++ Producer consumer queue with (very) fast and reliable handover | Hi I am looking into having thread handover using a fast and reliable producer consumer queue. I am working on Windows with VC++.
I based my design on Anthony Williams queue, that is, basically a boost::mutex with a boost::condition_variable. Now typically the time between notify_one() and waking up varies between 10 (... | The short answer is yes, from there it really is down to operating system management, and thread scheduling. RTSs (Real time systems) can bring those 50 micros to about 15 micros, and more importantly, they can get rid of the outliers. Otherwise spinning is the only answer. If there are more queues than cores, the idea... |
6,959,190 | 6,959,422 | Avoiding function overloading | In the following program I've a function overloading. One with just a single argument, another with two arguments and another with three. In the following example it looks simple because the function is not too long. What if the function is very long and it looks ugly to write the same function again and again with dif... | First of all if your function is long and ugly you should refactor it into a set of smaller functions or even classes.
As to your actual question, I would use the overloaded functions as wrappers like this:
int function(int a, int b, int c)
{
return a * b * c;
}
int function(int a, int b)
{
return function(a, b, a... |
6,959,261 | 6,959,582 | How can I simulate alignas(T)? | I have an array which is used as the underlying memory of an object of type T:
char memory[sizeof T];
.
.
.
new(memory) T(whatever);
How can I make sure memory is aligned correctly for T objects? In C++0x I could just say:
alignas(T) char memory[sizeof T];
but Visual Studio 2010 does not support that particular featu... | The usual (portable) solution is to put the memory declaration in a union with whatever built-in type in T requires the most alignment.
The simplest way would be to use a union with all of the likely
candidates:
union MaxAlign
{
int i ;
long l ;
long long ll ... |
6,959,443 | 6,959,512 | Compile C++ Meta Program in VS2010 | I am unable to compile the below program in VS2010. Keeps compiling endless and got into heap not available. Any help is much appreciated.
#include <iostream>
class function_t
{
public:
virtual void operator ()()=0;
};
class greet_t : public function_t
{
public:
virtual void operator()(){ std::cout << "hello ... | I believe the problem is in your template code:
template<int count, function_t** f> class loop_t
{
public:
static inline void exec()
{
(*(*f))();
loop_t< count-1, f>::exec();
}
};
Notice that you instantiate this inner template:
loop_t< count-1, f>::exec();
The problem is that you've neve... |
6,959,533 | 6,959,594 | C++, std::ofstream, exception | What is wrong in this code and how to fix it?
int _tmain(int argc, _TCHAR* argv[])
{
std::ostream * o = &std::cout;
char text[4096];
char *file = "D://test.txt";
if ( file != NULL )
{
strcpy ( text, file );
strcat ( text, ".log" );
o = & std::ofstream ( text );
}
*o << "test"; //Exception
return 0;
}
| o = & std::ofstream ( text ); this creates a temporary ofstream object whose address is assigned to o but the object is instantly destroyed, so o points to a deleted object. This should work (using static):
int _tmain(int argc, _TCHAR* argv[])
{
std::ostream * o = &std::cout;
char text[4096];
char *file = "... |
6,959,665 | 6,959,729 | When do constructors of static members of template classes get called in C++? | There is plenty of information on when constructors of static members of ordinary classes are called. However, I am seeing some strange behavior with regard to template classes.
What should the output of the following program be? (Note I use printf to avoid any static initialization order fiasco complications with s... | In a class template, when performing implicit instantiation, the members are instantiated on demand. Since the code does not use the static member, it is not even instantiated in the whole application.
When you do an explicit intantiation, the whole class and all of its members are instantiated, and that includes the s... |
6,960,480 | 6,960,679 | Problem in including STL header files | I have created Dialog Based application in MFC (VS 2008).When I do "#include" in Dlg.cpp it showing following error.
Is Some Component is missing in the VS 2008 Installation
c:\program files (x86)\microsoft visual studio 9.0\vc\include\xmemory(43) :
error C2665: 'operator new' : none of the 5 overloads could convert ... | Any STL includes in your MFC project should be included prior to the definition of DEBUG_NEW. This was a problem in the past (no longer seems to be, as I cannot reproduce it in VS 2010).
// myfile.cpp
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// This will cause the error
#include <vector>
Whereas
// myfile.cpp
// w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.