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,924,681 | 5,924,696 | Are Elipses in case statements standard C/C++ | I was browsing some code in the linux kernel and I came across the statements like case '0' ... '9':
To try this out I created the test program below.
#include <iostream>
int main()
{
const int k = 15;
switch (k)
{
case 0 ... 10:
std::cout << "k is less than 10" << std::endl;
break;
... | That is the case range extension of the GNU C compiler, it is not standard C or C++.
|
5,924,702 | 5,925,295 | PyQt4 create windows that are unresizable | For some reason, any widget I create using PyQt4 cannot be resized. When i try and resize the window with the mouse nothing happens. The following simple program reproduces this behavior on my machine:
from PyQt4.QtGui import QMainWindow, QApplication
from sys import argv
app = QApplication(argv)
mw = QMainWindow()
ap... | I have found the solution - it turns out I had broken my compiz settings in a rather... unique manner, which caused Qt apps to not resize correctly. Thanks to everyone who answered however!
|
5,924,707 | 5,924,782 | fwrite chokes on "<?xml version" | When the string <?xml version is written to a file via fwrite, the subsequent writing operations become slower.
This code :
#include <cstdio>
#include <ctime>
#include <iostream>
int main()
{
const long index(15000000);
clock_t start_time(clock());
FILE* file_stream1 = fopen("test1.txt","wb");
fwrit... | On Windows, most (all?) anti-virus software works by hooking into the file read and/or write operations to run the data being read or written again virus patterns and classify it as safe or virus. I suspect your anti-virus software, once it sees an XML header, loads up the XML-malware virus patterns and from that point... |
5,924,708 | 5,924,799 | How would I create multiple arrays using a class constructor without creating more than one array in the class? | I am working on an exercise in operator overloading. I've created a matrix class and I am supposed to overload operators so I can do arithmetic on matrices efficiently.
My directions say that I am supposed to make two matrix arrays using the class constructor that has 2 parameters and a third matrix array that will be... | You are misunderstanding the question. You are required to make a Matrix class that has 1 two dimensional array and then use the constructor to make two different matrices and then add them and store the result into a third one. So you will end up with something like this
matrix::matrix(int Size, int Range)
{
... |
5,924,763 | 5,924,806 | C++ getting rid of Singletons: alternative to functors and static methods | My noble quest is to get rid of singletons and static classes.
Background:
I have the following structures:
CmdFrequently instantiated object, it holds a name of the command (string), and functor to the static method of any class as a pointer.It is typically created in main classes such as Input, Console, Render, etc.... | This is a job for the function class. You can find one in Boost, or in TR1 or C++0x. It looks like std::function<void()>, for example. This is often partnered with bind, which you will need if you want to refer to functional objects in a generic way, rather than take them by value, and is also found in Boost, TR1 or C+... |
5,924,775 | 5,924,787 | Create undeletable file and hidden | I'm using win32. I wanna create a hidden and undeletable file using CreateFile() if possible. I haven't tried anything so far because the documentation is complex.
Here is an example where my app would be useful.
Let just say we have two people living in the same room, like in college. One of them Always goes on the ... | It's not possible to create a hidden and un-deletable file.
The closest you can get is creating a file with the hidden attribute and having a process run at all times to keep the file locked, preventing deletion.
This, of course, doesn't prevent the user from checking 'Show Hidden Files' in folder options, closing the... |
5,924,870 | 6,179,994 | What is decltype(0 + 0)? | (Prompted by an answer.)
Given N3290, §7.1.6.2p4, where the list items are unnumbered, but numbered here for our convenience:
The type denoted by decltype(e) is defined as follows:
if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named b... | From 5.19 [expr.const], every literal constant expression is a prvalue.
A literal constant expression is a prvalue core constant expression of literal type, but not pointer type. An integral constant expression is a literal constant expression of integral or unscoped enumeration type.
Therefore rule 4 applies to all ... |
5,925,177 | 5,925,243 | Check for exited child processes in POSIX? | I'm trying to write a program that checks for exited child processes and restarts them if they have exited. It needs to restart the processes as they exit, without waiting for any other processes to have exited. I'm a little lost. Here's the code that I've done so far. It's not finished or correct, really. But perhaps ... | The problem with your approach is that you are going to block on waitpid until that 1st [0th] child dies and any of the others may die in the meantime.
You can:
(1) Use wait() instead of waitpid(). This will process any of the children but it will block.
(2) poll for dead children using waitpid() and the WNOHANG flag... |
5,925,254 | 5,957,179 | Boost c++ static link paths under cygwin | I wrote a program in c++ leveraging header files from boost. When I compiled it I noticed I had some undefined symbols for boost system and boost file system (which I expected). I've finally gotten my program compile and link, but I arguably don't understand why. If someone could lend some insight on the following I wo... | Okay - so found some stuff. First in terms of search paths see: http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html. This helps clarify search paths when you link.
Secondly - note the idea of using -mt at the end of the name is from an older boost convention which is no longer necessary.
See: http://groups.google.com/... |
5,925,282 | 6,169,963 | Instantiating shared_ptr's in boost::python | I had a question about boost python. I've been working on exporting some functionality of a project into boost python, and I haven't found a way to solve the following problem:
I have a set of StatusEffect objects that i store and use throughout the game. At the game startup, I want to be able to call a python script t... | I hope I am understanding your question. If you declare your python class with the shared_ptr as shown at http://wiki.python.org/moin/boost.python/PointersAndSmartPointers, then boost::python will automatically convert StatusEffect objects you create in python to shared_ptr<StatusEffect> if necessary (you can try this ... |
5,925,577 | 5,925,603 | What programming language for a webserver | What should be the programming language chosen for web server.
The only thing I'm looking for is efficiency, doesn't matter how much time will it take to develop.
I recently saw some benchmarks where results show JAVA faster.
I don't know how much those benchmark programs are relevant to developing a web server.
Well, ... | There are many languages that can be used to write a Web server, and many languages have already been used to write webservers.
Java is used to build Apache Tomcat and the Jetty Web Server. Resin is another example of a Web server written in Java.
The Apache Web Server was written in C.
The POW Webserver was writt... |
5,925,658 | 5,930,164 | Does anyone know C++ XML parser/writer similar to .Net's XML Document? | I'm writing a native C++ project and I need a simple XML parser/writer. I already know XmlDocument in C#, so something similar could be quite good, but if there isn't, does anyone know a quick-to-use XML parser/writer?
I'm trying to shorten my "learning of the library" time to minimum.
Thanks!
| I ended up using RapidXML (http://rapidxml.sourceforge.net/).
For me, its intuitive, and was really easy to learn.
No body recommended it so I added my own answer :-\ ...
|
5,925,927 | 5,925,935 | Different answers from strlen and sizeof for Pointer & Array based init of String |
Possible Duplicates:
C: differences between pointer and array
Different sizeof results
Basically, I did this...
char *str1 = "Sanjeev";
char str2[] = "Sanjeev";
printf("%d %d\n",strlen(str1),sizeof(str1));
printf("%d %d\n",strlen(str2),sizeof(str2));
and my output was
7 4
7 8
I'm not able to give reasons a... | Because sizeof gives you the size in bytes of the data type. The data type of str1 is char* which 4 bytes. In contrast, strlen gives you the length of the string in chars not including the null terminator, thus 7. The sizeof str2 is char array of 8 bytes, which is the number of chars including the null terminator.
S... |
5,925,951 | 5,926,044 | Difference in digits10 between GCC and MSVC | I have the following code:
#include <iostream>
#include <limits>
int main()
{
std::cout << std::numeric_limits<unsigned long long>::digits10 << std::endl;
return 0;
}
GCC 4.4 returns 19
MS VS 9.0 returns 18
Can someone please explain Why is there a difference between the two? I would have expected such a c... | If Visual C++ 2008 returns 18 for std::numeric_limits<unsigned long long>::digits10, it is a bug (I don't have Visual C++ 2008 installed to verify the described behavior).
In Visual C++ (at least for 32-bit and 64-bit Windows), unsigned long long is a 64-bit unsigned integer type and is capable of representing all of... |
5,925,960 | 5,925,976 | i wanted to create a function where i can enter a string and it would output a a jumbled version of the string | i cant seem to figure out what wrong
for some reason it wont compile and it think theres a problem on my jumbleString function
#include <iostream>
#include <iomanip>
#include <string>
#include <istream>
using namespace std;
int main ()
{
int lengthofstring, x, countWords(string str), countConsonant(string str, in... | the problem is changing i inside the loop (I guess you meant to change k):
if you did mean to set k, change i = rand() % length; into k = rand() % length;
also, your question is a variant of the permutation problem, which Fisher-Yates solves. I would suggest looking at it, you will probably get better "randomness" ... |
5,926,060 | 5,926,069 | How to convert object to int? | I have a class named object that have some instance vars. I want to save it to file. How can I cast it to type(e.g. int) that can be written to file?
| If I understand correcty you want to save an object to hard drive? That is called serialization. You might want to check the boost library for that.
|
5,926,087 | 5,926,230 | Why does CreateFile return invalid handle? | I have CreateFile() to create a hidden file type but the problem that it keeps returning invalid handle.
file = CreateFileW(_T("hey.txt"),
GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
0, 0);
error = GetLastError();
WriteFile(file, buff, sizeof(buff),
&dwRet, NULL);
Any idea?... | It would probably be best if you showed the exact code that you're using including all the error checking, and how you do it, is important (especially in the case of this question)...
The correct error checking for your code should be something more like...
file = CreateFile(_T("hey.txt"), GENERIC_WRITE, 0, NULL, CREAT... |
5,926,094 | 5,926,110 | Complex data structures while embedding\extending Python with C++ | Python documentation gives a nice introduction to Extending and Embedding Python with C\C++. However, in many cases there's a need to transfer complex data structures between the languages.
What would be the best way to achieve this?
| Create your own type and fill the tp_*attr members appropriately.
|
5,926,113 | 5,926,142 | c++ question, about * and -> | when I have a pointer like:
MyClass * pRags = new MyClass;
So i can use
pRags->foo()
or
(*pRags).foo()
to call foo.
Why these 2 are identical? and what is *pRags?
Thank you
| pRags->foo() is defined as syntactic sugar that is equivalent to (*pRags).foo().
the * operator dereferences a pointer. That is, it says that you're operating on what the pointer points to, not the pointer itself.
|
5,926,194 | 5,926,223 | how to use this c++ template function. simple beginner question | I found this merge sort function but i dont know how to use it.
please help
#include<iostream>
#include<stdlib.h>
#include<vector>
using namespace std;
template <typename Comparable>
void mergeSort(vector<Comparable*> &v)
{
mergeSortPart(v, 0, v.size() - 1);
}
template <typename Comparable>
void mergeSortPart(vec... | As the parameter to mergeSort is vector<Comparable*>, it can only sort vectors of pointers, and not vectors of ints or other objects.
|
5,926,279 | 5,926,290 | c++ arguments evaluation order |
Possible Duplicate:
Order of evaluation in C++ function parameters
In C++
is the order of arguments evaluation defined or undefined?
My friend said it's defined , and like a STACK, been pushed from rightmost to left.
Is this right or not?
Thank you
| No it is not defined by the C++ standard.
|
5,926,338 | 5,926,359 | Why this is not a vexing parse? | Basically this is a follow up of this question about most vexing parse. I can understand that this is due to the ambiguity between the function declaration and variable definition.
But in Comeau online, I just tired the following.
class T{
public:
T(int i){
}
int fun1(){
return 1;
}
};
int ... | The 10 cannot be a parameter type name, so this must be a variable declaration.
The compiler must choose a function declaration when it can do that, but in many cases like this it cannot and there is no ambiguity.
|
5,926,618 | 5,926,704 | Inserting element into vector from different classes | Class A{
public:
int a;
vector<A> test;
};
Class B{
public:
B();
B(const B &rhs);
~B();
B & insertTest(A element,A element1) {
element.test.pushback(element1); //doesn't work
}
B & insertTest1(A element) {
test1.pushback(element);//works
};
private... | The following doesn't work because element is passed by value
B & insertTest(A element,A element1) {
element.test.push_back(element1); //doesn't work
}
The following works since you are modifying test1, which is a member of this
B & insertTest1(A element) {
test1.push_back(element);//... |
5,926,770 | 5,927,080 | Pageheap does not make my application break | I expected that Pageheap will force my application to crash while executing the 2nd and 3rd statements in the below code piece. But this is not happening. I enabled full page heap for the application.
What extra things should I do to make pageheap to break my application at second and third statements?
char *test =new... | Allocations are rounded up N bytes, where N is a multiple of 8 and depends on which version of Windows you're using. Let's assume allocations are rounded up to the nearest 8 bytes, for this case.
Pageheap works by inserting a 'guard page' at the end of each allocation and protecting it from read/write access, so any at... |
5,927,023 | 5,927,049 | How to return an array from a function and loop through it? | #include <iostream>
int* fib(int);
int main()
{
int count;
std::cout<<"enter number up to which fibonacci series is to be printed"<<std::endl;
std::cin>>count;
int *p=new int[count];
p=fib(count);
int i;
for(i<0;i<=count;i++)
std::cout<<p[i]<<std::endl;
return 0;
}
int* fib(in... | Several issues with your code
for(i<0;i<=count;i++)
should actually be
for(i=0;i<count;i++)
and
for(j=0;j<=d;j++)
must read
for(j=0;j<d;j++)
And remove the line
delete ar;
since it does not have any effect after the return statement. Additionally you can get rid of the instantiation
int *p=new int[count];
in main... |
5,927,038 | 5,927,065 | returning array from a function |
Possible Duplicate:
howto return a array in a c++ method?
How an array can be returned from a function in c++?please accomplish your answer with a simple example too if possible.thankx in advance.
| Return a pointer to the start of the array, like:
int* getArray(int numElements) {
int* theArray = malloc(sizeof(int) * numElements);
return theArray;
}
...you can use it like:
int* myArray = getArray(3);
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
//do this when you are done with it
free(myArray);
|
5,927,194 | 5,928,993 | How to read Manifest.mbdb in cpp | How to decrypt the iTune Backup file of Manifest.mbdb using CPP code?
| Have you seen this question?
How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup
Most of the code there is Python rather than C++, but perhaps you can port it if you really need it to be C++ for some reason.
|
5,927,215 | 5,927,288 | fibonacci series between two numbers | #include<iostream>
int* fib(int);
int main()
{
int count;
std::cout<<"enter number upto which fibonacci series is to be printed"<<std::endl;
std::cin>>count;
int *p=new int[count];
p=fib(count);
int i;
for(i<0;i<=count;i++)
std::cout<<p[i]<<std::endl;
return 0;
}
int* fib(int ... | If (5*N*N + 4) or (5*N*N - 4) for a given N >= 0 is a perfect square then the number is Fibonacci. Employ this method to generate Fibonacci series between two numbers.
|
5,927,217 | 5,927,280 | Dynamic 2D array losing second dimension | I have a dynamically allocated, 2D array that is being populated within a pair of for loops. For some reason by the end of the for loops all of the elements are in inaccessible memory.
/*************Start Positive Phase*************************/
double *posHidActivations = new double[FEATURES];
memset(posHidActivation... | As you note:
posVisActivations[j]+=m_VisLayer[i]; // commenting out this line fixes
The index for posVisActivations is j, which ranges from 0 to m_FEATURES, but posVisActivations is declared to be an array with m_numRatings elements.
So, you are writing past the end of the array. You probably meant to use i as the i... |
5,927,348 | 5,927,496 | ISO C++ forbids declaration of ... with no type | I'm using C++ to make a Qt mobile application for maemo.
I have my class declaration, but I get this error:
ISO C++ forbids declaration of 'QGeoPositionInfoSource' with no type
My code is following:
phonehelper.h
#ifndef PHONEHELPER_H
#define PHONEHELPER_H
#include <QObject>
#include <QGeoPositionInfoSource>
class... | I did not see that I had to use QtMobility namespace like this using namespace QtMobility;
|
5,927,586 | 5,927,749 | When can I access an object member directly in memory? No getters called | It is usually allowed to do something like that (no comments on the code please :-))
class SimpleClass {
int member;
};
SimpleClass instance;
int* pointer = (int*) &instance;
However, if I define my class as:
class SimpleClass {
virtual void foo();
int member;
};
I can't do that anymore. Well, I guess I ... | You can only do this safely if your class is plain old data (POD).
From Wikipedia:
A POD type in C++ is defined as either a scalar type or a POD class. A POD class has no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, a POD clas... |
5,927,648 | 5,928,796 | Inheriting from a template class, using a type defined in the derived class | I'm trying to inherit from a template class, using a type defined in the derived class.
I have tried this, but it doesn't work.
class A : std::vector<A::B>
{
enum B { foo, bar };
};
Is there an elegant way of doing this ?
Edit : I know that it works if B is defined earlier. But i'm looking for a solution that allo... | In my view, the best (admittedly indirect) solution is to use composition rather than inheritance:
class A
{
enum B { foo, bar };
std::vector<B> bs;
};
If for some reason you need (or really want) to use private inheritance to embed the vector in your object, then the type will need to be defined before the cl... |
5,927,665 | 5,928,271 | Tiling with QGraphicsScene and QGraphicsView | I'm creating a image visualizer that open large images(2gb+) in Qt.
I'm doing this by breaking the large image into several tiles of 512X512. I then load a QGraphicsScene of the original image size and use addPixmap to add each tile onto the QGraphic Scene. So ultimately it looks like a huge image to the end user when ... | QGraphicsScene is smart enough not to render what isn't visible, so here's what you need to do:
Instead of loading and adding pixmaps, add classes that wrap the pixmap, and only load it when they are first rendered. (Computer scientists like to call this a "proxy pattern"). You could then unload the pixmap based on a t... |
5,927,676 | 5,927,885 | Monte Carlo Sims - Please check my algorithm | Basically, the problem simulates the following:
There is an urn with 50 green balls and 50 red balls.
I am allowed to pick balls from the urn, without replacement, with the following rules: For every red ball picked, I lose a dollar, for every green ball picked, I gain a dollar.
I can stop picking whenever I want. Wors... | Your algorithm is fine, but you are wasting information. For a certain pair (g, r) you calculate it's ExpectedValue and then you throw that information away. Often with recursion algorithms remembering previously calculated values can speed it up a LOT.
The following code runs in the blink of an eye. For example for g ... |
5,927,826 | 5,927,968 | XCreateWindow fails on CentOS 5.6 with error: BadValue | I'm using the following code to create a fake window for some integration tests:
class CXWindowsClipboardTests
{
protected:
virtual void
SetUp()
{
m_display = XOpenDisplay(NULL);
int screen = DefaultScreen(m_display);
Window root = XRootWindow(m_display, screen);
XSetWindowA... | You're using the CWEventMask but not initializing attr.event_mask. This could be your problem. (since the structure is created on stack, it'll contain random data in that field.)
|
5,927,965 | 5,928,024 | C++ control I/O of another program simultaneously | I'm controlling Gnuplot within my program for fitting and plotting; however, to get the fit parameters back, I want to use Gnuplot's print-function:
FILE *pipe = popen("gnuplot -persist", "w");
fprintf(pipe, "v(x) = va_1*x+vb_1\n");
fprintf(pipe, "fit v(x) './file' u 1:2 via va_1,vb_1 \n")
fprintf(pipe, "print va_1"); ... | I found this ready-to-use answer: Can popen() make bidirectional pipes like pipe() + fork()?
In the pfunc you supply, you have to dup2 the file descriptors received as arguments to stdin an stdout and then exec gnuplot, for example:
#include <unistd.h>
void gnuplotProcess (int rfd, int wfd)
{
dup2( STDIN_FILENO, rf... |
5,928,051 | 5,928,206 | How to draw a curve approximated to original one | I have a set of points and i want to draw a curve which should be approximated to original curve.
Let say ,in hawk-eye system(used in cricket) i have a set ofco-ordinates of ball during the entire flight of ball , now how can i draw such a curve going through ball's space co-ordinates and looks appromixately to orig... | Curves are almost always rendered in four steps:
Approximate or interpolate a set of points using a curve or spline algorithm. Choices may include:
Cubic splines, which pass through all of the data points and produce a smooth curve
Bézier curves, which do not pass through all the points, but which lie within the enve... |
5,928,226 | 5,929,546 | OOP design problem: responsibility in containee or container? | I focus a lot on making my software design flexible and reliable, and one of the key concepts to achieve this is encapsulation.
Lately I have faced a special design problem and I can't argue (with myself) what is the best solution.
A concrete example illustrating the problem: A device has an address (on a bus). The dev... | Driven to the logical extreme, a bus is an object by itself. Reading or writing a register is a bus operation, different busses have different ways to access a register. Create a bus interface with methods ReadRegister and WriteRegister.
Overdoing this is certainly a consideration, I imagine the odds that you'll ever... |
5,928,349 | 5,928,936 | Container of 2 Types | Is there any C++ container that can store 2 (or more) types of values, such as ints and chars? I want to make a blackjack game. The deck has to consist of both ints and chars. I don't want to initialize it with just numbers (so don't say anything about that!). I am a very beginner programmer, so don't make it too comp... | Since you're a beginner, just use the basic stuff: a struct.
#include <vector>
#include <iostream>
struct MyStruct{
char cval;
int ival;
};
int main(){
using namespace std;
vector<MyStruct> myvec;
MyStruct values;
values.cval = 'S';
values.ival = 42;
myvec.push_back(values);
values.cval = 'A';
... |
5,928,407 | 5,928,428 | C++ - an exception-safe way to assure a global cleanup function gets called | Context:
Suppose an external library requires that its globalCleanup() function gets called in order to assure all its resources are cleaned up (it might allocate some global resources during any of its calls.) A client function client() does this before each of its many returns but of course this is not exception-safe... | class Cleaner {
public:
Cleaner() {}
~Cleaner() { ExtLib::CleanGlobal(); }
};
void client() {
Cleaner cleaner;
// Code that works with ExtLib
}
|
5,928,483 | 5,928,997 | DLLImport -> how to handle a HANDLE in C# | in my C# code I want to import a C++ DLL. I use the dllimport and it works fine with a some of the functions. But in one function I get a HANDLE which I need later to call another function.
[DllImport("SiUSBXp.dll")]
public static extern int SI_Open(UInt32 deviceNum,ref IntPtr devHandle ); // this function gets... | Your SI_Write function looks quite like Windows Kernel32's WriteFile.
So, I would do this:
[DllImport("SiUSBXp.dll", SetLastError = true)]
static extern int SI_Open(uint dwDevice, ref IntPtr cyHandle);
[DllImport("SiUSBXp.dll", SetLastError = true)]
static extern int SI_Write(IntPtr cyHandle, byte[] lpBuffer,
ui... |
5,928,571 | 5,936,969 | Stack independent c/c++ bluetooth api? |
I wanted to know if there is any stack independent C/C++ bluetooth api for windows (XP, Vista, 7, x86 and x64).
My target is to create a connection and send/receive some time critical data over bluetooth.
My researches gave me the following options and there disadvantage for this task:
Windows Sockets for BluetoothOn... | I guess one option would be to use C++/CLI to interface with my managed Bluetooth library 32feet.NET which supports most of the stacks on Windows. http://32feet.codeplex.com/
|
5,928,748 | 5,938,968 | Threading in different methods with Qt | I have a class which has several methods and I want to call each of those methods in a different thread.
class Base : public QThread
{
copy();
move();
remove();
etc();
....
....
run();
}
Is this possible or should I inherit different classes which implement the functionality in their r... |
Is this possible or should I inherit different classes which implement the functionality in
their run() method? ( which would lead to several derived classes )
That depends on whether you want those methods to execute concurrently (on a thread pool, or on dedicated threads), or serialized.
If serialized:
Use the A... |
5,928,846 | 5,928,870 | c++ system() orphan & zombie processes | I have a little application, let's call it "launch.exe". It is a c++ appl.
What I do in it is I call system() 3 times to launch 3 other applications. let's call these A, B, and C.
problem #1
A, B, and C are GUI apps and "launch.exe" is not able to progress until A exits. Then it is stuck again until B exits. Then s... | Use spawn instead, this won't block the launcher until the child exits.
Or, since you're already using Qt, use QProcess.
There is no portable way to spawn a subprocess as a different user, but the Windows-specific way is CreateProcessWithLogonW.
|
5,929,125 | 5,929,334 | opencv houghCircles ( .... ?PARAM1?, ?PARAM2?) | cvHoughCircles(Mat& image, vector<Vec3f>& circles, int method, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0)
according to documentation:
param1 - The first method-specific parameter.
in the case of CV_HOUGH_GRADIENT it is
the higher threshold of the two passed... | Currently, the only implemented method in cvHoughCircles() is CV_HOUGH_GRADIENT.
So,
param1 - refers to the edge threshold that will be used by the Canny edge detector (applied to a grayscale image). cvCanny() accepts two thresholds and is internally invoked by cvHoughCircles(). Therefore the higher (first) threshold... |
5,929,291 | 5,930,170 | C++ Random Number Causing Crash when printing out value only. Very strange | I need a value between 0.0 and 1.0. So I seed the random number generator using time. Then I get a value between 0 and 10 using the rand function. After that I take that value and divide it by 10 to get my decimal value. My issues is that the program will randomly crash when I try and print out the value generated ... |
For the sake of the program one can assume the function is wholly independent
That's a big mistake, it never is. This has heap corruption written all over it. Which rarely causes a crash at the line of the code that corrupts the heap. Always later, sometimes much later.
|
5,929,328 | 5,929,490 | How to capture that session logoff started from windows service | I have a service which constantly checks some application and assures that it wasn't closed. If this app closed - service launches it again.
The problem starts when user decides to log off the session. During logoff all applications are closing including the mine one. But the service is still running and constantly tr... | Have your service run two applications: the one it is a watchdog for, and a second one which you implement yourself. This second one can then respond to the log-off event by sending a message to the service (a la David Heffernan's answer), and the service will then know not to restart the watched job.
|
5,929,398 | 5,929,417 | c++ bitset error in class | I'm trying to make a floodfill algorithm in C++, so my plan was to make an 2D array, and then each item would be an object, with property's to check for walls around it.
I note walls the following way,
1 = top
2 = right
4 = bottem
8 = left
so 13 would mean, top/bottem/left wall
but when i use std::bitset<sizeof(int)> ... | This will work:
std::bitset<sizeof(int)> bits;
You'll need to initialize it in constructor:
Hokjes::Hokjes() : bits(w) { }
|
5,929,402 | 5,929,433 | C++ Cannot instantiate a class from another file in main.cpp | I cannot get this to work
Addr.h
#ifndef ADDR_H
#define ADDR_H
class Foo{
public:
Foo(); // function called the default constructor
Foo( int a, int b ); // function called the overloaded constructor
int Manipulate( int g, int h );
private:
int x;
int y;
};
#endif
Addr.cpp
#include "add... | #include "addr.cpp"
You're including the .cpp file to your main.cpp, which is what causing the problem. You should include the header file instead, as:
#include "addr.h" //add this instead, to your main.cpp
Because its the header file which is containing the definition of the class Foo.
|
5,929,533 | 5,929,633 | Compile Error when Single Inheritance Approach[Qt Newbie] | I'm an PyQt programmer and trying to learn C++ Qt.
I'm following this link for learning how to import my ui files. But when I'm trying to compile, I'm getting that error:
[utdmr@utdmr-arch cpp]$ qmake -project && qmake && make
/usr/bin/uic ui.ui -o ui_ui.h
g++ -c -m64 -pipe -march=x86-64 -mtune=generic -O2 -pipe -Wall... | You should put the function definition into a .cpp file.
So create gui.cpp with the following contents:
#include "gui.h"
Gui::Gui(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
}
removing it from the .h file.
The reason you were getting the error is that the header file was being included in... |
5,929,688 | 5,929,751 | Overloading '<<' so it is usable with more than one object | I'm starting to get a grasp of operator overloading but I've hit a wall. I cant figure out how I would make '<<' work the way it is redefined to work with more than one type of object from my class. I have to use one of my class constructors to initialize two separate matrices so I need to make two different objects li... | This will work with more than one object because the << overload returns a reference to the stream. << is evaluated1 left to right, so if you do:
stream << a << b << c;
it is equivalent to:
((stream << a) << b) << c;
now, since your (stream << a) function returns an ostream&, we could think of this as:
((stream) << b... |
5,929,766 | 5,929,788 | cannot appear in a constant-expression | In the following c++ program:
static const int row = (dynamic_cast<int>(log(BHR_LEN*G_PHT_COUNT)/log(2)));
static const int pht_bits = ((32*1024)/(G_PHT_COUNT * G_PHT_COUNT * BHR_LEN));
unsigned char tab[pht_bits][1<<row];
I get the error message double log(double)’ cannot appear in a constant-expression.
why am I get... | To you that are downvoting my answer. Tell me that this code does not work:
#include <stdio.h>
double log(double foo)
{
return 1.0;
}
static const int row = static_cast<int>(log(4)/log(2));
int main(void)
{
printf("%d\n", row);
return 0;
}
Original (changed from (int) to static_cast, not that it matters)
sta... |
5,929,862 | 5,930,950 | Memory pool algorithms | I am looking for smarter algorithms in handling VBOs in OpenGL.
As it stands, I currently store each of my models in 4MB VBO's.
If the model is larger than 4MB, it is stored separately.
The objects are stored such that the models are pooled together to decrease the number of binds.
The problem I am experiencing has bee... | VBOs are not like regular memory, there is no need for any kind of sophisticated "memory management". You allocate a own, apropriately sized VBO for each distinct mesh and be done with. Any attempt to outsmart the driver will just result in inferior performance.
Also there is no benefit in attempting to make your VBOs ... |
5,929,971 | 5,956,171 | C++ cURL "empty reply from server" every time | I am trying to write a C++ program to read from a website using cURL. I have started with using the code from the cURL example simple.c. If I use that code exactly, no matter what URL I try to access, I obtain error #52: "empty reply from server". This is for any URL I try. If I use cURL from the command line, it s... | "Empty reply from server" means that libcurl didn't receive any response from the server after it sent off its request. In HTTP every request always gets something back so this is not even responding with HTTP and is thus a rather sever error.
You use a very old libcurl so possibly you're experiencing a bug that existe... |
5,929,994 | 5,930,060 | C++ Decompress a gzip array of bytes | Here is the complete situation: I'm working on a map reader for .tmx files, from tiled. Most times the tiles are saved in a base64 string, which contains an array of bytes compressed by gzip. Right now I can read the array of compressed bytes, but I have no idea how to decompress it. I read some docs about zlib and boo... | #include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
int main()
{
using namespace std;
ifstream file("hello.gz", ios_base::in | ios_base::binary);
filtering_streambuf<input> in;
in.push... |
5,930,056 | 5,930,199 | Generating a SHA256 hash with Crypto++, using a string as input and output? | I need an example of how to use Crypto++ to generate a SHA256 hash from a std::string and output a std::string. I can't seem to figure it out. Everything I've tried gives me invalid output.
Here's the new code after interjay's answer:
string SHA256(string data)
{
byte const* pbData = (byte*) data.data();
unsign... | This line will give the wrong results:
unsigned int nDataLen = sizeof(pbData);
It will always give you the size of a pointer. What you want instead is data.size().
Also, you don't need this part:
if(!CryptoPP::SHA256().VerifyDigest(abDigest, pbData, nDataLen))
{
return SHA256(data);
}
It should always verify corr... |
5,930,188 | 5,930,703 | "cord" library that comes with Boehm GC causes undefined reference errors | I have a project that uses Boehm GC, so I thought that I might use the cord string library that comes with it. The problem is that all my calls to the cord functions cause "undefined reference" errors.
I do have a file named libcord.so in /usr/lib (this is a Linux system), and I told CMake to link the target with gc an... | From what I can see, the cord.h file does not seem to include extern "C" statements in it, and so the name mangling is being done incorrectly when you are compiling liblang.so with a C++ compiler.
In the source where you #include <cord.h> you probably need something like:
extern "C" {
#include "cord.h"
}
|
5,930,346 | 5,930,417 | C++ code to execute a file every hour | I am currently faced with a problem where I need to execute a batch file every hour, can anyone provide a code spinet that will launch a designated file every hour e.g. myfile.bat ?
| Depending on your system environment you can easily accomplish this with a cronjob.
With a cronjob you can schedule it for any minute / hour / day / etc...
You can supply the cronjob to execute a path to a function where you can place a c++ exe to run the service you need.
For instance: I have a cronjob scheduled every... |
5,930,352 | 5,930,367 | C++ array declare issue | This code is giving me segfault :
#include <stdio.h>
int main(int argc,char** argv[]){
int ar[20000000];
return 0;
}
But if I reduce the size of array by 0 - then its fine. Am I exceeding the max size? What if I want to store that amount of integers? Thanks.
| It probably has to do with the fact that you're trying to allocate over 70 megabytes of data on the stack. Windows has a default stack size of 1 megabyte per thread IIRC. Try allocating it on the free-store with new, like so:
int* ar = new int[20000000];
and when you're done using it, delete[] it:
delete[] ar;
|
5,930,370 | 5,930,508 | C/C++ va_arg - Is there a way to skip an argument? | I am wanting to add functionality to sprintf(). Specifically, I want to be able to pass my own POD data types to it, but I am unsure of how to do this.
Supposedly, if you create the va_list, you can pass it off to vsprintf() and have it do the hard work for you - but I still need to access the va_list, and extract item... | Given that va_arg must be called in the right order and with the right type for proper behavior I think you have to consume the fmt piecemeal while processing the parts you care about and passing the rest to vsprintf:
void
mysprintf(char *dst, char *fmt, ...)
{
char *p = fmt;
va_list va;
va_start(va, fmt);... |
5,930,402 | 5,930,424 | Given a range, I have to calculate the frequency of numbers in an array. Is the given solution efficient? | #include<iostream.h>
int main()
{
int a[10]={1,2,3,5,2,3,1,5,3,1};
int i;
int c[10]={0};
for(i = 0 ; i < 10 ; i++)
c[a[i]]++;
for(i=0;i<10;i++)
cout<<i<<": "<<c[i]<<endl;
return 0;
}
The running time of the Algorithm is O(n) but its taking an extra space of O(n). Can I do better?
T... | No you can't. That's the best you can do.
|
5,930,415 | 5,933,460 | Access variable in Dlg class from App class | I am writing a Dialog Based C++ application with MFC for the GUI. After the creation of the project, Visual Studio also created two classes ProjectNameApp and ProjectNameDlg. When adding a Menu to my application the menu item handlers (for the menu buttons) are added as methods to the ProjectNameApp class. In one of th... | The last I dealt with any of this was in VS-2008, but if memory serves the CDialog object is probably allocated on the stack in CProjectNameApp::InitInstance(). There is probably some code there that looks kind of like:
CProjectNameDlg dlg;
int nResponse = dlg.DoModal();
One thing you could do is to add a pointer to ... |
5,930,464 | 5,930,527 | Reading input into dynamically-sized array | What I've been trying to do, is read a line from stdin and split it, by using whitespace as seperators.
Let's say I have this as input:
2
1 2
3 4
The first line gives me the amount of lines I'd like to read, they're all lines with integers seperated by an unknown amount of whitespace (i.e. could be 1 space, but i... | so given all you wanted is a nudge, here are a couple of hints..
std::getline() - allows you to read from a stream into a std::string.
You can then construct a std::istringstream using this string which you've just read in. Then use this stream to read your ints
for example:
std::string line;
if(std::getline(std::cin,... |
5,930,470 | 5,930,652 | How to use the Document/View architecture in MFC | I'm still working on a Data Acquisition program in MFC and am getting stuck working with the Document/View architecture. Basically, I want my application to have a couple windows. One is used to show a video that's recorded from a high speed camera, another has a plot displaying data from the DAQ system, and maybe an... | Your different windows (for video display, data display and configuration) are actually all views (different view classes) for a single document, which manages the data (assuming the DAQ works on the video data?).
I suggest you pack your application into an MDI app, thus having a main window, with all those different v... |
5,930,711 | 5,930,855 | Inherit a template class with an inner class and access the inner class within the inherited class | I have a template class "BinaryHeap" which also declares a public class "Item" within itself.
Now I want to extend the BinaryHeap with a hash for element lookup and therefore inherited it. I called it "HashedBinaryHeap", which should use the same Item class like BinaryHeap does.
The stub looks like this:
template<class... | Ok, solved it!
void appendItem(const typename HashedBinaryHeap<T>::Item & item);
This did the trick - I didn't know about typename...
|
5,930,713 | 5,931,578 | How can i implement the erase method? | void reserve( int newCapacity ){
Object *oldArray = objects;
int numToCopy = newCapacity < theSize ? newCapacity : theSize;
newCapacity += SPARE_CAPACITY;
objects = new Object[newCapacity];
for( int k=0; k < numToCopy; k++ )
objects[k] = oldArray[k];
theSize = numToCopy;
theC... | Seems like this ought to do it:
iterator erase ( iterator position ) {
copy(position+1, end(), position);
resize(size()-1);
return position;
}
iterator erase ( iterator first, iterator last ) {
copy(last, end(), first);
resize(size()-(last-first);
return first;
}
|
5,930,738 | 5,931,032 | Dynamically sized boost::asio::buffer | I'm reading from a boost::asio::ip::udp::socket like this:
using boost::asio::ip::udp;
// ...
char recv_buf[128];
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);
Now, this works perfectly fine, but the maximum amount of characters that I am able to rec... | UDP datagram size does not vary all that greatly: it will never be greater than 65535, leaving room for 65,527 bytes of data after the 8-byte header.
|
5,930,826 | 5,931,181 | How to enable experimental C++11 concurrency features in MinGW? | When trying to compile the following code
#include <thread>
#include <iostream>
void foo() { std::cout << "foo\n"; }
int main()
{
std::thread t(foo);
t.join();
}
I get an error:
C:\Test>g++ -g -Wall -lpthread -std=c++0x
main.cpp
main.cpp: In function 'int main()':
main.cpp:12:2: error: 'thread' is not a member o... | To the best of my knowledge, MinGW does not support yet the new c++0x concurrency features (as of GCC 4.5). I remember reading a mailing list exchange in which it was pointed out that in MinGW the following ifdef from the thread header is not satisfied:
#if defined(_GLIBCXX_HAS_GTHREADS)
I guess this is somehow relate... |
5,931,158 | 5,931,238 | Looking for opinions on when to unwind loops with if statements | I'm wondering when (if ever) I should be pulling if statement out of substantial loops in order to help optimize speed?
for(i=0;i<File.NumBits;i++)
if(File.Format.Equals(FileFormats.A))
ProcessFormatA(File[i]);
else
ProcessFormatB(File[i]);
into
if(File.Format.Equals(FileFormats.A))
for(i=0;i<File.NumB... | When you are finished the code and the profiler tells you that the for loops are a bottleneck. No sooner.
|
5,931,203 | 5,931,270 | Virtual function not functioning properly |
Possible Duplicate:
class has virtual functions and accessible non-virtual destructor
I got this code from following a tutorial by thenewboston:
#include <iostream>
using namespace std;
class Enemy {
public:
virtual void attack(){};
};
class Ninja: public Enemy {
public:
void attack(){
cout << "ni... | Your compiler is urging you to add a virtual destructor for your three classes. In this specific case, it doesn't really matter, but it's generally a good idea to have a virtual destructor for any class that may be used polymorphically.
Consider the following example:
class Fight
{
public:
Fight(Player* player, Ene... |
5,931,214 | 5,931,334 | Isn't the template argument (the signature) of std::function part of its type? | Given the following code, what is the reason behind the ambiguity? Can I circumvent it or will I have to keep the (annoying) explicit casts?
#include <functional>
using namespace std;
int a(const function<int ()>& f)
{
return f();
}
int a(const function<int (int)>& f)
{
return f(0);
}
int x() { return 22; }... | The problem is that both function<int()> and function<int(int)> are constructible from the same function. This is what the constructor declaration of std::function looks like in VS2010:
template<class _Fx>
function(_Fx _Func, typename _Not_integral<!_Is_integral<_Fx>::value, int>::_Type = 0);
Ignoring the SFINAE part,... |
5,931,265 | 5,931,455 | Nested Classes in c++ | class A{
public:
template<typename Obj>
class MyVec{
//some methods...
};
MyVec<A> a; //-> doesnt work
//vector<A> a; //using stl vector-> this works
};
class B{
public:
void someMethod();
private:
A::MyVec<A> b;
};
In the method, when I do sth like:
void someMetho... | I've taken your code and modified it as minimally as possible to get something that compiles. This seems to work fine. And so the error is not in the code you have shown us.
#include <iostream>
#include <string>
class A
{
public:
template<typename Obj>
class MyVec{
public:
//My pushback jus... |
5,931,463 | 5,931,475 | Finding the 1500000th Fib Number Using C++ | I wrote the following code to find the 1500000th Fibonacci number(Please ignore horrible indenting, I wrote this in about 2 minutes). I need it as a string. This should, hypothetically work:
#include <cstdlib>
#include <iostream>
#include <sstream>
int i;
int b=1;
int c=2;
using namespace std;
int main(int argc, char ... | Use a Bignum library.
|
5,931,546 | 5,931,561 | C++ return type question | Is there any difference between these:
struct Class* CreateClass();
and:
Class* CreateClass();
It's just a factory function declaration. You can see that one has struct at the start and one doesn't. I've tried it both ways and it doesn't seem to make a difference.
Which should I be using?
| It's from C; there's no difference* in C++.
*Okay, I lied, sorry. :P You can confuse yourself if you really want to, and make them be different if you use a typedef with the same name but a different underlying type, but normally they're not different. That's assuming Class is already declared, though... if Class is un... |
5,931,564 | 5,932,925 | How do I initialize static constant member variables in a subclass? | I'm trying to make a template which can make a few different types of classes that differ mainly in the name of things, i.e. a resistor should output "Resistance: 4 ohm" where a capacitor would output "Capacitance: 4 farad" in the same function call, without overloading. Ideally the units would just be static const std... | Initializing public/protected members of base class inside a derived class constructor is not allowed by current standard. One has to rely on other techniques to achieve it. There are 2 ways to address your problem.
(1) Declare virtual method returning std::string for appropriate label/values. However, this will cause ... |
5,931,572 | 5,931,887 | How is programming an Arduino different than standard C? | I have a background in programming embedded systems (TI MSP430, Atmel ATxmega). How is programming an Arduino different than those? What knowledge about C can I take in to programming the Arduino?
| While I don't know about the ATXMega, the 8-bit AVR chips like the ATmega328 used on the newer Arduinos use the AVR-GCC compiler. This allows for compiling C and even C++ to an AVR chip. One level above the AVR-GCC is the AVR Libc, a C library that makes programming for the AVR a higher level task (no longer have to re... |
5,931,601 | 5,931,633 | Error at compiling, not a typo as far as I see | class Triangulo: public Figura
{
public:
int x1, y1, x2, y2, x3, y3;
void dibujar_triangulo()
{
cout<<"Se ha dibujado un triangulo color "<<color<<" con coordenadas "<<
"("<<x1<<","<<y1<<")"<<endl<<"("<<x2<<","<<y2<<")"<<endl<<"("<<x3<<","<<y3<")"<<endl;
}
};
I've got this error:
in... | It is a typo. You only wrote < before the last ")" in your function. Some things are just easier to spot with properly formatted code:
void dibujar_triangulo()
{
cout << "Se ha dibujado un triangulo color " << color << " con coordenadas "
<< "(" << x1 << "," << y1 << ")" << endl
<< "(" << x2 << ",... |
5,931,639 | 5,953,282 | cleaning up unmanaged c++ thread on c# application exit | Here's my setup:
1) c# application starts up and calls an exported unmanaged c++ dll function
2) the dll function spawns a thread via win32 CreateThread
3) this new thread does it's "work" in a while loop, checking for an exit flag
When I exit the c# application, the thread exits immediately.
Questions:
1) What can ... | When your C# app exits:
Set a flag visible to the thread.
Call WaitForSingleObject on the HANDLE returned by CreateThread. This will make it wait for the thread to exit.
Optionally be a good citizen and call CloseHandle on the thread's HANDLE to free its resources, though this doesn't really matter if the app is abou... |
5,931,735 | 5,932,031 | Finding largest rectangle in 2D array | I need an algorithm which can parse a 2D array and return the largest continuous rectangle. For reference, look at the image I made demonstrating my question.
| Generally you solve these sorts of problems using what are called scan line algorithms. They examine the data one row (or scan line) at a time building up the answer you are looking for, in your case candidate rectangles.
Here's a rough outline of how it would work.
Number all the rows in your image from 0..6, I'll wo... |
5,931,971 | 5,931,979 | c++ ifstream undeclared identifier | I am in Visual Studio and am getting 'ifstream undeclared identifier' with this code (same for ofstream)
#include <iostream>
#include <iomanip>
#include <fstream>
void main()
{
ifstream infile("file.txt");
ofstream outfile("out.txt");
}
do I need to include something else?
| You need to scope it. Use using namespace std; or preface ifstream and ostream with std::
For example, std::ifstream
Currently, the compiler does not know where these structures are defined (since they are declared/defined within the std namespace). This is why you need to scope your structures/functions in this case.
|
5,932,079 | 5,933,154 | Heterogeneous pointer container | I'm currently using an enum to map into an array of Base*. Each Derived type is given an index by the enum.
enum DerivedType {
DERIVED_TYPE_1 = 0,
DERIVED_TYPE_2,
...
NUM_DERIVED_TYPES
};
class Base {
};
class Derived1 : public Base {
static const DerivedType type;
};
const DerivedType Derived... | Though I'm not 100% confident that I understand the question correctly,
probably what you mentioned(or similar one) can be implemented
with boost::fusion and boost::mpl.
For example:
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/at_key.hpp>
#include <boost/mpl/vector.hpp>
namespace bf = boost::... |
5,932,172 | 6,003,870 | collaborative filtering library in C++ | does any of you know any good specific library that contains implementations of common algorithms specifically geared towards collaborative filtering/recommendation system that is written in C++
so just like a machine learning library except that it's specifically geared towards collaborative filtering and/or recommend... | Found some time ago on Google Code (I haven't used them yet):
http://code.google.com/p/recsys-nju/
http://code.google.com/p/recsyscode/
http://code.google.com/p/recsysexperiment/
|
5,932,391 | 5,932,408 | Determining if a string is a double | I would like to see if a string contains a double as its sole contents. In other words, if it could possibly be the output of the following function:
string doubleToString(double num)
{
stringstream s;
s << num;
return s.str();
}
| You want the strtod function.
bool isOnlyDouble(const char* str)
{
char* endptr = 0;
strtod(str, &endptr);
if(*endptr != '\0' || endptr == str)
return false;
return true;
}
|
5,932,496 | 5,932,597 | Convert java method into cpp | public boolean isDoubleValue(String s) {
try {
Double.valueOf(s);
return true;
} catch (Exception e) {
return false;
}
}
But i want to convert this method into QT cpp.
Can any one help me?
Thanks,
Nagaraju
| Since you need it in Qt (from your comment), you can use
double QString::toDouble ( bool * ok = 0 ) const.
And you can check the value of ok and return accordingly..
|
5,932,631 | 5,933,566 | C++: Boost: Need help with directory navigation logic | So, I'm trying to change my directory to save files, and then change back to the directory I was previously in.
Essentially:
cd folder_name
<save file>
cd ../
Here is the code I have so far:
void save_to_folder(struct fann * network, const char * save_name)
{
boost::filesystem::path config_folder(Config::CONFIG_FO... | According to the docs, the current_path method is a little dangerous because it might be modified by other programs at the same time.
So it would probably be better to operate from the CONFIG_FOLDER_NAME.
Can you pass a larger path name to fann_save? something like:
if( !(boost::filesystem::exists(config_folder)))
{
... |
5,933,126 | 5,933,375 | Can i allocate memory faster by using multiple threads? | If i make a loop that reserves 1kb integer arrays, int[1024], and i want it to allocate 10000 arrays, can i make it faster by running the memory allocations from multiple threads?
I want them to be in the heap.
Let's assume that i have a multi-core processor for the job.
I already did try this, but it decreased the per... | It depends on many things, but primarily:
the OS
the implementation of malloc you are using
The OS is responsible for allocating the "virtual memory" that your process has access to and builds a translation table that maps the virtual memory back to actual memory addresses.
Now, the default implementation of malloc i... |
5,933,172 | 5,933,245 | How the bits are stored in C++, How to represent similar functionality in Java | I have in C++:
typedef struct _msk {
char abc[4];
//some more variables
}
_msk mr;
if (some condition >= 70) {
mr.abc[0] |= 0xC0; //C0 in binary 11000000
mr.abc[1] |= 0x20; //20 in binary 100000
mr.abc[2] |= 0x44; //44 in binary 1000100
}
here OR operation is goin on after which the value will b... |
So in memory is it like
(0th)11000000(1st)100000(2nd)1000100
as these are in array?
almost: (0th)11000000(1st)00100000(2nd)01000100
how many bits can be actually stored
in [4](total 0+1+2+3+4).
Not 0+...+4, but 0+...+3, 4 chars of size 8 bits = 32 bits (indices: 0, 1, 2, 3)
And you can still use the bitwise o... |
5,933,212 | 5,933,257 | Why getting linker error with vector? | I have for homework to write my own abstract class Vector. I make some of the code, but when I try to compile it I have error. This is the code:
vector.hh:
#ifndef VECTOR__HH__
#define VECTOR__HH_
template<class T> class Vector {
int capacity_;
int size_;
T* buffer_;
void ensure_capacity(unsigned size... | The linker error is coming because, for template classes the definition should always be visible. Either you can move all the content of vector.cc into vector.h. Or you can simply include vector.cc wherever you include vector.h.
side note:
Following lines in your .h file doesn't help:
#ifndef VECTOR__HH__
#define VECTO... |
5,933,227 | 6,051,192 | Visual Studio Addin - Get Name\Path of binary of a c++ project? | I want to get the binary name of a C++ Project with a Visual Studio C# Addin.
I googled and found, that the the EnvDTE.Configuration.properties should have a element called "AssemblyName" but C++ projects do not seem to have this element.
Did somebody know where could I get this information inside a visual studio addi... | For VC++ projects you need to get access to the VCConfiguration object which you should be able to get at from the EnvDTE.Project's Object property like:
EnvDTE.Project project = ...
VCProject vcProj = (VCProject)project.Object;
IVCCollection configs = (IVCCollection)vcProj.Configurations;
VCConfiguration config = (VCC... |
5,933,451 | 5,933,641 | Why are generated binaries so large? | Why are the binaries that are generated when I compile my C++ programs so large (as in easily 10 times the size of the source code files)? What advantages does this offer over interpreted languages for which such compilation is not necessary (and thus the program size is only the size of the code files)?
| Modern interpreted languages do typically compile the code to some manner of representation for faster execution... it might not get written out to disk, but there's certainly no guarantee that the program is represented in a more compact form. Some interpreters go the whole hog and generate machine code anyway (e.g. ... |
5,933,817 | 5,933,909 | c++ undefined reference to <a function> | HI,
I have some questions about .h files and .cpp files in c++/linux(ubuntu).
It is possible to compile a .h file using g++ or you can just compile a .cpp file that includes the .h file?
From a .h file and it's .cpp file (.cpp where i include some code to the methods i've defines in .h file) I create a .so file using ... |
Generally there is no need to compiling a .h file, it simply generates a huge file with .gch extension I guess.
The error you are getting is a link time. While creating the .so file, you do not actually link the code. So all undefined symbol are assumed to be present at some place. When you link it, the linker will fi... |
5,933,879 | 5,934,945 | boost and cpp-netlib make compile ERROR | [SOLVED] created symlinks from /usr/lib/lib/* to /usr/lib*
[UPDATE 3] NEW VERSION:
Ok, I think I fixed something
use find / -name "libboost_system.*"
outout was
/usr/include/boost/lib/libboost_system.so
/usr/include/boost/lib/libboost_system.a
/usr/include/boost/lib/libboost_system.so.1.46.1
/usr/lib/lib/libboost_sys... |
The -l flags must come after the source files on linker command-line.
Yes, that means you'll have to split the LD definition to LD and LIBS, put all the -L and -l flags in the later and change the link command to:
$(LD) $(OBJ) $(LIBS) -o $@
The library (.so (dynamic) or .a (static)) files have to be the same version a... |
5,933,945 | 5,934,348 | what actually happens during a c- style typecasting regarding address space of casted objects? | According to book, C++ FAQ by Cline,the following code depicts improper inheritance.
notice that i can add a banana which is a kind-of fruit into a bagofApples which should actually contain only apples.. but due to the inheritance relationship banana is added to the bagofApples.
but the question is what actually happen... | Firstly, if this code comes from the book then get another book:
I understand it illustrates a deliberate mistake in publicly deriving a BagOfApples from a BagOfFruit (which is nonsensical because public derivation means people can continue to use the BagOfApples as a BagOfFruit, thereby inserting objects into it that... |
5,933,955 | 5,933,996 | What is a good open source C/C++ math library that supports vector math and complex numbers? | I am working on a project that needs vector math and complex numbers.
I am looking a for a good open source API that supports C/C++ and hopefully has decent performance.
I can write these functions myself but it will be ugly and slow.
| You can use the C++ complex numbers library
Also, Boost provides linear Algebra package
|
5,933,980 | 5,934,239 | Detect Incorrect stack variable usage | My application gives certain works to the worker agency to execute in a thread pool thread as given below
void Execute ProcessWork
{
int nRes = 0;
CFireProcessMessageWork *pProcessMessageWork = new CFireProcessMessageWork();
// Incorrect use of stack variable
pProcessMessageWork->m_pStatus = &nRes;
... | The problem is that each one of those lines makes sense to the compiler. There is nothing wrong with them, and just the combination is not really good. Even then, it would require a good amount of extra work and analysis to determine that it is a wrong use.
Consider for example, that you could be joining the worker thr... |
5,934,145 | 5,934,536 | compilation error in macro | I have downloaded jsvm software, and I am getting many errors while compiling. Few of them is as follows.
/usr/include/c++/4.3/bits/algorithmfwd.h:248:41: error: macro "max" passed 3 arguments, but takes just 2
And the file algorithmfwd.h is as follows
template<typename _Tp>
const _Tp&
min(const _Tp&, const _Tp&);
te... | Somewhere, you have defined a macro max, which is not allowed if you
include any headers from the standard library (which has a set of
overloaded functions named max). You'll have to find out where this
macro is defined, and get rid of it. Two immediate possibilities come
to mind:
You've defined it as a macro in on... |
5,934,275 | 5,934,352 | Binary compatiblity between VS 2010 and VS 2010 SP1 C++ binaries | I am contemplating installing SP1 for VS 2010. Are binaries compiled using VS 2010 and VS 2010 SP1 binary compatible? Or does it introduce yet another version/assembly of MSVCR100 and MSVCP100?
| The answer seems to be YES binaries are compatible, atleast between VS2010 and VS2010 SP1.
And here is a reference saying so.
Note: I googled it out of curiosity :)
|
5,934,298 | 5,934,438 | How to convert a hex string to an unsigned long? | I have following hex value
CString str;
str = T("FFF000");
How to convert this in to an unsigned long?
| #include <sstream>
#include <iostream>
int main()
{
std::string s("0xFFF000");
unsigned long value;
std::istringstream iss(s);
iss >> std::hex >> value;
std::cout << value << std::endl;
return 0;
}
|
5,934,322 | 5,934,479 | how to do the validation of email id in MFC? | I used this code for validating email id , im getting few errors i dono how to solve it,,, im new to MFC,, if im silly pls forgive me
BOOL CMailDlg::Validate(CString m_sFrom)
{
m_sFrom = NulltoString(m_sFrom);
CString strRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
Regex re = new Regex(strRegex)... | You will need to include the regex string in quotes and escape the \. C++ doesn't have native support for regex as you might find is say Perl, it is implemented using a string. \ is the C++ escape character and used to include things like new lines into strings, as such if you want an actual \ in your string you must d... |
5,934,506 | 5,937,235 | nokia qt sdk problem | hi i want to make an application for nokia in nokia qt sdk.
i select mobile application when i create new project but when i run the project it built the exe file of my project i want a sis file so i can check it on my nokia device.
please give me the suggesion how i develop my project for nokia mobile in nokia qt sdk
| Does this help ?
http://www.forum.nokia.com/Develop/Qt/Getting_started/Step_3.xhtml
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.