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 |
|---|---|---|---|---|
4,953,321 | 4,953,356 | in C++, how to handle hash collision in hash map? | in C++, how to handle hash collision in hash map? and how much time will spend to search an element if a collision occurred?
And, what is a good hash function?
| There are dozens of different ways to handle collisions in hash maps depending on what system you're using. Here are a few:
If you use closed addressing, then you probably would have each item hash to a linked list of values, all of which have the same hash code, and would then traverse the list looking for the eleme... |
4,953,448 | 4,953,804 | Module oriented code & messages between | This is more of a design question that others may have had similar experience with & know of good solutions.
The general problem here is say you are building a modular framework, each module has a set of inputs and outputs (possibly structured). Is there any good definition language for the inputs & outputs (protocol ... | Sounds like you're interested in interface description language (IDL). Select from the list whatever suits your needs the best:
http://en.wikipedia.org/wiki/Interface_description_language
|
4,953,777 | 4,953,849 | Subclasses with different array implementations | Let's say I have a base class template MyBase:
template <class T>
class MyBase{
private:
T data;
public:
MyBase(T _data);
};
I want to subclass this twice (at least for now):
data should be a dynamic 2-dimensional array: T **data
data should be a fixed 2-dimensional array: T data[rows][cols]
I'm still a bit ... | Here you are trying to use inheritance for code reuse which, in my opinion, is not a good approach to design; inheritance is for freedom of implementation while composition is for code reuse.
In this case, if it were really necessary to support these different cases, I would formalize a 2d array:
template<typename T> c... |
4,953,843 | 4,953,976 | Why can't Visual Studio find my DLL? | In Visual Studio 2010, under VC++ Directories > Executable Directories, I have specified the path to glew32d.dll. However, when I run the executable, it still complains.
On the other hand, if I copy the DLL into the local folder and run the executable then, it doesn't complain.
Can someone please tell me how to fix thi... | Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.
Placing the DLL file into the same folder as the ex... |
4,953,983 | 4,954,025 | Unable to access contents of initialized struct from a vector | I have a struct:
typedef struct
{
Qt::Key qKey;
QString strFormType;
} KeyPair;
Now I initialize KeyPair instantiations so I could use it for my Automated Test App.
KeyPair gTestMenu[] =
{
{ Qt::Key_1 , "MyForm" },
{ Qt::Key_1 , "SubForm" },
{ Qt::Key_Escape, "DesktopForm" }
};
KeyPair gBrowseMe... | You've to use insert to populate the vector with your different arrays. Here is how you should do it.
//initialized with one array
std::vector<KeyPair> vMasterList(gTestMenu, gTestMenu + 3);
//adding more items
vMasterList.insert( vMasterList.end(), gBrowseMenu , gBrowseMenu + 3);
And then reimplement your pressKe... |
4,954,034 | 4,954,058 | Simple template inheritance issue C++ | template <class T>
class baseclass{
protected:
T data;
public:
baseclass(){};
void setData(T d);
};
template<class T>
void baseclass<T>::setT(T d){
data = d;
}
Shown above is my base class, one protected member variable, one setter.
template <class T>
class aclass : public baseclass<T>
{
public:
... | The reason that this doesn't work is a quirk in the way that C++ templates do name resolution. In particular, if you have a template class that inherits from another class that depends on a template type (as you're doing in this case), you cannot access the members of that base class directly without giving the compil... |
4,954,120 | 4,954,178 | What exactly is a com object, and how do I use it? | What exactly is a com object, and how do I use it?
| The essence of COM is a language-neutral way of implementing objects that can be used in environments different from the one in which they were created, even across machine boundaries. For well-authored components, COM allows reuse of objects with no knowledge of their internal implementation, as it forces component im... |
4,954,140 | 4,954,188 | How to redirect qDebug, qWarning, qCritical etc output? | I'm using a lot of qDebug() << statements for debug output. Is there any cross-platform way I can redirect that debug output to a file, without resorting to shell scripts? I'm guessing that open() and dup2() will do the job in Linux, but will it work compiled with MinGW in Windows?
And maybe there is a Qt way to do it?... | You've to install a message handler using qInstallMessageHandler function, and then, you can use QTextStream to write the debug message to a file. Here is a sample example:
#include <QtGlobal>
#include <stdio.h>
#include <stdlib.h>
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &... |
4,954,148 | 4,954,217 | Factory method pattern | What exactly is the factory method? How can it be implemented with dll?
| The basic idea with a factory is that a function returns a heap-allocated object derived from a known base class. Thus, in your situation you'd presumably have some code in your main application that calls a factory in the dll, getting back an object of unknown dynamic type and implementation, but you'll know it satis... |
4,954,176 | 4,954,288 | Java Line IO vs C++ IO? | Note that this is NOT a "better-than" discussion.
I'm a C++ programmer, and it makes me feel incredibly dumb not to know how to do very much Java file IO.
I need to store a number of different data types in a file to be read back later. These include integers and Strings of variable length.
In C++, I could just use:
/... | In Java, you use a InputStream or OutputStream
for raw binary I/O. You compose other I/O types on top of these in order to add functionality. For example, you might use a BufferedInputStream to make an arbitrary input stream become buffered. When reading or writing binary data, it is often convenient to create a DataIn... |
4,954,339 | 4,954,364 | what is __SGI_STL_PORT? | I've been looking over some code for a class and I see in one place it has this line:
#ifndef __SGI_STL_PORT
What is __SGI_STL_PORT ?
When will this be defined?
| This is a "feature test macro"; it will be defined when using the STL port implementation of the standard template library (so, for example, if you include <vector> and it was provided by the STL port version of the library, then this macro will be defined). This can be useful for taking advantage of implementation-spe... |
4,954,352 | 4,954,385 | What does CCriticalSection do? | What the diffrence between this code:
::EnterCriticalSection( &m_CriticalSection );
//...
::LeaveCriticalSection( &m_CriticalSection );
and the code:
static CCriticalSection cs;
cs.Lock();
//...
cs.UnLock();
| No difference practically. CCriticalSection is the only syntatic sugar of the former. It internally uses EnterCriticalSection and LeaveCriticalSection!
EnterCriticalSection and LeaveCriticalSection are low-level win32 APIs, while CCriticalSection is a MFC class which wraps these functionalities. It has a member data of... |
4,954,448 | 4,954,512 | try catch using RAII? | I have a class which has some methods like follows (And more):
template<class T>
Logpp& operator<<(T const& obj)
{
*p_Stream << obj ;
return *this ;
}
Logpp& operator<<(char const* zString)
{
*p_Stream << zString ;
return *this ;
}
Logpp& operator<<(std... |
Q1: Is it advisable to use exceptions like this? (In each function). I am not familiar using exceptions so I am not sure.
There's no particular problem, but no particular reason either unless you're planning to enrich the exception information, differentiate some ios_base::failure functions from others etc.. You onl... |
4,954,752 | 4,955,657 | What are any real sets of rules compilers use to decide whether to inline a function? | We have a macro for signalling errors in a common utilities library that goes like this:
#define OurMacro( condition ) \
if( condition ) { \
} else { \
CallExternalFunctionThatWillThrowAnException( parametersListHere ); \
} \
What I refer to as parametersListHere is a comma-separated list of consta... | GCC has a fairly large set of options that expose how their process works, documented here. It's of course not exact, given that it will be tweaked over time and it's CPU-dependent.
The first rule is "their body is smaller than expected function call code".
A second rule is "static functions called once".
There are al... |
4,954,758 | 4,955,083 | QTreeView switch tab positions | I have a qt object QTreeView and I want to switch tab positions.
Basicly i have a filled TreeView. And the function
columnViewportPosition ( int column )
returns 0 for the first column and let's say 50 for the second. I want to switch them so that the are displayed in a different order, so that columnViewportPosit... | Found it out by myself. Its actually really easy.
If we just call the header() function to get the QHeaderView, it has all the necessary functions.
For example the function swapSections called with swapSections(1, 0) will swap the first and second column.
|
4,954,865 | 4,955,030 | Any reason to prefer static_cast over a chain of implicit conversions? | Suppose I have a class implementing several interfaces
class CMyClass : public IInterface1, public IInterface2 { };
and in a member function of that class I need to obtain a void* pointer to one of those interfaces (typical situation in IUnknown::QueryInterface().
The typical solution is to use a static_cast to achie... | You could use this template:
template<class T, class U> T* up_cast(U* p) { return p; }
usage:
struct B {};
struct C : B {};
int main()
{
C c;
void* b = up_cast<B>(&c);
}
Note that the '*' is implicit. If you prefer up_cast<B*>, adjust the template accordingly.
|
4,955,104 | 4,955,132 | Why I can't do this (error C2275: 'A' : illegal use of this type as an expression) | Why I can't do this?
compiler says
warning C4832: token '.' is illegal
after UDT 'A : see declaration of 'A'
error C2275: 'A' : illegal use of this
type as an expression : see
declaration of 'A'
class A{
public:
std::string getString(){return "olalal";}
};
class B{
public:
std::string getStringFromA... | You can only call non-static member functions on an object.
E.g.
std::string B::getStringFromA()
{
A object_of_type_A;
return object_of_type_A.getString();
}
Alternatively, you can create a unnamed temporary A and call getString() on that, E.g.
class B {
public:
std::string getStringFromA() { return A().ge... |
4,955,134 | 4,955,577 | How to make sure a chained logging statement is atomic? | I have a logging class which has operator<< overloaded. So I can do things like this:
oLogger << "Log this" << " and this" << " and " << 10 << endl;
oLogger`<< "Something else" << endl;
The logger does this without any problems. But, I want the logger object to be shared among threads. Then, I don't want it printing o... | Slight alternative to Nim's answer:
Create
class LockedLog {
static MutEx mutex; // global mutex for logging
ScopedLock lock; // some scoped locker to hold the mutex
Logger &oLogger; // reference to the log writer itself
public:
LockedLog(Logger &oLogger) : oLogger(oLogger), lock(mutex) {}
template ... |
4,955,249 | 4,955,425 | Something unexpected happened | I'm trying to play with handling unexpected exceptions, but cannot make it to work. This is example from: C++ Reference
// set_unexpected example
#include <iostream>
#include <exception>
using namespace std;
void myunexpected () {
cerr << "unexpected called\n";
throw 0; // throws int (in exception-specificatio... | Documentation of unexpected says:
The C++ Standard requires that unexpected is called when a function throws an exception that is not on its throw list. The current implementation does not support this.
So the answer is that VC10 is a non-compliant compiler.
|
4,955,399 | 4,955,675 | Visual Studio 2010 C++: Get size of memory block allocated by malloc | How can I get, given a pointer to a block of memory allocated with malloc, the size of it?
For example:
void* ptr = malloc( 10 ); //Allocate 10 bytes
printf( "%d", GetMemSize( ptr ) ); //Should print 10
I want to do this for debugging purposes.
| In Visual C++ you can use _msize() for that.
|
4,955,575 | 4,955,764 | Obtaining %appdata% from windows service [C++] | As in the topic - is there any way to get currently logged user appdata environment variable?
In an application there is no problem to do that with SHGetFolderPath() or simply getenv("appdata") but in service these methods doesn't work. It runs as "SYSTEM" account.
I think that should be a way to obtain %appdata% usin... | From a service viewpoint, there's no such thing as "the" currently logged-on user. There might be zero, one or more. Furthermore, it generally indicates a design error if your service needs it. What is the real problem you're trying to solve?
|
4,955,609 | 4,955,668 | How to specialize only some members of a template class? | Code:
template<class T>
struct A {
void f1() {};
void f2() {};
};
template<>
struct A<int> {
void f2() {};
};
int main() {
A<int> data;
data.f1();
data.f2();
};
ERROR:
test.cpp: In function 'int main()':
test.cpp:16: error: 'struct A<int>' has no member named 'f1'
Basically, I only want to specialize ... | Consider moving common parts to a base class:
template <typename T>
struct ABase
{
void f1();
};
template <typename T>
struct A : ABase<T>
{
void f2();
}
template <>
struct A<int> : ABase<int>
{
void f2();
};
You can even override f1 in the derived class. If you want to do something more fancy (inclu... |
4,955,740 | 4,955,884 | State machine in C++ via singleton? | I think a good way of implementing a state machine is to use the singleton pattern.
For example it can look like this:
class A
{
private:
friend class State;
State* _state;
void change_state(State* state) { _state = state; }
};
class State
{
virtual void action(A *a) = 0;
private:
void change_stat... | Your StateA, StateB classes have no data members. Presumably other states won't have modifiable data members either, since if they did then that state would be weirdly shared between different instances of A, that is different state machines running concurrently.
So your singletons have avoided half of the problem with... |
4,955,743 | 4,956,328 | Does a QGraphicsView take ownership over its associated graphics scene? | I was wondering... if I allocate a graphics scene
QGraphicsScene* scene = new QGraphicsScene();
and associate it with a graphics view
this->ui->graphicsView->setScene(scene);
does the graphics view take ownership of the scene? In other words, does the graphics view delete the scene in its destructor or should I delet... | The answer is no.
That's because Qt makes it possible to display one model (QGraphicsScene in this case) in many views which is a standard feature of every model/view framework.
Documentation of QGrahpicsView::setScene() lacks information about what happens to ownership of a scene but the situation is the same as with ... |
4,955,841 | 4,955,876 | no. of arguments in boost::bind | How many maximum arguments can we pass to boost::bind()
| by default it's 9.
http://www.boost.org/doc/libs/1_45_0/libs/bind/bind.html#NumberOfArguments
|
4,955,963 | 4,956,020 | gcc std::istream 'error: invalid cast from type ‘std::streamsize’ to type ‘std::streamsize’' | Alright, so here is a really weird one. I am reading raw data into a buffer, nothing fancy, my code went like so:
typedef unsigned char Byte;
/* ... */
static Byte SerializeBuffer[2048];
/* ... */
std::streamsize readInBuffer =
data.read((char*)SerializeBuffer, sizeof(SerializeBuffer));
But I would ke... | If data is an istream, keep in mind that the member read returns a reference to data (the stream itself), not the number of characters read.
The void * stuff is probably because the compiler, to assign it to the std::streamsize member, tries to use the implicit conversion to void * (the one that is used when you do if(... |
4,956,033 | 4,956,139 | Multiply by 0 optimization | Suppose i have:
double f(const double *r) {
return 0*(r[0]*r[1]);
}
should compiler be able to optimize out the segment, or does it still have to perform operation, in case the values might be inf or nan?
gcc -O3 -S test.c:
.file "test.c"
.text
.p2align 4,,15
.globl f
.type f, ... | It isn't only inf and NaN that prevent the optimization there, it's also the sign - 0.0 * something negative is -0.0, otherwise it's 0.0, so you actually have to compute the sign of r[0]*r[1].
|
4,956,249 | 4,956,315 | Using malloc instead of new, and calling the copy constructor when the object is created | I wanted to try out TBB's scalable_allocator, but was confused when I had to replace some of my code.
This is how allocation is done with the allocator:
SomeClass* s = scalable_allocator<SomeClass>().allocate( sizeof(SomeClass) );
EDIT: What's shown above is not how allocation is done with scalable_allocator. As ymett... | You'll need to use placement new after getting the raw memory from malloc.
void* mem = malloc(sizeof(S));
S* s = new (mem) S(); //this is the so called "placement new"
When you're done with the object you have to make sure to explicitly call its destructor.
s->~S();
free(mem);
|
4,956,439 | 4,964,382 | Programable way to determine the current double-tap speed setting in Windows 7 | I'm implementing a touch interface for Windows in Win32 (C++). I would like to find out the current double-tap (not double-click) speed that Windows is set to. I know Windows is set to accept double-taps as various messages (depending on whether you're using gestures or not), but I'm looking at doing something a bit mo... | Since there doesn't seem to be a specific double-touch notification, I suspect the application is expected to decided for itself if a WM_TOUCH is part of a double tap. The most common way to do that is probably to check the timing between touches. By default, I'd imagine that most apps use the mouse double-click sett... |
4,956,592 | 4,956,843 | Is there a fastest way to count object repetitions in an array than a HashTable? | I'll try to be as clear as I can. I have already implemented my solution and it works, I just need to know if it would be best to use other data structure instead of a Hash table
It's a college question, but I already submitted to the teacher and it works, I just wanted to see if anyone would have done it differently.
... | 2 things
first: If you are going to hash colors:
If R, G and B are colors from 00 to FF the simplest thing is to just create a hash function that is 24-bit i.e. RRGGBB then mod it by some prime number that is the size of your hash table. What size is your hash-table? Is it a prime number?
For example 65536 would be a ... |
4,956,612 | 4,956,777 | Getting around const'ness of a C++ method in derived class | I have to use a framework which defines an important hook method as const, like this
class FrameworkClass {
...
virtual void OnEventA(unsigned value) const;
...
}
In my derived class I have to save the value that I get through the hook
class MyClass: public FrameworkClass
{
...
virtual void OnEventA(unsigned... | mutable is too "broad" workaround because affects methods that use const'ness correctly. to workaround inappropriate const'ness there's const_cast:
class MyClass: public FrameworkClass
{
...
virtual void OnEventA(unsigned value) const { const_cast<MyClass*>(this)->savedValue = value; } // error!
private:
unsigne... |
4,956,842 | 4,956,909 | Working directory - solution | How do I make the working directory the "solution directory" but not through the properties, but through the code?
I'm working in windows.
| If you mean you want to find the directory that has a .sln file in it and work with it, there is no concept in C++ of such a thing as a .sln or a Makefile, or anything else really that was used in the build process to compile your project.
The concept is that you are building machine code to run without a specific runt... |
4,957,025 | 4,957,167 | Const Methods that Return References | class Foo
{
int Bar;
public:
int& GetBar() const
{
return Bar;
}
}
Is it okay that GetBar is a const method? It's not actually changing anything, but it's providing the "outside world" with a means of changing it.
| You have a typo in your code, this is what you probably meant:
class Foo
{
int Bar;
public:
int& GetBar() const
{
return Bar; // Removed the ampersand, because a reference is returned, not an address
}
}
And no, this is not legal. When tagging a method with const, not only are you promisi... |
4,957,042 | 4,960,033 | Duplicate packets in Multicast Receiver Socket | There seems to be a bug in the following MulticastReceiver implementation.
On creating two instances for <224.0.25.46,13001> and <224.0.25.172,13001>, I get each packet twice in each stream. Any pointers ? My guess is REUSEADDR ?
class MulticastReceiverSocket {
protected:
const std::string listen_ip_;
const ... | One approach you can take is to be smart about how you join the groups, so rather than create a socket, bind (with REUSEADDR) and then join group for each pair of ip, port, only construct a single socket and bind to a given port, and then issue multiple IGMP joins on the same socket.
i.e. in your case, only one socket ... |
4,957,080 | 4,957,112 | Why sizeof Variablename / sizeof * VariableName not work as desired? | class Simple {
string *data ;
//some functions and declaration of some variable,const, dest
};
When I did ;
data = new string [10] ;
cout << sizeof data / sizeof *data << endl ;
==> 1 // output
data = new string [50];
cout <<sizeof data / sizeof *data <<endl ;
==> 1 // output
**Why** do all ... | Because it simply doesn't work at all.
It only works for plain old arrays that are declared this way :
string a[10];
and it is the only case when this work.
in your case, you can't retrieve the size from the pointers you have. you have to either store the size of what you have, or just use the STL containers which al... |
4,957,185 | 4,957,230 | How to call function from inherited class? | I have the code:
class A{ //base class
public:
virtual std::string getString(){return "class A";}
};
class B: public A{
public:
std::string getString() {return "it is B class";}
};
class C{
public:
C(){
B b;
a = b;
}
std::string test() {return a.getString();}
private:
A a;
};
... | You need to implement like this:
class C{
public:
C(){
a = new B;
}
std::string test() {return a->getString();}
private:
A *a;
};
This will call getString() from class B and not A.
What you're trying to do is called "dynamic polymorphism" which is achieved through pointer (or reference) of type... |
4,957,189 | 4,957,279 | why do " int ClassName :: VariableName " always needed to complete linkage? | class X {
static int i;
// some other function, variable declaration, cons, dest
};
int X :: i ; **(!)**
Why must I write that (!) line, always ?
If I dont write, compiler cannot complete internal linkage, and so it gives ( I assume ) linker error. Why ?
| This is known as the One Definition Rule. Each global object (technically, each object with external linkage) must be defined in exactly one source file (technically, in one translation unit). However, it can be declared as many times as you like.
Typically, a class definition will be in a header file, which might be i... |
4,957,473 | 4,957,776 | Lua variable scope, function forward declaration and refactoring a Lua script by using the 'require' statement | I am finding Lua's scoping rules a bit confusing. I have submitted below, a snippet of a Lua script to highlight the issues I want to ask question(s) about:
-- 'forward definitions'
-- could these be moved to the bottom of the script to 'tidy up' the script?
-- could these reside in another file imported by require 'fi... | lhf is correct, you can refactor your code and it will still work. Keep in mind, though, that while everything in this particular example script is global, it is often a good idea, if working with variables that are effectively temporary (say, within the scope of a loop or single function), to declare them as local.
I... |
4,957,497 | 4,957,617 | Exact comparison in set lookup | I've got a struct (say Foo) which contains simply strings and a double and I've created a set which also has a comparator class which compares a subset of those attributes. So my Declaration looks like: std::set<Foo, FooComp>
When I call find() would I expect all the attributes of Foo to be used as a key or would FooCo... | std::set::find() will use FooComp, as long as the double does not form part of that comparison, it should be fine.
std::find requires operator==, so again depends if you've define this and what that includes, as long as it does not include the double (or includes the double in a sensible way), then you're good.
So, dep... |
4,957,509 | 4,957,562 | Where do I leave freeglut.dll without admin rights? | I have installed freeglut to develop with openGL in Visual Studio 2008. But when playing the exe after building, freeglut.dll can't be found. This is quite logical, because I haven't put it into C:\Windows\System32. I can't, because I'm no admin.
What I would like to do now is copy the dll to the ouput folder. I've alr... | Have a post build step that copies that dll from your project folder to the output one.
Under your project properties, Post-Build event, put a command line that copies the file from its source location to ${OutDir}
|
4,957,550 | 4,957,645 | DLLImport does not find the dll | I used DLLImport[absolute path of the C++ dll] in my asp.net C# code to call a method that is inside a C++ dll. And that works perfectly.
I then published the website on IIS and it says it cannot load the dll.
Can you please suggest how to resolve this issue?
| I use a Native LoadLibrary to load the DLL from a specific location. The below URL talks about how this can be done.
I am assuming you have the right permission set's available to work with unmanaged code, you use something on the lines of:
private static bool CanCallUnmanagedCode
{
get
{
try
{
new Securit... |
4,957,582 | 5,219,634 | How can I prove that inline functions default to internal linkage? | How can I prove that inline functions iin class default to internal linkage?
In other words/:
How can I display output of internal linkage to console?
EDIT: unix platform
| Here is an FAQ about inline functions http://www.parashift.com/c++-faq-lite/inline-functions.html.
|
4,957,677 | 4,967,601 | CrtIsValidHeapPointer problem with Oracle OCCI MetaData::getString | I am trying to get a name of a column from an oracle table using the MetaData class. I get a vector of MetaData objects from the ResultSet and then I loop over them executing the getString() function on each item, the problem is that on the second iteration, when exiting the loop to start a new iteration, it crashes o... | Nothing in that code does any direct heap deallocation, although, of course, std::string does allocate and deallocate heap memory. However, that shouldn't be a problem unless
the heap is corrupted by some other operation or
you pass std::string across executable boundaries, resulting in one executable (e.g. the DLL)... |
4,957,732 | 4,957,904 | my own smart pointer template compilation error | I am having following simple program from scott meyers book. I am compiling using Visual studio 2009.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Top { };
class Middle: public Top { };
class Bottom: public Middle { };
template<typename T>
class SmartPtr {
public:
... | First of all, create two copy constructors. One to accept the same type and the other to accept any other type that can be dynamically casted to the base type. Here's what I mean.
template<typename T>
class SmartPointer
{
// No dynamic_cast and hence no overhead
SmartPointer(const SmartPointer<T>& other):heldPt... |
4,957,739 | 4,958,474 | Is static_cast misused? | I have mixed feelings about static_cast, as it is the safest C++ cast available, but allows both safe and unsafe conversions at the same time, so you have to know the context to say if it is actually safe or might lead to UB (e.g. when casting to a sub-class).
So why isn't there a safer explicit cast? Here is an exampl... | In this particular case I believe that it's always known that the casting will be upwards and that therefore static_cast should be perfectly safe.
It does appear that using your implicit_cast would probably be safer, and allows you to explicitly pick which base class you want to implicitly cast to (which is apparently ... |
4,957,979 | 4,958,059 | help in c++ mfc dialog | i need help knowing how to post up a message in mfc project. but i need to do it in a class which is not the dialog class.
i need it to check some values in another class and i want to be able to write some message in a window or something just to check some values
im hope my explanation was clear.
thanks in advance fo... | To send/post a message you can use (A) the CWnd methods SendMessage()/PostMessage() or (B) the ::SendMessage() / ::PostMessage() functions.
This can be done from anywhere, i.e. you can also send messages from non-window classes. The only thing you need is the target CWnd object (case A) or the handle of its window (cas... |
4,958,078 | 4,958,151 | C/C++ implementation of multithreaded boss/workers model | I am looking for a C/C++ implementation of a multi threaded job dispatcher.
Boss thread (the main function) reads the job (eg executing msgrcv in a while(1) loop).
The boss reads the new job and depending on the destination dispatches the job to the
corresponding thread. The worker thread executes the job.
I don't ha... | Sound like you're after a thread pool. One can be found here (it requires boost). I'm sure Googling for "thread pool" or something similar will yield other posibilities.
|
4,958,503 | 4,958,592 | Running a c++ exe inside a C# application Problem | I have a c++ exe that I am trying to run in a C# project. Every time I try it the console opens up with the output and is not outputted to the panel as desired. This works if I use another exe created in C#.
Is this even possible using a C++ exe or am I missing something?
cheers
my code:
http://pastebin.com/n1vXsknB
| Console applications have the option of creating and writing to the console instead of their output streams. In this case, there's nothing you can do, short of hooking using Detours.
If you can change the C++ program, then you can make it use its output streams instead of the console.
|
4,958,742 | 4,958,979 | C++ move dll files from root to sub folder | I'm making a program in visual c++. The program relies on some dll files, which I don't want to place in system32. Now the dll files is in the same folder as my .exe, but i would like to move them to a sub folder. The problem is, if I move the files, my application fails to start and comes with this error message:
MyP... | I believe this is the article you are looking for:
http://www.codeguru.com/Cpp/W-P/dll/article.php/c99
Each application can now store it own path the registry under the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
The use the application path, set a key for your application, us... |
4,958,893 | 4,959,104 | How to set text alignment on a column of QTableView programmatically? | So far the only solution I have found is to subclass QItemDelegate and implement my alignment rule in the paint() function. Is it really the simplest way?
I am using the C++ API.
| The alternative to subclussing QItemDelegate is to subclass your model and override data() method.
QVariant MyModel::data(const QModelIndex& index, int role) const {
if (index.column() == yourCellIndex && role == Qt::TextAlignmentRole) {
return Qt::AlignLeft;
} else {
return QVariant();
}
}
... |
4,959,272 | 4,959,373 | In C++ what is the proper term for splitting an int into bits | I see in some C++ code things like:
// Header
struct SomeStruct {
uint32_t nibble1:4, bitField1:1, bitField2:1, bitField3:1, bitField4:1,
padding:11, field5Bits:5, byteField:8;
};
What is this called? I typically like to google before asking here, but I have no idea what to even type in. I'm hoping ... |
They are called bitfields (MSVC) (GCC)
Endianess usually refers to the order of bytes. However bit order can be important, see the above links.
They behave as an unsigned int (uint32_t) in your case.
|
4,959,380 | 4,959,426 | C++ Command-Line program design UI? | I am given a task to develop an C++ command-line(terminal, I am using, will run the program in Linux/Ubuntu) display. But I dont like the command-line design, is there anyway to improve the UI design?
Note: I must run the program in terminal!!
| ncurses. It's a lib to be able to put text wherever you want in the terminal, so you can effectively draw, ascii-art style in the terminal. It's also a very old library, so it may be a little tedious to use.
|
4,959,495 | 4,964,543 | Jni Reference Table overflow | In my android application I make extensive use of a native method that returns some data.
However after a number of calls I obtain a crash.
The native called method is :
static jbyteArray JNIGetIcon(JNIEnv* e, jclass clazz)
{
ByteBuffer buff;
buff.Write(*icon, 48, 32, r66Api::IBitmap::TEncoding::EEnc_Rgba8888);... | I think you're looking at the wrong function. According to the log message you've got a whole bunch of pinned character arrays (the "[C"). 1013 of them to be exact.
Look for a GetStringChars or GetStringCritical call that doesn't have a matching Release.
|
4,959,999 | 4,960,204 | Question about function design | I just had an interview question about how I design a simple function - find the second largest number in an Int Array.
int findSecondLargest(int * arr, int len){
int second = 0;
...
return second;
}
However, I was asked the following questions about how I deal with the issues.
If the len is less than 2(... | Following the standard library model, when searching a sequence, we don't return the value we are looking for, we return an iterator to the value(a pointer in this case). If we don't find the value, we return an iterator to one past the last element, the signature would look like this:
// end is not the last element, ... |
4,960,085 | 4,960,195 | Single instance of ATL COM class | I have a COM class. It can be accessed by processes outside my own. Each process creates it's own instance of the class. Is there a way to have a COM object that is shared amongst all processes that CreateInstance() it?
COM Singleton is the only thing that comes to mind. However, I don't have any experience using this.... | The codebase I inherited accomplishes this by declaring a static 'implementation' instance in the COM project.
The COM class simply offers an interface to that instance. This way, multiple instances of the COM class effectively provide access to a singleton implementation object within the COM server.
Note that this ... |
4,960,089 | 4,986,862 | Converting mpfr_t (or any other arbitrary precision library type) to __float128 | I guess I have two questions really.
1) I was wondering if anyone knows a way to convert mpfr_t types into __float128 types in GCC. I've looked around and found a thread on the mpfr bugfixes site where someone discusses their attempt to write a converter from __float128 to mpfr_t, but it seems to have dropped off somet... | You might want to look at gfortran's implementation for translating to intrinsics (the code is C). It makes a couple steps through an intermediary tree structure but the end result is the same.
|
4,960,399 | 4,960,477 | std::cin.clear() fails to restore input stream in a good state | In order to test bool i/o, I tried to run this short program:
#include <iostream>
int main()
{
while(true)
{
bool f;
if (std::cin >> f)
std::cout << f << '\n';
else
{
std::cout << "i/o error\n";
std::cin.clear();
}
}
return 0;
}
Here is the output I get:
g++ -Wall -ansi -pedantic -o boolio bool... | Add this line after clearing cin:
std::cin.ignore();
This way, the stream ignores whatever is left on its buffer.
|
4,960,407 | 4,960,427 | Indentation of "public" and "private" visibility modifiers | I usually indent the public: and private: access specifiers like this:
class Foo()
{
private:
void Bar1() {}
public:
void Bar2() {}
}
Xcode doesn't seem to like this, however, so I feel like I'm doing something incorrectly. What is considered common practice for indenting private: and public:?
| "Religious" question :-) You will get many different answers I think.
I say:
Which ever you like as long as you are consistent.
|
4,960,643 | 4,960,881 | How to access iPhone filesystems via USB (from Windows) | I wish to make an SMS analysis tool that downloads the SMS.db file from an iPhone device, connected via USB. I am coding in C++ and would like to know how applications such as DiskAid and iPhone Explorer access the entire filesystem via USB?
Thanks in advance!
| iPhone Explorer requires iTunes; probably it works by employing the iTunes COM API (I know there is one). Anyway, it does not show the full filesystem; just the parts that iTunes exposes. And AFAIK, the SMB.db is not exposed.
Or maybe it taps into some lower-level API that iTunes itself consumes.
Not sure about DiskAid... |
4,960,757 | 4,960,833 | Detecting characters in C++ char stream | I am working on a piece of arduino code that is using the BlackWidow version with wifi built in. Using the WiServer.h library, I'm using the SimpleClient.pde example with mods to send a call to a webserver that will simply return an integer - 0, 1, or 2. The end goal is to turn on a pin for the proper red, green, or y... | This is not robust AT ALL, but
Serial.print(data[len-1])
See what that gets you
|
4,960,949 | 5,125,860 | Magick++ Convert JPEG from CMYK to RGB Colorspace | I use the ImageMagick Magick++ API to work with images in my C++ program. It reads images out of PDF files. There are some Images that have a CMYK colorspace. How can I convert such images to RGB correctly?
Thanks for your help!
| I solved it now. I used the image->channel(AllChannels) method. The colors are not exactly the same as before, but it use usable.
|
4,960,975 | 4,961,029 | Pass pointer to auto_ptr with C++ | i have a function that does this:
static MyClass* MyFunction(myparams)
{
return new MyClass(myparams)
}
and i would be able to call this function inside another one that has the following signature:
void MyFunction2(std::auto_ptr<MyClass> myparam)
but when I try to do it i have a compiler error:
Impossible to co... | std::auto_ptr<> has an explicit constructor, like any other smart pointer. That means that there is no implicit conversion from T* to std::auto_ptr<T> to prevent from accidentally deleting an object. Hence you need to convert your raw pointed to std::auto_ptr<> explicitly:
MyFunction2(std::auto_ptr<MyClass>(MyFunction(... |
4,961,031 | 4,961,067 | Unable to use a struct that uses a template as a parameter in a method | I have the following code:
template <typename A, typename B>
struct TheStruct {
A a;
B b;
};
class TheClass {
public:
void do_something(TheStruct<A,B> blah);
}
I get compiler errors on the do_somethng method that resembles error: 'A' was not declared in this scope...
What is the correct syntax for defin... | You'll need to either make TheClass a template:
template <typename A, typename B>
class TheClass {
public:
void do_something(TheStruct<A,B> blah);
};
Or you'll need to make do_something() a template:
class TheClass {
public:
template <typename A, typename B>
void do_something(TheStruct<A,B> blah);
};
|
4,961,096 | 4,961,629 | Which data structure should I use | I am trying to figure out the best data structure to use for this problem. I am implementing a key value store with keys that are strings. The values get added frequently and will generally only get looked up 1 or 2 times. Initially I used an std::map, but I found the performance to be unoptimal, as the overhead of add... | It is hard to come with a fast solution without any knowledge on the actual problem. In particular, how big is your dataset, where is the real data stored (is it stored in the container or somewhere else?). What other operations do you need to perform on the container? Do you need to delete elements from the container?... |
4,961,155 | 4,961,334 | boost::iostream zlib compressing multiple files into one archive | i'm having trouble packing a bunch of files into one archive. the boost docs are very limited on this topic and i've searched the web for several hours now, but i can't find a solution.
What i have so far:
boost::filesystem::ofstream ofsArchive("some.zip");
boost::iostreams::filtering_ostreambuf outFilter;
boost::iostr... | zlib does not implement the Zip file format, it just implements the stream compression used within Zip (see the zlib FAQ). To my knowledge (which I should warn you is by no means total), Boost does not include functionality to read or write Zip archives. There are libraries that do provide that functionality of course,... |
4,961,164 | 4,961,180 | How do I make named pipes work between c++ and .NET? | I just had a really tough time making Named Pipes work between c++ and .NET.
I had no problems creating Named Pipes that worked between 2 c++ apps, or between 2 .NET apps.
| I dont have problem with this communication, i use this scenario in some project.
C++ side:
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\pipename");
CHAR chReadBuf[1024];
DWORD cbRead;
BOOL fResult;
fResult = CallNamedPipe(
lpszPipename, // pipe name
_Message, // message to server
st... |
4,961,740 | 4,963,221 | Winlogon Notification DLL -- Create Process as the user who logged in | I have a requirement to run an app as a user unlocks his computer. This works swimmingly in Win 7 with regular task scheduler. For XP -- ive Created a C++ DLL to do this. This seems to work great, except that it does so under the system account (and thus doesnt show up ont he user's desktop).
I have 2 functions, the fi... | Did you make sure the hToken value is not NULL? If it is not, try using DuplicateTokenEx() to retreive the user's primary token, then pass that to CreateProcessAsUser().
WINLOGINDLL_API void Test (PWLX_NOTIFICATION_INFO pInfo)
{
if( !pInfo->hToken )
return;
STARTUPINFOW lpStartupInfo;
PROCE... |
4,961,846 | 4,961,889 | Saving char in a file problems | Hey.
I have some problems writing char to a file with ofstream.
this is how the code looks (Just to show how it works. This is NOT the real code).
char buffer[5001];
char secondbuffer[5001];
char temp;
ifstream in(Filename here);
int i = 0;
while(in.get(secondbuffer) && !in.eof[])
{
i++;
}
for(int j = 0; j < i; j++)
{
... | You need to null-terminate secondbuffer. You are adding all the characters read from the stream, which do not include the trailing NULL.
on the line before fout, add
secondbuffer[j]='\0\';
|
4,961,902 | 4,961,953 | inet_ntoa() and Windows User Permissions | Is it possible to still use inet_ntoa() and not worry about Windows User Permissions? Do I need to put a try/catch block around inet_ntoa() to catch any possible problems if User Permissions prevent me from getting the IP address of an interface?
| inet_ntoa doesn't raise exceptions. It returns NULL in case of an error.
It's hard to see how user permissions could come into this function since it is just an integer to string conversion.
|
4,961,909 | 4,966,740 | templates may not be ‘virtual’ | Given the code below, the compiler is showing a message pointing that error: templates may not be ‘virtual’. Does anyone have a suggestion on how to solve the bug?
template < class FOO_TYPE>
class CFoo{
public:
...
template < class BAR_TYPE >
virtual void doSomething( const CBar<BAR_TYPE> &)... | The easiest reason to see why this is illegal is by considering the vtable. Sure, that's just one common implementation, and others are allowed. But all virtual functions in C++ are designed such that they can be implemented with a vtable.
Now, how many entries are there in the vtable of CFoo<int> ? Is there an entry f... |
4,961,919 | 4,961,952 | Can a existing static method made global using function pointer? | I have a static method in a cpp file (not in class) .
I want to use it globally without redeclaring it as extern .
In that case is it possible to use a global function pointer to this static method and
use this function pointer globally ??
| It is possible to do what you want, but why would you avoid using extern when it does exactly what you are trying to emulate through a much more convoluted (and unreadable) mechanism?
|
4,961,944 | 4,962,104 | return by value function optimization | Sample Function 1
int func1 (int arg)
{
return arg + 10;
}
Sample Function 2
int func1 (int arg)
{
int retval = arg + 10;
return retval;
}
func_xyz (int x);
int main ()
{
int a = 10;
int p = func1 (a);
func_xyz(p);
}
Is there any difference between runtime behaviour of th... | in THEORY in function2 a local variable will be initiated (which will take just a bit more space), then the calculation will be calculated and value will be copied to the variable's location.
After that the copy will be copied to the return value. So that's an extra copy operation.
in REALITY compilers do that optimiz... |
4,961,950 | 4,962,425 | Is it possible to selectively define a type in a derived class | I have a class template which looks like this:
template <Base>
struct foo : Base
{
typedef int some_type;
};
and I have a base which looks like this:
struct some_base
{
typedef float some_type;
};
Now foo<some_base>::some_type will be int as the derived foo will hide the Base::some_type. What I would like to do, ... | Anything is possible with a bit of template metaprogramming :)
Start by writing a metafunction that determines whether a type has a nested type called "some_type". Something like this:
template <typename T>
struct has_some_type
{
typedef char no; // type with sizeof == 1
typedef struct { char... |
4,962,225 | 4,962,632 | Setting up the constant buffer using SlimDX | I've been following the Microsoft Direct3D11 tutorials but using C# and SlimDX. I'm trying to set the constant buffer but am not sure how to either create or set it.
I'm simply trying to set three matrices (world, view and projection) using a constant buffer but I'm struggling at every stage, creation, data input and p... | Something similar to this should work:
var buffer = new Buffer(device, new BufferDescription {
Usage = ResourceUsage.Default,
SizeInBytes = sizeof(ConstantBuffer),
BindFlags = BindFlags.ConstantBuffer
});
var cb = new ConstantBuffer();
cb.World = Matrix.Transpose(world);
cb.View = Matrix.Transpose(view);
c... |
4,962,379 | 4,962,722 | window without wndproc | I am curious it is possible to create a window without using WndProc.
So I would like to register the window-class with the lpfnWndProc field set to NULL;
And using the msg ( that is given by TranslateMessage(&msg) ) in my own way.
Is there any disadvantages of this?
Thanks ahead, and sorry for my grammar.
Edit #1:
Oka... | AFAIK, you can't set it to NULL. However, you'll notice that DefWindowProc's signature matches the WindowProc callback's signature. Simply give it DefWindowProc if you'd like a reasonable default.
|
4,962,381 | 5,037,983 | Isapi filter - state | I have a isapi filer and I want to add a logic based on the incoming domain ( my server farm hosts many domains).
There domain list is dynamic , I can export these domain list into a text file and read it from the isapi , but is there a way to keep this file in memory (is array or linked list) to save the IO call.
simi... | How are your worker processes distributed across your servers? Do you have one server with one worker process, or multiple servers?
If you have one server with one worker process, you can just read the file into a static array or string to manage it (just make sure you account for concurrent threads reading/modifying... |
4,962,520 | 4,962,974 | ATL templates for IDispatch derived classes | Tomorrow I have planed to do some IDispatch related work, and I will have to create a class that supports this interface.
I have been using ATL classes for a while to create COM objects and manage COM pointers, so I would like to use them for my class as well. But research so far, and discussions with colleagues have l... | ATL has an IDispatchImpl class.
|
4,962,942 | 4,962,977 | Is it confusing to omit the "private" keyword from a class definition? | I recently removed a private specified from a class definition because it was at the top, immediately after the class keyword:
class MyClass
{
private:
int someVariable;
// ...
I thought that it was redundant.
A coworker disagreed with this, saying that it effectively "hid" the private nature of the data.
Most of ... | If you are very familiar with all the default access levels then you probably won't see any difference in readability if you omit them whenever they are unnecessary.
However you will find that many people you work with aren't 100% sure about the default access level rules. This is especially true for people who regular... |
4,963,031 | 4,963,050 | Is it a good practice to use enum as int? | So, I have a variable "state" in a class. I want to declare it as an integer so I can save some if statements.
int state;
One way to do this is to declare an enum State {One = 0, Two = 1, Three = 3}, and then in the switch statement, it would become:
switch (state)
{
case One:
dosomething();
break;
case Two:
... | Yes that is a good way to do it. You generally use enums to make life easier, a lot of different numbers that don't really tell other coders anything isn't quite helpful.
So this is a perfectly good way of using it, it makes your code readable and understandable.
Altough as @James McNellis pointed out, naming your enum... |
4,963,173 | 4,963,283 | Best data storage method for small personal application(SQL Database, XML, or other file type) | I have done a little research here on SO and haven't found exactly what I was needing.
I am currently learning C++ to help transition my companies MSSQL Delphi driven application over to C++. In order to help facilitate my learning I am working on a personal application for my home use. Since I don't really think I wi... | Use SQLite. It gives you much of the power of a DBMS, including a mostly complete implementation of SQL-92 but is completely embedded in your app, and has no installation footprint.
For C++, several libraries are available that wrap an OO API around the fairly RAW C interface. See this SO question for recommendations.
... |
4,963,295 | 4,965,635 | setLastModified date with Qt | I need to set the last modified date for some files. It is an essential ability for my application.
I don't see how I can do this with QT. I don't see a method/function for it.
I can read the dates with Qt but I don't see how I can set the dates.
Now... I know some (I think all actually) windows API's from MS have th... | The posix function for this is utime(2), which is also available on windows as part of MSVCRT (see MSDN). So using that should cover Mac, Linux, and Windows.
Since QAbstractFileEngine doesn't expose this functionality, I don't think it'll be available in any other Qt filesystem APIs either.
|
4,963,610 | 4,963,633 | Visual c++ native memory management best practices | I am an old C# programmer and a C programmer (without dynamic memory allocation), but would like to learn a bit about Visual C++ programming. The question that bothers me is related to memory management in C++. In C#, garbage collector takes care of the memory management, but in C++, it is necessary that some rules are... | If you write your code correctly, you won't have to worry about this, at least not directly. There are library facilities available to you that handle memory management and other resource management for you, completely automatically, so that you don't have to.
C++ provides something far better than a garbage collect... |
4,963,652 | 4,963,728 | Single line pointer operations | I've been struggling with a homework problem in C++.
the problem is as follow:
Write one statement that performs each of the following tasks. Assume that num1 is a floating-point variable. Assume also that ar1[100] and ar2[100] are arrays of type char:
Declare ptr as a pointer to an object of type double
Assign the a... | A double is a floating-point value, so ptr = &num1 should be ok. On the other hand, double *ptr = new double; not only declares a pointer to a double, but also initializes it. double* ptr is sufficient as declaration;
Casting a float* to a double* will likely not produce anything useful, because float and double probab... |
4,963,689 | 9,025,642 | Xpressive >>= Operator | I am toying around with Boost Xpressive and am having trouble with the following snippet
#include <iostream>
#include <string>
#include <boost/xpressive/xpressive.hpp>
using namespace std;
using namespace boost::xpressive;
int main()
{
string s("123");
sregex rex = _d;
rex >>= _d;
smatch what;
r... | Xpressive doesn't support the >>= operator. The fact that this code compiles at all could be considered a bug. Try:
rex = rex >> _d;
However, building up a regex piecemeal like this will make the regex perform poorly.
|
4,964,390 | 4,964,504 | Utilizing MMX with Managed C++ | From what I understand, the JIT does not compile the MSIL into native machine code that will utilize MMX instructions on x86. If this is true (as I'm having a hard time finding up to date information on the matter), then I want a way to utilize MMX in my code. I am working on an application that will be doing almost ... | MMX is an integer instruction set, not floating point. It only supports 64-bit packed byte, word and double-word integers. SSE has floating point support. Use #pragma managed in your code to switch between machine code and MSIL generation.
|
4,964,470 | 4,964,573 | Trouble with allocating new memory for array in C++ | Ok I'm having a hard time understanding what I'm doing wrong. In my header file, I have a pointer to an array of pointers to images:
Image **images;
int maximum; //size
This is part of a class called scene. Now, scene has a member function called changemax, which changes the size of the images array. You can decrease ... | You certainly have a memory leak here:
newArray[i]=new Image;
if(images[i] !=NULL) {
// ...
}
else {
newArray[i]=NULL;
}
Why are you creating two new arrays? You only need to create one new array, copy the contents of the old array into the new array, destroy the old array, and then assign images to point to ... |
4,964,482 | 4,964,508 | How to create two classes in C++ which use each other as data? | I'm looking to create two classes, each of which contains an object of the other class type. How can I do this? If I can't do this, is there a work-around, like having each class contain a pointer to the other class type? Thanks!
Here's what I have:
File: bar.h
#ifndef BAR_H
#define BAR_H
#include "foo.h"
class bar {
p... | You cannot have two classes directly contain objects of the other type, since otherwise you'd need infinite space for the object (since foo has a bar that has a foo that has a bar that etc.)
You can indeed do this by having the two classes store pointers to one another, though. To do this, you'll need to use forward d... |
4,964,515 | 5,185,475 | AES Limitations and MixColumns | So we all agree keys are a fixed-length of 128bits or 192bits or 256bits. If our context was 50 characters in size (bytes) % 16 = 2 bytes. So we encrypt the context in 3 times, but the remaining two bytes how will they be stored in the State block. Should I pad them, the standard doesn't specify how to handle such cond... | In the mix columns stage the exponents are being multiplied.
take this example
AA*3
10101010*00000011
is
x^7+x^5+x^3+x^1*x^1+x^0
x^1+x^0 is 3 represented in polynomial form
x^7+x^5+x^3+x^1 is AA represented in polynomial form
first take x^1 and dot multiply it by the polynomial for AA.
that results in...
x^8+x^6+x^4+x^... |
4,964,630 | 4,965,223 | System Tray Icon in C++ | I got a basic window made from C++. What I need to do is whenever I click the Minimize button the window will be placed in the System Tray and whenever I double click on the Icon it will restore...
| check msdn about
a struct: NOTIFYICONDATA
and a function:
BOOL Shell_NotifyIcon( DWORD dwMessage,PNOTIFYICONDATA lpdata);
and also a demo here.
Hope you can understand:)
|
4,964,710 | 4,964,732 | Function to go back 1 UTF-8 character? | I have a function which goes forward 1 utf-8 character and returns the number of bytes it took to get there:
// Moves the iterator to next unicode character in the string,
//returns number of bytes skipped
template<typename _Iterator1, typename _Iterator2>
inline size_t bringToNextUnichar(_Iterator1& it,
const _Ite... | Just decrement the iterator instead of incrementing it.
// Moves the iterator to previous unicode character in the string,
//returns number of bytes skipped
template<typename _Iterator1, typename _Iterator2>
inline size_t bringToPrevUnichar(_Iterator1& it,
const _Iterator2& first) const {
if(it == first) return... |
4,964,863 | 4,970,446 | C++ Qt Multiple Definitions | I'm trying to create a simple GUI application (so far) in Qt with C++ using the MinGW compiler. However, the compiler is informing me that I have a multiple definition of 'WiimoteScouter::WiimoteScouter(QWidget*)' on line 4 of wiimotescouter.cpp. I am using a check to make sure the header isn't included multiple times,... | I've seen this happen before when a source file got duplicated in the project (.pro or .pri) file. Check all of the "SOURCES =" and "SOURCES +=" lines in your project file and make sure the cpp file is not in there more than once.
|
4,965,355 | 4,965,511 | Converting statvfs to percentage free correctly | I have a terribly uncomplicated test program that prints out the following numbers.
i.e.
int main(int argc, char* argv[])
struct statvfs vfs;
statvfs(argv[1], &vfs);
printf("f_bsize (block size): %lu\n"
"f_frsize (fragment size): %lu\n"
"f_blocks (size of fs in f_frsize units): %lu\n"
"f_bfre... | df's data may be based on f_bavail, not f_bfree. You may find it helpful to look at the source code to df to see how it does things. It has a number of edge cases it needs to deal with (eg, when the used space exceeds the amount of space available to non-root users), but the relevant code for the normal case is here:
... |
4,965,373 | 4,965,411 | Should I use C++11 lambdas now? | Here is my dilemma: I really like lambda and have been using Boost.Fusion and Phoenix a lot lot. They are pretty mature and play nicely across many compilers.
What about the C++11 lambdas? They are really nice and much more easier to use then boost alternatives (no more functors!). Recent ICC and GCC compilers supp... | Do you need to be able to compile your code using a compiler that doesn't support C++11 lambdas?
If so, then you can't use them (obviously). Otherwise, there's really not much reason not to use them.
There have been few changes to the specification of lambda expressions in C++11, so there is little risk to using the... |
4,965,784 | 4,966,992 | G++ SSE memory alignment on the stack | I am attempting to re-write a raytracer using Streaming SIMD Extensions. My original raytracer used inline assembly and movups instructions to load data into the xmm registers. I have read that compiler intrinsics are not significantly slower than inline assembly (I suspect I may even gain speed by avoiding unaligned... | The simplest way is std::aligned_storage, which takes alignment as a second parameter.
If you don't have it yet, you might want to check Boost's version.
Then you can build your union:
union vector {
__m128 simd;
std::aligned_storage<16, 16> alignment_only;
}
Finally, if it does not work, you can always create you... |
4,966,002 | 4,966,034 | Is if(pointerVar) the same as if(pointerVar!=NULL)? | Simple question:
Is if (pointerVar) the same as if (pointerVar!=NULL)?
Also, is if (!pointerVar) the same as if (pointerVar==NULL)?
Give me your most technically correct/pedantic answer. The two statements seem and make sense to operate the same. Is there anything wrong with the former though (besides its slightly lowe... | For the most pedantic answer, here's the relevant sections of the spec.
First, here's how if statements work, from §6.4.4:
The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable implicitly converted to type bool. If that conversion... |
4,966,194 | 4,966,357 | How could I detect when my application is minimized? | I have a program with an option to enable minimizing to the taskbar's notification area. In order for this to work, I need a reliable way of detecting when the user has minimized the application.
How can I do that using the Windows API in a C++ application?
| When the user minimizes the window (either using the box on the title bar, or by selecting the "Minimize" option from the system menu), your application will receive a WM_SYSCOMMAND message. The wParam parameter of that message will contain the value SC_MINIMIZE, which indicates the particular type of system command th... |
4,966,346 | 4,966,406 | data extraction in C++ | Hello all I am reading from a data file using the code
//................
//...................
char databuff[20];
char ch;
for(int i=0;i<15;i++) {
f[0].getline(databuff,((2*sizeof(double))+(2*sizeof(char))));
//...............
//...............
cDisp=databuff;
cDisp1+=cDisp;
... | You could create a strstream on top of your databuff and just read using double d0, d1; char t; str >> d0 >> t >> d1;
Alternatively, you could try strchr to locate the ',', then use atof on the two substrings (or std::find if you want the C++ way.)
|
4,966,364 | 4,966,381 | How do I access abstract private data from derived class without friend or 'getter' functions in C++? | So, I am caught up in a dilemma right now. How am I suppose to access a pure abstract base class private member variable from a derived class?
I have heard from a friend that it is possible to access it through the base constructor, but he didn't explain. How is it possible?
There are some inherited classes from base ... | It is not possible. Private members are only accessible in the class in which they are defined (plus its friends), by design.
Every class is solely responsible for its private member variables. If a subclass needs to access those, they either have to be declared protected or, preferably, accessed indirectly through so... |
4,966,705 | 4,970,621 | Unable to access contents of initialized struct in a map | I have a struct:
typedef struct
{
Qt::Key qKey;
QString strFormType;
} KeyPair;
Now I initialize KeyPair instantiations so I could use it for my Automated Test App.
KeyPair gDial[] =
{
{ Qt::Key_1 , "MyForm" },
{ Qt::Key_1 , "SubForm" },
{ Qt::Key_Escape, "DesktopForm" }
};
KeyPair gIP[] =
{
... | I think Henning's answer is the way to go.
*gDial and *gIP in your code mean gDial[0] and gIP[0].
So, you insert only the first element of the KeyPair array into mMasterList.
Your pressKeyPairs's declaration
template<size_t nNumOfElements> void pressKeyPairs(KeyPair(&keys)[nNumOfElements]);
itself is correct. It takes ... |
4,966,726 | 4,986,134 | Traits and passing traits as template parameters | When is it practical to pass traits as template parameters rather than simply using some existing traits struct like
typedef basic_ofstream< char, char_traits<char> >
vs.
typedef basic_ofstream< char >?
I have some tile classes which I would like to have some common ground (traits), so I designed tile_traits to cont... | The design of traits is as much art as anything else. There are no hard and
fast answers here. I believe this question has gone unanswered because it is
impossible to give a good answer without knowing a lot more about the problem
you are solving.
In general traits classes are a useful "customization point". That is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.