question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,869,531 | 5,873,297 | How do I keep my QAbstractTableModel in sync with my data store? | In my app, I have a class for keeping a list of items:
class Database : public QObject
{
Q_OBJECT
public:
Database(QObject *parent, const QString &name);
const Entry& item(int idx) const { Q_ASSERT(idx < itemCount()); return _items.at(idx); }
const QString& name() const { return _name; }
int itemC... | I think I see your problem.
One the one side you're doing the right thing and trying to keep the data seperate from the model, on the other hand your data isn't aware of the model itself.
There is a reason why you should call begin...Rows() before changing the data and end...Rows() afterwards. Namely the QPersistentMod... |
5,869,573 | 5,869,619 | std::list erase incompatible iterator | I have list with objects. I get some items from that list and do something with items. If work is done without errors i wish to delete these items from list. After that, on erase I get exception of incompatible iterator. I understand that tmp is different list. But how to solve this problem?
#include <list>
class A
{
... | You can't erase from one list using iterators from another list. An iterator "points" to some node in a list. Its pointing to something in a specific list. When you copy those things into another list, you have two lists with two sets of nodes now. Your iterator points to only one of those copies, not to both.
In the ... |
5,869,694 | 5,869,724 | problem copy original vector into my vector | i have a question:
if i have:
void test (std::vector<int> *original)
{
myvector = vector<int>();
myvector.reserve(&original.size());
copy(original.begin(),original.end(),back_inserter(myvector));
}
I want to copy a vector in my original target vector
I have 3 error:
Error 1 error C2228: left of '.size'... | Note that original is a pointer. You have to write it like this:
void test (std::vector<int> *original)
{
myvector = vector<int>();
myvector.reserve(original->size());
copy(original->begin(), original->end(), back_inserter(myvector));
}
Pointers are dereferenced with ->, not with .. & means "take the addre... |
5,869,902 | 5,870,216 | C++: Mutex and deallocation | I am writing a small program as part of a University course. In this program, I have a global Boost Mutex which helps me to coordinate two threads.
In my small library, I have to write a cleanup function that, when invoked, literally cleans up after itself.
What I am asking now is: if I create a Mutex, am I supposed to... | Boost mutexes appear to be written to perform all their cleanup in their destructors. If you want to ready that same mutex for resuse, probably you'd want to call .unlock() on it once.
If you really feel the need to manually get rid of it, I suppose you could make it a pointer and create it with a new. That way you ca... |
5,870,038 | 5,870,075 | Uninitialized pointers in code | I am learning C++ and I came to know that pointers if left uninitialized could point to random locations in memory and create problems that memory might be used by some other program.
Now if that is the case we should never have this line in any part of our code:
int* ptr;
Instead we should have something like
int* ... | int* ptr = NULL; //Is this going to avoid the problem
This will cause ptr to point to NULL which you can explicitly check for as a default/uninitialized value. It prevents the problem you describe, but a careless programmer can still accidentally dereference a null pointer without checking, causing undefined behaviour... |
5,870,111 | 5,870,219 | Why can't my c++ lambda function be captured? | Say I have a templated Action
template <class ArgT>
struct Action
{
Action(::boost::function< void(ArgT) > func)
: func_(func)
{
}
void operator()(ArgT arg)
{
func_(arg);
}
private:
::boost::function< void(ArgT) > func_;
};
I use Action like so :
class XCallbackInvoker... | If you capture by copy then you cannot modify it by default, since the operator() of the lambda is declared const. You need to add mutable to your lambda to allow modifications of the captured variables:
XCallbackInvoker (Action< int > callback)
: CallbackInvoker< X >(
Action< ::boost::shared_ptr< X > >(
... |
5,870,209 | 5,870,437 | linkage problem of dynamic library | I'm trying to dynamically load libraries that implement a base class, defined in another library. I've followed instructions depicted here:
http://www.linuxjournal.com/article/3687?page=0,1
I created a shape class and put it in a separated library (not a real library since its just a header file, but put it that way),... | You have only declared factory as extern in shape.h.
You should put something like:
std::map<std::string, maker_t *, std::less<std::string> > factory;
into shape.cpp to reserve space (i.e. create a defined symbol) in shape.o.
|
5,870,284 | 5,870,340 | Can I use parameters for the table name in sqlite3? | I'm having some strange feeling abour sqlite3 parameters that I would like to expose to you.
This is my query and the fail message :
#query
'SELECT id FROM ? WHERE key = ? AND (userid = '0' OR userid = ?) ORDER BY userid DESC LIMIT 1;'
#error message, fails when calling sqlite3_prepare()
error: 'near "?": syntax error'... | Ooookay, should have looked more thoroughly on SO.
Answers:
- SQLite Parameters - Not allowing tablename as parameter
- Variable table name in sqlite
They are meant for Python, but I guess the same applies for C++.
tl;dr:
You can't pass the table name as a parameter.
If anyone have a link in the SQLite documentation ... |
5,870,566 | 5,870,693 | Should I prefer "default" calling convention over __fastcall when I don't really care of the calling convention? | We have a huge C++ codebase with lots of COM objects. Each function exposed to COM must have __stdcall calling convention (usually STDMETHODCALLTYPE macro) and so we have lots of functions marked STDMETHODCALLTYPE.
Now I see a function that is not directly called through COM, but rather called only from within our C++... | The only reason why the COM stuff explicitly sets the calling convention is because it is used across DLL boundaries.
So my advise would be to drop the explicit setting of the calling convention and set it by the compiler settings.
In general:
If the functions are exported as a DLL set a macro that defines the calling ... |
5,870,746 | 5,870,800 | Does creating a custom graph data structure violate any principles? | I'm working on a small scientific course project related to circuit testing using continuous methods. The program would parse circuit definition files and then build an easily modifiable graph structure representing the circuit.Then certain modifications are done to that graph, and it is topologically sorted. After sor... | 1)Can (or even may) the code be as simple?
Not only can it be, it should be. There is no need for code to be complicated.
2)Don't I violate any of the thousands of principles of Software Design with making assumptions about the data structures?
Um, how can you do otherwise. This question doesn't make sense to me.
3)Sho... |
5,871,044 | 5,871,187 | Why can't my C++ compiler deduce template argument for boost function? | I define a method like so:
template <class ArgT>
void foo(ArgT arg, ::boost::function< void(ArgT) > func)
{
func(arg);
}
and use it like this --for instance--:
foo(2, [](int i) -> void { cout << i << endl; });
Why can't the compiler deduce the type since it's definitely an int?
I get 'void foo(ArgT,boost::functio... | While C++ lambdas are strictly monomorphic, they are merely shorthand for function objects (aka functors), and in general functors can be polymorphic; i.e., their call operators can be overloaded or templated. As a result, functors (and, consequently, lambdas) are never implicitly convertible to templated std::function... |
5,871,298 | 5,871,364 | puzzled by compiler warning that suggests compound assignment of int8_t promotes to int | I can usually understand the reason behind a compiler warning, but this one seems just plain wrong.
#include <stdint.h>
uint8_t myfunc(uint8_t x,uint8_t y)
{
x |= y;
return x;
}
The intel compiler with -Wall complains:
conversion from "int" to "uint8_t={unsigned char}" may lose significant bits
x |= y;
... | That's integer promotions at work.
in
x |= y;
both operands of the | operator are promoted to int
x = (int)x | (int)y;
then the result is converted back to uint8_t losing precision.
|
5,872,114 | 5,872,150 | Good resource/book to learn about memory leaking in C++? | I'm looking for a good resource/book to learn about memory leaking in C++.
I use Linux Ubuntu and QtCreator as a IDE ( is there a way to see them there ? ).
| What is a Memory Leak?
A memory leak, occurs when a computer program consumes memory but is unable to release it back to the operating system. In C/C++ whenever a program allocates dynamic memory on the heap it should also release the same or it results in memory leak.
In C dynamic memory is allocated on Heap using t... |
5,872,118 | 5,916,275 | How to get ALL data from 2D Real to Complex FFT in Cuda | I am trying to do a 2D Real To Complex FFT using CUFFT.
I realize that I will do this and get W/2+1 complex values back (W being the "width" of my H*W matrix).
The question is - what if I want to build out a full H*W version of this matrix after the transform - how do I go about copying some values from the H*(w/2+1) r... | I actually searched the nVidia forums and found a kernel that someone had written that did just what I was asking. That is what I used. if you search the cuda forum for "redundant results fft" or similar you will find it.
|
5,872,148 | 5,872,348 | Cant use typedef of one class in dll from another project | I have written a dll in which I have namespace VT in witch class public ref class Database in witch I have typedefs:
public:
typedef System::Collections::Generic::Dictionary <System::String^, Database^> SubkeyDictionary;
typedef System::Collections::Generic::Dictionary <System::String^, System:... | A typeset is more like an alias than a actual type and I will check shortly, but I suspect that this is not exposed as a .NET type that can be used from other assemblies.
However, all is not lost. Rather than using a typeset you could do the following
public:
ref class SubkeyDictionary : public System::Collections::G... |
5,872,415 | 5,872,526 | C++ Sort vector of <T> according to vector of double | I want to sort a vector of T according to a vector of double. That is, if I have
vector<T> a;
vector<double>b;
If a is {t1, t2, t3, t4} and b is {3, 1, 5, 2}, I want to obtain {t2, t4, t1, t3}.
I don't know how to declare the template. I'm trying something like
template<vector<class T>> vector<T> sortByArray(vector<T>... | What you should do is create a struct or class like this:
template <typename T> struct dataPair
{
dataPair(double s, T o)
: m_sortData(s)
, m_otherData(o)
{
}
bool operator< (const dataPair &rhs) { return (m_sortData < rhs.m_sortData); }
double m_sortData;
T m_otherData;
}
Then, yo... |
5,872,469 | 5,872,502 | Wildcarding vector templates | I have to create vector of a special type depending on a user input.
e.g. the user has to choose if he wants to create a vector of ints or a vector of strings.
Is it possible to predefine a vector and define it clearly in a e.g. switch-case?
something like:
vector<WILDCARD> vec;
switch(input) {
case 1:
vec = vector... |
Is it possible to predefine a vector and define it clearly in a e.g. switch-case?
No. C++ is a statically-typed language. That means, type of every variable must be known at compile time, and once its known, it cannot be changed later on - not even at compile-time. So what you're doing is not possible.
If you want to... |
5,872,484 | 5,872,710 | How bad is this goto? | I created a tetris game where you can restart after a game over. I implemented this quick and dirty with a goto (see code). The Game class relies on destructors, are these called with these goto's? How bad is this goto, is it acceptable, or what should I do instead?
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE h... | To answer the question about destructors no one else seems to have covered. According to 6.6/2 the destructors will be called for you. Quote:
On exit from a scope (however
accomplished), destructors (12.4) are
called for all constructed objects
with automatic storage duration
(3.7.2) (named objects or temporar... |
5,872,645 | 5,873,058 | How can I write a 'pass reference by value' wrapper in C++? | I'm writing a compiler for a class, and we've decided to adopt java-like semantics for our variables. Basically, reads behave like pointer dereferences, and writes behave like pointer assignment.
So then, how can I write a wrapper class that has these semantics? Basically, every operator except assignment will be pass... | First of all, I'm totally against any attempts to turn C++ into Java (which is basically what C# is), and I'm especially puzzled by the idea of giving up value-semantics of C++, since the most useful uses of RAII essentially requires value-semantics, this is not something I would ever want to give up. But, for argument... |
5,872,685 | 5,872,701 | Constant map iterator won't set to mymap.begin() | map<string,Shopable*>::iterator it = mymap.begin();
The iterator appears to be constant, but items.begin() doesn't return a constant iterator. Or, that's what I think because the mouseover error is something like:
"No conversion from 'std::Tree_const_iterator<...> to std::Tree_iterator<...> exists'".
Why?
| Use const_iterator as :
map<string,Shopable*>::const_iterator it = mymap.begin();
From the error, its clear that mymap.begin() returns const_iterator. That is because mymap is const in the function where you've written this, something like following:
void f(const std::map<int,int> & m)
{ //^^^^^ note this
st... |
5,872,915 | 5,873,023 | Converting a C++ class to a C struct (and beyond) | Past few days I have been "downgrading" > 1000 filem of C++ code into C.
It's been going well until now. Suddenly I'm face to face with a class...
The compiler pointed out the error first in the header file:
class foobar {
foo mutex;
public:
foobar() {
oneCreate(&mutex, NULL);
}
~foobar() {
... | Turn foobar into a normal struct
struct foobar {
goo mutex;
};
Create your own "constructor" and "destructor" as functions that you call on that struct
void InitFoobar(foobar* foo)
{
oneCreate(&foo->mutex);
}
void FreeFoobar(foobar* foo)
{
oneDestroy(foo->mutex);
}
struct foobar fooStruct;
InitFoobar(&fooS... |
5,872,926 | 5,872,988 | Why doesn't boost::any have a "getter"? | Using boost::any is very useful but it's very depressing that it has no getter, and always we have to use any_cast for casting it to type we want. But why it has no such thing? In my opinion the one bellow can be useful member. Is there some bad things I can't see?
template <class T>
void get(T * handle)
{
*handle ... | Probably because it'd behave the exact same as any_cast, but it would be less descriptive. any_cast indicates that you're performing a cast, a type conversion. You're trying to get the value out of the any object. So it's clear to the user that the operation can fail if you call it with the wrong type.
A get function i... |
5,873,384 | 5,873,411 | C++: LPWSTR prints as an address in cout | I have a variable of type LPTSTR, which I print to std::cout with <<. In an ANSI system (don't know exactly where it is determined) it worked fine, it printed the string. Now in a Unicode system I get a hex address instead of the string. So, why does LPSTR (to which LPTSTR is resolved if UNICODE is not defined) act dif... | For Unicode strings you want wcout.
You may be seeing hex because the ANSI/ASCII output stream doesn't know how to handle Unicode characters.
LPTSTR and LPWSTR are actually C-isms inherited from the C Windows API days. For C++ I would strongly encourage you to use std::string and/or std::wstring instead.
If you need t... |
5,873,455 | 5,873,486 | Multi inheritance from templated classes | I was trying to do some practical work, and was thinking to do something like this but couldn't find any solution to it, how to run this program? (note: this is just a theory or say abstract practical nothing to do with real world relationships)
template<typename T> class animal
{
public:
T data;
animal():data(... | template<typename T, typename Foo>
class lion : public animal<T> ,public amph<Foo>
...
lion<int, int> mylion;
|
5,873,488 | 5,873,537 | Error when comparing std::vector Sizes | I am running into a weird issue with some simple code using the standard C++ library elements map and vector.
I have a graph that is represented as a map<int, Edgelist> where an Edgelist is defined as a vector<int>. I also have a match function which compares two graphs and returns true if the pattern is contained in t... | This creates a vector with 2 elements initialized to 0:
p3[1] = std::vector<int>(2);
This creates a vector with one element initialized to 2:
p3[1] = std::vector<int>(1, 2);
|
5,873,510 | 5,876,025 | QList::iterator only returns (error)0 | I am using a QList and I want to iterator though it, but the iterator that i get from it keeps failing, even if I use the auto keyword or not.
for( auto iter = myModel->getList().begin(); iter != myModel->getList().end(); ++iter )
{
if( (*iter)->getList().empty() )
{
if( (*iter)->getData()->getCode() =... | I see two issues with the code.
a) myModel->getList() returns a copy of your QList declared something like this:
QList<T*> YourModel::getList()
you actually should get an access violation. But I don't know if that's what happening.
b) If you only rely on what Visual Studio is saying about iter, forget it, its wrong. ... |
5,873,844 | 5,874,629 | new and delete in a c++ library being called from a C program | I have a series of c++ classes stored in a library with a C interface (see example below). And I have a C program that includes this c++ libary via the C interface. This seems to work well until I tried to create a class in the libary with new and delete.
I am using gcc to compile the C code and g++ for the C++ libary,... | Quoting unapersson: It's not linking in the C++ runtime. You should use "g++" as the link command, rather than "gcc".
|
5,873,901 | 5,873,950 | Introducing a dummy argument via STL or Boost | Suppose one wants to fill a vector with random numbers. Then there is a following obvious solution:
vector<int> result;
result.resize(n);
for (int i = 0; i < n; ++i) {
result[i] = generateRandomNumber();
}
OK, it obviously works, but I would like to understand what is the simplest STL/Boost way to get rid of the f... | The C++ standard library has std::generate() and std::generate_n();
For example:
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <iterator>
int generateRandomNumber()
{
return std::rand();
}
int main()
{
int n = 10;
std::vector<int> result;
generate_n(back_inserter... |
5,874,255 | 5,874,313 | Is Virtual Inheritance necessary for Exceptions? | I understand the need for virtual inheritance when using multiple inheritance -- it solves the Dreaded Diamond Problem.
But what if I'm not using multiple inheritance? Is there a need for virtual inheritance at all?
I seem to recall hearing that it was important for exceptions (throw a derived class, catch by base cla... | You're probably thinking about this Boost.Exception guideline, which I'll copy here for completeness:
Using Virtual Inheritance in Exception Types
Exception types should use virtual inheritance when deriving from other exception types. This insight is due to Andrew Koenig. Using virtual inheritance prevents ambiguity ... |
5,874,493 | 5,874,607 | Why is destructor of boost::thread detaching joinable thread instead of calling terminate() as standard suggests? | According to the draft C++0x standard, this code:
void simplethread()
{
boost::thread t(someLongRunningFunction);
// Commented out detach - terminate() expected.
// t.detach();
}
... should result in an terminate() call, but in current (boost 1.46.1) implementation of boost threads it doesn't, thread sim... | The reason is largely historical. boost::thread came first. The proposals for std::thread were derived from boost::thread and originally had the behavior that boost::thread does now.
However during the standardization process a significant number of people wanted std::thread::~thread() to join() in the destructor if ... |
5,874,786 | 5,877,810 | Another problem with decltype | //THIS IS JUST A FRAGMENT OF A static_numeric_limits.h for the purpose of this example
#include <limits.h>
template<class T>
struct static_numeric_limits;
template<>
struct static_numeric_limits<signed char>
{/*min was outside of range for enum*/
static const signed char min = SCHAR_MI... | The error here is what type decltype is deducing from your expression; unfortunately the error messages aren't clear about it, and it's actually a bit of a tricky problem.
Consider the type of the expression 0 + 0. It's an int, yes, but more importantly it's an rvalue (informally, it's a temporary). This means that dec... |
5,874,824 | 5,874,938 | Removing ..'s in boost filesystem::complete | This should be simple: I'm composing an absolute path with boost filesystem, however it's returning a really ugly path:
D:/Projects/SomeDir/vc10/../resource/plugins/SomeFile.dll
Is there a boost way of automatically handling .'s and ..'s?
All I'm doing is:
boost::filesystem::complete("../resource/plugins/SomeFile.dll"... | boost::filesystem::complete("../resource/plugins/SomeFile.dll").normalize()
|
5,875,041 | 5,875,882 | How can I get IntPtr pointer from object | I'm working on a finger-print device, the manufacture (Upek) gave me a c++ BSAPI.dll so I need to use wrappers to get this to work in .net.
I'm able to work with it all from in-memory, I could grab and match the finger prints.
Now I'm stuck trying to get the data out to a file and then loading it back in to memory and ... | Here is C# code I got (I think from the BIOAPI sample code) a long time ago to interface with BioAPI. The DoMarshall method returns an IntPtr pointing to allocated memory large enough to hold the array.
I have not worked with Managed C++, so I am not sure what changes are needed, but maybe it will point you in the... |
5,875,125 | 5,875,220 | Logger Not Storing Recorded Information to File After a Crash | Well, what good is a logger if it only keeps a record when things go well?
It is a very simple thing, the logger, that I wanted to test before I expanded it:
// Logger.h
class Logger : boost::noncopyable
{
public:
static void write(std::string const& msg, int line, std::string const& file);
private:
Logger... | Depends on when it crashes, I would say. If it's during the log output, all bets are off.
First I would make sure that the log output gets flushed after every invocation, so I'd use std::endl instead of \n in write(). You'd also have to verify that this would indeed be sufficient or if you have to take additional steps... |
5,875,320 | 5,875,329 | How do I express the Delphi operator "<>" in c++? | I have had a tough time translating some Delphi code into c++. the code is :
if (GetWindowlong(Stringgrid1.Handle, GWL_STYLE) and WS_VSCROLL) <> 0
then ShowMessage('Vertical scrollbar is visible!');
Ive never really used Delphi before so im not sure what the "<>" operator is. I looked it up and found out that its call... | <> is just not-equals (similar to VB, for some silly reason). C++ uses != for pointer inequality like any other inequality.
|
5,875,323 | 5,875,372 | C++ STL: Using derived virtual class as "Strict Weak Ordering" for std::sort() | I hit a wall using std::sort(). I have a pure virtual class (named Compare) that the caller of a method derives from (named MyComp). I use the pure virtual class for my API's prototype:
void Object::DoSort(Compare &comp) {
std::sort(this->mKeys.begin(),this->mKeys.end(), comp);
}
the caller:
class MyComp: public C... | std::sort (and other STL functions) take comparator objects by value, so your object is being copied, but the derived part (including its vtbl) is being "sliced away".
You could wrap your object in a proxy:
class Proxy
{
private:
Compare &cmp;
public:
Proxy(Compare &cmp) : cmp(cmp) {}
bool operator()(const ... |
5,875,729 | 5,875,908 | Execute an external executable within the same process space in C++ | I'm trying to find an easy way to execute a java vm in windows using a C++ wrapper. I can use CreateProcess() to launch java.exe directly with all of my parameters that I need to give it. The problem is this now shows up as two processes in process manager. So, if I kill the parent process, the java.exe instance still ... | You can replace java.exe with your own executable. This article from the Java Glossary discusses how java.exe works and where to find the source for it. It's possible that you could get by simply by copying and then renaming java.exe
|
5,875,778 | 5,878,207 | Execute RDMSR and WRMSR instructions from C/C++ code | I need to control C-State configuration. Specifically, I'd probably like to execute the following asm code:
__asm
{
rdmsr
and eax, 0x00
or eax, 0x01
wrmsr
}
Currently, I got this exception on rdmsr line:
Unhandled exception at 0x00e3139e in MessWithCStates.exe: 0xC0000096: Privileged instruction.
How c... | Chances are, you are running this code on an x86 processor within Ring 3. You do not have the privileges to execute this command. Period. This is a hardware limitation. The only way to execute that instruction is to go into Ring 0 and chances are, your OS won't let you do that. You will need to write a kernel-mode driv... |
5,875,909 | 5,877,041 | Is there an open source for free tool for MS Visual C++ Express to build using gcc? | While the Microsoft compiler typically builds faster code, I'm in an environment where building Linux applications with gcc is required. I prefer MSVS and the Express versions as my IDE and have been able to configure it such that Intellisense and all the other nice features are working. However, I have been unable to ... | Try CMake: http://www.cmake.org/. It is a cross-platform, cross-ide build system. It will generate
VS project for you, and ordinary makefiles (or eclipse, or what you need).
Then, use VS to edit the code, and "make" to build it. I did it myself to develop windows + linux on virtual machine. And it worked fine.
|
5,876,136 | 5,876,243 | Why Pointers to Undefined Structs are Sometimes Illegal in C and C++ | Why is
void foo(T*);
illegal in both C and C++ (because T is undefined), whereas
void foo(struct T*);
is valid, even though it still does not define T? Is there any situation in which it makes a semantic difference to the caller whether T is a struct or some other type (class/enum/typedef/etc.)?
| In C, because pointer to structs (any struct) all have the same width and alignment properties
6.2.5/27 (C99 Standard)
A pointer to void shall have the same representation
and alignment requirements as a pointer to a character type.
Similarly, pointers to qualified or unqualified versions of
... |
5,876,295 | 5,876,305 | why does pointer get its previous value returning from a function | guys how does the ptr get its previous value? code is simple, I just wondered why it doesn't store the address value that it's been assigned within the function.
#include<stdio.h>
#include<stdlib.h>
void test(int*);
int main( )
{
int temp;
int*ptr;
temp=3;
ptr = &temp;
test(ptr);
printf("\n... | You passed the pointer by value.
The pointer inside test is a copy of the pointer inside main. Any changes made to the copy do not affect the original.
This is potentially confusing because, by using an int*, you're passing a handle ("reference", though actually a reference is a separate thing that exists in C++) to an... |
5,876,312 | 5,880,760 | Simple and Fast Video Encoding/Decoding | I need a simple and fast video codec with alpha support as an alternative to Quicktime Animation which has horrible compression rates for regular video.
Since I haven't found any good open-source encoder/decoder with alpha support, I have been trying to write my own (with inspiration from huff-yuv).
My strategy is the ... | You want to try a Golomb Code instead of a Huffman Code. A golomb code is IMO faster to decode then a huffman code. If it doesn't have to be loseless you want to use a hilbert curve and a DCT and then a Golomb Code. You want to subdivide the frames with a space-filling curve. IMO a continous subdivision of a frame with... |
5,876,516 | 5,876,957 | Using Open CV Iterators segfault | I want to do something like eigenfaces but with different images (not faces). I have a vector of images, images. From these images, I want to make a Mat object, data which contains in each row, a image written out as a row vector. This is what I tried to do:
// This is basically a matrix that needs to have a bunch of i... | I think that in your matrix each field has 1 byte (CV_8UC1), but you iterator is "unsigned short" iterator. Unsigned short usually has 2 bytes. change it to
data.begin<unsigned char> ()
also check stdint.h: http://en.wikipedia.org/wiki/Stdint.h
|
5,876,576 | 5,876,659 | Variable renaming for plagiarism detection for C/C++ | I have a couple of simple C++ homeworks and I know the students shared code. These are smart students and they know how to cheat moss. I'm looking for a tool that can rename variables based on their types (first variable of type int will be int1, first int array will be intptr1...), or does something similar that I can... | Yep, the tool you're looking for is called a compiler. :)
Seriously, if the programs submitted are exactly the same except for the identifier names, compiling then (without debugging info) should result in exactly the same output.
If you do this with debugging turned on, the compiler may leave meta-data in the executab... |
5,876,722 | 5,877,289 | pion::net HTTPServer persistent connections | I'm working on a low-latency high-throughput, minimalistic HTTP server (almost real-time message switch).
I'm very fond of pion::net, and I've seen numerous references that it supports persistent connections (thus potentially saving the whole TCP ordeal):
http://boost.2283326.n4.nabble.com/Boost-HTTP-td2637928.html
Cou... | Persistence is a property of TCPConnection (see the setLifecycle method). So if you choose to go the WebServer / Webservice route set the Lifecycle property accordingly in WebService::operator().
Also, since you're talking HTTP you should set the connection persistence according to the info the client sends you (namely... |
5,876,844 | 5,876,898 | Why are function declaration mandatory in C++ and not in C? | So one of my previous exams had this question, and till now I've been reading that you don't need a declaration in any of the languages?
Which is right? Will C++ give an error if there's no declaration, or will it run?
| In a discussion that involves both C and C++ "function declaration" is a rather vague term. These languages are significantly different in this regard.
In C++ language there's only one kind of function declaration: declaration with all parameter types and return type. Such declarations are necessary because C++ languag... |
5,876,914 | 5,878,071 | C++ access modifier auto indentation in Visual Studio 2010 slowly driving me crazy - can it be changed? | When programming C++ in Visual Studio, it insists on giving me these awful indentations on access modifiers - my condolences if anyone actually likes them this way ;) (a joke folks!)
public class MyClass
{
public:
MyClass();
~MyClass();
int wowAnInt();
}
Needless to say, I want this:
public class MyClass
{
... | The closest you can get with the built-in Visual Studio editor settings is to change the indenting mode from "Smart" to "Block" (Tools -> Options -> Text Editor -> C/C++ -> Tabs -> Indenting).
When you do this, you can indent anything however you like, you just lose the "automatic indenting." Basically, whenever you... |
5,877,194 | 5,878,514 | Win32 scrollbar "slop distance" constant? | On Windows, when you use the mouse to click and drag in a scrollbar to scroll it up and down, you can move the mouse approximately ~120 pixels away from the scrollbar before the dragging stops working. (By contrast, on the mac you appear to be able to move it anywhere on the screen and the drag will still happen.)
Is t... | GetSystemMetrics has a lot of these values. However, there is no Windows API that retrieves this value.
As an aside, you should think carefully before simulating a control. There is a lot more code to implementing the control correctly (including support for accessibility, keyboarding and other behaviours) that will t... |
5,877,267 | 5,877,781 | How to extract strings from a c++ string using regex | I'm using regex by using #include <regex.h> If I have a string s, how can I use regex to search for a pattern p?
| #include <regex.h>
#include <iostream>
#include <string>
std::string
match(const char *string, char *pattern)
{
// Adapted from:
http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html
int status;
regex_t re;
regmatch_t rm;
if (regcomp(&re, pattern, REG_EXTENDED) != 0) {
... |
5,877,287 | 5,877,300 | Can someone explain this C++ comma operator short-circuiting example? | Can someone explain this C++ comma operator short-circuiting example?
bIsTRUE = true, false, true;
bIsFALSE = (true, false), true;
bIsAlsoTRUE = ((true, false), true);
Why does the second version short-circuit and return false (at least in MSVC++) and the other two versions do not but return true?
| The comma operator has lower precedence than assignment, so these are parsed as
(bIsTRUE = true), false, true;
(bIsFALSE = (true, false)), true;
(bIsAlsoTRUE = ((true, false), true));
The comma operator does not short-circuit. It evaluates its left operand, ignores the result, then evaluates its right... |
5,877,420 | 5,877,461 | c++ cin input not working? | #include <iostream>
#include <string>
struct Car{
std::string model;
unsigned int year;
};
int main(){
using namespace std;
int carNum;
cout << "How many cars do you wish you catalog? ";
cin >> carNum;
Car * cars = new Car[carNum];
for (int i=0;i<carNum;i++){
cout << "Car #" ... | Simple reason.
When you do cin >> whatever, a \n is left behind (it was added when you pressed Enter). By default, getline reads until the next \n, so the next read will simply read an empty string.
The solution is to discard that \n. You can do it by putting this:
cin.ignore(numeric_limits<streamsize>::max(),'\n');
J... |
5,877,504 | 5,877,526 | Access c++ queue elements like an array | Can queue elements be accessed like an array? If not, then what containers similar to a queue can?
| This is a task ideal for std::deque. Its optimized for adding/removing onto the end but also provides random access to elements in the middle. To quote the linked article:
A deque is very much like a
vector: like vector, it is a sequence
that supports random access to
elements, constant time insertion and
remo... |
5,877,530 | 5,878,492 | Qt C++: Static list of font families | This may be more a general C++ programming question than Qt specific. The problem I'm having is with static members and initializing them.
I have a table model class which inherits QAbstractTableModel and I want each to have a list of all system font families using QFontDatabase::families(). I'm trying to make this l... | Non-trivial initialization of static variables is typically problematic. The functions you call for the initialization may depend on resources that are not initialized yet at the time. And you have no control on the order of what static is initialized first.
Using constructor is not a bad idea. You just have to make su... |
5,877,575 | 5,878,560 | A way for c++ code to access records from the UniVerse database? | I know there is some kind of connection between .NET and UniVerse, by using UniObjects. But I believe that obligates use of .NET, and C# or VB.NET.
Also, I know by reading UniVerse manual that UniVerse can call C/C++ code from within UniVerse, but what I want is the other way around.
Can UniObjects be used for c++ pro... | Yes, although you have to hunt for it.
On the U2 DevZone site Rocket Software has just launched, there is an article about writing a PDO Driver for PHP access. This driver is written in C (iirc) and has all the source code supplied. It uses the U2 InterCall to interact with the U2 system (UniVerse & UniData). You shoul... |
5,877,779 | 5,877,814 | c++: logger class without globals or singletons or passing it to every method | Does anyone knows if it's possible to have a class like a logger without :
using a singleton or a global (a la std::cout)
passing an instance/pointer/reference to every method which needs it
I take the example of a logger class, but I have a few classes in my application which would benefit from this (for example, t... | I would imagine you could do something similar to what is done in Java with the Log4j package (and is probably done with the Log4c version of it):
Have a static method which can return multiple logger instances:
Logger someLogger = Logger.getLogger("logger.name");
The getLogger() method isn't returning a singleton obj... |
5,877,918 | 5,878,230 | In c++, not waiting doesn't mean running in the background? | In my c++ program, I try to run programs in the background by simply not waiting for them.
However in Linux, if I start vi in the background like this: vi &, then vi doesn't show up. In my program, vi will still pop up even if I don't wait for it to terminate.
So does that mean that I'm not really running it in the bac... | What's going on here is rather complicated (for more information than you probably require, see glibc's manual section on job control) but the short version is: Only the foreground process group can access the terminal. Any other process gets automatically ^Zed by the kernel if it tries to access the terminal.
When yo... |
5,877,960 | 5,877,985 | Testing for a space character inside a string...? | I'm trying to test if a character in a string is a space, and I'm getting extremely frustrated:
string my_string;
cin >> my_string;
for (int i = 0; i < my_string.length(); i++)
{
if (my_string[i] == ' ') // this never becomes true...
{
cout << "this text should pop, but never does" << en... | when you say
cin >> my_string;
you are taking formatted input. std::cin discards any whitespace in that line, and it reads up to and yields only a single word.
try instead
std::string my_string;
std::getline(std::cin, my_string);
to get a single line, or
#include <iterator>
// ...
std::string my_string((std::istream... |
5,878,052 | 5,878,850 | Does using ignore(numeric_limits<streamsize>::max()) in the IOStreams library handle arbitrarily massive streams? | In the C++ standard (section 27.6.1.3\24), for the
istream ignore() function in the IOStreams library, it implies that if you supply an argument for 'n' of numeric_limits::max(), it will continue to ignore characters
forever up until the delimiter is found, even way beyond the actual
max value for streamsize (i.e. the ... | The standard says that numeric_limits<streamsize>::max() is a special value that doesn't affect the number of characters skipped.
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, extracts characters and discards them. Characters are extracte... |
5,878,364 | 5,878,747 | Is there any problem with this code? | #include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
cout << "Hello.";
ifstream attack,output;
attack.open("CattackList");
output.open("finaltestOutput.txt");
if (!attack)
cout << "file1 not opened.\n";
if (!output)
cout << "file2 not open... | Let's see...
#include<iostream>
#include<fstream>
#include<cstring>
Please put a space after each #include.
if (!attack)
cout << "file1 not opened.\n";
if (!output)
cout << "file2 not opened.\n";
Error messages should go to cerr, not cout.
char buf1[100],buf2[100];
attack.getline(buf1,100);
Did you allow spa... |
5,878,369 | 5,880,248 | c++/c# Marshal a struct to get a fixed pointer | I have an older app which accepts dll plugins. Each plugin has a function that creates a new instance of a "widget". This function identifies the new "widget" instance by returning a unique int. In the c++ plugin template I have it's done by declaring a new widget struct and returning its pointer cast as an int as a un... | You seem to imply that the returned integer identifier is just a cookie, and isn't treated by the app as a pointer. That would mean that the app never performs operations on the widget, but always asks the plugin to perform the operations on the app's behalf. If that's the case then there's no reason why you can't use ... |
5,878,415 | 5,879,247 | how to add a new compiler switch in bjam | I need to compile a library in managed c++ and looking into msvc.jam, I cannot find any feature that would add the /clr switch to my compile flags.
How would I add such a feature?
If possible, I would like to avoid modifying msvc.jam.
| The makefile macro you want for compiler flags is CXXFLAGS, and its equivalent on the bjam command line is cxxflags (lower case):
bjam toolset=msvc cxxflags=/clr
|
5,878,424 | 5,878,468 | Composition of template class | I have a template class:
template<typename A, typename B>
class A {
};
In another .h file
template<typename A, typename B>
class A; //forward declaration
How could I declare m_A over here? I keep getting C++ forbids declaration of A with no type error:
class B {
A* m_A;
};
| If you don't know the types that you want to instantiate A with when inside of B, then you will have to also make a template out of B
template<typename A1, typename B1>
class B
{
A<A1, B1>* m_A;
};
Either that, or you would have to instantiate A as a specific type, i.e.,
class B
{
A<Type_1, Type_2>* m_A;
};
|
5,878,522 | 5,888,615 | QT overview/tutorial? | Does anyone know of any good tutorials/articles which give a broad overview of QT? I'm not looking for a verbose "type this in and this is what it does" kind of tutorial (e.g. Nokia's/Troll Tech's tutorials, I can look at the api docs up for this stuff), but rather something which explains the thought process and consi... | I recommend reading the following conceptual documents from the Qt Documentation itself:
The Core
Object Model presents the why and how Qt extends the plain C++ object model with the metaobject compiler and what features it adds.
Object Trees and Ownership illustrates the preferred way of managing dynamically allocate... |
5,878,545 | 5,878,613 | Unmanaged C++ COM and Managed C++ .NET4 interop | I have an ATL COM service which I can connect to via my Windows Forms Application .NET4 application, written for the most part in managed c++.
I can successfully retrieve a pointer to the interface (via CoCreateInstance()), but run into issues when attempting to implement an event sink. I wish to create an unmanaged c+... | In your managed C++ application add a reference to the COM server using "Add reference" option, this will create a managed wrapper (assembly) for your COM component which you will be able to consume in your "managed c++ code". The events in your COM component should be available as .NET events which can be handled usin... |
5,878,573 | 5,878,598 | C++ header confusion | So in the down time before summer semester, I'm trying to learn a little C++ on my own. I'm working through a book, but not using the compiler provided. Instead, I'm using MinGW. The problem I've encountered is that the headers the two compilers need appear to be somewhat different. For example, where the text uses
#i... | You better read the MinGW documentation and samples. String manipulation can be a bit different from one compiler to other.
You can also install visual studio express, it's free.
|
5,878,775 | 5,878,802 | How to find and replace string? | If s is a std::string, then is there a function like the following?
s.replace("text to replace", "new text");
| Replace first match
Use a combination of std::string::find and std::string::replace.
Find the first match:
std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);
Replace the first match:
s.replace(pos, toReplace.length(), "new text");
A simple function for your convenience:
void rep... |
5,878,907 | 5,880,038 | Using an unordered_map of unordered_sets | If I have an unordered map of unordered_sets indexed by strings, such as
static boost::unordered_map<std::string, boost::unordered_set<std::string> > UseMap;
I had a couple question about using this data structure. Is there anyway for me to insert a new value into the set indexed in the map without having to use a po... | First question, yes, it should be fine as long as you assign the result to a reference.
Do this:
boost::unordered_set<std::string>& set = UseMap[character];
Now set is a reference to a value in the map. (I'm not sure what auto gives you, so I put the type in full; you may be able to get away with using auto.) Any chan... |
5,878,957 | 5,879,012 | value of allocated array not initialized | If I have:
int array[20];
What is the value of array[0] if nothing has been initialized there yet? Is there a way to check if it has been initialized?
| "...suppose I have..." You have it where?
If you have something like this in namespace scope, then it is an object with static storage duration, which is always zero-initialized.
If you have something like this in local scope, then it is an object with automatic storage duration, which is not initialized at all. The v... |
5,879,805 | 5,881,306 | CMake write header file using GLOB result | I have a GLOB expression such as:
file( GLOB HEADER_FILES path/*.h )
And would like to generate a header file that contains a definition for each HEADER_FILES entry. For example, if the file is called "path/my_class.h" then the macro should be:
#define PATH_MY_CLASS_FILE /full/path/to/path/my_class.h
This can be easi... | Try something like this:
file(GLOB HEADER_FILES path/*.h)
foreach(header ${HEADERS_FILES})
# here replace / for linux and \ for windows
string(REPLACE "/" "_" header_path header)
string(TOUPPER header_path final_header_path)
file(APPEND headers_defines_file define
PATH_${final_header_path} ${CMAKE_CURREN... |
5,880,065 | 5,880,129 | Problem with global template function | For some reason I can't seem to call my global template function in GCC...
Global function defined in "globals.h":
template <typename T1, typename T2> inline T1 Min (const T1 & v1, const T2 & v2)
{
return v1 < v2 ? v1 : v2;
}
Call to function from class defined in "test.h":
#include "globals.h"
class Test
{
publi... | g++ version 4.3.4 compiles these correctly, giving an error only for the last line. See http://ideone.com/cD13Y. What version are you using?
|
5,880,173 | 5,880,234 | How to send Return/Enter character to the Console using WriteConsoleInput/WriteConsole | I have the following piece of code. I want to send the command "uci" and then Return/Enter to the console. However, I got no success doing so. Please kindly advise. Thank you!
#include <conio.h>
#include <iostream>
#include <windows.h>
DWORD WINAPI test(LPVOID lp)
{
system("edit");
return 0;
}
int main(int a... | \n is a reserved key code; use VK_RETURN instead.
From https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
|
5,880,345 | 5,880,920 | How can I accept multiple data types into my input stream? | template< typename T >
void somefunction()
{
T value;
cout << " value = ";
cin >> value;
}
Now this seems a bit weird but can we have a function template that accepts multiple
datatypes( say float and int).
| In case you wish to restrict the template function, your best bet is to use specialization. Create a generic method which does nothing, or asserts/throws exception, but with specialized implementations for precisely your types. Something like,
template< typename T >
void somefunction()
{
std::cerr << "Not implement... |
5,880,539 | 5,880,604 | Programming in VC++ to run outside Windows | I had the following question about programming in VC++ 2008
If I make a Win32 Console Program in Windows 7 will it work in any Windows below 7?
Can I make a C++ Application independent of the .NET Framework? If yes, please brief me on how to do it.
Can I make applications in VC++ to be run on other operating systems l... | 1> Depends: if don't use any Windows 7 specific API, you will have no problems running the program on Windows Vista; if you don't use any Vista specifica API you will have no problem running it on XP, etc.
2> Sure, you just need to make a native only project instead of a C++/CLI one
3> You will need an emulator like "w... |
5,880,715 | 5,880,750 | error C2436 member function or nested class in constructor initializer list | I have a function pointer declared in my header, like this:
typedef void (intCB)(int );
and I have a class member declared like this:
private:
intCB m_intCB;
In my constructor's initialization list I want to initialize it with 0:
MyClass::MyClass : m_intCB(0)
{
#ifdef SOMETHING
m_intCB = &someOtherFunc;
#e... | That's not a function pointer, you are missing a *. Try:
typedef void (*intCB)(int);
|
5,881,243 | 5,881,406 | XML or CSV for "Tabular Data" | I have "Tabular Data" to be sent from server to client --- I am analyzing should I be going for CSV kind of formate or XML.
The data which I send can be in MB's, server will be streaming it and client will read it line by line to start paring the output as it gets (client can't wait for all data to come).
As per my pre... | I would use CSV, with a header which indicate the id of each field.
id, surname, givenname, phone-number
0, Doe, John, 555-937-911
1, Doe, Jane, 555-937-911
As long as you do not forget the header, you should be fine if the data format ever changes. Of course the client need be updated before the server starts sending... |
5,881,533 | 5,885,711 | Huge static library file when compiled using VS2005, normal size when compiled using gcc | I'm compiling a static library that contains mainly templated classes. When this is compiled using gcc, the resulting .a file is around about the 40Mb mark. This is pretty big, but not entirely unexpected due to the amount of templating going on. However, when I compile the same code using VS2005, the resulting .lib fi... | A debug build disables inlining and also the linker options that discard duplicate code, so you get lots of copies of every template and inline function.
You can enable it with /OPT:REF /OPT:ICF in your linker options. But it should be there by default in a release build.
Unfortunately I think that only helps with your... |
5,882,139 | 5,883,016 | How to increase character limit in MFC static control | We are using MFC static control in a dialog box to display some content to user. Both static control and dialog box are defined in a resource file (.rc) as LTEXT and DIALOG. Problem is if content is more than 256 character, it gets truncated. Does anyone know how can this limit be increased. The control and dialog box ... |
You can vote for this problem here. Don't expect miracles, the resource compiler is neolithic. You'll have to work around it by using more than one static control or setting the text at runtime in the WM_INITDIALOG message handler. Don't overestimate the user's patience.
|
5,882,156 | 5,882,190 | Why does this small C++ program not compile using G++? | The following code will not compile with G++ 4.5 or 4.6 (snapshot). It will compile with the Digital Mars Compiler 8.42n.
template <int I>
struct Foo {
template <int J>
void bar(int x) {}
};
template <int I>
void test()
{
Foo<I> a;
a.bar<8>(9);
};
int main(int argc, char *argv[]) {
test<0>();
return 0;
}... | Since the bar in a.bar is a dependent name, the compiler doesn’t know that it’s a template. You need to specify this, otherwise the compiler interprets the subsequent <…> as binary comparison operators:
a.template bar<8>(9);
The compiler behaves correctly.
The reason for this behaviour lies in specialisation. Imagine ... |
5,882,331 | 5,882,455 | Can calls to memory allocation and constructor be interleaved with other operations required to perform a "new" expression? | Suppose I have a following class:
class Sample {
public:
Sample( int ) {}
};
some function returning an int
int SomeFunction()
{
return 0;
}
and this code:
Sample* sample = new Sample( SomeFunction() );
Now I expect the following sequence:
SomeFunction() is run, then
::operator new() is run to allocate ... | The order is unspecified. [5.3.4]/21 reads:
Whether [operator new] is called
before evaluating the constructor
arguments or after evaluating the
constructor arguments but before
entering the constructor is
unspecified. It is also unspecified
whether the arguments to a constructor
are evaluated if [operat... |
5,882,772 | 5,882,800 | String going crazy if I don't give it a little extra room. Can anyone explain what is happening here? | First, I'd like to say that I'm new to C / C++, I'm originally a PHP developer so I am bred to abuse variables any way I like 'em.
C is a strict country, compilers don't like me here very much, I am used to breaking the rules to get things done.
Anyway, this is my simple piece of code:
char IP[15] = "192.168.2.1";
char... | That's because you get a not null-terminated string when separator length is forced to 2.
Always remember to allocate an extra character for the null terminator. For a string of length N you need N+1 characters.
Once you violate this requirement any code that expects null-terminated strings (puts() function included) w... |
5,882,787 | 5,883,383 | Loading and painting bmp win32api c++ | i am trying to show a bmp in the screen using this code: (this code is from a book but i cant show the windows when i compile only appear the white window)
#include "resource2.h"
#include <vector>
#include <windows.h>
using namespace std;
HWND window1;
HWND window2;
HINSTANCE happ;
HDC handledevice;
PAINTSTRUCT ps;
H... | Have a look at this example here
http://www.functionx.com/win32/Lesson13.htm
bmhdc=CreateCompatibleDC(handledevice);
IN WinMain you're using handledevice - which isn't yet initialised, so selecting the bitmap would cause problems, but it's probably 0, so it would use the desktop DC. Usually I wouldn't do this in WinMa... |
5,882,872 | 5,882,896 | Reading a full line of input | I'm trying to store the input that user enters through console. so I need to include the "enter" and any white space.
But cin stops giving me input after the first space.
Is there a way to read whole lines until CTRL+Z is pressed, or something?
|
is there a way like readLines till CTRL+Z is pressed or something ??
Yes, precisely like this, using the free std::getline function (not the istream method of the same name!):
string line;
while (getline(cin, line)) {
// do something with the line
}
This will read lines (including whitespace, but without ending... |
5,882,993 | 5,883,056 | Define Custom (STL-compatible) Iterator where Value Type is not CopyConstuctible or Assignable | I wish to define a custom iterator which uses a value type that can not be copied.
The rationale for this is that the iterator will be responsible for module enumeration under Windows, and I'm using the CreateToolhelp32Snapshot/Module32First/Module32Next APIs to avoid having to preprocess the entire module list (e.g. E... | If you tag your iterator as an InputIterator rather than a ForwardIterator, then the behavior you describe is not unexpected. Incrementing an InputIterator invalidates copies of it, so it doesn't matter what they appear to point to after that.
You can use it with standard algorithms that accept an InputIterator, which ... |
5,883,073 | 5,883,529 | Button held down by code | I am writing a game and am trying to make a person move with the arrow keys.
I have this code
if (Key_Down(DIK_DOWN))
{movedown(player)}
This works but as I want the player to take four steps every time the key is pressed I created and animation loop. so the player cannot input any more move commands until the animati... | Simply keep track of the keystate in a variable. So you can reset a move counter. Something like this, combining both:
int MovingDown = 0;
...
if (!Key_Down(DIK_DOWN)) MovingDown = 0;
else if (MovingDown < 4) {
MovingDown++;
movedown(player);
}
|
5,883,414 | 5,885,678 | Why is my child window unresponsive to mouse events? | I have created a customized static window which displays a bitmap image, this window is the child window of some other window. Now I want to capture mouse events for this window, so that I can provide functionality to crop the image.
But the problem is Mouse events are not passed to this child window....
following is ... | The window class that you use for the window will determine certain default behaviors for the window. The Static window class is particularly difficult to work with, because Windows makes assumptions that the window will never change its contents, and won't interact with the user in any way. You'll probably find that t... |
5,883,462 | 5,883,503 | Linux CreateProcess? | I developing on the Linux platform.
I want to create a new proccess in my library without replacing the current executing image.
Because I am developing a library, I don't have a main function.
And I want to continue the new process after the invoker application closes (Just like CreateProcess Windows API).
Is it possi... | posix_spawn is probably the preferred solution these days.
Before that fork() and then execXX() was the way to do this (where execXX is one of the exec family of functions, including execl, execlp, execle, execv, execvp, and execvpe). In the GNU C library currently, at least for Linux, posix_spawn is implemented via fo... |
5,883,711 | 5,885,050 | Factory pattern, implementing a dynamic list of factories | I'm implementing an abstract factory pattern (in c++), but there is a slight problem.
I'd like to avoid creating a place which must know at compile time what factories exist.
Usually in the examples I see something like this.
Factory * getFactory()
{
if(/*we should make factoryA*/)
{
return FactoryA::in... | Somthing Simple:
class BaseFactory
{
public:
BaseFactory()
{
std::list<BaseFactory*>& fList = getFactoryList();
fList.push_back(this);
// If you are feeling brave.
// Write the destructor to remove the object from the list.
//
// No... |
5,884,465 | 5,885,697 | boost::program_options config file option with multiple tokens | I can not seem to be able to read from config file multitoken options like I can from command line. What is the syntax for the config file?
This is how the option description is added:
//parser.cpp
- - -
po::options_description* generic;
generic=new po::options_description("Generic options");
generic->add_options()
("c... | You can achieve the behavior you seek by writing a custom validator. This custom validator accepts :
./progname --coordinate 1 2
./progname --coordinate "1 2"
#In config file:
coordinate= 1 2
Here is the code:
struct coordinate {
double x,y;
};
void validate(boost::any& v,
const vector<string>& values,
coordina... |
5,885,114 | 5,886,521 | How to play a sound instantly after another sound ended? | I cant ensure this by checking if the sound has stopped in my program because the sounds are handled in different thread, isnt that right?
So the problem comes when i want to be 100% sure that once a sound has stopped from playing, another sound would start instantly after it with no possibility for any delay.
The seco... | I am not aware of any function in OpenAL that would let you do such a thing direcly, e.g. by blocking or notifying you, so gapless playback in a way as you said would be possible. Any solution like "sleep for the duration of the first sound, then start the second" is bound to fail, because sleep is not reliable. Checki... |
5,885,338 | 5,885,379 | Does this model need a mutex? | I'm designing a program with a server that let's two clients communicate. There's one client that executes commands and another that makes the other client execute them.
To make this work, I have two threads: one thread for the controlled-client, another for the controller-client.
The controlled-client always stays con... | Yes, this needs a mutex.
vector.pop_front() and vector.push_back() executing at the same time would create all sorts of mess - assuming the nonstandard vector.pop_front() does what the name implies.
Side note: use a queue or a list rather than a vector
|
5,885,348 | 5,885,571 | Modulo based load balancing without a mutex? | I might be going about this all wrong, but here's my problem and proposed solution:
You have a 50+ gigabyte file with hundreds of millions of independent records that need to be processed very quickly. My current solution is getting 74 million records / hour. I'm using a blocking queue for the I/O thread, and each wo... | Rather than using a blocking queue and having the worker threads pull from it, give each thread it's own queue and have the I/O thread push batches of work into each thread's queue.
A circular queue would be very good for this, assuming you don't mind taking the extra effort to implement some way to keep track of how ... |
5,885,598 | 5,885,829 | C++ templates problem | I'm trying to develop 2 classes, Node and Connection, but I don't have experience in C++ or C++ templates.
The Node contains a list of connections and a Connection contains 2 nodes.
So I suppose that a node has a template parameter that specifies which type of connections are in the list and that a connection has a t... | Assuming that you want different types of Nodes, but that Connections are nothing but a link between two Nodes (that is, that you don't need to do any specialisation on the Connections) then you could do something like:
template <class Node>
class Connection
{
Node& node1;
Node& node2;
};
template <class Node>... |
5,885,634 | 5,885,679 | create new instance of a class without "new" operator | Just a simple question. As the title suggests, I've only used the "new" operator to create new instances of a class, so I was wondering what the other method was and how to correctly use it.
| You can also have automatic instances of your class, that doesn't use new, as:
class A{};
//automatic
A a;
//using new
A *pA = new A();
//using malloc and placement-new
A *pA = (A*)malloc(sizeof(A));
pA = new (pA) A();
//using ONLY placement-new
char memory[sizeof(A)];
A *pA = new (memory) A();
The l... |
5,885,723 | 5,885,790 | A simpler form of pimpl | Why not choose this design :
// A.hpp
class A
{
public:
void do_something();
};
// A.cpp
#include "A.hpp"
#include <vector>
std::vector<int> impl_database_for_do_something;
static void impl_helper_for_do_something(const std::vector<int>& database){}
void A::do_something(){ impl_helper_for_do_something(impl_data... | If you use global vectors to store state as you propose, you will somehow have to make sure that different instances of class A use different parts of the vector (besides the obvious difficulties of doing so, consider how much harder this gets if different threads use different instances of A). This design only makes v... |
5,885,982 | 5,886,040 | Polymorphism makes function inaccessible | I have a map of Shopables which has things in it that were initialised like this:
Shopable* something = new Consumable();
Consumable has a function Heal, but Shopable doesn't. I need the map to stay as a Shopable map for some function parameter, but when I try and do:
consumables[itemName]->Heal(this);
in another fun... | Either dynamic_cast, or create a virtual dummy Heal under Shopable.
Consumable *con = dynamic_cast<Consumable*>(consumables[itemName]);
if(con)
con->Heal();
//else this shopable is not really a consumable
Alternatively, create a virtual function called Heal() under Shopable, with nothing in it. Or with a debugger ... |
5,886,062 | 5,886,096 | c++: how to read from and write to a folder | I've found tons of examples on file IO, but nothing with folders?
anyone have a quick example?
Note: I'm on *.nix
| You shouldn't be reading and writing to folders - that's the file system's job. If you want to read a directory, take a look at opendir and friends.
|
5,886,112 | 5,886,203 | C++ I have two questions | Please help me with my homework:
There is an array a [20] of float numbers, Enter number
in the array. Find the sum of negative number.
Enter 10 integer numbers in the array a [10]. Find the
sum of positive numbers.
| General psuedo-code to get you in the right direction for finding the sum of positive numbers in the array:
float result = 0;
for(int i = 0; i < array_length; i++)
{
if(array[i] > 0)
result = result + array[i];
}
For the sum of negative numbers, just switch the if-statement. Of course, this isn't exactly C++ cod... |
5,886,156 | 5,889,439 | How to print format string into a window? | A window handle HWND hwnd has already been available, now I want to print a format string
into a window described by this hwnd. I am not familiar with Windows API, Thanks very much for your help.
For example:
num = 23;
printFunction(hwnd, "number is %d", num);
Is there a function to solve this problem? Thank you!
UPD... | sprintf(myString, "number is %d", num);
SendMessage(hwnd, WM_SETTEXT, NULL, (LPARAM)myString);
|
5,886,536 | 5,886,662 | Why is including a header file such an evil thing? | I have seen many explanations on when to use forward declarations over including header files, but few of them go into why it is important to do so. Some of the reasons I have seen include the following:
compilation speed
reducing complexity of header file management
removing cyclic dependencies
Coming from a .net ... | "to master forward declarations" is not a requirement, it's a useful guideline where possible.
When a header is included, and it pulls in more headers, and yet more, the compiler has to do a lot of work processing a single translation module.
You can see how much, for example, with gcc -E:
A single #include <iostream> ... |
5,886,628 | 5,908,734 | Efficient way to draw Ellipse with OpenGL or D3D | There is a fast way to draw circle like this
void DrawCircle(float cx, float cy, float r, int num_segments)
{
float theta = 2 * 3.1415926 / float(num_segments);
float c = cosf(theta);//precalculate the sine and cosine
float s = sinf(theta);
float t;
float x = r;//we start at angle = 0
float... | There is no way to draw a curve in openGL, just a lot of straight lines. But if you used vertex buffer objects then you won't have to send each vertex to the graphics card which will be much faster.
My Java Example
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.