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 |
|---|---|---|---|---|
5,934,892 | 5,935,012 | How do I delete this Void Pointer? | #define ALIGNBUF(Length) Length % ALIGNSIZE ? \
Length + ALIGNSIZE - (Length % ALIGNSIZE) : Length
short NumCols;
long * ColLenArray, * OffsetArray;
ColLenArray = new long(NumCols * sizeof(long));
OffsetArray = new long(NumCols * sizeof(long));
// THIS CODE SHOULD NOT BE NEEDED TO UNDERSTAND THE PROBL... | You should try avoid mixing void* and new. In C++ actually, new is meant to automatically determine the type of the pointer; then why should not use it. At least you can use char*, if you are simply dealing with raw bytes.
Other point is new void*[SIZE] allocates void**. So you should change the declaration to void **D... |
5,935,075 | 5,935,135 | High Performance Math Library for Vector And Matrix Calculations | Where Can i find fast library for vector and Matrix Calculations?
I need high performance.
Update:I need it for games calculations.
| Edit: Sorry, I'm not high enough to add comments anywhere but just noticed you mentioned it is for games, unless you are writing your engine in software without any hardware acceleration, then the benefits you will get from the matrix manipulations (assuming that they are for TCL) are about nil in comparison to the res... |
5,935,413 | 5,935,524 | Is there a safe version of strlen? | std::strlen doesn't handle c strings that are not \0 terminated. Is there a safe version of it?
PS I know that in c++ std::string should be used instead of c strings, but in this case my string is stored in a shared memory.
EDIT
Ok, I need to add some explanation.
My application is getting a string from a shared memo... | If you define a c-string as
char* cowSays = "moo";
then you autmagically get the '\0' at the end and strlen would return 3. If you define it like:
char iDoThis[1024] = {0};
you get an empty buffer (and array of characters, all of which are null characters). You can then fill it with what you like as long as you don'... |
5,935,489 | 5,935,565 | Having some issues with shared libraries | I am compiling a program for source, and it is not finding some dynamic libraries that are compiled with it. Here is the output when I run the executable. (It compiles fine)
dyld: Library not loaded: libipeqtcanvas.so.7.0.14
Referenced from: /Users/zrbecker/testipe/bin/./ipe
Reason: image not found
Trace/BPT trap
... | You can set LD_LIBRARY_PATH (or actually, DYLD_LIBRARY_PATH, since you're on OS X) at runtime to include the library directory.
export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:/path/to/lib"
|
5,935,505 | 5,935,604 | IF Performance with changing condition style | I have this code
void test()
{
If (condition)
{
doSomthing();
}
}
test();
doSomethingMore();
Is there any performance effect with change it to:
void test()
{
If (!condition)
{
return;
}else
doSomthing();
}
}
test();
do... | You're really asking the wrong question. The performance is completely irrelevant here. Any optimizing compiler will render it absolutely insignificant, probably producing exactly the same binary for both styles.
No, in fact the real question is which code snippet is more readable. Your fellow human beings are the ones... |
5,935,605 | 5,935,758 | How do I access a class from inside another class? | The next part of the assignment tells me that the Class RacingCar contains four wheel objects as defined by class Wheel. Implement the wheels as an array of objects on the heap.
class RacingCar{
int speed;
public:
void Accelerate(int value) {
speed = speed + value;
}
void Brake(int value) {
... |
Implement the wheels as an array of objects on the heap.
Kind of pointless really, but it's an exercise, so ...
the assignment tells me that the Class "RacingCar" contains four wheel objects as defined by class Wheel.
When your assignment says "contains four wheel objects" you can translate this requirement to "the... |
5,935,643 | 5,935,682 | Compiler warning when switching on an enum | enum ENUM(Option1,Option2,Option3);
string func(ENUM x)
{
switch(x)
{
case Option1: return "Option1";
case Option2: return "Option2";
case Option3: return "Option3";
}
}
This compiles and works but gives a compiler warning that not all control paths return. However isn't the point that if you use enums prope... | What happens if for some reason x is neither Option1, nor Option2, nor Option3?
Sure, you could argue that will never happen, but since the method has to return something, you have two options:
add a return string(""); at the end.
add a default to the switch that returns string("").
As CodeGray points out, the seco... |
5,935,840 | 5,935,976 | Updating C++ Class Libraries | I've got a shared object with a selection of classes performing various tasks. I'm wondering what are some of the best practices in updating these libraries without effecting those that consume them. How would I add a new class method while minimizing the impact, for example?
I've implemented the Pimpl idiom, what othe... | Read about binary-compatibility. As long as that is given (and the interface and behavior of the existing functions doesn't change) you should be fine.
Here is a link to an article to get you started: http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++
And another one:
http://labs.qt.nokia.com/2009/08... |
5,936,251 | 5,936,378 | How to follow C++ bit storage in Java? | if I have in c++:
char abc[4];
abc[0] = 0xC0; //11000000 in binary
abc[1] = 0x20; //00100000 in binary
abc[2] = 0x44; //01000100 in binary
abc[3] = 0x20; //00100000 in binary
So how this will be stored in memory -
11000000 00100000 01000100 00100000 or the reverse way ??
-----------------------------------
0th... | Endian is not an issue. If you use char[4] the lowest address 0 will be first, the highest 3 will be last, so you get in memory
char[0] char[1] char[2] char[3]
whatever you do.
If you do a int x = *(reinterpret_cast<int*>(abc)), then you get different results, depending on endianness, because the (4byte-) int is somet... |
5,936,318 | 5,936,345 | C++: Is it possible to use dynamic binding with a template parameter? | I have a template function which accepts a function-object ('functor') as a template parameter:
template <typename Func> int f (void) {
Func func;
return func ();
};
struct Functor {
virtual int operator () (void) = 0;
};
struct Functor0 : Functor {
int operator () (void) {
return 0;
}
};
... |
Is there a way to use something similar to dynamic binding
No. This is fundamentally impossible. At some point in your code you need to have the case distinction. Of course, that doesn’t have to be written manually; you can use macros (or again templates) to generate the necessary code. But it needs to be there.
|
5,936,450 | 5,936,500 | Basic example code compiling help required - I can't get any SDK examples to work | I'm very new to C++; I've worked with several SDKs now on various applications and every time come across the problem that I can't get the 'example code' to compile. This is a very broad question basically regarding ANY example code that is given over the net - what is the standard procedure to make things compile? I k... | I like this page:
http://www.cprogramming.com/tutorial.html
|
5,936,752 | 5,936,832 | How do you exchange private data with Pimpl without exposing your internals? | If you have an object B that needs a copy of a private member of an object A, and the private member is hidden by a Pimpl, how do you make it happen without exposing your internals?
// Foo.h
class Foo
{
private :
struct impl ;
impl * pimpl ;
};
// Foo.cpp
struct impl { std::string data; }
//main.cpp
Foo A;
Foo B... | // header
class Foo
{
public:
void Copy( const Foo & );
private :
struct impl ;
impl * pimpl ;
};
//cpp file
struct impl {std::string data; }
void Foo::Copy( const Foo & f ) {
pimpl->data = f.pimpl->data;
}
|
5,936,774 | 5,961,177 | Eclipse c++ library not found in debug mode but found in release mode | I'm trying to debug a program i wrote in c++ using eclipse but i am encountering a problem when choosing the debug option.
/home/dupinf/workspace/HashTest/Debug/HashTest:
/sw/st/gnu_compil/gnu/linux-rh-ws-4-x86_64/lib64/libstdc++.so.6:
version `GLIBCXX_3.4.15' not found
when I just run the release, it works smoothly... | So I found what was the problem :
1) Go to the launch configuration for my debug
2) Go to the environment tab
3) Add the LD_LIBRARY_PATH variable with the path to my library
4) check the box to overwrite exist variable.
Then i can debug smoothly.
Note that even if you have modified you LD_LIBRARY_PATH in your terminal,... |
5,936,863 | 5,936,911 | C++ SIGSEGV Segmentation fault in loop | I have the following code which ends up in a segmentation fault.
for (int a=0; a<inputFileList.size(); a++)
{
fileLines = readFile(inputFileList[a].c_str());
for (int i = 0; i < fileLines.size(); i++)
{
if (fileLines[i].find("text") != string::npos)
{
... | The while should probably read
while (i < fileLines.size() && fileLines[i].find("message") == string::npos)
|
5,936,992 | 5,937,023 | Creating a new file with group permissions | This seems straight forward enough , but i have not been able to identify how i could achive this in C++.
I am creating a file as
ofstream logfile(LOG_FILE, ios::out | ios::app);
The file is created with the following permissions.
-rw-r--r--
What i really want is
-rw-rw-rw-
For obvious reasons , i do not want to... | Take a look at the chmod call. This is used to change the permissions of a file.
|
5,937,008 | 5,994,844 | How to determine Signalled state of Win32 Event? | I have an auto-reset event object created like this:
handle = CreateEvent(NULL, true, false, NULL);
...and (for some unit testing purposes) I want to check if it's signalled at a certain point. I'm aware of the 'correct' way of using events - this is purely for a diagnostic harness.
For a manual reset event I can just... | I don't see a simple way to do it. You could "mock" the event for testing purposes.
Wrap the event in an C++ object, and change all the code to use its methods.
class MockEvent {
public:
MockEvent () : m_handle(::CreateEvent(NULL, TRUE, FALSE, NULL) {}
~MockEvent () { ::CloseHandle(m_handle); }
BOOL Set... |
5,937,073 | 5,937,111 | operator<< and std::stringstream reference? | I have a class that holds a reference to a stringstream (used as an overall application log). How do I add text to the referenced stringstream?
An example (as I cannot post actual source here...)
main
stringstream appLog;
RandomClass myClass;
.....
myClass.storeLog(&applog);
myClass.addText("Hello World");
cout << appL... | De-reference the pointer first
void RandomClass::addText(const char text[])
{
if ( m_refLog != NULL )
(*m_refLog) << text;
}
In the constructor, initialize the member pointer to stringstream with NULL
RandomClass::RandomClass() : m_refLog(NULL)
{
...
}
|
5,937,243 | 5,937,382 | How can I incorporate libraries into my executable, so that users don't need to have the DLLs? | I'm developing software using ITK and VTK, and it's all going very well. However, I would like to deploy the software onto end-user machines that do not have ITK or VTK installed. When I build the software, and run it on a machine that doesn't have the ITK or VTK installed, I get errors, such as "Cannot load libItkBa... | You have two options:
Add the installer of those libraries into your installer and run it automatically if the libraries are not found on the system. This is how it's usually done if you have an installer and is the preferred option in that case.
Use static version of the libraries. Since the libraries use BSD license... |
5,937,332 | 5,937,490 | Unsigned long and bit shifting | I have a problem with bit shifting and unsigned longs. Here's my test code:
char header[4];
header[0] = 0x80;
header[1] = 0x00;
header[2] = 0x00;
header[3] = 0x00;
unsigned long l1 = 0x80000000UL;
unsigned long l2 = ((unsigned long) header[0] << 24) + ((unsigned long) header[1] << 16) + ((unsigned long) header[2] << 8... | Your value of 0x80 stored in a char is a signed quantity. When you cast this into a wider type, the value is being signed extended to keep the same value as a larger type.
Change the type of char in the first line to unsigned char and you will not get the sign extension happening.
To simplify what is happening in your ... |
5,937,377 | 5,939,791 | porting game made using cocos2d c++ on iPod Touch | I have used cocos2d c++ to create a small game on my Windows machine. It looks great and now I am planning to put it on my iPod Touch. Can anyone tell me how can I achieve this without actually porting my app on objective c?
I have MAC machine and I can arrange for Apple Developer license as well.
Please help me in thi... | A few years ago, Joel asked the same thing. There are very interesting comments there, you should take a look. This one is very enlightening:
Google "Objective-C++". That will give you ideas how to allow your C++ to interface with Objective-C APIs.
After a quick search on stackoverflow, I found that at that time, s... |
5,937,451 | 5,937,585 | Why is the segmentation fault? | I have this program, any idea as to why it gets segmentation fault?
#include <stdlib.h>
#include <ctime>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <dlfcn.h>
#define LT_SIGACTION (*lt_sigaction) // For handle to actual sigaction in lib... | From the sigaction man page, you should have the SA_SIGINFO flag defined:
sa.sa_flags = SA_SIGINFO;
Otherwise, it's not calling your function with 3 args. Not sure if lt_sigaction has any differences in usage.
|
5,937,474 | 5,937,763 | How to compile and start VSC++ Projects Faster? | What techniques do you use to compile and start VSC++ projects fast?
For us, especially the loading of all the dlls take a long time. Is there a way to speed this up? The project loads a ton of .dlls and some of them are especially slow.
Now that we use unity build for our projects, it already compiles blazingly fast! ... | DLLs have a default load location embedded into them. This is typically defaulted by the development tool to the same address for all DLLs. This means that whenn the DLLs are loaded into memory, there are a lot of collisions and the DLL has to be readdressed and loaded into a free memory location. When working on a ... |
5,937,653 | 5,938,060 | c++ templates in ubuntu linux .cpp | I am currently working in Ubuntu9.10 - c++.
I need to define an generic object in a method. I have to define the method in .h file. How can I do it? I did the following:
file.h
class ana
{
//code
public:
template <class T> bool method (T &Data);
};
file.cpp
//code
template <class T>
bool ana::method(T &Data)
{
//co... | Putting function definitions together with declarations (in the header files itself) definitely helps and is the way of choice. But, in case you want to separate the function definitions, have the following lines at the end of the .cpp file. Its called explicit instantiation.This will take care of linker errors. I trie... |
5,937,723 | 5,938,127 | How to handle heaps in C++ | I know this is probably one of those "you just have to try it" kind of questions, but since I do not have actual test data available yet, I'd like to get some input on your experience while I am still designing the code.
I have a data structure that implements a priority queue with some added functions. What I usually ... | If you insert k elements into a heap of size n, make_heap() will be faster roughly from the point where k⋅log2(n) > 3⋅n. That means when k > 3⋅n / log2(n). You could calculate this value before a mass insertion and then decide what method will be faster.
Note that this value is only a rough estimation, because the actu... |
5,937,780 | 5,937,806 | finding multiple ocurrences of a string | How can I find multiple occurrences of a string within a string?
And replace the found string with another string in all occurrences?
Say, I have the string below:
"A cat is going. It is black-white stripped."
I want to replace all occurrences of "is" with are.
| string.replace() is what you want. Check it out here. Of course, that will have to be run multiple times, until the string you want replaced returns string::npos on a find(). Try this out:
int main(int argc, char *argv[]) {
if(argc != 3) {
cout << "Usage: <binary> <toFind> <toReplace>" << endl;
exit(1);
... |
5,937,897 | 5,937,994 | Can we define a structure on type? | So I am looking on question about struct vs class difference... And I do not get one thing - can we define a structure on type? like tiped class... If yes please provide some samples.
| If you mean, Can you use a struct much like you would use a class? the answer is yes. In C++ the only difference is the defaults for visibility. Members of a class default to private; members of a struct default to public. If you create a class and make all the members public, it's pretty much the same as a struct. I u... |
5,937,992 | 5,939,003 | How can I shorten a singleton call? | I have a singleton class that basically deals with logs. Every place at which I call it in the code, I have to type:
LogClass::GetInstance()->WriteToLog("text");
How can I shorten this call so that I can just type WriteToLog("text") and it will call the function on the singleton object?
| I like to use a reference and an operator() overload.
In LogClass.h file
class LogClass
{
public:
static LogClass& GetInstance()
{
static LogClass singleton;
return singleton;
}
void operator()( std::string msg );
//...
};
extern LogClass& myDebug... |
5,938,052 | 5,938,071 | Assigning values to enumerated types | enum options {Yes,No};
class A{
int i;
string str;
options opt;
};
int main{
A obj;
obj.i=5;
obj.str="fine";
obj.opt="Yes"; // compiler error
}
How can assign const char * to opt?
| Just do
obj.opt=Yes;
This code:
obj.opt="Yes";
attempts to assign a string literal (a completely different type) to an enum type, which C++ doesn't automagically convert for you.
How can assign const char * to opt?
You'll have to do this manually, I like to keep a set of free functions around for doing conve... |
5,938,119 | 5,938,248 | Linking statically against pion network library | I am trying to link pion network library 4.0.3 in my application. I tried to simply compile pion::netlib in RELEASE_STATIC mode - which worked. However, when I linked against it in my application I get alot of unresolved externals.
Then I found out that RELEASE_STATIC configuration defines PION_STATIC_LINKING, and from... | This could most probably be because you are compiling your project using /MT (Multi-threaded) settings for Code Generation, while pion network library was compiled using /MD (Multi-threaded DLL) or vice-versa. Try changing your configuration to /MD if it's /MT or vice-versa. To do this, go to Project -> <ProjectName> P... |
5,938,501 | 5,938,566 | undefined reference compiler error in c++ | I am getting the error message below when I try to compile my code -
In function
'__static_initialization_and_destruction_0':
home/user/main.cpp:50: undefined
reference to
'PhysEng2D::PhysEng2D(void)'
The only code on line 50 is -
PhysEng2D Physics;
The header file for PhysEng2D is -
#ifndef _PHYSENG2D_H... | You need to compile each cpp file, then link them.
g++ -c -Wall main.cpp
g++ -c -Wall physeng2d.cpp
g++ -o myapp main.o physeng2d.o
You also should remove the PhysEng2D:: prefix from the class definition in the .h
|
5,938,656 | 5,938,868 | Constructor? or something else? |
Possible Duplicate:
What is this weird colon-member syntax in the constructor?
So I was looking through some samples in a Direct X 10 book, when I came across this
PeaksAndValleys::PeaksAndValleys()
: mNumRows(0), mNumCols(0), mNumVertices(0), mNumFaces(0),
md3dDevice(0), mVB(0), mIB(0)
{
}
I understand this is p... | This is called an initialization list, and is used for initializing class members. It is useful both as a shorthand and it is required for initializing members that do not have a default constructor. For example:
#include <iostream>
using namespace std;
class Foo {
public:
Foo(int x) { cout << "Foo(" << x << ")" <... |
5,938,885 | 5,938,907 | Mysterious SIGABRT in destructor if certain member variables are initialized in the constructor | I have the following Qt class:
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
GLWidget(QWidget *parent = 0);
private:
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
double posX;
double posY;
double posZ;
};
When I put this in the constructor, my program produce... | Did you check the core file to see where it died?
That said, the most likely scenario is division by zero and/or assertion that X and Y are not zero.
EDIT: Also it seems likely that when you don't initialize the values the program is behaving wrong but it just appears to work correctly/better.
EDIT2 in response to comm... |
5,938,940 | 5,939,062 | Problems with C++ Pointers in CUDA-Matlab compilation | Hey there,
I have the following code-snippet:
double *f;
f = a_function(parameters...);
printf("%f", *(f+1));
loopAry(f, 5);
void loopAry(double *in, int size)
{
printf("%f\n", *(in+1));
for(int i = 0; i < size; i++)
{
printf("\nin[%d]=%f ", i, *(in+i));
}
}
(mex-file in matlab). Now the... | You declare the array as a local variable that will go out of scope at the end of the function. The f pointer than points to the location where the array used to be but isn't anymore.
You should dynamically allocate the array:
double *vals = new double[5];
vals[0] = dat[0]*dat[0]*dat[0];
vals[1] = dat[1]*dat[1]*dat[1];... |
5,939,077 | 5,939,131 | Chaining Bool values give opposite result to expected | Unthinkingly I wrote some code to check that all the values of a struct were set to 0. To accomplish this I used:
bool IsValid() {
return !(0 == year == month == day == hour == minute == second);
}
where all struct members were of type unsigned short. I used the code as part of a larger test but noticed that it wa... | == groups from left to right, so if all values are zero then:
0 == year // true
(0 == year) == month // false, since month is 0 and (0 == year) converts to 1
((0 == year) == month) == day // true
And so on.
In general, x == y == z is not equivalent to x == y && x == z as you seem to expect.
|
5,939,272 | 5,939,316 | Strange problem with dynamic cast C++ | I'm just new to C++, and doing a small project which implementing some inheritance. It can basically be summarized below:
//.h file
class Food{
public:
Food();
virtual ~Food();
};
class Animal{
public:
Animal();
virtual ~Animal();
virtual void eat( Food f);
};
class Meat : public Food{
public:
Meat();
~Meat();... | When you have a function like this:
void Carnivore::eat(Food f)
it takes its parameter by value. That means a copy of the provided object is made.
In this case, you're specifying a type Food, so you end up with a Food object. No magic polymorphism, nothing. Just a bog-standard Food object.
This is known as slicing; pl... |
5,939,278 | 5,939,714 | Usage of objects or pointers to objects as class members and memory allocation | A similar question has been asked here:
Class members that are objects - Pointers or not? C++
so I'll keep it brief.
Say I have an object that contains three stl vectors. Is my thinking correct that if they are regular members of the class, the memory of them will be "together" for the whole object? e.g. my memory woul... |
Say I have an object that contains three stl vectors. Is my thinking correct that if they are regular members of the class, the memory of them will be "together" for the whole object? e.g. my memory would look sth like 10 blocks vector A, 5 blocks vector B, and then 15 blocks vector C.
Each vector occupies a fixed si... |
5,939,486 | 5,942,427 | Anonymous struct in typedef of trait class | Sorry for the funny title.
Prior to C++0x, there are restrictions in the use of function-local structs (“local types”) as template arguments. My question is essentially if similar restrictions apply to anonymous structs. Specifically, in the context of a trait class:
template <typename T>
struct trait;
template <>
str... | A typedef declaration that defines an anonymous class and a typedef-name for that class, the typedef-name is the name of the class for linkage purposes. It is therefore legal to use that class as a template parameter if it meets the other criteria.
See 7.1.3p5 of the C++03 standard
If the typedef declaration defines a... |
5,939,494 | 5,939,845 | How to use UTF8Encoding in Visual C++ | I need to change the below c# code to c++ code.
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
on this website i found the c++ code for UTF8Encoding from which i created this code
voi... | string is a different data type in C++ as it is in C#. Try using System::String^ instead.
|
5,939,787 | 5,940,476 | How to transfer larger objects through a socket in QT? | I would like to send/recieve image files and 2 ints as messages in a client server program.
I'm using QLocalSocket and QImage for this.
However I don't know how to read from the socket only after the image and the integers are fully written to the buffer, since the readyRead signal is already fired after the first coup... | The BMP format has size information and PNG format has size information for each chunk. These are formats with what QImage serializes.
If you don't want to extract the information from raw data then serialize QImage first to QBuffer (so you know/control size and format better). Then stream that size and buffer.
|
5,939,822 | 5,941,625 | 2D Discrete laplacian (del2) in C++ | I am trying to figure out how to port the del2() function in matlab to C++.
I have a couple of masks that I am working with that are ones and zeros, so I wrote code liket his:
for(size_t i = 1 ; i < nmax-1 ; i++)
{
for(size_t j = 1 ; j < nmax-1 ; j++)
{
transmask[i*nmax+j] = .25*(posmask[(i+1)*nmax + ... | The problem is that the line you have there:
transmask[i*nmax+j] = .25*(posmask[(i+1)*nmax + j]+posmask[(i-1)*nmax+j]+posmask[i*nmax+(j+1)]+posmask[i*nmax+(j-1)]);
isn't the discrete Laplacian at all.
What you have is (I(i+1,j) + I(i-1,j) + I(i,j+1) + I(i,j-1) ) / 4
I dont' know what this mask is, but the discrete L... |
5,940,002 | 5,940,090 | Catching boost serialisation archive exceptions | I have the following situation.
This is a code snippet, edited to demonstrate the problem.
ifstream ifs("empty_file");
if(!ifs.is_open()) {
ui.display("Error: Unable to open file \"empty_file\"\n");
return;
}
archive::text_iarchive ia(ifs);
try {
ia >> some_class;
} catch (...) {
ui.display("This shoul... | Maybe the exception is thrown by the constructor. Try constructing your text_iarchive object within the try, like this:
try {
archive::text_iarchive ia(ifs);
ia >> some_class;
} catch (...) {
ui.display("This should catch every single exception\n");
}
Assuming that catches the exception, you'll want to cat... |
5,940,110 | 5,940,154 | How do you pass 'this' as an argument to another class constructor without circular dependencies? | I'm thinking specifically of the Strategy pattern (Design Patterns, GoF94), where it is suggested that the context passed to the strategy constructor can be the object which contains the strategy (as a member) itself. But the following won't work:
//analysis.h
class StrategyBase;
class Strategy1;
class Strategy2;
cla... | analysis.cpp also needs to include strategy.h to pick up the full definitions of the strategies. Since it's a source file there's no circular dependency.
|
5,940,453 | 5,940,951 | C++: Evaluate own mathematical function (function-array like multidimensional analysis) entry-wise | Hey there,
I want to evaluate a mathematical function (user-defined) which returns several values in an array (this function is a vector based function f:R^n->R^m with n input coordinates and m output functions) in C++ for certain parameters, e.g.:
double *my_func(const mxArray *point)
{
double *dat = mxGetPr(point... | When you say "user_defined" I presume you mean that someone else writes my_func() and then your code calls it?
If this is the case, consider running many calls to my_func() in parallel rather than trying to break the function up. This means whoever writes my_func() only needs to write one function, and you will be resp... |
5,940,690 | 5,940,754 | Set with custom function object comparator c++ | I have a file, on it's first line is the english alphabet, in a random order, after that, names. I should sort the names according to the alphabet given. My class looks something like this:
class MyCompare(){
private:
static map<char, int> order;
public:
MyCompare(string alphabet){
//loop throug... | Read the first line, then create your set, then enter the loop.
if (myfile.is_open()) {
getline (myfile,line);
MyCompare st(line);
set<string, MyCompare> words(st);
while (getline(myfile,line)) {
words.insert(line);
}
myfile.close();
// use words here
}
|
5,940,780 | 5,940,907 | Vector of object pointers, initialisation | I'm not very experienced with C++ yet, so bear with me if this is basic stuff.
I have some code like that below. L is an abstract class (it has a number of pure virtual functions), and A, B and C are regular classes all derived from L. There may be any number of these, and they are all different.
int main() {
// ..... |
but there really has to be a better way to initialise that vector. Right?
I don't think so, at least not without C++0x. Which way would you prefer? Your initialization code is completely fine.
I figure I can't make it const, however, because the various objects may themselves change internally.
You can still make t... |
5,940,846 | 5,941,412 | Convert a double to a QString | I am writing a program in Qt. I want to convert a double into a QString in C++.
| Use QString's number method (docs are here):
double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);
|
5,940,944 | 5,940,987 | how to extract the functions from a c++ header file with haskell? | i need to get all the functions from a c++ header file with haskell (not methods only functions), i need the input parameters and the return type also the method name.
how could i realise this? olny with regex? or must i write a whole parser (bottom-up or top-down)?
| To extract all the function declarations from a header file, you'll need a parser, not a regex. Parsers for C++ are hard to come by, but luckily we have some:
Language.C, for parsing C files
LibClang, for parsing C++ files
Using either of these you'll be able to robustly process C or C++ headers, and extract declarat... |
5,940,986 | 5,941,202 | transferring object ownership on std::allocator rebind | I have a Visual Studio 2008 C++ application where I am implementing a replacement for the standard allocator used in containers like std::vector. But, I've run in to an issue. My implementation relies on the allocator owning a handle to a resource. In the case where the rebind feature is used, I would need to transfer ... | What happens if you declare h_ as mutable?
|
5,941,070 | 5,941,187 | How do I display this number pattern in C++? | I have to display this number pattern:
-3 1 5 9
7 12 17
15 21
using:
int number = __________________; // assign correct initial value
int row, col;
for (row = 1; row <= 3; row++)
{
// adjust number so it displays the correct first value in the row
________________________________________________
for ... | Try this
number = -3
for(row = 1; row <= 3; row++){
for (col = 0; col < 5 - row; col ++){
display (number + col * (3 + row));
}
number += 12 - row * 2;
}
With your restrictions, that would be:
int number = 0; // assign correct initial value
int row, col;
for (row = 1; row <= 3; row++)
{
// adjust... |
5,941,363 | 5,941,460 | parser for c++ headers to extract functions with standard linux tools? | Is there something like this? I need to extract C++ functions from header files with all the parameters they use. It would be nice if i can use standard Linux programs
| You can use understand 4 C++ which is a front end tool that browse your source code and generate metrics for your source code. It also has a powerful API that allows you to write your own static analysis tools. So far understand works on windows, and a bunch of other linux based OS's. Though I've only used the windows ... |
5,941,471 | 5,941,888 | C++ algorithm for flood filling a binary image | I am trying to simulate a matlab function "imfill" for flood filling a binary image (2D matrix of 1's and zeros).
I want to specify a starting point in the matrix, and flood fill like a 4 connected version of imfill would do.
Does this already exist out there somewhere in the C++ world? If not, what would be the most e... | If your images are just 2D arrays of 1s and 0s, then I don't think you need an actual graphics library.
When I've filled in simple grids in the past, I just used the STL queue to store a list of points, and then worked through those. The queue would start with the initial point, then I'd test the adjacent points. If th... |
5,941,617 | 5,941,673 | Heap corruption while freeing memory | I have a class as follows
struct CliHandler {
CliHandler(int argc, char** argv);
~CliHandler();
int doWork();
int argc_;
char** argv_;
private:
CliHandler(const CliHandler&){}
CliHandler& operator=(const CliHandler&){}
};
//Constructor
CliHandler::CliHandler(int argc,
... | Change the code to:
argv_[i] = (char*) malloc(strlen(argv[i]) + 1) ;
strcpy(argv_[i], argv[i]);
It's because your StrCpy likely trashes your memory. You have to account for the terminating nul byte as well, provided your StrCpy works like the standard strcpy (which it has to in order to be useful, better just use ... |
5,941,843 | 5,941,889 | Vector iterator override operator -> | I have for homework to make my own abstract class Vector. This vector should have iterator. I make iterator in public part of the Vector. This is my code for iterator:
class iterator {
friend class Vector;
Vector* v_;
int position_;
iterator(Vector* v,int position)
: v_(v),
position_(position... | I believe you're really wanting a slightly modified definition that gets the value at the current position of the vector, i.e., return &((*v_)[position_]); if you've overloaded the operator[] of your vector class. Otherwise in order to get access to the buffer_ of your vector, you have to dereference the vector first ... |
5,941,908 | 5,973,185 | How can I implement an efficient whole-word string replacement in C++ without regular expressions? | Perhaps I'm overlooking something obvious but I was wondering what the fastest way to implement whole-word string replacement in C++ might be. At first I considered simply concatenating spaces to the search word, but this does not consider the string boundaries or punctuation.
This is my current abstraction for (non-wh... | I think you can do this, both doing whole-word matching and doing it efficiently. The key is to:
detect "whole-word" boundaries using 'std::isalpha', which should work with Unicode & any locale.
do the replace "out of place" by creating a separate 'output' string that you swap with 'input' at the end of processing, i... |
5,941,964 | 5,942,006 | Where is <regex> in Visual Studio 2005? | I am back-porting a VS2010 project to VS2005 (don't ask why..). In VS2010 the following works just fine:
#include <regex>
But in VS2005 its a fatal error:
fatal error C1083: Cannot open include file: 'regex': No such file or directory
Any ideas?
EDIT: I should add that I am a C++ / VS newbie. If is simply not part... | There is no <regex> in VS2005. That header is part of the new C++ standard features which are partially supprted by VS2010, but not supported at all by VS2005.
However, <regex> is based on boost.regex, which can be downloaded for Windows at boostpro.com
|
5,942,168 | 5,942,307 | C library to build video directly from buffers on Linux, preferably portable to Windows and Mac OS X | I have a program that creates frame buffers in OpenGL. I can save out the buffers as .png or as .jpg files, and I am familiar with some utilities on Windows (like http://www.radgametools.com/bnkmain.htm) that will convert multiple image files to .mpg
But I would like an open source library to call with my buffer alrea... | Since you are looking for a library, I suggest taking a look at OpenCV (it's cross-platform library supported on Windows/Linux/Mac).
I've written the code below some time ago. It loads two JPG images from the current directory and creates a video file with it. I believe it's more than enough to get you started.
#includ... |
5,942,229 | 5,942,644 | Custom C++ cout class - output to both console and log file | I'm working on a program that makes heavy use of "cout << strSomething;" to log information to the console. I need to modify the program so that all console output goes to both the console AND a file. Although I can modify the "cout <<" in our code, there are several large third party libraries that also use "cout <<... | The sync calls can be replaced with pubsync. As for the overflow call I think that may be a typo. as it looks as if it should be a call to sputc.
|
5,942,328 | 5,942,353 | Default constructors C++ | Lets say I have this class:
class X {
public:
int x;
};
I saw that if I create an instance of X locally, x will not be initialize to 0, only if I create it globally.
Does this mean that the default constructor isn't synthesized by the compiler(I doubt it) for objects created localy or it will be synthesized but n... | Constructors in C++ don't generally initialize members to 0. You have to explicitly initialize members with a value.
The reason that in the global case the memory is zero, is because static memory gets initialized to zero before anything else happens to it. In your case, the implicitly generated default constructor get... |
5,942,447 | 5,942,582 | Intermediate code from C++ | I want to compile a C++ program to an intermediate code. Then, I want to compile the intermediate code for the current processor with all of its resources.
The first step is to compile the C++ program with optimizations (-O2), run the linker and do most of the compilation procedure. This step must be independent of ope... | Just a suggestion - google clang and LLVM.
|
5,942,462 | 5,942,514 | C++ Array of Arrays, defining parts separately | I'm trying to make an array of arrays containing 2 lists of strings (one singular and one plural).
string item_name[2][6];
string item_name[0] = {"bag of CinnaCandies", "can of Arizona Tea", "Starbucks Mocha Frappe", "copy of Section 8: Prejudice", "Sushi Box", "pair of Nike Jordans"};
string item_name[1] = {"bags of C... | Initialise normally, but instead of a regular constant you use a sub-array:
string item_name[2][6] = {
{"bag of CinnaCandies", "can of Arizona Tea", "Starbucks Mocha Frappe", "copy of Section 8: Prejudice", "Sushi Box", "pair of Nike Jordans"},
{"bags of CinnaCandies", "cans of Arizona Tea", "Starbucks Mocha Fr... |
5,942,574 | 5,942,634 | Why specify class name when declaring member functions? | class C : public B
{
public:
void C::Test();
};
What is the point of specifying C in the declaration of the member function?
| You shouldn't do this. Many modern compilers will treat this as a syntax error, for example, g++ 4.2.1 will!
|
5,942,602 | 5,942,923 | Static members being destroyed while there are still outstanding instances? | I need to access a static data member from a destructor, but on program exit it seems that it cannot be guaranteed to still exist! For some reason, the static members are being destroyed whilst there are still outstanding instances of the class. It's odd because I've never heard the advice "Never access static members ... | This is clearly a problem of static destruction order. I would recommend something like the following:
class MyClass {
public:
MyClass() { add_instance(m_name, this); };
~MyClass() { erase_instance(m_name); }
private:
long m_name;
static std::map<long, MyClass*>& get_instance_ma... |
5,942,761 | 5,942,900 | String/char arrays inside struct | I am trying to create a struct that has multiple string arrays inside of it. For my purposes I wanted to use std::string arrays but char * arrays would also work if they can get the job done. Either way I can't figure out how to initialize things. This is what I have:
initialize.h
#include <string>
struct myStruct
{
... | You cannot use the { } array initialization syntax to assign values to arrays. It can only be used when initializing the array right after definition:
int a[3] = { 3, 4, 5 };
but not
int a[3];
a = { 3, 4, 5 }; //error
you will not get around a loop or a manual initialization of every member. But I think the new C++0x... |
5,942,871 | 5,943,093 | Why define constants in a class versus a namespace? |
Possible Duplicate:
Static members class vs. normal c-like interface
I am looking at somebodies code and there are several dozen constants defined in a class like this:
// header file
class Defines
{
public:
static const int Val1;
static const int ValN;
static const char* String1;
static const char* ... | In general, there's no reason to use a type this way. I have seen it argued that if the "collection of constants" evolves into a concrete object, starting this way makes the transition easier. In practice, I've never seen this happen. It just hides intent, and potentially flutters the code with private constructors.
O... |
5,943,425 | 5,943,442 | Is there a data type in Python similar to structs in C++? | Is there a data type in Python similar to structs in C++? I like the struct feature myStruct.someName. I know that classes have this, but I don't want to write a class everytime I need a "container" for some data.
| Why not? Classes are fine for that.
If you want to save some memory, you might also want to use __slots__ so the objects don't have a __dict__. See http://docs.python.org/reference/datamodel.html#slots for details and Usage of __slots__? for some useful information.
For example, a class holding only two values (a and b... |
5,943,571 | 5,943,605 | Copying Methods from Member | I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For ex... | Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member ... |
5,943,721 | 5,972,122 | c++: program settings - boost.PropertyTree or boost.program_options? | I was looking for a solution to store program settings or options or configuration in C++. These could be settings that are exposed in a GUI and need to be saved between runs of my code.
In my search I came across boost.PropertyTree which seemed to be a good choice. I know boost is well respected code so I'm comforta... | After some digging around I think boost.PropertyTree is still the best solution because it gives me the capability to save the options after changing them from within the program which is a requirement.
|
5,943,892 | 5,944,034 | Windows C++ bring launched child process to foreground | I am launching a child process via CreateProcess API. However, because it takes some time to start up and show its main window, its possible for the user to click elsewhere in the parent window while this is happening. The child window then goes to the background. How would I get it back into the foreground from the pa... | I've used SetWindowPos() for this in the past. It's kind of a swiss army knife, it can move and resize windows, as well as change their z-order position. You just want to change its z-order to HWND_TOP.
|
5,943,910 | 5,943,967 | Using unordered_map of C++0x | I am using an unordered_map which is included as:
#include <unordered_map>
and the program is compiled as follows:
g++ Test.cc -std=gnu++0x -o test
Am I using the unordered_map of TR1 or that of C++0x. Or is it both the same?
| I believe gcc puts their TR1 headers in <tr1/unordered_map>, so you should be getting the C++11 version. But they are very similar.
|
5,943,960 | 5,944,088 | c++ getting TwoRandomNumbers, min and max |
Possible Duplicate:
C++ Random number homework question
Guys, I need help (yes, last minute homework help). I'm suppose to write a function named getTwoRandomNumbers that uses two parameters to return two different random numbers. The function is suppose to accept two parameters that specify the minimum and maximum... | First off, you're on the right path with passing back both values through the parameters of the function. Then it seems like you're also trying to get the 2nd value back through the function return.
Since you need to get more than 1 value from the function, ignore the return value and just use the 2 parameters passed ... |
5,944,001 | 5,944,044 | C++ Function Call vs. New Blocks for Push/Popping on the Stack | I was reading about variable scope in C++ and encountered an interesting block structure:
int main(int argc, char **argv) {
int local;
{ // New level of scope
int more_local;
}
return 0;
}
I understand that variables are popped out of the stack at the end of each block denoted by the closing ... | Well, you could say that your first example could be seen as an inlined function. :P
But generally, function calls and opening a new scope have nothing to do with each other.
When you call a function, the return address and all arguments are pushed on the stacked and popped from it after the function returns.
When open... |
5,944,210 | 5,944,240 | Performance wise... exec(c++) or straight PHP? | Wondering what would be quicker for a mysql open, select, and a generic output of the data:
A) C++ code compiled, an being called through exec() (or something equivalent)
or
B) Straight PHP Code.
Given that all code is equally coded in both C++ and PHP.
Did a test:
this is the C++
Document Length: 100000 bytes
C... | So let's see. Let's fire up a shell, pass it some arguments, which fires up another app, which loads a series of .so libraries, and THEN connects to mysql, does stuff, then has to return a potentially huge lump of output via printf() or equivalent, which then has to be fed back to PHP, parsed as plain text, torn apart,... |
5,944,234 | 5,944,647 | Win32_NetworkAdapter Class returns NULL for boolean NetEnabled; | I am using this example of the WMI: http://msdn.microsoft.com/en-us/library/aa390423%28v=vs.85%29.aspx
I retrieved information from the Win32_NetworkAdapter Class like the Name, and MACAddress;
However, when I get boolean NetEnabled; the vtProp VARIANT is NULL?
Any suggestions would be appreciated. Thanks. (Windows ... | From the documentation you linked to:
NetEnabled
Data type: boolean
Access type: Read-only
Indicates whether the adapter is enabled or not. If True, the adapter is enabled. You can enable or disable the NIC by using the Enable and Disable methods.
Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: Thi... |
5,944,428 | 5,944,486 | Parsing tab separated data | I have a text file (~10GB) with the following format:
data1<TAB>data2<TAB>data3<TAB>data4<NEWLINE>
I want to scan through it and do processing only on data2. What is the best (fastest) way to extract data2 in C++.
EDIT: Added NEWLINE
| Read the file line by line. For each line, split on the tab. That will leave you with an array containing the fields, allowing you to work with the second field (data2).
|
5,944,616 | 5,944,640 | Not a recognized operator or type when #define new is added | I'm trying to solve a part of my program, which has a #define new. Everything works well, until I try to create a class template that overrides the new operator, when I get the errors:
C:\Define_New_problem\main.cpp:18: error: expected type-specifier before 'dPushMemManFileLine'
C:\Define_New_problem\main.cpp:18: error... | Don't.Ever.#define.Keywords.
Please, just don't. It only makes problem. A #define replaces all occurences of the defined word with what you define it to be, so after the #define'd new gets expanded, the operator overload looks like the following:
static void* operator dPushMemManFileLine( __FILE__, __LINE__ ) ? 0 : new... |
5,944,797 | 5,958,345 | It takes quite a moment for socket.read_some to return after socket.close has been called, in linux | I'm using Boost.Asio as a simple socket library.
When I open a socket, I create a thread which keeps reading on that socket, and returns when the socket has been closed, or some other errors occured.
while((read = socket->read_some(buf, ec)) != 0) {
// deal with bytes read
}
This code works well on Windows and Mac... | Finally I found the reason: in Linux if you close a socket with socket::close, the socket is not closed. You must close a socket gracefully to close it successfully.
socket->shutdown(shutdown_both); // add this
socket->close();
|
5,944,861 | 5,944,913 | C++ virtual method problem | I have two structs, in which I'm trying to overwrite a method in the base struct.
The base struct is defined as:
template <class T>
struct compareFunction : public std::binary_function<T,T,bool> {
virtual bool operator() (const T & first, const T & second) {
//This function is always called
retur... | According to the code you've posted, in order to have a overridden derived class' function to be called, you MUST call it from a pointer or reference to the base class type, not an object whose type is of the base class itself. So when you create code like this:
cmpType x = compareVar;
x(std::pair<int,double>(8,20.0),... |
5,944,880 | 5,944,931 | C++: Reading from stringstream | I have an istringstream object with string of format
STRING,INT,INT,INT
eg.
"name,20,30,40"
I want to read the values into variables of specific types such as std:string and int.
How can I do that?
| The lazy way:
getline(stream, str, ',');
char c;
stream >> i1 >> c >> i2 >> c >> i3;
It is "lazy" because it does not handle format errors in any sensible way.
The smarter ways would be split on commas into a vector of strings (which can then be converted into integers as needed), or use a full-fledged parser, such as... |
5,944,882 | 5,944,893 | Problem with temporaries |
Possible Duplicate:
return type in c++
#include<iostream>
int& fun();
int main()
{
int p=fun();
std::cout<<p;
return 0;
}
int & fun()
{
int a=10;
return &a;
}
why does this code give error as,error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'..Actually i ... | &a generates a temporary which cannot be bound to a non-const reference.
Moreover your code has several flaws.
1) &a has type int* whereas you are returning by reference i.e int &. The types don't match.
2) Even if you change &a to a in the return statement you code still won't work because returning a local variable ... |
5,945,007 | 5,945,078 | Use visual basic and c++/c# in tandem | Quick question. I am developing a visual object recognition system in c++/c# as a class which needs to be used in a VB program. Is there any way to utilize c++code from VB? I.E. call methods, return variables, etc.
Thanks,
Kidovate
| If your C++ component is a COM object there is no issue. When you say "c++/c#", those are worlds apart, if it it C# then vb will see it natively, otherwise you will need to do some COM interop.
|
5,945,507 | 5,945,551 | Why doesn't C++ enforce const on pointer data? |
Possible Duplicate:
Why isn't the const qualifier working on pointer members on const objects?
Consider the following class that has a pointer member int *a. The const method constMod is allowed by the compiler even though it modifies the pointer data. Why doesn't the compiler make the pointer data const in the cont... | It's just an ownership issue... there's no way the compiler can know if the pointed-to object is logically part of the object or not, so it's left for the programmer to police such issues. const members are allowed to perform operations with side effects, as long as they don't modify their own apparent value. It's no... |
5,945,555 | 5,945,641 | examples of how to write beautiful c++ comments | maybe is stupid question but is there any way to write good looking (short ) format
to write comments for c++ function,headers,variable ? any visual examples?
| What do you mean by good looking here ?
I do it like this ..
int c;//! loop Counter
/**
* compares (XOR) two Types
* return boolean result
*/
bool compare(Type l, Type r);
Its doxygen format. there are populer formats for documenting codes in Comment. Doxygen is one and another one is naturaldocs. there are even m... |
5,945,756 | 5,946,063 | wxWidgets: undefined reference to wxURL | When I create a wxURL object I get an undefined reference error:
#include <wx/url.h>
....
wxURL url(L"http://site.com/file.txt");
)]+0x8d)||undefined reference to `wxURL::wxURL(wxString const&)'|
)]+0xba)||undefined reference to `wxURL::~wxURL()'|
)]+0x15e)||undefined reference to `wxURL::~wxURL()'|
Why might that ... | When you compile your code, are you linking the corresponding .cpp files / libraries (related to wxURL) also ? That's essential, because your errors are link time.
|
5,945,897 | 5,945,936 | What is dynamic initialization of object in c++? | What is dynamic initialization of objects in c++?
Please explain with an simple example...
| Dynamic initialization is that in which initialization value isn't known at compile-time. It's computed at runtime to initialize the variable.
Example,
int factorial(int n)
{
if ( n < 0 ) return -1; //indicates input error
else if ( n == 0 ) return 1;
else return n * factorial(n-1);
}... |
5,945,910 | 5,946,103 | Error raised Debug Assertion Failed _BLOCK_TYPE_IS_VALID when delete is used | I am trying a simple code in C++ but I am getting Debug Assertion Failed _BLOCK_TYPE_IS_VALID error when I delete the pointer. I don't know what I am making wrong. here is my code.
hash_map<string,string> m_hashDetails;
m_hashDetails.insert(hash_map<string,string>::value_type("test",*(new string("test123"))));
... | You have allocated using operator new; BUT you are not storing the pointer to it. Rather you are storing of the allocated chunk;
int *p = new int(1); // ok, can be deleted later
int i = *new int(1); // memory leaked already, cannot delete as pointer is missed
Also, std::string is not a pointer type, so you cannot dele... |
5,946,189 | 5,947,538 | C++ version of CopyOnWriteArrayList | Java has CopyOnWriteArrayList, which enables me to iterate and mutate using 2 different threads simultaneously, without having any external locking.
Do we have any similar thread safety data structure for C++?
| There's nothing in the standard library which would support this. Given
the interface to C++ standard containers, I'm not sure it's possible.
You'd have to start with something like:
template <typename T>
class CopyOnWriteVector
{
boost::shared_ptr<std::vector<T> > myData;
void uniqueCopy()
{
myDat... |
5,946,218 | 5,946,252 | how to use #if,#else,#endif... inside c macro | #include < iostream >
#define MY_CHK_DEF(flag) \
#ifdef (flag) \
std::cout<<#flag<<std::endl; \
#else \
std::cout<<#flag<<" ,flag not define"<<std::endl; \
#endif
int main()
{
MY_CHK_DEF(FLAG_1);
MY_CHK_DEF(FLAG_2);
MY_CHK_DEF(FLAG_3);
...
}
complier report:
main.cpp:3:24: error... | You can't do it. #if, #else, and #endif must be the first tokens on the logical line. Your definition is just one logical line, so it doesn't work,
|
5,946,225 | 5,946,294 | C# or C++ - Good Resource for an Overview on Windows Graphics - 2D, drawing pixels directly | I have this odd little lifesim program I've been working on that involves data in a 2d array. This was never supposed to be a big thing, and I initially looked at a few snapshots of it by just writing it out to an external bitmap, pixel by pixel, which I then open and look at. This doesn't give me any sort of live upda... | You could try the WriteableBitmap class in WPF and see if it fits your purposes.
A tutorial
All you would have to do is keep the data in the 2D array and write it to the WriteableBitmap. Set the WriteableBitmap as the image source of a WPF Image and you're done.
Let me know if you need an example.
|
5,946,233 | 5,946,358 | Dijkstra's algorithm with an 2d-array | For the past few days I've tried to implement this algorithm. This far I've managed to make a dynamic 2d array and insert the distances between nodes, a function to remove a path between nodes and a function that tells me if there is a path between two nodes.
Now I would like to implement a function that returns the sh... | You are probably thinking to much.
You need 2 things. A clean graph structure you understand. A good description of the algorithm you understand.
If you have both. Just start writing some code. Helpers needed will become obvious on the way.
-- edit --
You will probably need some of the following datastructures
std::v... |
5,946,596 | 5,947,292 | How to write text into window? | Parent form handle hwnd is existed. Now I want to populate it with edit controls into which output-text is written. I am not familiar with WIN32 API, Thanks for showing me some code examples. Thank you!~
| http://msdn.microsoft.com/en-us/library/ms633546(VS.85).aspx
If you want to set text using chars then you can use SetWindowTextA so you don't need to bother with multibyte to/from wide characters.
I suggest the Programming Windows book by Charles Petzold.
You say hwnd is your parent then you could create the edit contr... |
5,946,704 | 22,421,565 | C++ Get Local IP address,differentiate between the VPN and local network | My computer is connected to the local network(ethernet adapter) with ip address 10.3.3.3 and it is connected with my VPN(PPP adapter) with the IP address 172.4.0.70
Now, how can I get my local IP(10.3.3.3) programmatically?
I had tested using the following code.
But I can't differentiate between the VPN and local netw... | Few years later...
Just ran into the same issue, and figured out a solution. You can use GetAdaptersInfo() to get all the local adapters, and then cycle through the list and pick the first with a valid subnet mask and a default gateway (my VPN adapter didn't have one).
If you have both WiFi and Ethernet with default ga... |
5,946,904 | 5,947,140 | Distributed build tools in Visual C++? | We're working on pretty large middleware software, and it takes 10-20 minutes each time we need to re-build the whole solution in VS2008 (quad-core parallel build on a single machine). I've heard there are rather expensive VS extensions like Incredibuild that make use of other machines in your network (we have about 10... | Well we had similar problems except that in our case it took over 40 minutes to build.
With Visual Studio 2008 we used Xoreax Incredibuild ( see Xoreax web site ) and it dramatically reduced the build time (i.e. to half the time or better). So I would say yes, such a tool can help. And, in my opinion it is not so expe... |
5,946,927 | 5,946,971 | converting boost shared_ptr to void* and vice versa | Can I convert boost shared_ptr to void* and back to boost::shared_ptr? I need this because I need to pass the shared pointer and a callback function to a timer function implemented in C. And in the call back I need to convert the void* pointer back to boost:shared_ptr. Doing so gave me errors.
I tried the same with a s... | Just one more asterisk:
boost::shared_ptr<A> b = *(boost::shared_ptr<A>*)(arg);
|
5,946,993 | 5,947,066 | Swap out generally used functions in C++ | Hey there,
I have a big code file currently in C++ with many functions which I often use in different versions of my program so I thought about swapping out the generally used functions: E.g. I have:
void doSomething(mxArray *in)
{
mexPrintf("Hello Matlab");
}
whereas mxArray and mexPrintf are defined in another f... | C++ (unlike C) will refuse to make dubious assumptions about the signature of functions for which it hasn't seen a declaration, and compilation will fail with an error message. If you don't get an error, then some header is picking up a declaration for that function. If you can't find it, then try running only the pr... |
5,947,061 | 5,947,153 | mutex as class member | class temp
{
boost::mutex mx;
void CriticalCode() {
boost::mutex::scoped_lock scoped_lock(mx);
//Do Something
return;
}
}
If this class is allocated on the heap (temp* T = new temp()), will this be thread safe (for each instance, not all instances together)?
If I make boost::mu... | 1)if this class is allocated on the heap (temp* T = new temp()) , will this be thread safe (for each instance, not all instances together ?
Yes. Since mx is not a static member of the class, there will be one lock per instance of the class.
2)if i make boost::mutex mx -> boost::mutex* mx , and allocate it in the cons... |
5,947,129 | 5,947,148 | how to set char * value from std string (c_str()) not working | i dont know but this not working for me im getting garbege value when i try to set char * value from function that returns std string :
string foo()
{
string tmp ="dummy value";
return tmp;
}
char* cc = (char *) foo().c_str(); // if i remove the casting im getting error
// when i print the cc i get garbage
pri... | The lifetime of the data pointed to by cc is the same as the lifetime of the string it came from (at best - if you modify the string it's even shorter).
In your case, the return value of foo() is a temporary that is destroyed at the end of the initialization of cc.
To avoid the compilation error in char *cc = foo().c_s... |
5,947,395 | 5,947,854 | Passing user data with timer_create | I am using timer_create to create a timer in Linux. The callback prototype is:
static void TimerHandlerCB(int sig, siginfo_t *extra, void *cruft)
How can i pass user data so that i can receive the same in the callback called after timer expiry.
Here's my sample code:
int RegisterTimer(iDiffInTime)
{
struct siga... | You are already doing it:
sigev.sigev_value.sival_ptr = &timerid;
You can specify anything in there (specifying &timerid is common to discern between multiple timers but is not required). Now in your handler:
static void timer_handler(int signo, siginfo_t *si, void *uc)
{
/* si->si_value.sival_ptr */
}
Quote from... |
5,947,437 | 5,947,469 | c++ what's the result of iterator + integer when past-end-iterator? | suppose you have a random access iterator (eg of std::vector myVector)
when iter + someInt is past-end-iterator,
iter + someInt == myVector.end() ??
or could it be different value than myVector.end() ?
| It's Undefined Behavior. Anything may happen. Just to name a few of the options: Nothing at all, program exits, exception, crash.
|
5,947,455 | 5,976,109 | Connecting qml-signals to Qt | I'm trying to use a qml-grid view in my code. I'm trying to couple it with my C++ code.
I've dynamically created a list view model and passed across the qml file. It works fine.
However, I'm facing trouble when I want to connect a Qml signal to Qt/c++ code. I've handled mouseArea in my Qml-rectangle and emitting a sign... | I could finally get this working. I'm not sure if this is the real solution to the problem, but finally this got it working:
I was setting the qml path as a relative path to my working folder. And yes the path was indeed correct, as I could see the qml and its contents. I just happened to change the qml path from relat... |
5,947,514 | 5,947,569 | How to detect automatic NT service will start | I'm working on a simple NT service with an application that will monitor it and display status in the task tray. On starting the monitor checks if the service is running and prompts to start it if it's not. This is fine until a reboot when the monitor starts before the service and prompts to start it even though it wil... | I don't think there's any way to predict what the service control manager will do in the future. However, I can think of a couple of things that could mitigate your situation:
Monitor the state of the service periodically, and when it goes to "starting", update your icon status appropriately
Check the autostart settin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.