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 |
|---|---|---|---|---|
7,507,150 | 7,508,222 | Unions between pointers and data, possible pitfalls? | I'm programming a system which has a massive amount of redundant data that needs to be kept in memory, and accessible with as little latency as possible. (uncompressed, the data is guaranteed to absorb 1GB of memory, minimum).
One such method I thought of is creating a container class like the following:
class Chunk{
... | This approach should be safe on all C++ implementations.
Note, however, that if you know your platform's memory alignment requirements, you may be able to do better than this. In particular, if you know that memory allocations are aligned to 2 bytes or greater (many platforms use 8 or 16 bytes), you can use the lower b... |
7,507,396 | 7,507,491 | Message Systems and parameters in OOP? | In the WinAPI, WndProc has lParam and wParam which are longs. This means you generally have to typecast them into the correct type.
I've read that message systems in OOP should not need to cast things and that this is a bad practice. Therefore, in a language like C++, how would a basic message system work, where each m... | For the general case I doubt you can do without some typecasting.
However, in C++ level design the typecasting can be mostly be centralized.
Look up visitor pattern.
Cheers & hth.,
|
7,507,526 | 7,507,573 | Initializing a member class of an object using a non-default constructor in C++ | I have a specific situation where I've got an object that I want to use the boost random number generators on, and it has lead to a greater question which I cannot seem to answer. Here is the example code of what I'm trying to produce.
First, my header:
Class MyObject {
protected:
double some variable;
boost... | What you want is an initializer list. For example:
Tree::Tree(int fruit_num)
: apples(fruit_num) // Initializes "apple" with "fruit_num"
{
}
You simply add a colon (:) after the constructor parameters and before the opening brace {. You can separate different member constructors with commas (,). Example:
Tree::Tr... |
7,507,606 | 7,507,658 | Convert string to wstring, encoding issues | I've read Stroustrup's Appendix D (particular attention to Locales and Codecvt). Stroustrup does not give a good codecvt and widen example (IMHO). I've been trying to knob turn stuff from the internet with no joy. I've also tried imbue'ing stringstreams without success.
Would anyone be able to show (and explain) the co... | It seems pretty obvious that he was smoking weed. As for the codepage conversions, look no further than iconv!
|
7,507,646 | 7,507,678 | Will every line in a program(except variable declarations) ultimately use atleast one system call? | I was thinking about system calls and code that we write! Lets say I have a program like below
#include<stdio.h>
int main()
{
int a=0,b=2,c;
c=a+b;
printf("The value of c is %d", c);
return 0;
}
Lets take the case of c = a+b; if it was c++ compiler, then i beleive there would be a call to operator+() funct... | No, not at all. I'm unsure if you have your definition of a system call correct. Stealing a definition from Wikipedia:
In computing, a system call is how a program requests a service from an operating system's kernel.
This means that the kinds of operations that result in system calls are I/O, timing, etc -- not math... |
7,507,682 | 7,507,874 | How to generate array-list of all combinations of a table in C/C++ | I want to make automated measurements varying several parameters.
There is a table with variable row/column-number containing parameter values, e.g.:
a1 b1 c1
a2 b2 c2
a3 b3 c3
Is there an easy was for generating list of Arrays containing all combinations in column direction like that:
a1 a2 a3
b1 a2 a3
c1 a2 a3
a1 b2... | You can use recursion:
int selection[rows]; // Stores which item is selected for each row
void func(int row_num) {
if (row_num == rows) { // If we've selected for all the rows
// Do your thing with selection[]
return;
}
for (int i = 0; i < columns; i++) { // For each possible selection you... |
7,507,775 | 7,507,864 | Compiling Windows C++ application with long doubles in VS2010 | At work we have MSVS2010 Ultimate, and I'm writing a program which runs exhaustive simulations using real numbers. I'm getting non-trivial round-off errors and I've already taken reasonable steps to ensure my algorithm is as numerically stable as possible.
I'd like to switch to 128-bit quadruple precision floating poin... | You could switch to a non-Microsoft compiler such as gcc, Borland, or Intel. Those all recognize long double as 80-bit extended precision, the native internal format of the 8087.
|
7,507,818 | 7,508,245 | Standard layout type and reinterpret_cast | Am I allowed to cast from my class to a structure if i have copied the members of the structure to my class?
#include <stdint.h>
#include <sys/uio.h>
class Buffer
{
public:
void * address;
size_t size;
Buffer(void * address = nullptr, size_t size = 0)
: address(address), size(size)
{
}
... | First off, you cannot cast away constness:
§5.2.10p2. The reinterpret_cast operator shall not cast away constness (§5.2.11). (...)
So you need at least to write that as
operator iovec const*() const
{
return reinterpret_cast<iovec const*>(this);
}
or
operator iovec *()
{
return reinterpret_cast<iovec *>(this... |
7,508,131 | 7,508,166 | Linking dependencies of a shared library | I was working with SFML, I compiled a little test program and added the linkage option -lsfml-audio. Then, I used ldd ./program to see the dynamic libraries it was linking to. Surprisingly, there were a lot, none of them had I manually selected in my makefile, nor using pkg-config --libs.
I started reading about share... | Shared libraries will generally link in their dependencies. However, static libraries are not capable of doing so. pkg-config --libs often includes all dependencies (direct and indirect) so that you can switch to static compilation by simply adding -static without having to add additional library dependencies as well.
... |
7,508,346 | 7,508,355 | Memory allocation operators and expressions | In C++, is 'new' an operator or an expression or some kind of keyword? a similar question that comes in mind is, should i call '=' an operator or expression?
| new is operator. You can overload it and write your own version of it. Also I think that = is operator. Expression is more complex thing which consist of operators, variables, function calls etc. And please try to get C++ language standard. It must describe all things you mentioned.
|
7,508,369 | 7,508,387 | Boost libs building - difference between runtime-link and link options | I'm trying to build boost libraries in Windows 7 with MSVC (VS 2010).
I have come across the options runtime-link and link in the bjam command line options. I would like to know how they are used and what is the exact difference between them.
I have built the Boost Regex library using this command line
bjam --with-reg... | runtime-link refers to how your compiler's runtime is linked. That is, it corresponds to VC's Multithreaded vs. Multithreaded DLL option. Runtime means the components required for using the standard libraries available with your compiler.
You have probably seen the dynamic link files at some point: MSVCRTXX.DLL (C runt... |
7,508,378 | 7,508,520 | Why isn't this loop vectorized? | One particular hot spot when I profile a code I am working on, is the following loop:
for(int loc = start; loc<end; ++loc)
y[loc]+=a[offset+loc]*x[loc+d];
where the arrays y, a, and x have no overlap. It seems to me that a loop like this should be easily vectorized, however when I compile using g++ with the optio... | You need to tell the compiler that x, y, and a do not overlap. In C/C++ terms that means telling the compiler that those pointers do not alias by declaring them with restrict (or __restrict). gcc is very aggressive about optimizations when it assumes no aliasing, so be careful.
|
7,508,392 | 7,508,413 | File I/O in c++ and linux command line redirect | I've got a program that accepts a text file with a map on it, then finds the shortest path and outputs that to another file.
it needs to work like this
./pathFinder -arg < inputMap.txt > outputMap.txt
My question is, with this input, what would get filled into argv[] and argc (do the redirects count as arguments), an... | argc will be 2, and argv[1] will point to "-arg".
Redirects will simply appear on stdin and stdout (wrapped by std::cin and std::cout).
|
7,508,475 | 7,508,513 | Is C++ preprocessor metaprogramming Turing-complete? | I know C++ template metaprogramming is Turing-complete. Does the same thing hold for preprocessor metaprogramming?
| No. The C++ preprocessor does not allow for unlimited state. You only have a finite number of on/off states, plus a include stack. This makes it a push-down automaton, not a turing machine (this ignores also the fact that preprocessor recursion is limited - but so is template recursion).
However, if you bend your defin... |
7,508,527 | 7,508,541 | strcpy() causes segmentation fault? |
Possible Duplicate:
Getting Segmentation Fault
Why does this code cause a segmentation fault?
char *text = "foo";
strcpy(text, "");
As far as I understand it, the first line allocates some memory (to hold the string "foo") and text points to that allocated memory. The second line copies an empty string into the loc... | Whenever you have a string literal (in your case, "foo"), the program stores that value in a readonly section of memory.
strcpy wants to modify that value but it is readonly, hence the segmentation fault.
Also, text should be a const char*, not a char*.
|
7,508,627 | 7,508,840 | FMod Memory Stream Problem | EDIT: Well...that's very interesting. I made settings into a pointer and passed that. Worked beautifully. So, this is solved. I'll leave it open for anyone curious to the answer.
I'm having an issue creating a sound in FMod from a memory stream. I looked at the loadfrommemory example shipped with FMod and followed... | Solved by turning settings into a pointer. See code below:
CSFX::CSFX(CFileData *fileData)
{
FMOD_RESULT result;
FMOD_CREATESOUNDEXINFO * settings;
_Sound = 0;
std::string temp = "";
for (int i = 0; i < fileData->getSize(); i++)
temp += fileData->getData()[i];
settings = new FMOD_CREATESOUNDEXINFO();
settings->c... |
7,508,931 | 7,509,277 | error: function returning a function | Although there is at least one similar question, I still ask mine since that one hasn't got solved and seems more complicated. I'm trying to simplify mine.
I have a .cpp file that uses .h as below, and compiling these sheds error as follows. Any idea is appreciated. Note that codes are simplified in order to minimally ... | Why are you specifying boost::signal0<>? The signalN templates are for deficient compilers that can't properly parse function signatures.
Either use signal and specify the function signature, as recommended for modern compilers:
typedef boost::signal<void()> PreUpdateSignal;
typedef boost::signal<void()> PostUpdateSign... |
7,508,975 | 7,508,986 | how to print out x amount of results per line | For this code I created that outputs the ASCII characters corresponding to ints, I need to print out 16 ASCIIs per line. How would I go about doing so? I'm not sure how to approach these? Do I create another for loop inside?
int main()
{
int x = 0;
for (int i = 0; i <= 127; i++)
{
int x = i;
... | Use another variable that counts up along with i. When it reaches 16, reset it and print a new line. Repeat until the loop terminates.
i.e.(I may be off by one here, I didn't think about it too deeply)
for (int i=0, j=1; i<=127; i++,j++)
{
int x = i;
char y = (char) x;
cout << y;
if (j == 16) {
... |
7,508,990 | 7,509,032 | How to read in a string of Numbers into an array | I am working on a programming assignment in which we are making our own BigNum class. One of the constructors needs to be set up so that it can take a number from a string (i.e. 342567) and reads it into an array. However if the number were 0000000342567 it would have to be able to skip over the 0s and just read 342567... | Add this just before your while loop:
for (int i=0; i < size; i++)
{
if (strin[i] >= '1' && strin[i] <= '9')
{
used = i;
break;
}
}
This way, your while loop begins reading the string only from the index where the number actually begins, skipping over all leading 0s.
This should handle the ... |
7,509,050 | 7,509,071 | The difference between type casting and using std::move()? | I am just a bit curious about the new function std::move() that has just been added into the newest C++ standard.
Finished reading an article about it and found out that the function's definition is
namespace std {
template <class T>
inline typename remove_reference<T>::type&& move(T&& x)
{
... | std::move is defined as a specialized cast:
static_cast<typename remove_reference<T>::type&&>(t)
You could do this if you really want. But it would be much shorter and obvious to everyone what you're doing if you just use std::move. The rules around && casting are weird, so it's best to just use move and forward when ... |
7,509,098 | 7,509,296 | How to create certificate object using PKCS 11 | I am currently working on a project using PKCS#11 to interact with an USB Token. I have read PKCS #11 v2.20: Cryptographic Token Interface Standard and I can create other objects using the C_CreateObject function, but when I create a Certificate with this code then the return code is always CKR_DOMAIN_PARAMS_INVALID. C... | The term 'domain parameters' refers to the parameters associated with a cryptographic algorithm, such as DSA or Diffie-Hellman.
Does the USB token support the key lengths and algorithms used your certificate?
Were the domain parameters generated locally? Does the USB support externally provided domain parameters?
Witho... |
7,509,318 | 7,525,449 | What is the reason for this Valgrind error? | Valgrind is complaining with a substr invocation.
string Message::nextField(string& input) {
int posSeparator = input.find_first_of(SEPARATOR);
string temp;
temp = input.substr(0, posSeparator); //Error points to this line
input.erase(0, posSeparator + 1);
return temp;
}
The error goes:
290 bytes i... | You don't check if the posSeparator is actually different from string::npos - this might cause problems in the erase. It's a wild shot, but it might fix a bug anyway.
|
7,509,320 | 7,509,367 | new vs. new (featuring malloc!) | In C++, it's standard to always use new over malloc(). However, in this question, the most portable way of overloading the new operator while avoiding platform specific code is to place a call to malloc() within it to do the actual allocation.
When overloaded, constructors are called and type-safety is kept. In addit... | The biggest downside I can think off is you can't explicitly call delete or delete [] on a pointer that has been allocated using malloc() without invoking undefined behavior. If you are going to go the highly un-recommended path and use malloc() to allocate memory explicitly for C++ objects, then you are still going t... |
7,509,332 | 7,509,354 | Repeat output x amount of times to the right and down | I am almost on track here. I need to output if the user enters 5 or any number, the program should display the following:
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
5 to the right going down 5 times.
I have the right idea so far. But i am not sure how to specifiy it to repeat the the xxxxx going down 5 times as well. I tried makin... | Use two loops:
for (int i=0; i!=inputInteger; ++i) {
for (int j=0; j!=inputInteger; ++j) {
cout << letterX;
}
cout << endl;
}
|
7,509,438 | 7,509,474 | C++: placing an array randomly inside a 2D array | I am making a Battleships-like game and need to place a battleship objects into a battlemap array randomly. Except when I do this, the ships are never placed in the bottom right quadrant (but they are successfully placed in the other 3 quadrants), and I don't know why. Basically, I get a random integer between 0 and th... | You are trying too hard to keep the ship from going off the side. Just allow x_start and y_start to be anywhere:
x_start = rand()%size_x;
y_start = rand()%size_y;
And let your at() function return true if it goes off the side:
bool BattleMap::at(int x,int y) const
{
if (x>=size_x || y>=size_y) return true;
// reg... |
7,509,573 | 7,509,622 | string as parameter in a function | i wrote a function to search if its parameter is in a given table obtab1.txt....the optab table has two columns out of which the parameter can only be in the first column....in the aviasm.h file i wrote this code....
class aviasm
{
public:
aviasm(char *,char *);
~aviasm();
void crsymtab();
bool in1(string ... | It appears as though you are trying to use string without the proper declarations, you will need this at the top of your file:
#include <string>
using std::string;
|
7,509,593 | 7,509,611 | Creating a dialog in new thread | Suppose if i create a thread using CreateThread, and I want a modal or modeless dialog in that thread. Do i need to use a seperate message loop for that like I have here,
while(GetMessage(&msg, 0, 0, 0)) // Get any window messages
{
TranslateMessage(&msg); // Translate the message
DispatchMessage(&msg); // Dis... | When you use a modal dialog, it creates its own message queue, that's why it works. If you want to use modeless dialogs then you will have to create a message queue yourself.
From the documentation for DialogBox:
The DialogBox macro uses the CreateWindowEx function to create the dialog box. (snip) and starts its own m... |
7,509,625 | 7,509,678 | Function counting characters of a string class being skipped? | I was trying to count the number of characters in a string class but for some reason the program is skipping over my function completely. This is just the test code from the main program, it still was giving me the same results. How come the counter function is skipped over?
#include <iostream>
#include <string>
using... | You're applying operator ++ the wrong way. It should be:
if (DNA.at(i) == 'a')
{
(*a_count)++;
}
else if (DNA.at(i) == 't')
{
(*t_count)++;
}
else if (DNA.at(i) == 'c')
{
(*c_count)++;
}
else if (DNA.at(i) == 'g')
{
(*g_count)++;
}
|
7,509,757 | 7,509,817 | Compile C++ source to a .dll | I am trying to create a simple example with JNI. I am having trouble compiling the .cpp source file. I will give all the steps that I have done/tried below. I am trying to follow the tutorial found here: http://java.sun.com/docs/books/jni/html/start.html#27008
I have a Java program called HelloJNI.java
public class Hel... | I use the following flags to compile:
JDK = "c:/Program Files/Java/jdk1.5.0_22/"
CFLAGS=-Wall -DGCC -DWINDOWS -I$(JDK)/include/win32 -I$(JDK)/include
However, I should mention that I was not able to run my JNI application if the dll was compiled with cygwin gcc. I compiled with the Visual Studio then and it worked.
|
7,510,101 | 7,512,031 | phoenix lambda and argument dereferencing | Can somebody show me how to implement an equivalent of the following using boost::phoenix lambda?
I know I could implement it in many other ways but I'm trying to learn the Phoenix lambda expressions and so far all my attempts in this example failed.
What I want to do is to use the std::remove_if to iterate through my ... | Boost phoenix (and boost lambda) do not support the -> operator. You can use the "pointer to member" operator (->*) as a reasonable alternative.
I find it useful to define the member pointer as a separate variable immediately before the line that uses a lambda expression:
bool (weak_ptr<Xyz>::*expired)()const = &weak_... |
7,510,165 | 7,510,216 | C++ Static variable and unresolved externals error | I was hoping I could get some clarification on static variables of a class.
For example:
I have two different classes which perform completely different functions, alpha and beta. Within alpha, I declare a static variable of type beta so it looks like this:
//alpha.h
#pragma once
#include <iostream>
#include "beta.h... | static variables inside a class must still be defined somewhere, just like methods:
Put this in main.cpp:
beta alpha::var;
|
7,510,182 | 7,518,365 | How does std::move() transfer values into RValues? | I just found myself not fully understanding the logic of std::move().
At first, I googled it but seems like there are only documents about how to use std::move(), not how its structure works.
I mean, I know what the template member function is but when I look into std::move() definition in VS2010, it is still confusin... | We start with the move function (which I cleaned up a little bit):
template <typename T>
typename remove_reference<T>::type&& move(T&& arg)
{
return static_cast<typename remove_reference<T>::type&&>(arg);
}
Let's start with the easier part - that is, when the function is called with rvalue:
Object a = std::move(Obj... |
7,510,336 | 7,510,376 | Why do parameters passed by reference in C++ not require a dereference operator? | I'm new to the C++ community, and just have a quick question about how C++ passes variables by reference to functions.
When you want to pass a variable by reference in C++, you add an & to whatever argument you want to pass by reference. How come when you assign a value to a variable that is being passed by reference ... | When you write,
int *p = ...;
*p = 3;
That is syntax for assigning 3 to the object referred to by the pointer p. When you write,
int &r = ...;
r = 3;
That is syntax for assigning 3 to the object referred to by the reference r. The syntax and the implementation are different. References are implemented using pointe... |
7,510,415 | 7,534,838 | When is a call to "synchronize()" not necessary in C++ AMP? | Background: For a C++ AMP overview, see Daniel Moth's recent BUILD talk.
Going through the initial walk-throughs here, here, here, and here.
Only in that last reference do they make a call to array_view.synchronize().
In these simple examples, is a call to synchronize() not needed? When is it safe to exclude? Can we tr... | Use synchronize() when you want to access the data without going through the array_view interface. If all of your access to the data uses array_view operators and functions, you don't need to use synchronize(). As Daniel mentioned, the destructor of an array_view forces a synchronize as well, and it's better to call sy... |
7,510,463 | 7,510,609 | Task monitor and manager in C++ | I'm looking to build a task monitor/manager using the Win32 API. It will be started (preferably as a windows service) with a command line argument specifying how many instances of a new process it should start.
task_man.exe 40
Will start 40 instances of the process
task.exe
Now, whenever a task.exe exits (correctly ... | The easiest way to tell if a process has exited is to wait on its handle. You can do that in a few ways:
Build an array of all the process handles, and use WaitForMultipleObjects (bWaitAll being FALSE) to wait on all of them. Then, when your code continues, you'll have to figure out which process ended, create a new o... |
7,510,566 | 7,510,611 | Tracking down memory leak in a plugin, using _crtBreakAlloc, _CRTDBG_MAP_ALLOC | We have several after effects plugins that we have good evidence are leaking memory. To investigate this, I am playing around with Memory Leak Detection and Isolation in the vcc compiler/runtime. I enabled leak detection with:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
And I get a nice dump of l... | You do have to recompile those DLLs with the same #defines - they turn calls to malloc() into calls to malloc_dbg() and this enables filenames and line numbers in the dump. That's all the "leak detection" does - each allocation is passed the filename and line number and they are stored and later dumped. No calls to mal... |
7,510,885 | 7,566,194 | Changing LOCALE_SISO639LANGNAME for LOCALE_USER_DEFAULT | Is there a way to change "LOCALE_SISO639LANGNAME" on runtime?
I would like to set another language for "LOCALE_SISO639LANGNAME" on runtime and when queried by "GetLocaleInfo", it should be new language instead of system default.
By the way, it seems, you can't set "LOCALE_SISO639LANGNAME" by using "SetLocaleInfo".
Tha... | LOCALE_SISO639LANGNAME is a constant (C++ #define) so you cannot really change it on runtime. If I understand you correctly, you want to replace GetLocaleInfo calls with this value as a first argument so that effectively another argument is passed to the API.
It would not be a big deal if it was all in your code (code ... |
7,510,967 | 7,511,055 | Initialize struct in class constructor | How can we initailize a struct pointer in constructor of a class.
Example:
struct my_struct{
int i;
char* name;
};
class my_class{
my_struct* s1;
my_class() {
// here i want to make s1->i = 10; and s1->name = "anyname" ;
// should i assign it like s1->i= 10; and call new for s1->na... | my_class() {
s1 = new (my_struct);
s1->i = 10;
s1->name = (char *) malloc(strlen("anyname"));
s1->name = "anyname";
// here i want to make s1->i = 10; and s1->name = "anyname" ;
// should i assign it like s1->i= 10; and call new for s1->name and strcpy(s1->name "anyname");
// it ... |
7,511,150 | 7,511,200 | Is there a fast way to replace two map contents? | In my code I have a map which holds a large amount of data (~100MB) I need to copy all that data from one map to another. currently I am doing this with swap but to my understanding, swap is a fancy way to do a copy. Is there a way to simply transfer the memory used by the two maps? I think that I can do this with poin... | Unless this came up in a profiler run as a bottleneck, you may be optimizing prematurely.
My compiler's std::map::swap() has the following comment, which indicates that a map swap is likely to be very fast:
/**
* This exchanges the elements between two maps in constant
* time. (It is only swapping a pointer,... |
7,511,211 | 7,511,337 | Address of Null pointer? | I came across the macro below
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
I kind of not able to digest this because in c++, when I try to deference a null pointer, I expect an unexpected behaviour... but how come it can have an address? what does address of null mean?
| For the purpose of the macro:
It assumes that there is an object of type TYPE at address 0 and returns the address of the member which is effectively the offset of the member in the structure.
This answer explains why this is undefined behaviour. I think that this is the most important quote:
If E1 has the type “point... |
7,511,355 | 7,511,480 | Why is std::bitset<8> 4 bytes big? | It seems for std::bitset<1 to 32>, the size is set to 4 bytes. For sizes 33 to 64, it jumps straight up to 8 bytes. There can't be any overhead because std::bitset<32> is an even 4 bytes.
I can see aligning to byte length when dealing with bits, but why would a bitset need to align to word length, especially for a co... | I assume that indexing into the bitset is done by grabbing a 32-bit value and then isolating the relevant bit because this is fastest in terms of processor instructions (working with smaller-sized values is slower on x86). The two indexes needed for this can also be calculated very quickly:
int wordIndex = (index & 0xf... |
7,511,800 | 7,511,992 | Runtime error when using vector iterator | I'm having a problem with the following code:
for(int j = 0; j < ensembleTemp.size(); j++)
{
ensemble[ensembleTemp[j]].clear();
ensemble[ensembleTemp[j]].insert(ensemble[j].begin(),
ensembleTemp.begin(), ensembleTemp.end());
}
ensembleTemp... | You're using the wrong index for the first parameter of insert, it (presumably) should be
for(int j = 0; j < ensembleTemp.size(); j++)
{
ensemble[ensembleTemp[j]].clear();
ensemble[ensembleTemp[j]].insert(
ensemble[ensembleTemp[j]].begin(),
ensembleTemp.begin(),
ensembleTemp.end());
}
... |
7,511,939 | 7,516,327 | itk x and y component of the gradient of an image | I would like to calculate the x and y component of the gradient of a 2D image. As in MATLAB is calculated with [dT2,dT1] = gradient(T);
ReaderType::Pointer T_g // image
FilterType::Pointer gradientFilter = FilterType::New();
gradientFilter->SetInput( T_g->GetOutput());
gradientFilter->Update();
With this sentence... | The output of the gradientFilter will be a vector image. I assume from your description it's
a 2d image!
ImageType::IndexType index;
index[0]=xcoord;
index[1]=ycoord;
gradientFilter->GetOutput()->GetPixel(index)[0]; // will return first component of xcoord,ycoord
|
7,512,224 | 7,512,255 | Is there a way to pass template arguments to a function on an object when the object type is a template argument? | To illustrate:
struct MyFunc {
template <size_t N>
void doIt() {
cout << N << endl;
}
};
template <typename Func>
struct Pass123ToTemplateFunc {
static void pass(Func f) {
f.doIt<123>(); // <-- Error on compile; is there a way to express this?
}
};
int main() {
Pass123ToTe... | You have to tell the compiler that doIt will be a template:
f.template doIt<123>();
|
7,512,227 | 7,512,359 | Is c lib a static in c++ program? | I have a c lib, algo.lib, which I need to call in my c++ program. I realise that the variables in algo.lib is static, which creates problem for my c++ program, when I call algo.lib multiple times, or use threads to call algo.lib concurrently.
For example, in algo.lib, there is a int a which is initiall set to 0. When I... | Yes, it is possible. If you rewrite it. If you only have the binary - then you cannot change this behavior. You can solve it by creating a separate executable that will do what you want with it and then exit, and pass the results back to the main program through some IPC. Basically - wrap it with your own implementatio... |
7,512,285 | 7,512,401 | Packaging a jre with my application | My application contains an c++ exe file which invokes a java program using JNI, thus requiring jvm.dll. However, I want my application to ship with its own embedded jre but after I copy the jre6 folder found in JAVA_HOME and added it to my installer, it fails to run the program(Error occurred during initialization of V... | You may download the required dll's from the appropriate sites, i.e. from this one.
|
7,512,378 | 7,513,078 | accessing operator overloading of class which is wrapped by std::shared_ptr | the idea is that I want a class which is wrapped by std::shared_ptr, can still be used
just like they weren't a pointer, for example the operator= which was defined in my class
can still be used after my class is wrapped by std::shared_ptr.
for example
template <class Ty> class shared_ptr_proxy : public std::shared_pt... | It depends on what you want the proxy for. A full proxy might make it look entirely like you had the value, so you'd provide the conversion operators.
In such case, it might not be a good idea to inherit from shared_ptr, though, because you might be inheriting functions that you want to rely on the implicit conversion... |
7,512,559 | 7,512,730 | Qt QIODevice::write / QTcpSocket::write and bytes written | We are quite confused about the behavior of QIODevice::write in general and the QTcpSocket implementation specifically. There is a similar question already, but the answer is not really satisfactory. The main confusion stems from the there mentioned bytesWritten signal respectively the waitForBytesWritten method. Those... | That previous question answers your question, as does the QIODevice::write(const char * data, qint64 maxSize) documentation:
Writes at most maxSize bytes of data from data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.
This can (and will in real life) return less th... |
7,512,569 | 7,512,605 | Changing the elements of an array member of a const object | Can anyone explain to me why the following code works:
#include <iostream>
class Vec
{
int *_vec;
unsigned int _size;
public:
Vec (unsigned int size) : _vec (new int [size]), _size(size) {};
int & operator[] (const int & i)
{
return _vec[i];
}
int & operator[] (const int & i) const
{
return _vec[i];... | The constness is with regards to the members of the class. You cannot change the value of v._vec, but there's no problem changing the content of the memory that v._vec points to.
|
7,512,619 | 7,529,079 | Problem with GtkTextBuffer , Confusing Runtime Error. Need Help? | I am using this code:
class editbook
{
GtkWidget* _nbook;
std::vector<GtkWidget*> _srcset; //and so on...
...........................................................................................
void editbook::add_page()
{
GtkWidget* tmp = gtk_source_view_new();
_srcset.push_back(tmp);
gtk_notebook_... | The problem in your code could be that the child widget added to GtkNotebook through gtk_notebook_append_page is not visible, try showing the child widget through gtk_widget_show call. Something on these lines :
void editbook::add_page()
{
GtkWidget* tmp = gtk_source_view_new();
_srcset.push_back(tmp);
gt... |
7,512,823 | 7,513,012 | C++: insert into std::map without knowing a key | I need to insert values into std::map (or it's equivalent) to any free position and then get it's key (to remove/modify later). Something like:
std::map<int, std::string> myMap;
const int key = myMap.insert("hello");
Is it possibly to do so with std::map or is there some appropriate container for that?
Thank you.
| In addition to using a set, you can keep a list of allocated (or free)
keys, and find a new key before inserting. For a map indexed by
int, you can simply take the last element, and increment its key. But
I rather think I'd go with a simple std::vector; if deletion isn't
supported, you can do something simple like:
... |
7,512,857 | 7,512,947 | generic programming in c++ and typedef inside a class | let's say I have the following code in A.cpp file:
template <typename T>
class A{
typedef T myType;
myType foo();
}
If I want to implement the foo function in this file , what is the syntax to write the function declaration?
I thought it'll be:
template <class T>
myType A<T>::foo(){
.
.
.
}
obviously it's wrong... | Yes, the typedef is only available within the class, and the return type is not in the class:
template <class T>
typename A<T>::myType A<T>::foo() {}
|
7,513,059 | 7,513,103 | C++, non parameter types for templates: only const variables? | I dont understand why a template parameter can be initialized only with a const variable.
As in, why doesn't the following code work:
#include <iostream>
template <class T,int dim>
class Vec
{
T _vec[dim];
int _dim;
public:
Vec () : _dim(dim) {};
~Vec () {};
// other operators and stuff
};
int m... | Integer types parameters must be compile-time constants. You have to either use an integer literal or make your variable const. The reason is the template is instantiated before runtime and if there's a chance you can later change a variable name the program will behave inconsistent with the template.
|
7,513,081 | 7,513,126 | Static constant members in a class C++ | How do I declare static constant values in C++?
I want to be able to get the constant Vector3::Xaxis, but I should not be able to change it.
I've seen the following code in another class:
const MyClass MyClass::Constant(1.0);
I tried to implement that in my class:
static const Vector3 Xaxis(1.0, 0.0, 0.0);
However I ... | class Vector3
{
public:
double X;
double Y;
double Z;
static Vector3 const Xaxis;
Vector3(double x, double y, double z)
{
X = x; Y = y; Z = z;
}
};
Vector3 const Vector3::Xaxis(1, 0, 0);
Note that last line is the definition and should be put in an implementation file
(e.g. [.cpp... |
7,513,133 | 7,513,199 | Run bash command in Cygwin from another application | From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
| From Python, run bash with os.system, os.popen or subprocess and pass the appropriate command-line arguments.
os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')
|
7,513,476 | 7,543,563 | STL thrust multiple vector transform? | I was wondering if there was a more efficient way of writing a = a + b + c?
thrust::transform(b.begin(), b.end(), c.begin(), b.begin(), thrust::plus<int>());
thrust::transform(a.begin(), a.end(), b.begin(), a.begin(), thrust::plus<int>());
This works but is there a way to get the same effect using just one line of c... | a = a + b + c has low arithmetic intensity (only two arithmetic operations for every 4 memory operations), so the computation is going to be memory bandwidth bound. To compare the efficiency of your proposed solutions, we need to measure their bandwidth demands.
Each call to transform in the first solution requires tw... |
7,513,556 | 7,527,879 | How to correctly refresh the ribbon's MFC default recent documents list? | How to correctly refresh the ribbon's MFC default recent documents list?
The list in not updating correclty.
I enabled it using this:
In the ribbon XML, inside the CATEGORY_MAIN tag i've created this
<RECENT_FILE_LIST>
<ENABLE>TRUE</ENABLE>
<LABEL>Recent Documents</LABEL>
</RECENT_FILE_LIST>
and in the ::... | Solution found.
in my derived CWinApp class, in the overwritten method AddToRecentFileList, i needed to read the recent file list again adding this at the end of the method:
m_pRecentFileList->ReadList();
|
7,513,583 | 7,513,859 | Size in bytes of a structure containing unordered_map | Need to find the exact size in bytes, occupied by a tree data structure that I have implemented. Node Structure is as follows
struct Node
{
int word;
int count;
unordered_map<int, Node*> map;
}node;
What I have been doing is
size(int)*2(for word and count) + map.bucket_count() ... |
Or instead of all this, is it better to use tools like MemTrack to find the memory used?
Yes. There's no telling from the outside how much memory an unordered_map or other complex, opaque object takes, and a good memory profiler might also show you how much overhead the memory allocator itself takes.
|
7,513,701 | 7,513,734 | Most efficient way to find 1s in a binary word? | I am unsure what something like this would be called, (hence the clumsy title) but I need something like this for something I'm working on. I can't describe it well in words, but I hope this drawing explains for me:
What would be the fastest way of getting the number of "on-bits", "3" in this example, when everything... | First do input &= 0xfffffff8 (or the equivalent for your input type) to clear the three rightmost bits. Then take your pick from here.
|
7,514,365 | 7,514,416 | Does the delete[] operator work with dynamically allocated memory returned through a pointer? | I'm wondering how the delete[] operators works with pointers returned by a function, rather then having the dynamic allocation in the same scope as the delete statement. Let's say I have a trivial function like this:
int *getArray()
{
int *returnVal = new int[3];
returnVal[0] = returnVal[1] = returnVal[2] = 0;... | You should only delete[] things obtained via new[]. In your code that's the value returned by getArray(). Deleting anything else is illegal.
However, I'm wondering, how does the C++ compiler know how big the
memory block that was allocated was.
Each implementation stores the allocated size (and the type I think) in... |
7,514,418 | 7,514,465 | How to split big switch statement | I'm making an online game and when I receive data from a client, i receive several 'structures' ( say 'my position', 'use potion 23', 'attack player 45', 'talk bla bla', logout, etc.), those structures are read securely and put into structs, pushed on a list and (later on, when the server has time) processed.
The thin... | You can
replace the switch with a mapping from the enums to handler functions (the function implementations themselves can be in the same file, or in different files, as you prefer), or
(the more object oriented solution) make all the structs in question inherit from a common interface declaring a handler method, make... |
7,514,655 | 7,515,012 | friend function, cpp | We had an assignment in school implementing a Matrix class that overloads all arithmetic operators. What I did was to (for example) define += as a member function, and then define + as a non-member function that uses += function (both in the same file, but + outside the class).
The school staff did something similar, ... | It is preferable not to declare functions friends, if they can be implemented in terms of the class's public interface (such as operator+ in terms of member operator+=.
Somehow with operators sometimes people tend to assume that when implemented as free functions they need to be automatically declared friends. E.g you ... |
7,514,766 | 7,514,816 | Is there a way for C++ application function to turn on the computer? | i need to find away to turn on the pc from c++ application ,
is there any way to do this?
Thanks
| If the computer is off, it can't be executing code, and therefore can't turn itself on programmatically.
ACPI changes that somewhat, but for us to be able to help, you have to be more specific about your exact requirements.
If you need to turn on a different computer, take a look at Wake-on-LAN.
|
7,514,950 | 7,515,068 | About shift operator in C++ | I am looking at big code base in C++. There is line mentioned as below
int capacity( ) const
{
return ( 1 << theTrees.size( ) ) - 1;
}
Here theTrees is
vector<int> theTrees
What is statement 1 << theTrees.size( ) likely trying to achieve? Assume we have tree size of 25 elements.
| A left shift by n is basically multiplying by 2 to the nth power. Whenever you have 1 << n you're just calculating the nth power of 2. E.g.:
1 << 0 = 1
1 << 1 = 2
1 << 2 = 4
1 << 3 = 8
Etc.
I suspect theTrees.size() returns not the number of elements in the tree but the height of the tree (number of levels), because... |
7,515,086 | 7,515,142 | Cross Threading between UI and Background Thread | I've written a program that allows the user interface thread to access a populated array at almost any time. This array is populated by a separate background worker thread within an object.
What will happen when the user interface thread accesses this array? Will it automatically lock it down before accessing it?
I'... | Array is not locked automatically. If it is accessed from multiple threads, it is your responsibility to provide synchronization.
Another way is to serialize array update from a worker thread(s) through Control.BeginInvoke call - in this case array is accessed/changed only from UI thread, and synchronization is not nee... |
7,515,097 | 7,527,541 | What are the differences between Intel TBB and Microsoft PPL? | I'm planning to start "playing" with task-based parallelism for a cross-platform project. I wanted to use Intel Threading Building Blocks. I'm starting with Windows and Visual Studio.
As I just want to prototype for the moment, I'm thinking about "playing" only on windows, then have enough knowledge to use the library ... | TBB is a superset of PPL (as in VS2010), so it provides all PPL API plus its own APIs that PPL does not have.
Note that namespace Concurrency in VS2010 also contains APIs of Concurrency Runtime (ConcRT, on top of which PPL is built), Asynchronous Agents and etc. TBB does not have most of that, though it has some (e.g. ... |
7,515,123 | 7,516,359 | Automatic destruction of static object | Why doesn't C++ create/destroy a static member of a template type.
Observe the following example:
#include <iostream>
struct Dump {
Dump() {
std::cout << "CTOR" << std::endl;
}
~Dump() {
std::cout << "DTOR" << std::endl;
}
};
template <typename T> struct X {
static Dump dump;
};
template <typename ... | I found something in § 14.7.1 Implicit instantiation.
1/ [...] The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, scoped member enumerations, static data mem... |
7,515,369 | 7,515,495 | How to capture camera devices on Windows using Libav? | Is there any way to capture frames from as many camera types as DirectShow do on Windows platform using Libav? I need to capture a camera output without using DirectShow filters and I want my application to work with many camera devices types.
I have searched the Internet about this capability of libav and found that i... | FFMPEG cannot capture video on Windows. Once I had to implement this myself, using DirectShow capturing
|
7,515,429 | 7,515,485 | C++ newbie: writing a function for extracting i vectors from a file. How do I get i/unkown number of vectors out of the function? | I am writing a function for getting datasets from a file and putting them into vectors. The datasets are then used in a calculation. In the file, a user writes each dataset on a line under a heading like 'Dataset1'. The result is i vectors by the time the function finishes executing. The function works just fine. ... | If each vector is of the same type you can return a
std::vector<std::vector<datatype> >
This would look like:
std::vector<std::vector<datatype> > function(arguments) {
std::vector<std::vector<datatype> > return_vector;
for(int i =0; i < rows; ++i) {
\\ do processing
return_vector.push_back(resu... |
7,515,528 | 7,515,563 | Constructor initialization order and reference passing | Hi I have a question about the constructor initialization order. Given below
struct B {}
struct A
{
B& b;
A(B& b) : b(b) {}
}
struct C
{
B b;
A a;
C() : b(),a(b) {}
}
struct D
{
A a;
B b;
D() : a(b),b() {}
}
I know that C is valid as b gets initialized before a. But what about D? b woul... | They're both valid because A doesn't call into B at all. If A accessed a data member or member function of B, then that would be invalid. In the existing case of A, it's impossible to produce an invalid example.
|
7,515,617 | 7,515,719 | copy-and-swap idiom, with inheritance | I read interesting things about the copy-and-swap idiom. My question is concerning the implementation of the swap method when inheriting from another class.
class Foo : public Bar
{
int _m1;
string _m2;
.../...
public:
void swap(Foo &a, Foo &b)
{
using std::swap;
swap(a._m1, b._m1... | You would swap the subobjects:
swap(static_cast<Bar&>(a), static_cast<Bar&>(b));
You may need to implement the swap function for Bar, if std::swap doesn't do the job. Also note that swap should be a non-member (and a friend if necessary).
|
7,515,798 | 7,518,007 | Problem at marshalling a standard C++ string to a C# string | I'm writing a wrapper for a DLL that manages an OCR device. The DLL has a method whose signature resembles the following:
unsigned long aMethod(char **firstParameter, char **secondParameter);
aMethod returns string pointers to all parameters.
I wrote this signature in C#... it is almost functional:
[DllImport(aDll.dll... | Try changing the CharSet to CharSet = CharSet.Ansi
|
7,515,869 | 7,516,041 | C++ collection class to call children functions | The project I'm working on has some pretty nasty collection classes that I feel could use a redesign. I'd really like to make a collection template class that takes model instances and provides a way to call type-specific functions of each child in the collection. For example, something like:
MyCollection<Student> Biol... | One way would be to use a method pointer:
template <typename T>
struct MyCollection {
template <typename U>
void ForEach(void (T::*func)(U),U param)
{
// for each item loop goes here
(item.*func)(param);
}
};
MyCollection<Student> BiologyStudents;
// [Fill the collection]
BiologyStudents.ForEach(&Stud... |
7,516,119 | 7,516,489 | Can a Visual C++ program be compiled and run on Mac OS X or Linux? | … and if so, how?
Specifically, I'd like to compile and run wavdiff on Mac OS X Snow Leopard 10.6.8. As far as I can tell (which isn't very far, since I'm a total novice at C++), this was created with MS Visual C++ or similar.
I'd be most grateful for answers that address the general case of compiling Visual C++ progra... | The C++ language is portable. In theory, C++ source code can be compiled to run on any platform.
However, there are a few caveats to be aware of:
behavior might be different on different platforms. The C++ standard leaves many things implementation-defined, which means that it's up to the individual platform and compi... |
7,516,158 | 7,519,958 | Why does set iterator pointer cause segmentation fault? | Bottom line, why would iterator cause segmentation fault?
Note, I'm typing here the relevant parts of my code and not copy pasting. If there is an error in compilation, please note but do not consider it the source of my issue.
In my code, I have a map of boxes for beads:
map<vector<int>,set<shared_ptr<bead> > > > ne... | To answer your edit the only way possible:
If you want, I can reask the question: When will iterator incremental cause a segmentation fault in c++?
Incrementing an iterator will cause a segmentation fault only if it is used incorrectly.
That's it.
The standard doesn't list the cases in which code must segfault, it on... |
7,516,323 | 7,517,119 | What Makes a Binary Stream Special? | std::fstream has the option to consider streams as binary, rather than textual. What's the difference?
As far as I know, it all depends on how the file is opened in other programs. If I write A to a binary stream, it'll just get converted to 01000001 (65, A's ASCII code) - the exact same representation. That can be ... | On Linux/Unix/Android there is no difference.
On a Mac OS/X or later there is no difference, but I think older Macs might change an '\n' to an '\r' on reading, and the reverse on writing (only for a Text stream).
On Windows, for a text stream some characters get treated specially. A '\n' character is written as "\r\n"... |
7,516,390 | 7,516,449 | Confusion about data alignment | suppose a struct defined like this:
struct S{
char a[3];
char b[3];
char c[3];
};
then what will be the output of printf("%d", sizeof(S)) ? On My compiler of Vc++ 2008 expression, the output is 9. And I got confused... I suppose the result be 12, but it is not. Shouldn't the compiler align the structure to... | The value of the sizeof-expression is implementation-dependent; the only thing guaranteed by the C++ standard is that it must be at least nine since you're storing nine char's in the struct.
The new C++11 standard has an alignas keyword, but this may not be implemented in VC++08. Check your compiler's manual (see e.g. ... |
7,516,478 | 7,516,776 | Does cocoa limit the overall performance of a C/C++ openGL app? | I'm looking to write a first OpenGL app on the Macintosh. Previously I've only done OpenGL programming in Windows. From what I've read, there are basically three choices:
Glut
Cocoa
Carbon
Glut is out of the question because I do not like the look of it, and from what I have read, a good share of Carbon is deprecated. ... | Most "pure C" frameworks (including SDL) still use Objective-C and Cocoa to create and manage the OpenGL window. You should not stress over a small amount of Objective-C in your overall application. You can do the bare minimum in Objective-C and build the rest of the application in C. It is in your best interest to use... |
7,516,515 | 7,516,674 | Inline functions in debug build (Visual C++ 2008) | The game engine I am working with is too slow in the debug build and is impossible to debug the game. One of the things I would like is for the compiler to inline small functions (especially in Vector/Matrix and container classes). This may or may not speed up the game in debug build. Before profiling heavily and tryin... | Project options -> C/C++ -> Optimization -> Inline Function Expansion. Turn this to /Ob2. Do this in your Debug configuration.
In Release, inline function expansion is implied by other optimization settings, so even though by default all configurations say "Default" for the setting, the behavior is indeed different.
I ... |
7,516,545 | 7,516,593 | Why is 'object slice' needed in C++ ? Why it is allowed ? For more bugs? | Why C++ standard allow object slice ?
Please don't explain c++ object slice concept to me as I knew that.
I am just wondering what's the intention behind this c++ feature(object slice) design ?
To get novice more bugs?
Wouldn't it be more type safe for c++ to prevent object slice ?
Below is just a standard and basic ... | It's allowed because of is-a relationship.
When you publicly1 derive Derived from Base, you're annoucing to the compiler that Derived is a Base. Hence it should be allowed to do this:
Base base = derived;
and then use base as it is. that is:
base.message(); //calls Base::message();
Read this:
Is-A Relationship
1. I... |
7,516,609 | 7,516,662 | Use COM interface without statically linking to library | This may be a bit of a newbie question, but I just don't know! To use a function in a DLL that might not be present on the system I can use LoadLibrary and then GetProcAddress. But how can I do the same thing for a COM interface? I can include the header file for the declarations, IID's, and so on.. but I don't want to... | There's no need to fight against linking windowscodecs.lib. Linking against it doesn't result in implicit linking as you would get for a non-COM library.
You still need to call CoCreateInstance() just as you would for any COM object. Think of this as being runtime binding equivalent to GetProcAddress.
|
7,516,726 | 7,516,760 | Set find member vs. using find on list | Since the items in a Standard Library set container are sorted, will using the find member on the set, in general, perform faster than using the find algorithm on the same items in a sorted list?
Since the list is linear and the set is often implemented using a sorted tree, it seems as though the set-find should be fas... | With a linked list, even a sorted one, finding an element is O(n). A set can be searched in O(log n). Therefore yes, finding an element in a set is asymptotically faster.
A sorted array/vector can be searched in O(log n) by using binary search. Unfortunately, since a linked list doesn't support random access, the same ... |
7,516,868 | 7,517,038 | file processing (for file with more than one fields) and problems associated with it | here is a code i wrote to create the symtab of a sic/xe .asm file....
#include<iostream>
#include<fstream>
#include<iomanip>
#include"aviasm.h"
using namespace std;
void aviasm::crsymtab()
{
ofstream outs("symtab.txt",ios::out);//creating the symtab
ofstream outi("intermfile.txt",ios::out);//creating the interm... | You should run your program inside a debugger. If you are using Windows, then MSVC provides a debug environment. If you are using Linux, compile your program with -g, and run the gdb debugger: gdb ./myprog. You would immediately discover that on this line:
in>>str[i++]; //the asm file has three or less fields in every... |
7,517,158 | 7,517,290 | templates function specialization, c++ | I am practicing function specialization, and I was trying to create a little storage object with a specialized print function. Here's my code:
#ifndef STORAGE_HPP_
#define STORAGE_HPP_
#include <iostream>
using namespace std;
template <typename T, int size> class Storage
{ //LINE 16 ERROR
public:
Storage():arr(n... | The problem is that you are trying to use a partial specialization of the entire class without having defined the partially-specialized class.
If print were itself a function template, the situation would be different, because you can indeed specialize function templates. However, your construction only has the entire ... |
7,517,260 | 7,517,329 | Question about optimization in C++ | I've read that the C++ standard allows optimization to a point where it can actually hinder with expected functionality. When I say this, I'm talking about return value optimization, where you might actually have some logic in the copy constructor, yet the compiler optimizes the call out.
I find this to be somewhat bad... | Eliding copy operations is the only case where a compiler is allowed to optimize to the point where side effects visibly change. Do not rely on copy constructors being called, the compiler might optimize away those calls.
For everything else, the "as-if" rule applies: The compiler might optimize as it pleases, as long... |
7,517,274 | 7,518,002 | How do I programmatically get the Keyboard Repeat settings in KDE? | I have a custom Motif Widget and I'd like to tie its behavior to the Keyboard Repeat settings.
How do I programmatically get the current KDE Control Center Keyboard Repeat settings of Delay and Rate? What API exists to query and set these values?
Also, how can I register to find out when the user changes these values?... | The XKB library functions XkbGetAutoRepeatRate and XkbSetAutoRepeatRate can be used to access the X server repeat delay and rate settings. The functions are documented on their own man pages. There is also XAutoRepeatOn and XAutoRepeatOff in the basic X library.
Note that the rate and delay settings are provided by t... |
7,517,277 | 7,517,336 | How can I initialize normal array member variable in initializer list? | I would like to do the following:
class MyClass {
public:
MyClass() : arr({1,2,3,4,5,6,7,8}) {}
private:
uint32_t arr[8];
};
but it doesn't work (compiler: expected primary expression before '}' token.). I've looked at other SO questions and people were passing around things like std::initial... | Your syntax is correct. Alternatively, you can say arr{1,2,3,...}.
Most likely is that your compiler just doesn't support this construction yet. GCC 4.4.3 and 4.6.1 both do (with -std=c++0x).
|
7,517,318 | 7,518,234 | How can I initialize a SparseVector in Eigen | How can I initialize a SparseVector in Eigen ? The following code:
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>
using namespace Eigen;
SparseVector<float> vec(3);
main()
{
vec(0)=1.0;
}
gives me the following error
error: call of an object of a class type without appropriate ope... | Looking at the documentation I noticed Scalar& coeffRef(Index i), and it says:
Returns a reference to the coefficient value at given index i. This operation involes a log(rho*size) binary search. If the coefficient does not exist yet, then a sorted insertion into a sequential buffer is performed. (This insertion migh... |
7,517,449 | 7,517,498 | Xcode support of lambda functions | I have a program coded in VS that I'm trying to port over to Xcode. There are several issues I have ran into including use of lambda functions. Since Xcode uses gcc 4.2 and thus doesn't support C++11, will I not be able to use any lambda functions?
If I want to work on the code from my laptop without rewriting much of... | You have few options:
Re-write your code to the C++ 2003 standard.
Install GCC that supports C++11 features being used in the code and not use Xcode (you may use other IDEs, for example QtCreator or Eclipse CDT).
Wait for Xcode that comes with LLVM C++ compiler that supports C++11 features.
|
7,517,479 | 7,517,577 | C++ System Time returning the same wrong value | I want to retrieve the last write date on a file. I have written this code for it, but it returns me 52428 in values like "Year" all the time
int LastErrorCode;
LPCSTR Path = "C:/Users/Username/Desktop/Picture.PNG";
WIN32_FIND_DATA Information;
if(!FindFirstFile(Path, &Information))
{
int LastErrorCode = GetLastEr... | The hex value for 52428 is 0xCCCC, which seems to indicate it has not been initialized. The function call is probably failing. Check the return codes from FindFirstFile and FileTimeToSystemTime (and then call GetLastError after a failure to find the error code).
Edit Based on the edits to the OP, the FindFirstFile c... |
7,517,538 | 7,517,627 | How to convert DWORDLONG to a char *? | res = pRecord->Usn ;
char sres[1024];
strcpy(sres,"");
ltoa(res,sres, 10);
I have this variable res, which is of type DWORDLONG, and I am trying to convert it into a string so that I can insert it into the database.
Also, how would I convert it back. Is there a equivalent of ltoa, or do you have to wri... | Use
boost::lexical_cast<std::string>(res);
or
std::ostringstream o;
o << res;
o.str();
or in C++11
std::to_string(res);
For going back in C++11 you would use
res=std::stoull(str)
or in C *shiver *
char* end;
res=strtoull(str.c_str(),&end,10);
|
7,517,588 | 7,517,877 | Different floating point result with optimization enabled - compiler bug? | The below code works on Visual Studio 2008 with and without optimization. But it only works on g++ without optimization (O0).
#include <cstdlib>
#include <iostream>
#include <cmath>
double round(double v, double digit)
{
double pow = std::pow(10.0, digit);
double t = v * pow;
//std::cout << "t:" << t << st... | Intel x86 processors use 80-bit extended precision internally, whereas double is normally 64-bit wide. Different optimization levels affect how often floating point values from CPU get saved into memory and thus rounded from 80-bit precision to 64-bit precision.
Use the -ffloat-store gcc option to get the same floating... |
7,517,625 | 7,517,660 | How do I convert functions that use C++ pass-by-reference into C? | I have a piece of code that is written in C++ and need it in C. I converted most of it but I can't figure out how to convert C++ pass-by-reference in functions to C code, i.e.
Example:
int& a;
it is used in some function as a input variable:
void do_something(float f, char ch, int& a)
When I compile it with C I get c... | The way to do this in C is to pass by pointer:
void do_something(float f, char ch, int* a)
Also when using a in do_something instead of
void do_something(float f, char ch, int& a)
{
a = 5;
printf("%d", a);
}
You now need to dereference a
void do_something(float f, char ch, int* a)
{
*a = 5;
printf("%d", ... |
7,518,105 | 7,518,141 | How can I force a c++ class method to accept only a handful of integer literals? | There is a class I'm refactoring which currently has a method:
void resize(size_t sz)
In the current codebase, sz is always 0,1,2,or 3.
The underlying class is changing from dynamic allocation to a preallocated array of maxsize==3.
How can I get a build time error if someone tries to resize to sz>3 ?
It is easy enough... | There's no way you can get a compile-time check for a run-time value. Imagine if you said,
resize(read_some_number_from_disk());
How is the compiler supposed to check that?
However, you can make the function a template, since template parameters are known at compile time:
class Foo
{
template <unsigned int N> void r... |
7,518,181 | 7,519,312 | Perl: IPC::Shareable and SWIG'ed C++ object don't agree | For a certain Perl project of mine I need several Perl processes to share some resources, located in a C++ library. (Don't ask, it's not the core of this question, just the context.)
Thus I am trying to delve my way into two "new" fields in this context: IPC::Shareable, and wrapping C++ using SWIG. It seems I am doing ... | What you are trying to do will not work. You will have to bite the bullet and do some form of message passing instead.
I don't quite remember how exactly SWIG wraps the C(++)-level objects for Perl, but it's most likely the usual, admittedly horrible "pointer in integer slot" strategy. In this setup, it will allocate a... |
7,518,232 | 7,518,802 | Segmentation Fault with Large Input | I know segmentation fault means that the process has attempted to access certain memory that it's not allowed to.
I'm running some program written by others using C++. And when my input is large (around 1GB), there'll be a segmentation fault even though I requested 30GB memory; while when input size is quite small, it ... | Your code calls malloc several times, but never free, so it uses quite a lot of memory. And it never checks for an out-of-memory condition...
My suggestion is that you change all the calls to malloc to something like:
size_t total_memory = 0;
void *my_malloc(size_t sz)
{
void *res = malloc(sz);
total_memory += ... |
7,518,405 | 7,521,876 | Can I import a VS2005 Solution for C++ App into an IDE for debugging it on Linux? | Can I import a VS2005 Solution for C++ app into some IDE that runs on Linux and allows me to debug the app? It is a working app and already has a makefile for Linux.
| Codelite allows you to import Visual Studio projects
http://www.codelite.org/
However, it also allows you to import Makefile based projects, and you will probably get more mileage using this method. You can then use the codelite IDE to debug your application. It is just a wrapper around the GDB debugger.
Although us... |
7,518,412 | 7,518,775 | Calling a copy constructor with instance being created | I am not asking about the logic of such a call, rather I'm interested in a difference of support b/w Visual C++ and GCC / Clang. Visual C++ will not allow a new instance of an object to be used as the parameter for its own copy constructor. GCC and Clang allow this. Considering that 'int i = i;' is allowed, I'm wonderi... | To quote the C++ standard (3.3.2):
The point of declaration for a name is immediately after its complete declarator and before its initializer
In your first statement, the declarator ends after int i, and so the name i is available where it's used in the initializer (= i), so the statement is well-formed, but its beh... |
7,518,597 | 7,518,762 | fail compile if required flags aren't present | I have some legacy code that needs certain gcc flags passed in. Can I add pre-processor checks for these flags?
For example, let's say I need -fno-strict-aliasing, can I do something like this:
#ifndef _FNO_STRICT_ALIASING
#error -fno-strict-aliasing is required!
#endif
| You can use
#pragma GCC optimize "no-strict-aliasing"
to compile the file with that flag (overriding what was specified on the command line).
You can also use
__attribute__((optimize("no-strict-aliasing")))
to apply the flag to a single function within a source file...
|
7,518,611 | 7,518,806 | using geometry shader to create new primitives types | Is it possible to output new primitive type from geometry shader other than was input? I'd like to input a point and render a triangle. The point would be used just as center for this triangle. If not, is there other option to input just point and render some other piece of geometry defined by that point?
With the help... | Yes, this is perfectly possible, that's what the geometry shader is there for. Just specify the input primitive type as point and the output primitive type as triangle (or rather triangle strip, no matter if it's only a single triangle) using either glProgramParameteri in the application or using the more modern layout... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.