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 |
|---|---|---|---|---|
2,683,964 | 2,684,130 | identifying the type | In my application, there is a inheritance hierarchy in which only the classes that are at the end of the inheritance chain are non-abstract classes. Also there is some usage of boost::variant. I want to write a function which takes a pointer and a Type and says whether the object belongs to that type.
For example
#defi... | Well there are two direct versions of this:
return (boost::get<Type*>(v) != 0);
And this:
return ( v.type() == typeid(Type) );
I am not sure how to handle that with your template overloading cleanly but you could do something like this:
template< typename Type, bool TypeisAbstract, bool TypeIsVariant,
typen... |
2,684,508 | 2,686,137 | MOC adding namespace to class names | I have this very strange problem while compiling the project.
MOC seems to be adding a namespace to the class name being moc'ed, although it's not mentioned anywhere in the file/class.
The namespace, however, exists in a library which I use, but it's hidden far away in the header files and I don't use it in the UI fi... | SmpTl is the namespace CaptureController is defined in, as it was found by MOC.
The Q_OBJECT macro expands into the declaration of the staticMetaObject-variable inside your class definition (among other things it expands into). The MOC-file contains the definition of that variable.
If this is not correct, please post y... |
2,684,581 | 2,684,586 | C++ constructor behavior | I'm declaring an instance of a class like so:
Matrix m;
This appears to implicitly initialize m (i.e. run the constructor). Is this actually the case?
| Yes, the default constructor is called.
If there is no default constructor, this statement is ill-formed. If there are no user-declared constructors, the compiler provides a default constructor.
|
2,684,603 | 2,684,625 | how do I initialize a float to its max/min value? | How do I hard code an absolute maximum or minimum value for a float or double? I want to search out the max/min of an array by simply iterating through and catching the largest.
There are also positive and negative infinity for floats, should I use those instead? If so, how do I denote that in my code?
| You can use std::numeric_limits which is defined in <limits> to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a - in front for negative infinity).
#include <limits>
//...
std::numeric_limits<float>::max();
std::numeric_... |
2,684,938 | 2,870,412 | How can you animate a sprite in SFML | Lets say I have 4 images and I want to use these 4 images to animate a character. The 4 images represent the character walking. I want the animation to repeat itself as long as I press the key to move but to stop right when I unpress it. It doesn't need to be SFML specific if you don't know it, just basic theory woul... | You may want some simple kind of state machine. When the key is down (see sf::Input's IsKeyDown method), have the character in the "animated" state. When the key is not down, have the character in "not animated" state. Of course, you could always skip having this "state" and just do what I mention below (depending o... |
2,684,971 | 2,685,065 | Context of Main function in C or C++ | Does the main function we define in C or C++ run in a process or thread.
If it runs in a thread, which process is responsible for spawning it
| main() is the entry point for your program. C++ (current C++ anyway) doesn't know what a process or thread is. The word 'process' is not even in the index of the standard. What happens before and after main() is mostly implementation defined. So, the answer to your question is also implementation defined.
In genera... |
2,684,981 | 2,685,294 | How to place multiple formats on the clipboard? | For example, what Wordpad did when I press "Ctrl+C"?
It places many different format to clipboard. So Notepad can get the text without any color or font...etc, and you still can keep the original format when you paste in another Wordpad window.
The MSDN said I should call SetClipboardData multiple times. But it doesn'... | You can use Delphi's TClipboard.SetAsHandle to put data on the clipboard in as many formats as you want. Open the clipboard first, or else each call to SetAsHandle will clobber whatever else was already there, even in other formats.
Clipboard.Open;
Clipboard.SetAsHandle(cf_Text, x);
Clipboard.SetAsHandle(cf_Bitmap, y);... |
2,685,074 | 2,685,157 | Marshal a C++ class to C# | I need to access code in a native C++ DLL in some C# code but am having issues figuring out the marshaling. I've done this before with code that was straight C, but seem to have found that it's not directly possible with C++ classes. Made even more complicated by the fact that many of the classes contain virtual or i... | There is really no easy way to do this in C# - I'd recommend making a simple wrapper layer in C++/CLI that exposes the C++ classes as .NET classes.
It is possible to use P/Invoke and lots of cleverness to call C++ virtual methods, but I wouldn't go this route unless you really had no other choice.
|
2,685,094 | 2,686,603 | How to get a flat, non-interpolated color when using vertex shaders | Is there a way to achieve this (OpenGL 2.1)? If I draw lines like this
glShadeModel(GL_FLAT);
glBegin(GL_LINES);
glColor3f(1.0, 1.0, 0.0);
glVertex3fv(bottomLeft);
glVertex3fv(topRight);
glColor3f(1.0, 0.0, 0.0);
glVertex3fv(topRight);
glVertex3fv(topLeft);
.
.
(draw a square)
.
.
glEnd();
I ge... | If you don't want the interpolation between vertice attributes inside a primitive (e.g. color in a line segment in your case) you'll need to pass the same color twice, so end up duplicating your geometry:
v0 v1 v2
x--------------x-----------x
(v0 is made of structs p0 and c0, v1 of p1 and c1... |
2,685,104 | 2,702,674 | Output of gcc -fdump-tree-original | If I dump the code generated by GCC for a virtual destructor (with -fdump-tree-original), I get something like this:
;; Function virtual Foo::~Foo() (null)
;; enabled by -tree-original
{
<<cleanup_point <<< Unknown tree: expr_stmt
(void) (((struct Foo *) this)->_vptr.Foo = &_ZTV3Foo + 8) >>>
>>;
}
<D.20148>:;
if (... | That looks like the compiler-generated code to manage the actual memory deallocation after the destructor is called and should execute right after your destructor code.
|
2,685,172 | 2,685,193 | g++ no matching function call error | I've got a compiler error but I can't figure out why.
the .hpp:
#ifndef _CGERADE_HPP
#define _CGERADE_HPP
#include "CVektor.hpp"
#include <string>
class CGerade
{
protected:
CVektor o, rv;
public:
CGerade(CVektor n_o, CVektor n_rv);
CVektor getPoint(float t);
string toString();
};
the .cpp:
#incl... | From the looks of it, your CVektor class has no default constructor, which CGerade uses in your constructor:
CGerade::CGerade(CVektor n_o, CVektor n_rv)
{ // <-- by here, all members are constructed
o = n_o;
rv = n_rv.getUnitVector();
}
You could (and probably should) add one, but better is to use the initiali... |
2,685,238 | 2,685,329 | Are there any high level language that don't support using C++ libraries? | Are there any high level language that don't support using C++ libraries?
| Using C++ libraries from other high-level languages has a couple of major obstacles:
if the library is OO, you need to be able to create a C++ object in the calling language - this is not easy.
C++ implementations use a technique known as "name-mangling" to ensure type-safe linkage. Unfortunately, there is no standard... |
2,685,333 | 2,685,368 | Mapping C structure to an XML element | Suppose I have a structure in C or C++, such as:
struct ConfigurableElement {
int ID;
char* strName;
long prop1;
long prop2;
...
};
I would like to load/save it to/from the following XML element:
<ConfigurableElement ID="1" strName="namedElem" prop1="2" prop2="3" ... />
Such a mapping can be trivially... | The technique you want is called serialization. You may want to read these articles:
http://www.codeproject.com/KB/cpp/xmlserialization.aspx
http://www.codesynthesis.com/products/xsd/ <=== Very close to what you want!
http://www.artima.com/cppsource/xml_data_binding.html
http://www.ibm.com/developerworks/xml/library/x-... |
2,685,336 | 2,685,397 | Running an XLL outside Excel? | I know this question has been posted before... but I haven't found any answer yet (besides from the generic answers about how XLL are actually DLL, etc).
Has anybody out there been successful calling a XLL from say C# (using DllImport) without having to load Excel with the XLL loaded as an addin?
Basically, you would h... | You're on the right track with needing to create your own XLCall32.dll and simulate Excel. That's non-trivial given what you can do via the interface that XLLs use to talk to Excel. It becomes easier the less of Excel that you need to use from within your XLL, so I guess if you have a known selection of XLLs that you n... |
2,685,506 | 2,685,605 | C++ STL question related to insert iterators and overloaded operators | #include <list>
#include <set>
#include <iterator>
#include <algorithm>
using namespace std;
class MyContainer {
public:
string value;
MyContainer& operator=(const string& s) {
this->value = s;
return *this;
}
};
int main()
{
list<string> strings;
strings.push_back("0");
string... | What would work would be using the constructor (which would make more sense instead of the assignment):
class MyContainer {
public:
string value;
MyContainer(const string& s): value(s) {
}
};
Then the second problem is that set also requires its contents to be comparable.
As to the cause, insert_iterator wor... |
2,685,555 | 2,685,569 | Passing a structure by value, with another structure as one of its members, changes values of this member's members | Sorry for the confusing title, but it basically says it all. Here's the structures I'm using (found in OpenCV) :
struct CV_EXPORTS CvRTParams : public CvDTreeParams
{
bool calc_var_importance;
int nactive_vars;
CvTermCriteria term_crit;
CvRTParams() : CvDTreeParams( 5, 10, 0, false, 10, 0, false, fals... | By the time I finished writing this question I found the answer. So I figured I'd post anyway if someone comes across the same problem. The code itself wasn't wrong (or at least, it wasn't completely wrong). However I am using MacOS X and apple-gcc on a ppc processor (G5). I was using the -fast flag for optimization. ... |
2,685,598 | 2,685,683 | #warning in Visual Studio | In gcc I can do compile-time warnings like this:
#if !defined(_SOME_FEATURE_)
#warning _SOME_FEATURE_ not defined-- be careful!
#endif
But in Visual Studio this doesn't work. Is there an alternative syntax for #warning?
| About the closest equivalent would be #pragma message, or possibly #error (the latter stops compilation, the former just prints out the specified error message).
|
2,685,626 | 2,686,021 | Explain Type Classes in Haskell | I am a C++ / Java programmer and the main paradigm I happen to use in everyday programming is OOP. In some thread I read a comment that Type classes are more intuitive in nature than OOP. Can someone explain the concept of type classes in simple words so that an OOP guy like me can understand it?
| First, I am always very suspicious of claims that this or that program structure is more intuitive. Programming is counter-intuitive and always will be because people naturally think in terms of specific cases rather than general rules. Changing this requires training and practice, otherwise known as "learning to pro... |
2,685,636 | 2,705,220 | Lua, game state and game loop |
Call main.lua script at each game loop iteration - is it good or bad design? How does it affect on the performance (relatively)?
Maintain game state from a. C++ host-program or b. from Lua scripts or c. from both and synchronise them?
(Previous question on the topic: Lua and C++: separation of duties)
(I vote for eve... | The best thing about lua is that it has a lightweight VM, and after the chunks get precompiled running them in the VM is actually quite fast, but still not as fast as a C++ code would be, and I don't think calling lua every rendered frame would be a good idea.
I'd put the game state in C++, and add functions in lua tha... |
2,685,679 | 2,685,765 | Parse int to string with stringstream | Well!
I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution.
I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers... | Have you tried just outputting the integer as is? If you're only converting it to a string to output it, then don't bother since cout will do that for you.
else
{
// toString( tempTotal, store ); // Skip this step.
cout << loop1 << " x " << loop2 << "= " << tempTotal << endl;
}
I have a feeling that it's lik... |
2,685,808 | 2,686,047 | Need advice on C++ coding pattern | Hi!
I have a working prototype of a game engine and right now I'm doing some refactoring.
What I'm asking for is your opinion on usage of the following C++ coding patterns.
I have implemented some trivial algorithms for collision detection and they are implemented the following way:
Not shown here - class constructor i... | If the various functions have something to do with each other, if it's more than helping but really have a common factor such as acting on the same entity, then put them in a class. On the other hand, if a function acts on the same entity as others, but you also want to reuse it for other entities that are convertible ... |
2,685,854 | 2,685,871 | Why should the copy constructor accept its parameter by reference in C++? | Why must a copy constructor's parameter be passed by reference?
| Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to make a new value, so we call the copy constructor, and so on...
(You would have infinite recursion because "to make a copy, you need to make a copy".)
|
2,685,917 | 2,686,076 | Is it possible that an C++ application use CRT 4053 when the manifest uses 762? | My application is compiled on a development PC with a manifest 762:
However at runtime, on another release PC, the application uses the 4053 version of the file.
c:\windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_e6967989\MSVCR80.DLL
Somewhere along the execution of my application I ge... | Because of a "publisher policy" that redirects requested DLL versions. Your manifest should not ask for 762 anymore, it's got cooties. You'll need to deploy the security update to your machine so the vc\include\crtassem.h gets updated.
|
2,685,977 | 2,685,999 | Memory randomization as application security enhancement? | I recently came upon a Microsoft article that touted new "defensive enhancements" of Windows 7. Specifically:
Address space layout randomization (ASLR)
Heap randomization
Stack randomization
The article went on to say that "...some of these defenses are in the core operating system, and the Microsoft Visual C++ ... | It increases security by making it hard to predict where something will be in memory. Quite a few buffer overflow exploits work by putting (for example) the address of a known routine on the stack, and then returning to it. It's much harder to do that without knowing the address of the relevant routine.
As far as I kno... |
2,686,096 | 2,686,150 | C++ Get Username From Process | I have a process handle with
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, THE_PROCESS_ID);
How can I get the username of the user that is running the process?
I am using unmanaged code (no .NET).
| Use OpenProcessToken to get the token (obviously), then GetTokenInformation with the TokenOwner flag to get the SID of the owner. Then you can use LookupAccountSid to get the username.
|
2,686,146 | 2,686,171 | Simple C++ container class that is thread-safe for writing | I am writing a multi-threaded program using OpenMP in C++. At one point my program forks into many threads, each of which need to add "jobs" to some container that keeps track of all added jobs. Each job can just be a pointer to some object.
Basically, I just need the add pointers to some container from several threa... | There's no built-in way to do this. You can simply use a lock to guard one of the existing container types. It might be a better idea to have each thread use it's own container, then combine the results together in the end.
|
2,686,230 | 2,686,347 | GDI+ With C++Builder? | How do I use GDI+ with C++Builder? Can someone give me a simple example of creating a surface and drawing a circle on it?
| It would be similar to coding a normal Windows program in C using Visual Studio.
Basically:
include "gdiplus.h"
link to gdiplus.lib
call GdiPlusStartup at the start of your program (before main window creation)
call GdiPlusShutdown at the end of your program (after the message loop has ended and the main window's bee... |
2,686,400 | 2,686,412 | Can I create functions without defining them in the header file? | Can I create a function inside a class without defining it in the header file of that class?
| Why don't you try and see?
[˙ʇ,uɐɔ noʎ 'oᴎ]
Update: Just to reflect on the comments below, with the emphasis of the C++ language on smart compiling, the compiler needs to know the size of the class (thus requiring declaration of all member data) and the class interface (thus requiring all functions and types declarati... |
2,686,429 | 2,695,419 | Another design-related C++ question | Hi!
I am trying to find some optimal solutions in C++ coding patterns, and this is one of my game engine - related questions.
Take a look at the game object declaration (I removed almost everything, that has no connection with the question).
// Abstract representation of a game object
class Object :
public Entity,
... | In this particular example, I'm not sure that it's desirable to separate Resize from Render, since Resize has a direct impact on the rendered image.
The way I do it is make the Entitys contain the Renderable. E.g. an Entity would have a member variable that is the sprite to be rendered. When the entity becomes visibl... |
2,686,542 | 2,686,571 | Converting integer to a bit representation | How can I convert a integer to its bit representation. I want to take an integer and return a vector that has contains 1's and 0's of the integer's bit representation.
I'm having a heck of a time trying to do this myself so I thought I would ask to see if there was a built in library function that could help.
| Doesn't work with negatives.
vector<int> convert(int x) {
vector<int> ret;
while(x) {
if (x&1)
ret.push_back(1);
else
ret.push_back(0);
x>>=1;
}
reverse(ret.begin(),ret.end());
return ret;
}
|
2,686,548 | 2,686,618 | Sorting eigenvectors by their eigenvalues (associated sorting) | I have an unsorted vector of eigenvalues and a related matrix of eigenvectors. I'd like to sort the columns of the matrix with respect to the sorted set of eigenvalues. (e.g., if eigenvalue[3] moves to eigenvalue[2], I want column 3 of the eigenvector matrix to move over to column 2.)
I know I can sort the eigenvalues ... | Typically just create a structure something like this:
struct eigen {
int value;
double *vector;
bool operator<(eigen const &other) const {
return value < other.value;
}
};
Alternatively, just put the eigenvalue/eigenvector into an std::pair -- though I'd prefer eigen.value and eigen.vector ... |
2,686,601 | 2,686,642 | operator << : std::cout << i << (i << 1); | I use the stream operator << and the bit shifting operator << in one line.
I am a bit confused, why does code A) not produce the same output than code B)?
A)
int i = 4;
std::cout << i << " " << (i << 1) << std::endl; //4 8
B)
myint m = 4;
std::cout << m << " " << (m << 1) << std::endl; //8 8
class myint:
cl... | Your second example is undefined behavior.
You have defined the << operator on your myint class as if it were actually <<=. When you execute i << 1, the value in i is not modified, but when you execute m << 1, the value in m is modified.
In C++, it is undefined behavior to both read and write (or write more than once) ... |
2,687,017 | 2,709,950 | Boost Shared Pointer: Simultaneous Read Access Across Multiple Threads | I have a thread A which allocates memory and assigns it to a shared pointer. Then this thread spawns 3 other threads X, Y and Z and passes a copy of the shared pointer to each. When X, Y and Z go out of scope, the memory is freed. But is there a possibility that 2 threads X, Y go out of scope at the exact same point in... | Several others have already provided links to the documentation explaining that this is safe.
For absolutely irrefutable proof, see how Boost Smartptr actually implements its own mutexes from scratch in boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp (or your platform's corresponding file).
|
2,687,208 | 2,687,236 | looser throw specifier for in C++ | I am getting an error that says:
error: looser throw specifier for 'virtual CPLAT::CP_Window::~CP_Window()'
On the destructor, I have never heard of this before and some Google Searches say this might be a GCC 4 problem, which I would not be sure how to work around since I need GCC 4 to build a Universal Binary.
My Env... | I assume that CPLAT has a base class? I'm also guessing that you did not put a throw specifier on CPLAT's destructor?
You can put throw(X) (where X is a comma-separated list of exceptions) at the end of a function's signature to indicate what exceptions it's allowed to throw. If you put throw() as the throw specifier, ... |
2,687,284 | 2,687,336 | Why won't this compile and how can it be implemented so that it does? | Here is some C++ code I'm playing around with:
#include <iostream>
#include <vector>
#define IN ,
#define FOREACH(x,y) for(unsigned int i=0;i<y.size();i++) { x=y[i];
#define ENDFOREACH }
using namespace std;
int main()
{
vector<int> ints;
ints.push_back(3);
ints.push_back(4);
ints.push_back(5);
i... | Others have already explained why it doesn't compile as is.
In order to make it work you have to give that IN a chance to turn into a comma. For that you can introduce an extra level of "indirection" in your macro definition
#define IN ,
#define FOREACH_(x,y) for(unsigned int i=0;i<y.size();i++) { x=y[i];
#define FOR... |
2,687,304 | 2,687,319 | CP_EXPORT in class declaration in C++ | What does it mean when a class is declared like this:
class CP_EXPORT CP_Window : public CP_Window_Imp
What does the CP_EXPORT portion mean/imply?
| CP_EXPORT is most probably a macro to conditionally export or import the class from a dynamic library.
For example, when using Visual C++, a macro is used to conditionally select between using dllexport and dllimport. This allows the same header to be used for both the project building the DLL itself and any projects ... |
2,687,342 | 2,687,964 | How can I get this code involving unique_ptr to compile? | #include <vector>
#include <memory>
using namespace std;
class A {
public:
A(): i(new int) {}
A(A const& a) = delete;
A(A &&a): i(move(a.i)) {}
unique_ptr<int> i;
};
class AGroup {
public:
void AddA(A &&a) { a_.emplace_back(move(a)); }
vector<A> a_;
};
int main() {
A... | Probably your standard library doesn't (yet) define unique_ptr<T>::unique_ptr(unique_ptr &&). I checked my headers in 4.5 and it's there, so maybe try upgrading.
When it fails to find the move constructor, it would look for the copy constructor and find it deleted.
I get other errors when I compile that, though.
EDIT: ... |
2,687,392 | 18,514,815 | Is it possible to declare two variables of different types in a for loop? | Is it possible to declare two variables of different types in the initialization body of a for loop in C++?
For example:
for(int i=0,j=0 ...
defines two integers. Can I define an int and a char in the initialization body? How would this be done?
| C++17: Yes! You should use a structured binding declaration. The syntax has been supported in gcc and clang since gcc-7 and clang-4.0 (clang live example). This allows us to unpack a tuple like so:
for (auto [i, f, s] = std::tuple{1, 1.0, std::string{"ab"}}; i < N; ++i, f += 1.5) {
// ...
}
The above will give yo... |
2,687,420 | 2,687,615 | Doxygen ignoring inherited functions, when class inherits privately but the functions declared public again | Sorry for long winded title, this makes a lot more sense with an example.
Suppose we have a class A:
class A {
public:
void someFunction();
void someOtherFunction();
};
And another class that privately inherits from A. However, we re-declare one of the inherited functions as public:
class B : priva... | I can't comment so I'll post this as an answer.
When you do private inheritance in C++, it's a variant of composition or agregation. It's like a "Car - has an - Engine" relationship, so maybe Doxygen has a problem with this syntactic way of doing things. You could probably turn this around a bit to get a good public in... |
2,687,448 | 2,687,548 | GDB doesnt like my typedef | It seems that the following is to deep for the debugger in Qt even though the program uses it without problem
typedef QMap <int, QStringList> day2FileNameType;
typedef QMap <int, day2FileNameType> month2day2FileNameType;
typedef QMap <int, month2day2FileNameType> year2month2day2FileNameType;
year2month2day2FileNameTyp... | I don't even use QT (although I do use gdb), but if you google 'gdb typdef', you get A LOT of hits like this one:
http://qtcreator.blogspot.com/2009/07/gdb-typedef-bug-update.html
So if what you say is true, that the program, unchanged, runs when you use the same structure minus the typdefs, I would assume that this is... |
2,687,475 | 2,687,498 | Potential problems porting to different architectures | I'm writing a Linux program that currently compiles and works fine on x86 and x86_64, and now I'm wondering if there's anything special I'll need to do to make it work on other architectures.
What I've heard is that for cross platform code I should:
Don't assume anything about the size of a pointer, int or size_t
Don'... | In my experience, once code works well on a couple architectures, it will port more easily to a third one. Input shouldn't be an issue. Structure alignment may be an issue if you do anything where alignment is an issue.
Pay attention to anything that might be platform-dependent: relying on bitfields being aligned the... |
2,687,537 | 2,688,435 | JSON_Spirit: mapping value.type() back to the type? | You can display a Value's type like this:
cout << val.type() << end;
and it print a number.
How can I map this number back to the actual type?
besides peeking in the header file, of course, which reveals all...
enum Value_type {
obj_type,array_type,str_type,bool_type,int_type,real_type,null_type
};
| Nope, that seems to be the canonical way:
switch(v.type()) {
case obj_type: pp_obj(v, lev+1); break;
case array_type: pp_array(v, lev+1); break;
case str_type: pp<string>(v, lev+1); break;
case bool_type: pp<bool>(v, lev+1); break;
case int_type: pp<int>(v, l... |
2,687,544 | 2,687,564 | Question about C++ inner class | HI,
In C++ inner class,
class A {
public:
void f1();
private:
void f2();
class B {
private void f3();
};
}
Does an inner class (B) has a pointer to its parent class (A)? (like it does in Java).
And can B calls its parent class public/private method (like it does in Java).
T... | No -- in C++, nesting classes only affects names and visibility, not the semantics of the class itself. As far as generated code goes, the nested class is no different from one that isn't nested.
All that's changed is the visibility and the name (e.g. if it's in a private: section of the outer class, it's not visible t... |
2,687,638 | 2,687,663 | Change character automatically whilst being input in c++? | I'm having trouble working this out. Basically my program has a standard input, I want to modify this so if the user enters a space it automatically replaces it with a / whilst they're typing. I have no idea how i'd even go about doing this or if it is even possible so I am grateful for any help either way.
| You would need to turn off echoing of the characters typed and then echo them yourself after validating them, replacing characters as necessary. There are different ways to do that for different operating systems (e.g. Linux vs. Windows), and even more unfortunately, that can mean taking control of the entire screen j... |
2,687,701 | 2,687,722 | How should I initialize a boost::array? | I am trying to understand the boost array. The code can be read easily from author's site.
In the design rationale, author (Nicolai M. Josuttis) mentioned that the following two types of initialization is possible.
boost::array<int,4> a = { { 1, 2, 3 } }; // Line 1
boost::array<int,4> a = { 1, 2, 3 }; // Line 2
... | this is a regular brace initialization list:
Boost array is defined like this:
struct array { T elems[N]; };
inner brace is for elems array initialization, outear brace is for struct initialization.
If you provide your own constructor, you no longer have plain old datatype any cannot initialize using brace
notice that... |
2,687,790 | 2,687,845 | How to accomplish covariant return types when returning a shared_ptr? | using namespace boost;
class A {};
class B : public A {};
class X {
virtual shared_ptr<A> foo();
};
class Y : public X {
virtual shared_ptr<B> foo();
};
The return types aren't covariant (nor are they, therefore, legal), but they would be if I was using raw pointers instead. What's the commonly accepted idiom ... | I think that a solution is fundamentally impossible because covariance depends on pointer arithmetic which is incompatible with smart pointers.
When Y::foo returns shared_ptr<B> to a dynamic caller, it must be cast to shared_ptr<A> before use. In your case, a B* can (probably) simply be reinterpreted as an A*, but for ... |
2,687,849 | 2,687,936 | How to prevent anyone from stealing my shared_ptr? | So, I use boost::shared_ptr for all the various reference-counting benefits it provides -- reference counting for starters, obviously, but also the ability to copy, assign, and therefore store in STL Containers.
The problem is, if I pass it to just one "malicious" function or object, the object can save the ptr and the... | It's good enough to use weak_ptr for guest objects, as you described in question. Otherwise you will have a problem with dead pointers.
I would consider to do application rearchitect to remove "malicious" functions/objects or at least fix their behavior.
|
2,687,867 | 2,687,917 | Win32 API prevent standby | What is the Win32 api function that prevents the system from going into standby?
Some programs use it, which is pretty annoying in my opinion.
I know there's a couple of WM_SYSCOMMAND messages you can trap to prevent the screensaver from coming on..
| SetThreadExecutionState. There's no Get and it doesn't take a thread handle. Done.
|
2,687,967 | 2,688,010 | ISO C++ forbids declaration of 'Stack" with no type | I have setup the following header file to create a Stack which uses an Array. I get the following at line 7:
error: ISO C++ forbids declaration of 'Stack" with no type.
I thought the type was the input value. Appreciate your help. Thank you.
#ifndef ARRAYSTACKER_H_INCLUDED
#define ARRAYSTACKER_H_INCLUDED
// Ar... | The error: ISO C++ forbids declaration of "identifier" with no type. error indicates that the declared type of identifier or identifier, itself, is a type for which the declaration has not been found.
For example, if you wrote the following in your code:
ArrayStack Stack;
The line above would give you such an error ... |
2,687,991 | 2,704,631 | Type problem when including tuple | I'm using Visual Studio 2008 with Feature Pack 1.
I have a typedef like this typedef std::tr1::tuple<std::string, std::string, int> tileInfo
with a function like this const tileInfo& GetTile( int x, int y ) const.
In the implementation file the function has the exact same signature (with the added class name qualifier... | It seems that when using the typedef as a return type or a local variable, even within the class, I had to qualify it with the class name as well. For example the GetTile signature in the header should have been TileMap::tileInfo& GetTile( int x, int y ); I thought that you didn't need to do this when the function is i... |
2,688,043 | 2,688,095 | Call/Return feature of classic C++(C with Classes), what modern languages have it? | On page 57 of The Design and Evolution of C++, Dr. Stroustrup talks about a feature that was initially part of C with Classes, but it isn't part of modern C++(standard C++). The feature is called call/return. This is an example:
class myclass
{
call() { /* do something before each call to a function. */ }
return() ... | The modern C++ equivalent would be a sentry object: construct it at the beginning of a function, with its constructor implementing call(), and upon return (or abnormal exit), its destructor implements return().
|
2,688,096 | 2,688,190 | How to Set ActiveX Control name and link on the install window of Internet Explorer? | I created a ActiveX control using ATL, already package it with signature.
I want to use it on the webpage, but at the install window the name is MyActiveX.cab with no link. the MyActiveX.cab name can be changed by modifying the html page's tag codebase attribute. but the name is still format like "XXX.cab" with no hyp... | Did you sign both control and CAB file?
It looks like you didn't sign the CAB file. The installation dialog shows info from the CAB file signature. Or maybe signature is invalid...
|
2,688,117 | 2,688,209 | C# style Action<T>, Func<T,T>, etc in C++0x | C# has generic function types such as Action<T> or Func<T,U,V,...>
With the advent of C++0x and the ability to have template typedef's and variadic template parameters, it seems this should be possible.
The obvious solution to me would be this:
template <typename T>
using Action<T> = void (*)(T);
however, this does no... | I think the syntax should be like this:
template <typename T>
using Action = void (*)(T);
I couldn't get that to compile either, though (g++ v4.3.2).
The general STL style function template is not strongly typed in the strictest sense, but it is type safe in the sense that the compiler will ensure that the template is... |
2,688,283 | 2,688,295 | User input... How to check for ENTER key | I have a section of code where the user enters input from the keyboard. I want to do something when ENTER is pressed. I am checking for '\n' but it's not working. How do you check if the user pressed the ENTER key?
if( shuffle == false ){
int i=0;
string line;
while( i<20){
cout << "Playing: ";
... | getline returns only when an Enter (or Return, it can be marked either way depending on your keyboard) is hit, so there's no need to check further for that -- do you want to check something else, maybe, such as whether the user entered something else before the Enter?
|
2,688,364 | 2,688,450 | C++ function overloading and dynamic binding compile problem |
Possible Duplicates:
C++ method only visible when object cast to base class?!
Why does an overridden function in the derived class hide other overloads of the base class?
#include <iostream>
using namespace std;
class A
{
public:
virtual void foo(void) const { cout << "A::foo(void)" << endl; }
virtual void... | The problem is, that inheritance is not carried over different namespaces. So to make it compile, you have to tell the compiler with the using directive:
class B : public A
{
public:
using A::foo;
void foo(int i) const { this->foo(); cout << i << endl; }
};
class C : public A
{
public:
using B::foo;
vo... |
2,688,491 | 2,688,552 | Efficiency of manually written loops vs operator overloads | in the program I'm working on I have 3-element arrays, which I use as mathematical vectors for all intents and purposes.
Through the course of writing my code, I was tempted to just roll my own Vector class with simple arithmetic overloads (+, -, * /) so I can simplify statements like:
// old:
for (int i = 0; i < 3; i... | If the operations are inlined and optimised well by your compiler you shouldn't usually see any difference between writing the code well (using operators to make it readable and maintainable) and manually inlining everything.
Manual inlining also considerably increases the risk of bugs because you won't be re-using a s... |
2,688,575 | 2,688,592 | C triple dereferencing |
Possible Duplicate:
Uses for multiple levels of pointer dereferences?
I have used functions with doubly dereferenced pointers (**var) to return values. However, I was recently asked a question to figure out a use-case where a triple dereferencing (***var) may be needed. I couldn't think of any practical scenario. Do... | Three dimensional arrays.
|
2,688,642 | 2,689,113 | How to write a simple Lexer/Parser with antlr 2.7? | I have a complex grammar (in antlr 2.7) which I need to extend. Having never used antlr before, I wanted to write a very simple Lexer and Parser first.
I found a very good explanation for antlr3 and tried to adapt it:
header{
#include <iostream>
using namespace std;
}
options {
language="Cpp";
}
class P... | look at these examples, there are some C examples which should help you on the way.
BTW the error message comes from that you are compiling with precompiled headers so it wants the stdafx.h include at the start of your .cpp file, you can add this in the grammar in the header{ } section.
|
2,688,713 | 2,688,727 | Copy constructor demo (crashing...) | Here is the program...
class CopyCon
{
public:
char *name;
CopyCon()
{
name = new char;
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char;
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete name;
name = NULL;
}
}
};
int main()
{
CopyCon objCo... | The problem is you are allocating only one char in the copy constructor.
In main you are assigning a 4-byte string (remember the null), but when you copy the object, you only allocate enough room for 1 byte.
What you probably want to do is change
name = new char;
to
name = new char[tcslen(objCopyCon.name) + 1];
And i... |
2,688,801 | 2,688,957 | Better name for CHAR_BIT? | I was just checking an answer and realized that CHAR_BIT isn't defined by headers as I'd expect, not even by #include <bitset>, on newer GCC.
Do I really have to #include <climits> just to get the "functionality" of CHAR_BIT?
| As you may know, whether or not an implementation wants to include other headers is unspecified. It's allowed, but not mandated. (§17.4.4.1) So you either have to be explicit or know your guarantees.
The only time a C++ header must include another is if it requires a definition in another. For example, <bitset> is requ... |
2,689,204 | 2,689,274 | C++ File I/O problem | I am trying to open a file which normally has content, for the purpose of testing i will like to initialize the program without the files being available/existing so then the program should create empty ones, but am having issues implementing it. This is my code originally
void loadFiles() {
fstream city;
city.open... | You have posted code for reading files, not creating empty ones - you need t expand your question in this regard. And what you have posted is not good code for reading. The eof() function detects end of file following a read, not before one - basically, you should almost never use it. Instead, you should test the succe... |
2,689,351 | 2,689,897 | Porting Symbian C++ to Android NDK | I've been given some Symbian C++ code to port over for use with the Android NDK.
The code has lots of Symbian specific code in it and I have very little experience of C++ so its not going very well.
The main thing that is slowing me down is trying to figure out the alternatives to use in normal C++ for the Symbian spec... | It would typically be a bad idea to try and port Symbian OS C++ to standard C++ without having a very good understanding of what the Symbian idioms do.
This could very well be one of these projects where the right thing to do is to rewrite most of the code pretty much from scratch. If you barely know the language you a... |
2,689,380 | 2,689,388 | Typedef C++, couldn't resolve its meaning | I read this typedef line in a C++ book, but I couldn't resolve its meaning:
typedef Shape* (*CreateShapeCallBack)();
Now, CreateShapeCallBack stands for what, any idea?
Thanks.
| It's the type of a pointer to a function that returns a pointer to a Shape and takes no parameters. You could use it like this:
Shape * Func() {
// do stuff - return Shape pointer
}
...
CreateShapeCallBack p = Func;
|
2,689,590 | 2,689,742 | Creating ostream manipulators for a specific class | I have a class that is derived from ostream:
class my_ostream: public std::ostream
{
// ...
}
I want to make a manipulator (for example do_something), that works specifically to this class, like this:
my_ostream s;
s << "some text" << do_something << "some more text";
I did the following:
std::ostream &do_somethi... | You need to add support for manipulators in your class:
#include<iostream>
class my_ostream : public std::ostream
{
public:
std::string prefix;
my_ostream():prefix("*"){}
// manipulator support here:
my_ostream& operator<<( my_ostream&(*f)(my_ostream&)){
f(*this);
return *this;
... |
2,689,642 | 2,689,668 | Why can I derived from a templated/generic class based on that type in C# / C++ | Title probably doesn't make a lot of sense, so I'll start with some code:
class Foo : public std::vector<Foo>
{
};
...
Foo f;
f.push_back( Foo() );
Why is this allowed by the compiler? My brain is melting at this stage, so can anyone explain whether there are any reasons you would want to do this? Unfortunately I'v... |
can anyone explain whether there are any reasons you would want to do this?
Curiously recurring template pattern.
|
2,689,709 | 2,689,761 | Difference between std::result_of and decltype | I have some trouble understanding the need for std::result_of in C++0x. If I understood correctly, result_of is used to obtain the resulting type of invoking a function object with certain types of parameters. For example:
template <typename F, typename Arg>
typename std::result_of<F(Arg)>::type
invoke(F f, Arg a)
{
... | result_of was introduced in Boost, and then included in TR1, and finally in C++0x. Therefore result_of has an advantage that is backward-compatible (with a suitable library).
decltype is an entirely new thing in C++0x, does not restrict only to return type of a function, and is a language feature.
Anyway, on gcc 4.5, ... |
2,689,860 | 2,689,875 | Why cant we create Object if constructor is in private section? | I want to know why cant we create object if the constructor is in private section. I know that if i make a method static i can call that method using
<classname> :: <methodname(...)>;
But why can't we create object is what I don't understand.
I also know if my method is not static then also I can call f... | Because it is not accessible to the program, that's what private means. If you declared a member function or variable private, you would not be able to access them either. Creating private constructors is actually a useful technique in C++, as it allows you to say that only specific classes can create instances of the ... |
2,689,963 | 2,690,246 | Container for database-like searches | I'm looking for some STL, boost, or similar container to use the same way indexes are used in databases to search for record using a query like this:
select * from table1 where field1 starting with 'X';
or
select * from table1 where field1 like 'X%';
I thought about using std::map, but I cannot because I need to sear... | Boost.Multi-Index allows you to manage with several index and it implements the lower_bound as for std::set/map. You will need to select the index corresponding to the field and then do as if it was a map or a set.
Next follows a generic function that could be used to get a couple of iterators, the fist to the first it... |
2,690,235 | 2,690,256 | c++ templates and inheritance | I'm experiencing some problems with breaking my code to reusable parts using templates and inheritance. I'd like to achieve that my tree class and avltree class use the same node class and that avltree class inherits some methods from the tree class and adds some specific ones. So I came up with the code below. Compile... | Both tree.h and node.h try to include each other, the include guards will prevent one of them from seeing the other.
Instead of #include "tree.h" try forward declaring tree like:
template <class T>
class tree;
in node.h
EDIT: As sbi suggested in a comment, it makes more sense to forward declare tree in node.h than the... |
2,690,245 | 2,690,585 | Proper use of "atomic directive" to lock STL container | I have a large number of sets of integers, which I have, in turn, put into a vector of pointers. I need to be able to update these sets of integers in parallel without causing a race condition. More specifically. I am using OpenMP's "parallel for" construct.
For dealing with shared resources, OpenMP offers a handy "at... | After searching around, I found the OpenMP C and C++ API manual on openmp.org, and in section 2.6.4, the limitations of the atomic construct are described.
Basically, the atomic directive can only be used with the following operators:
Unary:
++, -- (prefix and postfix)
Binary:
+,-,*,/,^,&,|,<<,>>
So I will just use loc... |
2,690,328 | 2,692,689 | Qt quncompress gzip data | I stumble upon a problem, and can't find a solution.
So what I want to do is uncompress data in qt, using qUncompress(QByteArray), send from www in gzip format. I used wireshark to determine that this is valid gzip stream, also tested with zip/rar and both can uncompress it.
Code so far, is like this:
static const... | You also forgot dataPlusSize.append(data);. However, that won't solve your problem. The problem is that while gzip and zlib have the same compressed data format, their headers and trailers are different. See: http://www.zlib.net/zlib_faq.html#faq18
qUncompress uses the zlib uncompress, so it can only handle the zlib... |
2,690,380 | 2,690,395 | Stack allocation fails and heap allocation succeeds!! Is it possible? | I have the following piece of snippet
Class Sample
{ Obj_Class1 o1;
Obj_Class2 o2;};
But the size of Obj_Class1 and Obj_Class2 is huge so that the compiler shows a warning "Consider moving some space to heap". I was asked to replace Obj_Class1 o1 with Obj_Class1* o1 = new Obj_Class1(); But I feel that there is no us... | It is very typical that the stack is smaller than the heap. They use different memory locations. The stack is typically about a megabyte in size (you can change it, but be careful) and is allocated per thread. The heap can consume gigabytes if needed.
|
2,690,435 | 2,690,453 | OBject access from different functions in VC++ | I have 3 function in my class B. These three function have to access member function of other class A.
I did this by creating object of class A in class B constructor and tried to access that object in functions of class B. But its showing error.
How can i assess the same object in these three functions. Where i have t... | You need to make a a member variable of class B like this:
class B
{
private:
A a;
// ...
}
That will make it available to all the member functions of B.
(Making it private isn't necessary - the decision to make it private, protected or public depends on whether you want to make it available only within B, within... |
2,690,473 | 2,690,501 | How do virtual destructors work? | I am using gcc. I am aware how the virtual destructors solve the problem when we destroy a derived class object pointed by a base class pointer. I want to know how do they work?
class A
{
public:
A(){cout<<"A constructor"<<endl;}
~A(){cout<<"A destructor"<<endl;}
};
class B:public A
{
public:
... | The key thing you need to know is that not using a virtual destructor in the above code is undefined behavior and that's not what you want. Virtual destructors are like any other virtual functions - when you call delete the program will decide what destructor to call right in runtime and that solves your problem.
|
2,690,601 | 2,692,208 | C++ wrapper for C library | Recently I found a C library that I want to use in my C++ project.
This code is configured with global variables and writes it's output to memory pointed by static pointers.
When I execute my project I would like 2 instances of the C program to run: one with configuration A and one with configuration B. I can't afford ... | C++ -Wrapper
You get away easier by pasting "the entire library" - only slightly modfied - into a class.
// C
static char resultBuffer[42];
void ToResult(int x) { ... }
char const * GetResult() { return resultBuffer; }
becomes
// C++
class CMyImportantCLib
{
private:
char resultBuffer[42];
void ToResult(int ... |
2,690,773 | 2,691,308 | Is it safe to spin on a volatile variable in user-mode threads? | I'm not quite sure if it's safe to spin on a volatile variable in user-mode threads, to implement a light-weight spin_lock, I looked at the tbb source code, tbb_machine.h:170,
//! Spin WHILE the value of the variable is equal to a given value
/** T and U should be comparable types. */
template<typename T, typename U>
... | Tricky. I'd say that in theory, this code isn't safe. If there are no memory barriers then the data accesses you're guarding could be moved across the spinlock. However, this would only be done if the compiler inlined very aggressively, and could see a purpose in this reordering.
Perhaps Intel simply determined that t... |
2,690,851 | 2,691,220 | What is "sentry object" in C++? | I answered this question, and Potatoswatter answered too as
The modern C++ equivalent would be a
sentry object: construct it at the
beginning of a function, with its
constructor implementing call(), and
upon return (or abnormal exit), its
destructor implements
I am not familiar with using sentry objects in... | Sentry object is a pattern, but I'm not sure which one of those below (maybe all).
C++ programs often heavily rely on knowledge when exactly an object (possibly of a user-defined class) is destroyed, i.e. when its destructor is called. This is not the case for languages with garbage collection.
This technique is used,... |
2,691,591 | 2,691,978 | HRESULT exception not caught in VS 2008 | I've got a stange situation in visual studio 2008 C++. I work on code that was originally written for visual studio 2003, where everything works well. Now, ported to VS 2008, the exception handling, which unfortuantely exists widely in the code, does not work anymore. standard code example:
try
{
HRESULT hr = ... | After starting the debugger, go to Debug / Exceptions, and select for which exceptions the debugger should stop when the exception is thrown.
|
2,691,611 | 2,691,657 | Destructors for C++ Interface-like classes | Starting to use PC-Lint on an existing code base (fear and trepidation).
One thing that it complains about is the following:
class IBatch
{
public:
virtual void StartBatch() =0;
virtual int CommitBatch() =0;
};
Which when another class derives from this to use it like an interface
base class 'IBatch' has ... |
A base class destructor should be either public and virtual, or protected and nonvirtual.
(Herb Sutter, Guru of the Week #18: "Virtuality")
|
2,691,650 | 2,691,725 | Getting Logical address of my system using C++ & Linux | Please suggest how to get the IP address of my system (logical address) using C++ and Linux.
| "Logical Address" is not meaningful. You either want an interface address (the IP that hosts on the same local network as the machine see), or you want the publicly-facing Internet address (the IP address hosts will see when this machine connects to them). The IP addresses will only be the same if the machine is direct... |
2,691,680 | 2,783,305 | Why does Visual Studio 2010 throw this error with Boost 1.42.0? | I'm trying to recompile application, that compiles fine with warning level 4 in visual studio 2005 and visual studio 2008.
Since the errors (look below) are coming from std:tr1, I'm thinking there's some conflict, but not sure how to fix. My first thought was to remove all references to boost, such as but then I get a... | the problem is with visual studio 2010, or I should say that with additional templates that were added to visual studio 2010 tr1, so, std::make_pair, doesn't always work. changed to pair<> and all errors magically went away.
so, if you have template problems in VC2010 and using std:make_pair, change it to pair<> and sp... |
2,692,065 | 2,692,105 | what does "throw;" outside a catch block do? | I just stumbled this code:
void somefunction()
{
throw;
}
and I wonder: what does it mean?
| The intent is probably that somefunction() is only ever called from inside some catch block. In that case, there would be an exception active when the throw; is executed, in which case the current exception is re-thrown, to be caught by the next outer handler that can handle that exception type.
If throw; is executed w... |
2,692,074 | 2,692,116 | Constructor initialising an array of subobjects? | Say I have several objects within a class, each of which needs constructing with a different value. I can write something like this:
class b
{
public:
b(int num)
{
// 1 for a.b1, and 2 for a.b2
}
};
class a
{
public:
b b1;
b b2;
a() : b1(1), b2(2)
{
}
};
However, is it possible to do the ... | You cannot do this directly; you need to initialize the array elements in the body of the constructor.
The elements of the array are default constructed before the body of the constructor is entered. Since your example class b is not default constructible (i.e., it has no constructor that can be called with zero par... |
2,692,139 | 2,692,523 | How do I get rid of these warnings? | This is really several questions, but anyway...
I'm working with a big project in XCode, relatively recently ported from MetroWorks (Yes, really) and there's a bunch of warnings that I want to get rid of. Every so often an IMPORTANT warning comes up, but I never look at them because there's too many garbage ones. So, i... | Items in <map.h> are in the global namespace while items in <map> are in the std namespace. Most likely you were just referring directly to the global versions and when you switched to <map> you were no longer seeing them because they moved to std::. In source files add a using namespace std to move on quickly. In head... |
2,692,383 | 2,692,431 | Convert struct into bytes | How would you convert any struct into byte array on processors with little-endian?
| You can use a char* to access any type of object in C++, so:
struct S
{
int a;
int b;
// etc.
};
S my_s;
char* my_s_bytes = reinterpret_cast<char*>(&my_s);
// or, if you prefer static_cast:
char* my_s_bytes = static_cast<char*>(static_cast<void*>(&my_s));
(There is at least some debate over the correctn... |
2,692,548 | 2,692,683 | Beginner C++ Question | I have followed the code example here
toupper c++ example
And implemented it in my own code as follows
void CharString::MakeUpper()
{
char* str[strlen(m_pString)];
int i=0;
str[strlen(m_pString)]=m_pString;
char* c;
while (str[i])
{
c=str[i];
putchar (toupper(c));
i++;
}
}
But this gives me the follo... | I'm going to go with the assumption that m_pString is a C style string (char *). You're doing way more fiddling than you need to be doing.
void CharString::MakeUpper()
{
char* str = m_pString; // Since you're not modifying the string, there's no need to make a local copy, just get a pointer to the existing string.
... |
2,692,609 | 2,692,630 | C++ Macro is not replacing all values | I have the following 2 macros:
#define SCOPED_ENUM_HEADER(NAME) struct NAME{ enum _NAME{
#define SCOPED_ENUM_FOOTER(NAME) };}; typedef NAME::_NAME NAMEtype;
Only the first instance of NAME get replaced by the passed NAME. What's wrong with it?
Is is to be used in such a way:
SCOPED_ENUM_HEADER(LOGLEVEL)
UNSET,
... | The problem is that NAME is not the same as _NAME; they are two totally separate identifiers.
If you want to add an underscore to the front of whatever the parameter NAME is, use the concatenation (##) operator:
_##NAME
You do need to be really careful with prepending an underscore, though. All identifiers beginning... |
2,692,728 | 2,692,756 | How to randomize a sorted list? | Here's a strange question for you guys,
I have a nice sorted list that I wish to randomize. How would i go about doing that?
In my application, i have a function that returns a list of points that describe the outline of a discretized object. Due to the way the problem is solved, the function returns a nice ordered lis... | Use std::random_shuffle. If you want to implement the method yourself you should look at the Fisher-Yates shuffle.
|
2,692,736 | 2,692,962 | D operators that are not in C++ | Are there any operators in D that are not in C++?
| Here is a list of some D tokens
/=
.
..
...
&
&=
&&
|
|=
||
-
-=
--
+
+=
++
<
<=
<<
<<=
<>
<>=
>
>=
>>=
>>>=
>>
>>>
!
!=
!<>
!<>=
!<
!<=
!>
!>=
(
)
[
]
{
}
?
,
;
:
$
=
==
*
*=
%
%=
^
^=
~
~=
Those for example:
<>
<>=
!<>
!<>=
!<
!<=
!>
!>=
are special operators to compare floating point variables. You can find the de... |
2,692,768 | 2,692,785 | How can I implement a fast map having multiple keys? | I'm looking for a C++ associative map container type which I can perform multiple key lookups on. The map needs to have constant time lookups, but I don't care if it's ordered or unordered. It just needs to be fast.
For example, I want to store a bunch of std::vector objects in a map with an int and a void* as the look... | Constant look up requires a hash map. You can use a the boost::unordered_map (or tr1). The key would be the combined hash of the int and the void pointer.
|
2,692,889 | 2,692,923 | Template debugging in C++ | I have a template class that is:
template <class identifier,class registeredObject>
class FxPairRegistry : public FxRegistry<pair<identifier,registeredObject> >
{
public:
registeredObject GetEntry(identifier, FxBool assertValue = true);
void RegisterInOrder(const pair<identifier,registeredObject> &ob);
typedef ... | It seems that here, you are typedef'ing a type called iter:
typedef typename std::vector<pair<identifier,registeredObject> >::iterator iter;
And then here:
iterator iter = mRegistryList.begin()
You are trying to define a variable called iter of type iterator, which (from the code you've shown) is not the name of any ... |
2,693,079 | 2,693,107 | Strange behavior of std::cout &operator<< | I came across something weird today, and I was wondering if any of you here could explain what's happening...
Here's a sample:
#include <iostream>
#include <cassert>
using namespace std;
#define REQUIRE_STRING(s) assert(s != 0)
#define REQUIRE_STRING_LEN(s, n) assert(s != 0 || n == 0)
class String {
publ... | This is all because of your code
cout << s.toLower().toString() << endl << s.toUpper().toString() << endl;
and how toLower and toUpper are implemented. Following code should work as expected
cout << s.toLower().toString() << endl;
cout << s.toUpper().toString() << endl;
The issue is that toLower and toUpper don't cre... |
2,693,147 | 2,693,369 | What's the difference between CArray<int, int> and CArray<int, int&>? | Same for CMap, CList, and pretty much everything that uses templates (I guess).
I find it a bit hard to understand when to use which. It's true that for classes and such, the <class, class&> form is usually what you want, but for basic types like int, float, etc., which form is preferred?
| I would say that if you don't really need something else, just use CArray<Type> and ARG_TYPE would be its default const TYPE&. Actually using Type& as ARG_TYPE is not a good idea. This theoretically allows CArray to modify the object/value you passed to the corresponding method. Of course CArray doesn't do anything lik... |
2,693,182 | 2,693,200 | DWORD to bytes using bitwise shift operators | I can't get it to work correctly.
#include <windows.h>
int main()
{
DWORD i = 6521;
BYTE first = i >> 32;
BYTE second = i >> 24;
BYTE third = i >> 16;
BYTE fourth = i >> 8;
i = (((DWORD)fourth) << 24) | (((DWORD)third) << 16) | (((DWORD)second) << 8) | first;
}
| BYTE first = (i >> 24) & 0xff;
BYTE second = (i >> 16) & 0xff;
BYTE third = (i >> 8) & 0xff;
BYTE fourth = i & 0xff ;
|
2,693,199 | 2,693,450 | Do Destructors Have Names According To The Standard? | Do class destructors have names in the pedantic sense according to the Standard?
Recall that constructors explicitly do not have names:
12.1.1 :
Constructors do not have names. A
special declarator syntax using an
optional sequence of
function-specifiers (7.1.2) followed
by the constructor’s class name
follo... | First of all, the Standard is ambivalent on the use of "name", i think. First, it says (added the other forms of names below, as corrected by the C++0x draft)
A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6... |
2,693,319 | 2,695,172 | QExplicitlySharedPointer and inheritance | What is the best way to use QExplicitlySharedPointer and inherited classes. I would like when the BaseClass exits on it's own to have a my d pointer be QExplicitlySharedPointer<BaseClassPrivate> and when I have a Derived class on top of this base class I'd like to have d be a QExplicitlySharedPointer<DerivedClassPrivat... | What about this:
template< typename P = BaseClassPrivate >
class BaseClass
{
public:
void myBaseFunc() { d->myBaseFunc(); }
protected:
QExplicitlySharedDataPointer< P > d;
};
class DerivedClass : public BaseClass< DerivedClassPrivate >
{
public:
void myDerivedFunc() { d->myDerivedFunc(); }
};
|
2,693,374 | 2,698,232 | Apply algorithms considering a specific edge subset | I've got a huge graph with typed edge (i.e. edge with a type property). Say
typedef adjacency_list<vecS, vecS, vertex_prop, edge_prop> Graph;
The "type" of the edge is a member of edge_prop and has a value in {A,B,C,D},
I'd like to run the breadth first search algorithm considering only edges of type A or B.
How w... | Finally I think the boost::graph way to do this is to use boost:filtered_graph and demo for usage
"The filtered_graph class template is an adaptor that creates a filtered view of a graph. The predicate function objects determine which edges and vertices of the original graph will show up in the filtered graph."
Thus, y... |
2,693,451 | 2,694,230 | problem with QDataStream & QDataStream::operator>> ( char *& s ) | QFile msnLogFile(item->data(Qt::UserRole).toString());
QDataStream logDataStream;
if(msnLogFile.exists()){
msnLogFile.open(QIODevice::ReadOnly);
logDataStream.setDevice(&msnLogFile);
QByteArray logBlock;
logDataStream >> logBlock;
}
This code doesnt work. The QByte that resul... | Assuming msnLogFile was not previously created using a QDataStream (if it was, then ignore this answer completely), you don't want to use the >> operator.
The reason is that when QDataStream is writing strings, it prepends the length of the string to the output bytes. This allows another QDataStream to read it back in... |
2,693,558 | 2,693,823 | Prototyping Qt/C++ in Python | I want to write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++.
Is this the right approach, and what tools (bindings, binding generators, IDE) should I use?
Ideally, everything should be available in the Ubuntu repositories so I wouldn't have to w... |
I want to write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++. Is this the right approach?
That depends on your goals. Having done both, I'd recommend you stay with Python wherever possible and reasonable. Although it takes a bit of disciplin... |
2,693,589 | 2,693,624 | array, I/O file and standard deviation (c++) | double s_deviation(double data[],int cnt, double mean)
{
int i;
double sum= 0;
double sdeviation;
double x;
//x = mean(billy,a_size);
for(i=0; i<cnt; i++)
{
sum += ((data[i]) - (mean));
}
sdeviation = sqrt(sum/((double)cnt));
return sd... | I'd guess that the value of mean is large relative to your data, so that some of the ((data[i]) - (mean)) values are negative, and so overall sum ends up being negative.
Then, when you try to compute sqrt(sum/((double)cnt)), you are taking the square root of a negative number, which results in complex number, which is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.