question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
6,001,633
6,001,655
C++ does address exist?
Suppose I have the following in C++: char buffer[SIZE]; char * ptr = &buffer[SIZE]; where ptr's value is never dereferenced. Is this even legal to do C++? That is use the memory address one stride from the last element of an array (say as a special value to compare to)?
If you said: char buffer[SIZE]; char * ptr = & buffer[SIZE]; then yes, it is legal. You are specifically allowed by the C++ standard to use the one-past-the-end of an array in this manner, and it is used extensively when (for example) working with iterators. Edit: But see comments by litb and Steve Jessop. If you want...
6,001,994
6,002,003
converting class file to jar file using c++
Is it possible to convert .class file to .jar file using c++ code? (i.e can we write a code in c++ that when executed converts given .class file to .jar file) If yes,how can i do that?
A .jar file is just ZIP archive containing .class files and possibly a manifest file. (The most important part of the manifest file is the name of the class to run with java -jar.) You can generate a .jar file quite easily in C++ from the .class file, by using a library which can generate ZIP archive files. If you don'...
6,002,014
6,002,199
Difficulty implementing classes with time-limiting code (C++)
I am writing a program to control a flashbulb. The flash fires in response to a key press by the user. I am trying to limit the occurence regularity of the flash to prevent the bulb burning out. I have already received some help from this forum, but am unable to implement the code with my own. A user suggested using a ...
There are a few major issues with your code: Missing a ';' at the end of the class definition. Missing a definition HANDLE hSerial before it is used. You are comparing the time and frequency incorrectly on the line if (timepassed >= (((double)frequency) / 10000)). If you wish to convert the counter from QueryPerforma...
6,002,170
6,002,186
Java - JNA and shared Libraries, UnsatisfiedLinkError when starting from a .jar on Linux
[Final Solution can be found in the comments to the accepted answer. Thanks to bmargulies] Hey Folks, I've got a quite weird error and I can't figure out the reason. So here's the setup: I'm building a platform-independent music player in Java. As native sound library I'm using the irrKlang engine ( http://www.ambiera....
On Linux you'll need to set LD_LIBRARY_PATH to include the directory containing that second shared library. This requirement is very hard to get around. LD_LIBRARY_PATH is only read by ld.so at the inception of the java process. You can't add to it later. You have to make one big shared lib, which means finding .a vers...
6,002,579
6,003,058
Checking a value defined in a header from a function in another file
I have a header file (head.h) in which I define the boolean value: bool flag = false; In main.c, I have a function: void WINAPI function (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil) { if (flag == false) ...
I believe you put #include "head.h" at the top of main.c (before #include "stdafx.h") and you use precompiled header(at least it's how I'm able to reproduce your issue with Visual Studio). #include "stdafx.h" should always go first .
6,002,594
6,003,781
Is there a way to have the C Preprocessor resolve macros in an #error statement?
Just as the title says. I want to use a preprocessor macro in the text of an #error statement: #define SOME_MACRO 1 #if SOME_MACRO != 0 #error "SOME_MACRO was not 0; it was [value of SOME_MACRO]" #endif In this example I want the preprocessor to resolve [value of SOME_MACRO] to the actual value of SOME_MACRO whic...
For completeness the C++0x way I suggested (using the same trick as Kirill): #define STRING2(x) #x #define STRING(x) STRING2(x) #define EXPECT(v,a) static_assert((v)==(a), "Expecting " #v "==" STRING(a) " [" #v ": " STRING(v) "]") #define VALUE 1 EXPECT(VALUE, 0); Gives: g++ -Wall -Wextra -std=c++0x test.cc ...
6,002,672
6,002,699
Operator overloading with friend function error
I am working on an assignment that introduces me to operator overloading. I have to overload some binary operators as member functions and also as friend functions. My member function that overloads the "+" operator works fine but my friend function that overloads the "-" operator seems to have trouble finding data tha...
The friend operator is not part of the class. Thus, it does not know size and range and array. You must use the objects a and b. It should be something like this: matrix operator - (const matrix & a, const matrix & b) { if(a.size != b.size) throw std::exception(...); matrix temp(a.size, a.range); for (...
6,002,774
6,002,978
Unable to reference variables... Why?
I have a very simple bit of code that won't work, and have no idea why The following: int flag = 0; if (flag == 0) { flag = 1; } Will not compile. It is already a quite complex program, and I am able to do other actions within the program with no problems at all, yet for some reason I can't reference a variable I ...
I assume you compile it to C language. You need to declare the variable at the beginning of the block: // beginning of block int flag=0; //Some code if (flag == 0) { flag = 1; }
6,003,053
6,003,079
library for mesh manipulation/deformation
Does anyone know of nice C++ library to get the Union, difference and intersection of 3d meshes?
You might want to have a look at CGAL. It supports various boolean operations.
6,003,074
6,003,147
How to create an interface using .NET for C++ application?
I have written all the code for an application in C++. It is standard C++ written using Visual Studio 2010. I want to create a GUI using .NET. Is it possible? Thank you!
There a plenty of options, here's a few off the top of my head: Wrap the c++ code in a Windows DLL, call the c++ code from .NET using p/invoke. Wrap the c++ code in a com object, .NET can directly use com objects. Wrap the c++ code inside some type of managed c++ wrapper (c++/CLI), load and use that new assembly in th...
6,003,139
6,003,452
How to determine the source of an QAction?
I want to know if there is any easy/elegant way to determine the source of an QAction? What I mean I have one QAction which is added to multiple QWidgets (with QWidget::addAction) and when the triggered signal of the action gets emitted I need to know which QWidget is the source because I need to query that specific wi...
I think you can use QAction associatedWidgets method to determine the list of widgets, to which action was added. Then you can examine this list for widget, that currently has focus. QList <QWidget *> widget_list = sender()->associatedWidgets(); for(int i = 0; i != widget_list.size(); ++i) { if (widget_list.at(i)-...
6,003,198
6,003,285
C++ Float Division and Precision
I know that 511 divided by 512 actually equals 0.998046875. I also know that the precision of floats is 7 digits. My question is, when I do this math in C++ (GCC) the result I get is 0.998047, which is a rounded value. I'd prefer to just get the truncated value of 0.998046, how can I do that? float a = 511.0f; floa...
Well, here's one problem. The value of 511/512, as a float, is exact. No rounding is done. You can check this by asking for more than seven digits: #include <stdio.h> int main(int argc, char *argv[]) { float x = 511.0f, y = 512.0f; printf("%.15f\n", x/y); return 0; } Output: 0.998046875000000 A float i...
6,003,282
6,014,202
Setting up midiIO library on Windows
I've downloaded the midiIO library and in the readme it says: edit the file Makefile.library and set the OSTYPE and OSSUBTYPE to match your hardware/os setup. type "make library" to compile the library. It will be created as lib/libmidiio.a in unix. edit the file Makefile.examples and set the OSTYPE and OSSUBTYPE to...
Ignore the makefiles and set up a fresh project in Visual C++. Make your target a static library (which will be a .lib file in Win32, not a .a file as in unix as you probably know). It is unlikely that the project will build out of the box, so you might have to deal with some compilation errors relating to unix-specifi...
6,003,368
6,004,441
Unresolved externals in C++ when using vectors and find
I have tried this code in a totally separate project, and it works fine (the only difference being that the project that is not working is being exported as a DLL). Here is the code: RTATMATHLIB.CPP #include "stdafx.h" #include "RTATMATHLIB.h" #include <math.h> #include <vector> #include <algorithm> #include <stdexcept...
I found another forum post, where somebody seems to have reported the same exact problem that you are having. Please check to see if you have _DEBUG defined either in your project settings (under C/C++ -- Preprocessor) or somewhere in your code (or include files). It looks as if std::vector thinks you are building a d...
6,003,373
6,003,411
Why can't I change a private member of a class from a friend class in a different namespace?
I am finding trouble accessing a private member of a class from a friend class. The class that holds the private member I want to change and the class where the change is made are in different namespaces. The friend class is defined after the class holding the data, so I've tried to forward declare the friend class out...
friend struct ::S; what you are really doing with friend struct S; is declaring as friend the class N::S (which is defined nowhere). Edit: To back up my idea that gcc behavior is correct and VC++ has a bug. 7.3.1.2/3 If a friend declaration in a non-local class first declares a class or function the friend class o...
6,003,603
6,268,238
PCH Warning: header stop cannot be in a macro or #if block - Visual C++ 2010 Express SP1
This is pasted from a website, which presumably was working. I did some googling and found that the issue I have now is a result of Visual C++ 2010 SP1, which I downloaded today, and is now giving me this error: PCH Warning: header stop cannot be in a macro or #if block. Hopefully someone will be able to help me with t...
I had the same issue and was looking for a solution. Following worked for me: Add #pragma once at the start of the file (even before the #ifndef APP_STATE_H header guard)
6,003,643
6,003,668
Java/C/C++/C#/PHP to Pascal converter?
Does anyone know if there is a Java/C/C++/C#/PHP to Pascal converter?
H2Pas is a popular tool to convert C headers to Pascal. I don't know of any to actually convert C code to Pascal code though. From a quick google search, I see several that may or may not be good: http://cc.embarcadero.com/item/23991 http://c2pas.sourceforge.net/ I am tempted to say you'll have to do a lot of it by h...
6,003,649
6,003,848
Add items to a vector recursively
I'm attempting to create a recursive function that outputs a vector of strings that contains all possible word combinations (while retaining order of letters) of a given string. Basically, the foundation of an auto-correct typing program, which produces effects similar that of the iPhone. vector<string> allPossibleWord...
(Update: 2130 GMT Sunday: I've significantly changed my answer. I think this works now.) Here is a complete program. There are other changes I think I would make, but I'm trying to keep to the spirit of your initial solution. It's important to return a single empty word when str.length()==0. #include <vector> #include ...
6,003,673
6,003,693
C++ member function called begin() question
Assuming that: vector<string> mvec; has some elements on it Partial code: for(vector<string>::iterator it1 = mvec.begin(); it1 != mvec.end(); ++it1) { for(string::iterator it2 = it1->begin(); it2 != it1->end(); ++it2) since: it1->begin() deference the object and then invoke the member function begin() of that obj...
Since it1 is an iterator for vector<string> when you derefence it you will get a string.
6,003,969
6,007,208
Dynamic struct member damaged while passing to function using CUDA/NVCC
I'm experimenting with CUDA and I ran into a very strange bug. I have the following files (tl;dr, skip them): main.cpp #include "main.h" #include "list.hpp" void print_graph(Graph& g); void init(Graph& g) { g.list = new List<int>; for (int j = 0; j < 5; j++) { g.list->push_back(j+1); } } int main...
The issue of alignment requirements in structures is discussed in some detail in Chapter 3 of the CUDA programming guide. The short answer is passing -malign-double to nvcc should fix the issue.
6,003,994
6,004,022
Where are the memory leaks?
I have this piece of code and for some reason it creates 6 memory leaks and I can't figure out where. Lemon::Lemon() { this->nrOf=0; int x=10; this->matrix=new int*[x]; this->lines=new string[x]; for (int i = 0; i < x; ++i) this->matrix[i] = new int[x]; for(int i=0;i<x;++i) ...
At this point: this->x=this->nrOf; nrOf has not been initialised - you have undefined behavior. And possibly you would benefit from using std::vector.
6,004,501
6,006,562
C++ Inheritance with pure virtual functions
I'm trying to create a class that serves as a base object, which will then be sub-classed (=implemented) to serve various purposes. I want to define one or more pure virtual functions, so that however subclasses the base class, is required and does not forget to implement them. There is one caveat, the pure virtual fun...
There is NO need to change the function signature. Look at following: class BaseItem {public: virtual std::string getDifferences(const BaseItem& item) = 0; }; class DerivedClass : public BaseItem {public: virtual std::string getDifferences(const BaseItem& item) // keep it as it's { const DerivedCl...
6,004,568
6,004,672
Viewing the contents of a variable in debug mode? (Other than with break points)
I'm writing a program which calculates the Mandelbrot Set (and then renders it in OpenGL under Windows) in order to utilise parallel programming techniques. I'm supposed to demonstrate the use of threads, mutexes, and semaphores; so at the moment I'm calculating the set using multiple threads (splitting the set up hor...
If you're on windows you could use OutputDebugString and view the results with a tool called DebugView. The downside is that it will print each value on a new line instead of updating it in place (which I guess is what you prefer). If you want to view a value that will be updated in-place, you could probably use Perfor...
6,004,610
7,383,856
can't debug small program on eclipse helios cdt using mingw/gdb under windows, console freezes
I've been trying to use Eclipse CDT to do some c++ examples, i can run them just fine with the run command, but whenever i try to Debug, the console window freezes up, I'm able to input, but the program doesn't continue. When I debug, i get the following output on the console window (no breakpoints, but breaks on main...
the following is from the Eclipse website's FAQ: http://wiki.eclipse.org/CDT/User/FAQ#Eclipse_console_does_not_show_output_on_Windows Eclipse console does not show output on Windows In Eclipse CDT on Windows, standard output of the program being run or debugged is fully buffered, because it is not connected to a W...
6,004,737
6,004,956
Override method for a family of subclasses
Given legacy code, the system has the following hierarchy of classes: Base ^ | ----------+--------------- ^ ^ ^ ^ ^ | | | | | A1 B1 C1 D1 E1 ^ ^ ^ ^ ^ | | | | | A2 B2 C2 D2 E2 ....... ^ ^ ...
struct Base { virtual void PerformFunctionality() { stuff(); SpecificPartOfFunctionality(); more_stuff(); } private: virtual void SpecificPartOfFunctionality() {} }; template<class Prev> struct Version3 : Prev { protected: // Not private if v4's override might need to call this. virtual void Speci...
6,004,763
6,004,795
Catching exceptions thrown without try/catch
I recall reading about how exceptions could be caught without the use of try/catch. Basically when an exception is thrown such as "Unhandled exception" via derefencing a null pointer, there would be a process that is triggered even when a try/catch is not coded for the exception. I believe it had something to do with a...
In C++, dereferencing a null pointer causes undefined behavior, which does not necessarily imply that an exception is thrown. On Unix systems, for example, a SIGSEGV signal is raised instead. On Windows, access violations raise a SEH exception. SEH exceptions are not the same as C++ exception; they are handled using __...
6,004,963
6,004,979
Why use #define instead of a variable
What is the point of #define in C++? I've only seen examples where it's used in place of a "magic number" but I don't see the point in just giving that value to a variable instead.
Mostly stylistic these days. When C was young, there was no such thing as a const variable. So if you used a variable instead of a #define, you had no guarantee that somebody somewhere wouldn't change the value of it, causing havoc throughout your program. In the old days, FORTRAN passed even constants to subroutines...
6,005,024
6,005,051
C++ class member pointer to global function
I want to have a class which has as a member a pointer to a function here is the function pointer: typedef double (*Function)(double); here is a function that fits the function pointer definition: double f1(double x) { return 0; } here is the class definion: class IntegrFunction { public: Function* function;...
Replace this: class IntegrFunction { public: Function* function; }; with this: class IntegrFunction { public: Function function; }; Your typedef already creates a pointer-to-function. Declaring Function* function creates a pointer-to-pointer-to-function.
6,005,076
6,005,262
Building glew on windows with mingw
Can anyone give me the correct command to build glew on windows with mingw? I have tried: gcc -static glew.c glewinfo.c visualinfo.c -I/path/to/glew/include but I am getting thousands of linker errors (missing reference). I can't build with Make because unfortunately the makefile has lots of unix only commands and i ...
To build it with MinGW, you should do (copied from the make log, with slight modifications and additional explanations): mkdir lib/ mkdir bin/ gcc -DGLEW_NO_GLU -O2 -Wall -W -Iinclude -DGLEW_BUILD -o src/glew.o -c src/glew.c gcc -shared -Wl,-soname,libglew32.dll -Wl,--out-implib,lib/libglew32.dll.a -o lib/glew32.dl...
6,005,103
6,005,106
How can I suppress g++ deprecation warnings in OCaml compilation when linking with C++ libraries?
When compiling an OCaml project which links against libraries requiring the C++ standard library (e.g. LLVM's OCaml bindings) using the -cc g++ argument to ocamlc with GCC >= 4.4 generates extremely verbose warning spew of the form: warning: deprecated conversion from string constant to ‘char*’ How is it possible to r...
The problem stems from ocamlc generating intermediate C code which triggers warnings when compiled in C++ mode by newer versions of GCC. But this generated code need not be compiled as C++. The only reason to pass -cc g++ for this common case of building against a wrapped C++ library is to ensure that the C++ standard ...
6,005,165
6,006,975
Export Weka Models for Use in C or C++
I have had a great deal of success using Weka for data exploration and deciding what classification algorithm is best for my problem. Now that I have a trained model that works, I would like to integrate it into the rest of my C++ program. Unfortunately, this seems like a difficult task: only Weka has native support fo...
My understanding is that J48 is Java implementation of Quinlan C4.5 algorithm with C code freely available at http://www.rulequest.com/Personal/ Is this what you are looking for?
6,005,255
6,005,324
What is the difference between Pause(), Sleep() and Wait() in C++?
I have been working through the CS106B course from Stanford, and while completing the Boggle assignment, I have noticed that the Sleep() function on Windows behaves differently from the Pause() function. For testing purposes, I have simply set up the board and used the provided gboggle.h file to highlight the Boggle ...
I've never seen the Pause command before; perhaps you could provide some code for it? Windows apps work on the idea of a message pump, and that painting is a low priority. If you sleep or wait in the message pump thread then you block it from doing any further handling of messages such as drawing the screen. You need t...
6,005,389
6,005,442
About dynamic cast and address of base and derived objects
I was reading through some of effective c++ and I realized I may be incorrect in my thinking along the way. class A { public: void laka() { const void * raw = dynamic_cast<const void*>(this); cout << raw << endl; } virtual ~A() = 0; }; A::~A() {} class B : public A { public: v...
Most implementations of inheritance put the first base class subobject at the beginning of the derived class, so you really need two base classes, both with data members, to be able to see this. Consider: #include <iostream> struct B1 { int x; virtual ~B1() { } }; struct B2 { int y; virtual ~B2() ...
6,005,520
6,005,540
How to embed resources into a single executable?
If you've ever used the tool Game Maker, it's a bit like that. I want to be able to take all my sounds, images, and everything else of the like and embed them into a single C++ executable. Game Maker would have a built-in editor, and would have the images embedded into the .gmk file, and when you'd open it it would rea...
The windows resource system works like this, so if you make a WinAPI or MFC application, you can use this. Also, Qt provides the same functionality, but in a platform independent way. They just write the files in raw binary format into a byte array in a normal C++ file, so they get compiled as data into the exe. Then t...
6,005,669
6,005,698
hex string to unsigned char[]
today I tried to convert a hex string to an unsigned char[] string test = "fe5f0c"; unsigned char* uchar= (unsigned char *)test.c_str(); cout << uchar << endl; This resulted in the output of fe5f0c hrmpf :-(. The desired behaviour would be as follows: unsigned char caTest[2]; caTest[0] = (unsigned char)0xfe; caTest...
Sure, you just have to isolate the bits you are interested in after parsing: #include <string> #include <cstdlib> #include <iostream> typedef unsigned char byte; int main() { std::string test = "40414243"; unsigned long x = strtoul(test.c_str(), 0, 16); byte a[] = {byte(x >> 24), byte(x >> 16), byte(x >> ...
6,005,948
6,011,137
How can I use my custom types (C++) in an objective-c project with xcode?
I have a few classes I wrote to deal with numbers having units transparently as if they were just ints or floats. In a nutshell: SI_Term speed(4, "mph"); SI_Term distance(10000, "feet"); SI_Term time = distance / speed; std::cout<<time.string(); and all the major operators are overloaded to work this way. Took a quite...
You are probably including (or importing) your h file in one of your .m files. Those need to be renamed to .mm too. In the end you'll probably name all .m fikes to .mm. And by the way, the cpp files, can simply remain cpp. No reason to rename them.
6,006,200
6,006,206
Why do simple doubles like 1.82 end up being 1.819999999645634565360?
Possible Duplicate: Why does Visual Studio 2008 tell me .9 - .8999999999999995 = 0.00000000000000055511151231257827? c++ Hey so i'm making a function to return the number of a digits in a number data type given, but i'm having some trouble with doubles. I figure out how many digits are in it by multiplying it by li...
This is because C++ (like most other languages) can not store floating point numbers with infinte precision. Floating points are stored like this: sign * coefficient * 10^exponent if you're using base 10. The problem is that both the coefficient and exponent are stored as finite integers. This is a common problem with ...
6,006,329
6,006,339
How to exit program execution in C++?
Which function is used in C++ stdlib to exit from program execution with status code? In Java, there's: System.exit(0)
Assuming you only have one thread: #include <iostream> int main() { std::cout << "Hello, World!\n"; return(0); // PROGRAM ENDS HERE. std::cout << "You should not see this.\n"; return(0); } Output: Hello, World! The return(0); can be placed anywhere you like - it'll end int main(), and hence yo...
6,006,352
6,006,370
What is the <?= operator in C++
Possible Duplicate: What does the >?= operator mean? I was wondering what is the <?= operator I keep seeing in C++ code. It doesn't compile on my system, but I'm sure it is correct. It's used like this:a <?= something; Also, what would I need to do to be able to compile it? EDIT POST: Please see this source code (it...
EDIT: Its an extension in older versions of GCC. See this : What does the >?= operator mean? But then the extensions are <? and >? . I still don't see <?=. 6.1 Minimum and Maximum Operators in C++ EARLIER POST: I assure you, there is no such operator in C++. Its certainly a mistyping. The programmer most likely wa...
6,006,505
6,035,396
RASDIAL API not connecting on 64bit systems [ Works awesome on 32bit systems / VPN]
I am basically trying to connect to a VPN connection using the windows api. It works like a charm on any windows 32bit systems. It always connects. But when I try to connect it on a 64 bit system. It always fails. Please could you suggest, if I am doing anything wrong. This is my code: LPRASDIALPARAMS rdParams...
Basically you would need to access the dll or lib from a 64bit application instead of 32bit. make sure your application is a 64bit app.
6,006,526
6,006,540
C++ writing 'or' instead of ||
Possible Duplicate: C++ alternative tokens? I'm working on an assignment in C++ with a friend of mine, and we've been doing lots of the coding on his computer/environment (a Macbook Pro with Eclipse). In some of the code he has written conditions using and and or rather than && and ||. The code compiles just fine on...
There are a handful of "alternative representations": and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, and xor_eq. They are a standard language feature of C++. Visual C++ only supports these as keywords if you compile with the /Za (standards conformance mode) flag.
6,006,527
6,030,496
Overloading on R-value references and code duplication
Consider the following: struct vec { int v[3]; vec() : v() {}; vec(int x, int y, int z) : v{x,y,z} {}; vec(const vec& that) = default; vec& operator=(const vec& that) = default; ~vec() = default; vec& operator+=(const vec& that) { v[0] += that.v[0]; v[1] += that.v[1]; ...
Recycling temporaries is an interesting idea and you're not the only one who wrote functions that return rvalue references for this reason. In an older C++0x draft operator+(string&&,string const&) was also declared to return an rvalue reference. But this changed for good reasons. I see three issues with this kind of o...
6,006,602
6,006,691
Pulling C/C++ standard library into your project namespace, good idea?
I'm porting some open source code so that it can build on another c++ compiler. One of the difficulties and themes that seem to keep cropping up are implementation differences of the provided standard library by the compiler. For example, one of the source files that I'm compiling includes <sys/types.h>. However, it gi...
This is a bad idea. Do not do things this way. Put the namespace declarations inside each header file. Never have a #include directive inside the scope of a namespace. Never is a strong word, and there are very rare cases in which you might want to do this. If the file you're #includeing also has #include directives, y...
6,006,614
6,006,629
C++ static polymorphism (CRTP) and using typedefs from derived classes
I read the Wikipedia article about the curiously recurring template pattern in C++ for doing static (read: compile-time) polymorphism. I wanted to generalize it so that I could change the return types of the functions based on the derived type. (This seems like it should be possible since the base type knows the derive...
derived is incomplete when you use it as a template argument to base in its base classes list. A common workaround is to use a traits class template. Here's your example, traitsified. This shows how you can use both types and functions from the derived class through the traits. // Declare a base_traits traits class t...
6,006,860
6,007,040
Why should one not derive from c++ std string class?
I wanted to ask about a specific point made in Effective C++. It says: A destructor should be made virtual if a class needs to act like a polymorphic class. It further adds that since std::string does not have a virtual destructor, one should never derive from it. Also std::string is not even designed to be a base cl...
I think this statement reflects the confusion here (emphasis mine): I do not understand what specifically is required in a class to be eligible for being a base clas (not a polymorphic one)? In idiomatic C++, there are two uses for deriving from a class: private inheritance, used for mixins and aspect oriented progr...
6,006,991
6,007,134
How exactly does memory handling (i.e, the function Release) work with Direct3D?
I came across a leak in a Direct3D application of mine, and I ended up correcting it, but I think the cause of the leak was due to my misunderstanding of how Direct3D handles its memory and interfaces. I haven't been able to find a definitive article/tutorial on it (please provide one if you have one), but from what I'...
Direct3D is based on COM, which is a technology that's at least 15 years old. Seems many people claim COM is dead and for that reason many overlook it, but reality is that there are many things in windows including Direct3D and MS's new Media Foundation that are all based on COM. I strongly suggest you take a look at ...
6,007,076
6,015,716
Add overlay / Manipulate using AVFoundation for iPhone?
I am new to the whole AVFoundation thing. Before I was using the good old UIImagePickerControllerSourceTypeCamera. I basically want to do a combination of adding a overlay of a semi-opaque overlay as well as manipulating the pixels to create a black & white effect, sepia, etc. I am displaying it and capturing it using ...
If you are going to do any significant amount of processing on the image then I suggest you use OpenGL ES. If it is simple, such as an overlay, then you can use CoreGraphics. Here is a quick snip it to get at the pixels. void modifyImage(CMSampleBufferRef source) { CVImageBufferRef imageBuffer = CMSampleBufferGetI...
6,007,169
6,014,159
How to get information about domain .NET C++
I am trying to create an application (Language C++ using .NET 2.0) which allows users to get information about a domain, for example if the domain is free or it is used, update date, creation date, expiration date etc. I know about some services which do that like whois.domaintools, whois etc. Now I want to know how ...
Check these urls: http://www.mentalis.org/soft/class.qpx?id=10 http://www.aspheute.com/english/20000825.asp. http://www.codeproject.com/KB/cs/whoisclient.aspx
6,007,185
6,007,998
hello world python extension in c++ using boost?
Here's my simple first attempt at a python extension using boost. Can someone help me to understand what's causing the compilation error? #include <iostream> using namespace std; void say_hello(const char* name) { cout << "Hello " << name << "!\n"; } #include <boost/python/module.hpp> #include <boost/python/de...
/usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory compilation terminated. This line tells exactly why it doesn't work. Your compiler doesn't know where is the pyconfig.h file. You have two options here: place pyconfig.h in a location that g++ knows about (...
6,007,292
6,007,297
whats wrong with this function? where did i make mistake?
I have this function declaration and its defination: declaration void laodFromFile( string const& fileName, Frames& frames, ostream& log =std::clog); defination: void loadFromFile( string const& fileName, Frames& frames, ostream& log =std::clog ) ...
It's a spelling mistake LoadFromFile and LaodFromFile...
6,007,378
6,007,421
Visual C++ Compiler Optimization Flags: Difference Between /O2 and /Ot
What's the difference between the /Ot flag ("favor fast code") and the /O2 flag ("maximize speed")? (Ditto with /Os and /O1.)
/O1 and /O2 bundle together a number of options aimed at a larger goal. So /O1 makes a number of code generation choices that favour size; /O2 does the same thing and favours speed. /O1 includes /Os as well as other options. /O2 includes /Ot as well as other options. Some optimisations are enabled by both /O1 and /O2. ...
6,007,440
6,007,467
Why i can't watch the expression a[1][1] after declare it by a[n][n] in c++?
my code: #include <iostream> using namespace std; int main() { int n=5; int a[n][n]; a[1][1]=5; return 0; } I got this error when trying to watch the expression a[1][1] in eclipse on line 6: Failed to execute MI command: -data-evaluate-expression a[1][1] Error message from debugger back end: Canno...
For some odd reasons this isn't valid C++ unless you make it const int n = 5; Otherwise the array size is formally unknown until runtime.
6,007,463
6,007,503
Which permissions are needed to delete a file in windows
In CreateFile() has DesiredAccess Like GENERIC_READ, GENERIC_WRITE, FILE_READ_ATTRIBUTES, etc. My question is what is the minimum/exact permissions needed to solely delete a file in the system? Thanks
If you just want to delete a file, use the DeleteFile function. It's documentation details what permissions you need, and a few things you should know, like: If you request delete permission at the time you create a file, you can delete or rename the file with that handle, but not with any other handle. There is good...
6,007,493
6,008,104
Integrating Box2D with an existing game class structure in SDL?
Sorry for the rather vague title, but it seemed befitting of a similarly vague question, though hopefully succinct enough that somebody will be able to answer it. I have spent a decent amount of time working on the framework for a 2D side-scrolling game in SDL, and now that I am comfortable with the library and have a ...
I would not suggest that your CMain class derives from the b2world, since it definitely is not a is-a relation but rather a has-a. I cannot tell if it is the perfect solution, since I do not know your overall architecture, but it seems like a good place fot the Singleton pattern. I suggest that you create a class imple...
6,007,535
6,107,598
How can i create QML canvas in my C++ code and attach video on that? Such as Java Canvas i can
How to create QML such canvas, and attach XOverlay video object on that canvas? Java: final Canvas canvas = new Canvas(); canvas.setPreferredSize(new Dimension(200, 200)); XOverlay.wrap(video).setWindowID(canvas); C++ #include <QtGui/QApplication> #include "qmlapplicationviewer.h" int main(int argc, char *argv[]) {...
Video playback in QML can be done through Qt Mobility's Video element: http://doc.qt.nokia.com/qtmobility-1.2/qml-video.html
6,007,563
6,007,870
Using std::tr1::bind with std::vector::push_back
Why my VS2010 can't compile this code: #include <functional> #include <vector> int main() { std::vector<int> vec; std::bind(&std::vector<int>::push_back, std::ref(vec), 1)(); return 0; }
Try this: struct push_back { void operator()(std::vector<int>& vector, int i) const { vector.push_back(i); } }; // somewhere else: std::vector<int> vec; std::tr1::bind(push_back(), std::tr1::ref(vec), 1)(); With C++03 note that push_back cannot be a local type; with C++11 it can but it would b...
6,007,568
6,007,702
What is max length for an C/C++ identifier on common (build) systems?
I don't remember the standard saying something of the max length for identifiers so in theory they can be long. In real life, those names could be limited by at least the compiler and linker implementations. While this should work on all systems int a; this snippet #!/usr/bin/perl print "int" . "b" x 2**16 . ";"; cr...
Microsoft C++: 2048 characters Intel C++: 2048 characters g++: No limit, as answered in this question: is there a length limit on g++ variable names?
6,007,594
6,008,065
Warnings like 'wcstok': This function or variable may be unsafe. Consider using wcstok_s instead
I am just using these wide character literals in my code to learn about them wchar_t* wpsub = wcstok(names, names_delim); wpsub = wcstok(NULL, names_delim); wchar_t* wcopied=new wchar_t[wcslen(wname) + 1]; strcpy(nameptr, "singh"); wcscpy(wcopied, wname); wcscat(wcopied, L" Singh"); why ...
There is another reason not to use the original strtok family function: [...] However, within a single thread, interleaving calls to one of these functions is highly likely to produce data corruption and inaccurate results. When parsing different strings, finish parsing one string before starting to parse the next. Al...
6,007,731
6,007,934
Can mutex implementations be interchanged (independently of the thread implementation)
Do all mutex implementations ultimately call the same basic system/hardware calls - meaning that they can be interchanged? Specifically, if I'm using __gnu_parallel algorithms (that uses openmp) and I want to make the classes they call threadsafe may I use boost::mutex for the locking? or must I write my own mutex such...
You should not mix synchronization mechanisms. E.g. current pthreads mutex implementation is based on futex and it is different from previous pthreads implementations (see man 7 pthreads). If you create your own level of abstraction, you should use it. It should be considered what is your need - inter-thread or inter-p...
6,008,449
6,008,585
Comparing std::string with constants vs comparing char arrays with constants In C++
I am trying to make a little text adventure to get a handle on C++. cin >> keyboard1; if ((keyboard1 == "inv")inventory(inv); This will work if keyboard1 is a string, but won't if it's a char array, is this because I haven't included the null at the end of the constant?
Let'say your code is the following: int main(int argc, char *argv[]) { std::string s; std::cin >> s; std::cout << s << std::endl; if (s == "inv") { std::cout << "Got it" << std::endl; } return 0; } This works as expected because of the way the stl class string overrides the == operator....
6,008,453
6,008,566
Linked List need help cant print my data. want to make an add func. in C - C++
this is my code. i wanted to print all my list datas. but i cant cause when i write while(llist->next != NULL) llist->next is NULL but i don't know why. please help me :) #include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; struct rame { int data; struct rame *next; }; int main(...
In your code llist = (rame*)malloc(sizeof(struct rame)); llist->data = 10; allocates one memory location to llist , and the data of this location is assigned 10 Next you do: llist->next = llist; llist->next->data = 15; The first line assigns the next link of the llist to itself, which makes the below state of the ...
6,008,470
6,008,551
Catch Segfault or any other errors/exceptions/signals in C++ like catching exceptions in Java
I wrote a Linux program based on a buggy open source library. This library sometimes triggers segfaults that I cannot control. And of course once the library has segfaults, the entire program dies. However, I have to make sure my program keeps running even if the library has segfaults. This is because my program sort o...
You cannot reliably resume execution after a segmentation violation. If your program must remain running, fence off the offending library in a separate process and communicate with it over a pipe. When it takes a segmentation violation, your program will notice the closed pipe.
6,008,702
6,008,778
what this "if(k.c[3] & c)" part of code doing?
#include<stdio.h> #include<iostream.h> main() { unsigned char c,i; union temp { float f; char c[4]; } k; cin>>k.f; c=128; for(i=0;i<8;i++) { if(k.c[3] & c) cout<<'1'; else cout<<'0'; c=c>>1; } c=128; cout<<'\n'; for(i=0;i<8;i++) { if(k.c[2] & c) cout<<'1'; else cout...
Bitwise Operation in your code c = 128 therefore the binary representation is c = 10000000 a & c will and every ith but if c with evert ith bit of a. Because c only has 1 in the MSB position (pos 7), so a & c will be non-zero if a has a 1 in its position 7 bit, if a has a 0 in pos bit, then a & c will be zero. This l...
6,008,712
6,008,740
C++: expected identifier before numeric constant
I'm trying to write a small program using MTL, but I'm getting the mentioned error when I try to make a MTL Matrix a member of a class. #include <boost/numeric/mtl/mtl.hpp> class myClass { private: mtl::dense2D<double> Ke(6,6); }; However, there is no problem with the same statement in main(): #include <boost/num...
You need to do that in the constructor's initialiser list. class myClass { mtl::dense2D<double> Ke; public: myClass() : Ke(mtl::dense2D<double>(6, 6)) { } };
6,008,920
6,011,412
Game crashes when I try to use the features of a b2Body -- why?
My app crashes when I try to use the features of b2Body from within my NSObject class. Here is the interface of my class: #import <Foundation/Foundation.h> #import "Box2D.h" #import "GLES-Render.h" #import "cocos2d.h" #import "HelloWorldScene.h" @interface Magnet : NSObject { b2Body* body; } @property (readwrite...
Without the crash, it is hard to say specifically what is going wrong. However, that code is rife with potential for crashes. you are using structures that are on the stack, not allocated. If the scope of that code goes away before you are done with those structures, it'll lead to crashes and undefined behavior. you ...
6,008,956
6,009,021
Proper usage of pthread_detach
I'm trying to get a function to start up another thread, and then return, with the thread still running. It seems like pthread_detach() would take care of the memory and whatnot for me, although I'm not entirely sure. This is the code for the function: void function() { pthread_mutex_lock(&state.continueLoopingMu...
I don't see anything wrong. Yes the pthread_detach will take care to release the resources of the thread.
6,009,004
6,009,012
Are value parameters implicitly moved when returned by value?
Consider the following function: Foo foo(Foo x) { return x; } Will return x invoke the copy constructor or the move constructor? (Let's leave NRVO aside here.) To investigate, I wrote a simple Foo class that is only movable but not copyable: struct Foo { Foo() = default; Foo(const Foo&) = delete; Foo(F...
If there is a move ctor for Foo, it should be selected. Function parameters are explicitly excluded from copy elision in return statements (FDIS §12.9p31, first bullet): in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a funct...
6,009,268
6,009,427
Generate a quick checksum for a large array of floats, without using any libraries?
In C (more specifically, C for CUDA), what is the best way to compute a checksum of a large array of floats (say twenty thousand values), that is easy to print with printf, without using any libraries? I could just sum all of the values in floating precision, but I'm afraid roundoff errors or saturation, or nan/inf val...
This is exactly what Cyclic Redundancy Checks are for. Boost has a CRC library, and there are dozens of source code implementations on the web. Probably a 16-bit CRC is best for you, because eyeballing the result is easy. But you might want a 32-bit CRC if you are paranoid about false positives.
6,009,374
6,009,538
How to return y value from vector 3 1D array
I have a vector 3 (x,y,z) 1D dynamic array full of vertex positions. How would I return the y value at a given x and z coordinate? Edit:: Sorry about the lack of detail. I am using c++, compiling in Visual Studio 2008. The vector is a vector class storing 3 float values defining an x, y and z variable, it is used for p...
I suppose you have something like struct Vec3D{ float x, y, z; }; Vec3D vec3d_arr[20]; Then, to get what you want, you'll need to iterate over the array. float GetYforXZ(Vec3D* arr, unsigned int length, float x_val, float z_val){ for(unsigned i=0; i < length; ++i){ if(arr[i].x == x_val && arr[i].z == z_val) ...
6,009,382
6,009,424
win32 controls: different coordinates in resource.rc and CreateWindow?
I'm creating a small win32 application. Currently I have 6 text labels coded in the resource file, like this: IDD_MAIN DIALOGEX 0, 0, 465, 279 STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "SpiderPigOverseer" FONT 8, "MS Shell Dlg", 400, 0, 0x1 BEGIN CONTROL "sa...
Coordinates in .rc files represented as Dialog units which are not equal to pixels. It is made for automatically adjust controls size depending on system font size. You can convert dialog units to pixels as follows: pixelX = MulDiv(templateunitX, LOWORD(GetDialogBaseUnits()), 4); pixelY = MulDiv(templateunitY, HIWORD(...
6,009,404
6,023,218
Include sqlite database into a C++ JNI project
I've written my C++ classes and now I have to create the library to use them on android. One classes handles a database, which I've prepared in advance (it includes pictures and strings). In Qt it works fine, so the code is robust. I have my Android project in Eclipse, the JNI seems to be OK, since on runtime android d...
I solved in another way. I loaded the database on the virtual SD card and changed the path of the database in my C++ class. Now it's working fine. Of curse, this is not the right way to do it, but i have to present the project no later than friday... I'found also the other solution, but it requires API 2.3 which includ...
6,009,825
6,365,615
How do I control output directories and files that are cleaned when using MPC?
I'm experimenting with OpenDDS (and ACE/TAO), which uses MPC (Make Project Creator) to generate the actual make files, and it's doing a couple really annoying things. First, it generates a lot of intermediate sources files (some IDL, and c++ headers/implementation), and it places them in the same directory with manuall...
To delete all the generated files (when using make files), simple do a 'make realclean'. 'make clean' simply cleans up the C++ compilation products (object files, library, & executables) while 'make realclean' removes all generated files. Changing the output directory for the generated files is probably not something ...
6,010,207
6,010,345
text on custom control
I have read and read, trying to find how to put text on a custom control. I have found stuff, but none of it has been clean and simple. So how do I draw text on a custom control? here is code... LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wparam, LPARAM lparam); LRESULT CALLBACK CustProc(HWND hwnd, UINT u...
You can catch the WM_PAINT message in your CustProc function and draw the text yourself. You can get a drawing context by calling BeginPaint, draw the text and close the drawing context by calling EndPaint. You can draw text with the TextOut function. Here is an example from MSDN: LRESULT APIENTRY WndProc(HWND hwnd, U...
6,010,793
6,011,904
Looking for simple practical C++ examples of how to use ICU
I am looking for simple practical C++ examples on how to use ICU. The ICU home page is not helpful in this regard. I am not interested on what and why Unicode. The few demos are not self contained and not compilable examples ( where are the includes? ) I am looking for something like 'Hello, World' of: How to ope...
There's no special way to read a UTF-8 file unless you need to process a byte order mark (BOM). Because of the way UTF-8 encoding works, functions that read ANSI strings can also read UTF-8 strings. The following code will read the contents of a file (ANSI or UTF-8) and do a couple of conversions. #include <fstream> #i...
6,010,838
6,010,892
How to stop doubles converting to scientific notation when using a stringstream
I'm making a function to return the number of decimal and whole number digits and am converting the inserted typename number to a string using sstreams. However the number when being converted to a string comes out in scientific notations which is not useful for counting the number of digits are in the normal number. ...
Use std::fixed stream manipulator as: ss << fixed << numb; -- Example, #include <iostream> using namespace std; int main () { double a,b,c; a = 3.1415926534; b = 2006.0; c = 1.0e-10; cout.precision(5); cout << a << '\t' << b << '\t' << c << endl; cout << fixed << a << '\t' << b << '\t...
6,011,045
6,011,224
Virtual function with fixed implementation not using most derived class for (*this)
Let's say I have the following code: struct Z; struct A { virtual void Do (Z & z) const; }; struct B : public A {}; struct Z { void use (A const & a) {} void use (B const & b) {} }; void A::Do(Z& z) const{ z.use(*this); } Right now, when I call B.do, the type of this is A, which make sense, because the im...
Since you now clarified that what you want is the visitor pattern, well, sorry, but that's just how it is. This answer shows how the visitor pattern with double dispatch works. I thought of a nice way using CRTP, but this may or may not work for you, depending on the circumstances. (Note: I used the code from the link...
6,011,428
6,011,523
Move constructors and the Strong Exception Guarantee
Just a quick question, on which I cannot find a good reference, especially with regard to current implementations of the future C++0x standard. Since move constructors can throw, it means that some standard library functions cannot provide the strong exception guarantee (eg. vector<T>::resize()). There was a proposal t...
I haven't checked the specific implementations, but the general idea is that if the move constructor can throw, the vector will have to copy the elements instead. That way it is possible to roll back in case of an exception. There is even a helper function move_if_noexcept defined in <utility> to help it decide what to...
6,011,435
6,011,479
Finding top elements of a map using Heap
I have a unordered_hashmap that maps a string (say personName or SSN) to a struct Attributes that has many attributes of that person including annualIncome. There are many such hash maps corresponding to different organizations such as mapOrganizationA, mapOrganizationB etc. I need to find the people (with attributes) ...
You can use make_heap, push_heap, pop_heap, sort_heap, is_heap to treat any non-associative container (or sequence, really) as a heap. That would not fit you map nicely, but I assume nothing would prevent you from storing the values (or pointers/references to those) inside, say, a list for this purpose? Also, perhaps ...
6,011,470
6,063,660
Getting error C2039 on vista32bit while the same code works correctly on XP
I'm using visual studio 2005. I executed my code in XP windows and it worked correctly, but when I want to do the same in vista32 it starts to say these errors which seems strange. I've searched a lot and found this a common problem but I couldn't find any clear and useful solution. If some body helps I would appreciat...
I just uninstall and again reinstall the visual 2005 and surprisingly it worked, tnx for all your advices. regards
6,011,493
6,011,664
c++ log function is using floating point precision
I am having an interesting seg fault in the following function when I give it a number very close to 1.0. Specifically when the number would be rounded to 1.0 at FLOATING POINT precision. double get_random_element(double random_number) { if (random_number <= 0.0 || random_number >= 1.0) throw std::runtime_...
I think quamrana has a good point (it immediately drew my attention too). However, I've been able to run this snippet for considerable length: #include <math.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_real.hpp> double get_random_element(double random_number) { if (random_number ...
6,011,640
6,011,652
How to specifiy comparison for pair?
There is a pair pair <string, int> myPair; I have a vector of myPair objects. I need to convert it to a min-heap using make_heap on the second value of pair i.e. the integer. How can I do that? I am not sure on how to define the comparison operations. I know I need something like this for heap to operate. But not sure...
Well, make_heap has an overload that takes an extra comparision operator, soo... // somewhere in global namespace typedef std::pair<std::string, int> myPair_type; struct mypair_comp{ bool operator()(myPair_type const& lhs, myPair_type const& rhs){ return lhs.second < rhs.second; } }; // somewhere at your call...
6,011,729
6,011,744
what does MD , LD etc stands for?
In c++ compiling, there is MD, MT and LD. MT is obviously multi-thread, what about others?
MD: use Multithread DLL Library MT: use Multithread, statically-linked library LD: Create a DLL See this MSDN link for more info
6,011,926
6,011,942
template struct as template class type
template<class T,class TV> struct CONJUGATE_GRADIENTS_HELPER{ DEFORMABLE_OBJECT<T,TV>* deformable_object; int partition_id; T time,dt; T alpha,beta; ARRAY<TV>* dX_full; ARRAY<double> *S_dot_Q_partial,*rho_new_partial,*supnorm_partial; }; typedef CONJUGATE_GRADIENTS_HELPER<T,TV...
Off goes the psychic answer, since I don't know what ARRAY exactly is... It seems your ARRAY class template overloads the function call operator operator() instead of the index operator operator[]. Just use it as if those () brackets where normal array indexing brackets []. Also, your code clearly shows a way to iterat...
6,011,957
6,014,102
boost unit test templates produces bloated code. How to avoid that?
I have about a hundred of simple tests done with boost unit test library. Not only I get very long compile times (in order of half a minute), but the size of the resulting executable gets really big - 4MB for just a hundred simple tests. If the tests are done without using boost test, the executable size is a mere 120k...
I. Which usage variant do you employ? If you employ single header variant of unit test framework, you should switch to offline variant (either static or dynamic) II. If you suspect that BOOST_AUTO_TEST_CASE macro is at fault, you have several options: Give up single assertion per test case policy and use number of "th...
6,012,047
6,012,445
Find and replace character next to for uppercase version in Visual Studio?
I have a situation where I have: @return hello world. @return goodbye world. and I'd like to find and replace so these become: @return Hello world. @return Goodbye world. Is this possible with Visual Studio 2008? Thanks
I think it's probably easiest just to create a small console application that takes in the whatever.c file and does it for you. I don't think the Find & Replace has this kind of functionality.
6,012,068
6,012,137
'warning C4709: comma operator within array index expression' - but no comma to be seen anywhere!
Take this little example code: struct Test{ operator int() const{ return 0; } }; Test test(){ return Test(); } int main(){ int arr[10]; arr[test()] = 5; } Compiling under Visual Studio 2010 with /W4 generates said warning. Interestingly, if I add but a simple default constructor, the warn...
Definitely it is a bug - misleading warning.
6,012,157
6,089,065
Is std::unique_ptr<T> required to know the full definition of T?
I have some code in a header that looks like this: #include <memory> class Thing; class MyClass { std::unique_ptr< Thing > my_thing; }; If I include this header in a cpp that does not include the Thing type definition, then this does not compile under VS2010-SP1: 1>C:\Program Files (x86)\Microsoft Visual Stud...
Adopted from here. Most templates in the C++ standard library require that they be instantiated with complete types. However shared_ptr and unique_ptr are partial exceptions. Some, but not all of their members can be instantiated with incomplete types. The motivation for this is to support idioms such as pimpl using sm...
6,012,190
6,012,208
Get the address of class's object in C++?
Suppose I have a C++ class as follows: class Point { // implementing some operations } Then: Point p1; Point p2 = p1; If I want to know the address of p2, then I can use &p2. But how can I get the address that p2 stores? Because p2 is not a pointer, so I cannot just use cout << p2;
What's wrong with the following: cout << &p2; As you say, p2 is not a pointer. Conceptually it is a block of data stored somewhere in memory. &p2 is the address of this block. When you do: Point p2 = p1; ...that data is copied to the block 'labelled' p1. But how can I get the address that p2 stores? Unless you add...
6,012,287
6,013,335
A more fundamental reason Java does not include operator overloading (at least for assignment)?
Referring to a ~2-year old discussion of the fact that there is no operator overloading in Java ( Why doesn't Java offer operator overloading? ), and coming from many intense C++ years myself to Java, I wonder whether there is a more fundamental reason that operator overloading is not part of the Java language, at leas...
Is this a correct assessment on my part? The lack of operator in general is a "personal choice". C#, which is a very similar language, does allow operator overloading. But you still can't overload assignment. What would that even do in a reference-semantics language? Are there any other operators, or more gener...
6,012,397
6,012,564
How to figure out how many decimal digits are in a large double?
Hey so I'm making a function that returns the number of decimals, whole numbers, or TOTAL numbers there are, but have been unable to make it work with either of these ways: multiplying by a really large number like 10 billion doesn't work because of the innacurate way computers store decimals, making 2.3 2.2999575697 ...
Only some decimal numbers can be stored in exact form as a floating point number. Because of this there is no way to determine how many decimal places are significant for any decimal number for which this is not true. As hammar suggested, read up on the floating point storage format, I believe that every programmer sho...
6,012,419
6,120,735
Application crashes when clearing the QTreeWidget
My application is crashing with a BAD_ACCESS when quitting and when clearing the QTreeWidget. This is how I'm populating the first level of the tree: std::set<UrlItem>::iterator i; for(i = crawler->getUrls()->begin() ; i != crawler->getUrls()->end() ; i++) { QList<QString> cells; cells.append(i->url); cell...
It seems I was setting the header the wrong way. This works fine: QList<QString> headers; headers.append(tr("Url")); headers.append(tr("Message")); headers.append(tr("Status code")); ui->resultTreeView->setHeaderLabels(QStringList(headers)); Now, what setHeaderItem was supposed to do and why it crashed my applicatio...
6,012,456
6,012,476
Vector initialization without using default constructor
How can I reduce the number of lines of code of the following without having a default constructor? #include <vector> enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }; enum Suit { HEART, DIAMOND, CLUB, SPADE }; struct Card { Card(Rank r, Suit s) : rank(r), suit(s) { } ...
You can use a loop and add the elements to the container in the body of the constructor: Deck() { for (int rank = (int)DEUCE; rank <= (int)ACE; ++rank) { for (int suit = (int)HEART; suit <= (int)SPADE; ++suit) { cards.push_back(Card((Rank)rank, (Suit)suit)); } } } This...
6,012,640
6,012,781
Locking strategies and techniques for preventing deadlocks in code
The common solution to preventing deadlock in code is to make sure the sequence of locking occur in a common manner regardless of which thread is accessing the resources. For example given threads T1 and T2, where T1 accesses resource A and then B and T2 accesses resource B and then A. Locking the resources in the orde...
The technique you describe isn't just common: it's the one technique that has been proven to work all the time. There are a few other rules you should follow when coding threaded code in C++, though, among which the most important may be: don't hold a lock when calling a virtual function: even if at the time you're wr...
6,012,663
6,012,671
Get Unix timestamp with C++
How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?
C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours: #include <iostream> #include <chrono> int main() { const auto p1 = std::chrono::system_clock::now();...
6,013,066
6,013,103
explicit specialization template class member function with different return type
I am trying to port some C++ code from Windows to Solaris(Unix). There are some template code need to be changed. I am using Solaris' compiler CC, g++ should have same issue. I have a particular part of code introduce some trouble. They are simplified as following: #include <exception> #include <cmath> #include <string...
// the template class template <typename T> class A { template<> double getValue(T t) { return exp( 1.5 * t ); } }; This isnt allowed by standard. do: template <typename T> class A { template<class R> R getValue(T t) { return get_value_impl<double>::apply(*this, t); } template<class R, class = void...
6,013,318
6,013,398
Exception when comparing an (int)double and (int)int
Hey so i'm using the pdCurses lib and stringStream to calculate and make a 5 character long string that represents a clock. It shows like 00:00, 0:00, 00.00, or 0.000. However when running my function i get an exeption thrown at this part: if((int)time >= 10) { if((int)time >= 60) { if((int)time >= 600)...
There's not really enough to go on here, but my guess is that the assertion is from the time_s.insert(0, min) call that's in the line along with the if((int)time >= 600) - the string is performing some reallocation and the heap has been corrupted (maybe by whatever is happening in the loop at the top of the function, b...
6,013,420
6,013,496
A "Sparse Map" Data Type (RLE-like) For C, C++, or .NET
Is there any library out there for C, C++, or .NET that implements a "sparse map"? (I don't know a better name for it.) I'm looking for something like run-length encoding, like for allocating files on a disk. The data structure should be able to hold information saying "Clusters 0 to 1000 have been allocated by file 1,...
"sparse map"? You likely mean interval tree. CGAL contains a robust implementation in C++.
6,013,527
6,013,652
webcrawler link extraction problem
im writing a simple webcrawler. the problem is, with the link extraction. i uses the cpp-netlib with boost. here a few lines of my CLink Class. CLink::CLink(const CLink& father, const std::string& relUrl ) { uri = relUrl; boost::network::uri::uri instance(relUrl); boost::network::uri::uri instanc...
You need to have a special case for absolute links (those that start with /). If the href starts with /, then the resulting link should be (using the terms from The URI template which come from the RFC): [scheme]://[authority][what you got in href] What you are currently constructing is: [scheme]://[authority][path][w...
6,013,585
6,013,675
Exception when comparing an (int)double and (int)int
Possible Duplicate: Exception when comparing an (int)double and (int)int IGNORE THIS POST. ACCIDENTLY REPOSTED Sorry
if((int)time >= 600){ time_s.insert(4, sec); should be, if((int)time >= 600){ time_s.insert(3, sec); // digit 3 instead of 4 From your code, I suppose the string size is 6 characters (0 to 4 and 5th character as nul). Inserting 2 digit at 4th position and 5th position would overwrite nul. Do cross verify, as I ...
6,013,638
6,013,775
Is it possible to "prepare" input from cin?
In his answer, specifically in the linked Ideone example, @Nawaz shows how you can change the buffer object of cout to write to something else. This made me think of utilizing that to prepare input from cin, by filling its streambuf: #include <iostream> #include <sstream> using namespace std; int main(){ strea...
#include <iostream> #include <sstream> int main() { std::stringstream s("32 7.4"); std::cin.rdbuf(s.rdbuf()); int i; double d; if (std::cin >> i >> d) std::cout << i << ' ' << d << '\n'; }