question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,133,957 | 6,133,987 | Image downsampling algorithms | What's the best re-sampling algorithm I can use to divide an image into half its original size. Speed is of primary importance but it shouldn't degrade quality too bad. I'm basically trying to generate an image pyramid.
I was originally planning to skip pixels. Is this the best way to go? From what I've read the image ... | Skipping pixels will result in aliasing, where high frequency changes (such as alternating light/dark bands) will convert to low frequencies (such as constant light or dark).
The quickest way to downsize to half without aliasing is to average 2x2 pixels into a single pixel. Better results can be had with more sophistic... |
6,134,255 | 6,134,304 | Why additional \r is injected in windows? | #include <iostream>
using namespace std;
int main( int argc, char *argv[])
{
cout << "Hello\nWorld";
}
D:\test>hw |od -c
0000000 H e l l o \r \n W o r l d
0000014
Why additional \r is injected in windows(doesn't happen on linux) ?
| It is a feature of Windows going back to the first days of MS-DOS. In those systems, the convention is that a line delimiter is the character pair "\r\n". Of course, in Linux/Unix/Solaris/etc., the line delimiter is the single character "\n"
There are various utilities, such as Linux's dos2unix and unix2dos which do ... |
6,134,440 | 6,134,584 | Convert char array to a vector with 4-bit elements | I want to use the following code segment
#include <iostream>
#include <iterator>
#include <vector>
#include <bitset>
#include <algorithm>
int _tmain(int argc, _TCHAR* argv[])
{
static const char szBits[] = "110101011010";
std::vector<std::bitset<4> > str(szBits, szBits + sizeof szBits);
std::cop... | std::vector<std::bitset<4> > str(szBits, szBits + sizeof szBits);
That is obviously wrong. It actually creates the vector's item from each char, instead of 4 char together.
This is what you should be doing:
static const char szBits[] = "110101011010";
std::vector<std::bitset<4> > str;
for(size_t i = 0 ; (i + 4) < s... |
6,134,551 | 6,547,563 | What are some resources for Linux developers learning OpenAL Effects Extension (EFX)? | What are some resources for Linux developers learning OpenAL Effects Extension (EFX)? Creative's site and google did not seem to offer much in the way of documentation or tutorials. Any pointers to references are greatly appreciated.
| The only kind of good source that I know is the "Effects Extension Guide" which comes as a PDF with the SDK (no official documentation is available on the internet otherwise, many attempts to find something have been futile, you also cannot download the Effects Extension Guide separately, it's only available with the S... |
6,134,666 | 6,134,873 | Pass BSTR from C++ DLL function to VB6 application | I have this code in my VB6 app:
Private Declare Function FileGetParentFolder Lib "Z-FileIO.dll" _
(ByVal path As String) As String
Output.AddItem FileGetParentFolder(FileText.Text)
Output is a list, FileText is a text field containing a file path. My C++ DLL contains this function:
extern "C" BSTR ZFILEIO_API FileGet... | Hopefully this will point you in the right direction. From memory...
VB6 uses COM BSTRs (2-byte wide character strings) internally, but when communicating with external DLLs it uses single- or multi-byte strings. (Probably UTF-8, but I don't remember for sure.) Your Path typedef to LPCSTR is an ANSI string, and that's ... |
6,134,679 | 6,134,712 | Delaying for milliseconds in C++ cross-platform | I'm writing a multi-platform internal library in C++ that will eventually run on Windows, Linux, MacOS, and an ARM platform, and need a way to sleep for milliseconds at a time.
I have an accurate method for doing this on the ARM platform, but I'm not sure how to do this on the other platforms.
Is there a way to sleep w... | For Linux and Mac OS X you can use usleep:
usleep(350 * 1000);
For Windows you can use Sleep:
Sleep(350);
EDIT: usleep() sleeps for microseconds, not milliseconds, so needs adjusting.
|
6,135,019 | 6,135,039 | C++ Pointer Confusion | Please Explain the following code
#include <iostream>
using namespace std;
int main()
{
const int x = 10;
int * ptr;
ptr = (int *)( &x ); //make the pointer to constant int*
*ptr = 8; //change the value of the constant using the pointer.
//here is the real surprising part
cout... | *ptr = 8;
This line causes undefined behavior because you are modifying the value of a const qualified object. Once you have undefined behavior anything can happen and it is not possible to reason about the behaviour of the program.
|
6,135,033 | 6,135,083 | boost thread move assignment vs. move constructor | The Boost.Thread library specification for the move constructor states for
Move Constructor:
Effects: Transfers ownership of the
thread managed by other (if any) to
the newly constructed boost::thread
instance.
whereas for Move Assignment :
Transfers ownership of the thread
managed by other (if any) to *th... | You're misunderstanding. Label your thread objects A and B, and the actual thread T.
If B owns T, move constructing A from B means A now owns T, and B owns nothing.
If B owns T, move assigning A from B means A now owns T, and B owns nothing, and whatever A had previously owned is not owned by anything (aka, detached). ... |
6,135,115 | 6,135,142 | C++ Protected / Public overloads | I have a class like this :
class Foo
{
public:
Foo()
{
for(int i = 0; i < 10; ++i)
v.push_back(i);
};
const vector<double>& V() const {return v;};
protected:
vector<double>& V() {return v;};
private:
vector<double> v;
};
And then a piece of code like this :
Foo foo;
for(int ... | It is not possible to overload on return value. Non-const method will be used when the object is non-const. It is possible to guide the compiler by:
const vector<double>& test = const_cast<Foo const&>(foo).V();
Or possibly nicer solution is to have the constant method have different name (eg.: ConstV). Or you can just... |
6,135,408 | 6,135,448 | Shall I make every function static, which do not touch the member variable? | What is the Design and Performance impact for making all functions static which do not touch the member variable of the class?
| You should actually consider making them non-static free functions, as explained in detail in this question. This question is also very interesting.
In a nutshell, these question explain that you should prefer non-friend non-member functions whenever possible (meaning when they do not access non-public members).
|
6,135,514 | 6,143,818 | Qt : how to implement QDialog StatusBar | I have QDialog that is heavily designed with QDesigner , I saw on the web that I could add QStatusBar with code like this :
#include <QDialog>
#include <QStatusBar>
#include <QLayout>
#include <QApplication>
#include <QTextEdit>
#include <QStatusTipEvent>
class Dialog : public QDialog {
public:
Dialog() : QDialog(){... | I presume when you say it doesn't work, that you are not seeing the status bar when you run.
I don't see any way to do this wholly in the designer. The designer certainly resists the idea of promoting something to a QStatusBar. I suppose you could fool the designer by subclassing QStatusBar, and then promoting a QWid... |
6,135,762 | 6,138,816 | Boost.Spirit.Qi: How to report parser warnings? | How to report parser warnings?
Similar to reporting error, but the parser must not stop.
Only log warning message and the subexpression caused the warning.
Example input:
select * from table where row>='' && row<>'hello'
Expected output:
Warning: expression is always true: row>=''
Warning: && is deprecated, use A... | If you want to continue parsing you can register an error handler as before, except that you have to specify accept as the handlers policy:
rule<Iterator> r = ... > !eps;
on_error<accept>(r, handler);
The appended > !eps forces the error in any case and invokes the handler as usual, but it will accept the match after ... |
6,135,799 | 6,135,920 | C2143 with nested template classes | Hi I am having some doubts regrading templates.
Please look into follwoing snippet.
template<class T_Type1>
class CSmall
{
public:
class Const_Itr
{
T_Type1 Outer_A;
};
private:
T_Type1 Inner_A;
};
template<class T_Type>
class CBig
{
public:
CSmall<T_Type>::Const_Itr* obj1;//ERROR C2143: s... | compiler has no clue if CSmall<T_Type>::Const_Itr is a type or a variable. So you should provide some help. While CSmall<int>::Const_Itr is obviously a type.
|
6,135,850 | 6,135,952 | How to instatiate a class from another class in Qt C++ | I had made 2 class in my project. I want to use a function from 1st class to the 2nd class the problem is I can't instantiate the 1st class to the 2nd class. By the way both classes were declared in different headers.
here is a sample code:
header 1:
class 1stclass{
public:
2ndclass *class2;
void function1(QS... | Class names aren't allowed to start with a number in C++.
Class1 and Class2 are valid names though.
|
6,135,855 | 6,135,886 | Is this example causing an undefined behaviour? |
Possible Duplicate:
Undefined Behavior and Sequence Points
The variable i is changed twice, but is the next example going to cause an undefined behaviour?
#include <iostream>
int main()
{
int i = 5;
std::cout << "before i=" << i << std::endl;
++ i %= 4;
std::cout << "after i=" << i << std::endl;
}
T... | Yes, it's undefined. There is no sequence point on assignment, % or ++ And you cannot change a variable more than once within a sequence point.
A compiler could evaluate this as:
++i;
i = i % 4;
or
i = i % 4;
++i;
(or something else)
|
6,136,010 | 6,136,130 | Is using an union in place of a cast well defined? | I had a discussion this morning with a colleague regarding the correctness of a "coding trick" to detect endianness.
The trick was:
bool is_big_endian()
{
union
{
int i;
char c[sizeof(int)];
} foo;
foo.i = 1;
return (foo.c[0] == 1);
}
To me, it seems that this usage of an union is incorrect because... | Your code is not portable. It might work on some compilers or it might not.
You are right about the behaviour being undefined when you try to access the inactive member of the union [as it is in the case of the code given]
$9.5/1
In a union, at most one of the data members can be active at any time, that is, the value... |
6,136,033 | 6,136,124 | Splitting a `char[]` in C++ | I have a char[] in YYYYMMDDHHMMSS format.
e.g. 2011052504572
I want to retrieve the year, month, date, hour, minute and second from this char. How do I do that?
NOTE:I cant use any third party dll.
Thanks,
Syd
| Use string::substr() for this purpose. Example,
string date = "20110524112233";
string year = date.substr(0, 4);
string month = date.substr(4, 2);
string day = date.substr(6, 2);
string hour = date.substr(8, 2);
string minute = date.substr(10, 2);
string second = date.substr(12, 2);
|
6,136,049 | 6,149,093 | Firebreath placing JPEG image inside the plugin window | I'm writing a plugin in firebreath, C++.
I don't have any experience with both, so my question may be very basic.
How do I place a JPEG image inside my plugin window?
Or at least, how do I do it in C++ simple program?
Thanks,
RRR
| There are a couple of other questions that may help you better understand this:
How to write a web browser plugin for IE, Firefox and Chrome
Directx control in browser plugin
Basically you'll get a drawing model from FireBreath with the AttachedEvent. Depending on your platform, you will draw to that window using platf... |
6,136,362 | 6,136,449 | Convert iterator to int | int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;
I'm trying to find index of an element in vector. It's ok with iterators, but I want it as int. How can I do it?
| You can use std::distance for this.
i = std::distance( names.begin(), std::find( names.begin(), names.end(), s ) );
You will probably want to check that your index isn't out of bounds, though.
if( i == names.size() )
// index out of bounds!
It's probably clearer to do this with the iterator before using std::dist... |
6,136,445 | 6,136,773 | Qt dialog how can I trigger accept() and reject() from function | I have situation that I open QDialog window from the main.cpp file and then I wait for the exec() method to return based on success or fail of the QDialog. Like this :
int main( ... ) {
LoginDialog *loginDlg = new LoginDlg;
if( loginDlg->exec() != Qt:;Accepted ) {
return 0;
}
//check the login ... | As liaK pointed out you can just call the following functions from your code:
loginDlg->accept();
loginDlg->reject();
You can also call the following equivalent function using the result as a parameter:
loginDlg->done(QDialog::Accepted);
loginDlg->done(QDialog::Rejected);
PS: Note also there is no Qt::Accepted value ... |
6,136,453 | 6,136,510 | vector::size and Segmentation fault | Why could this code throw segmentation fault?:/
listeners = new vector<Listener*> ();
... /* other code */
if (listeners != NULL) {
int i = listeners->size();
}
| Just because the pointer isn't NULL doesn't mean it points to a valid vector<Listener*> object.
Run your program through valgrind to detect memory corruption issues, and make sure that you run your code through your debugger, too.
If you still have problems, post a test that reproduces the issue (rather than little sni... |
6,136,513 | 6,491,961 | Signals when debugging | I'm developing an application (a service/daemon, really) on Linux in C++ that needs to interface with a piece of hardware. If my program doesn't release the resources for this peice of hardware cleanly when terminating, then I have to reload the device driver, a process that takes about 10 minutes and for obvious reaso... | It turns out the problem had nothing to do with Netbeans or Eclipse, but rather gdb.
gdb can be configured to handle signals in a variety of ways. If you run:
gdb
then type:
info signals
You'll get a list of signals and gdb actions on what to do if it receives that signal:
Signal Stop Print Pass to progra... |
6,136,699 | 6,137,841 | std::regex equivalent of '/g' global modifier | In Perl, I can do this:
$text = '1747239';
@matches = ($text =~ m/(\d)/g);
# @matches now contains ('1', '7', '4', '7', '2', '3', '9')
Using C++ regex matching, what's the best way to replicate this behaviour so
that I get a match set including all the matches?
I have this at the moment:-
compiledRegex = std::regex(r... | You should call regex_search several times. Its return value specifies whether there are more matches. Each time you call it you get a new match. The iterator returned by results goes over the group submatches defined in your regular expression. The first entry is always the entire match, that's why in your case count ... |
6,136,800 | 6,880,698 | Unicode test strings for unit tests | I need some Utf32 test strings to exercise some cross platform string manipulation code. I'd like a suite of test strings that exercise the utf32 <-> utf16 <-> utf8 encodings to validate that characters outside the BMP can be transformed from utf32, through utf16 surrogates, through utf8, and back. properly.
And I alwa... | Although this isn't quite what you asked for, I've always found this test document useful.
http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
The same site offers this
http://www.cl.cam.ac.uk/~mgk25/ucs/examples/quickbrown.txt
... which are equivalents of English's "Quick brown fox" text, which exercise all the... |
6,137,009 | 6,142,032 | Microsoft Visual Studio: How to keep the console open without manually reading input? | I'm writing some C++ with Microsoft Visual Studio 2010 Express, and I'm wondering if there is a way to display command output somewhere in the IDE instead of an external console window, or at least keep that window open.
Reading something from STDIN would work for a console application, but this is a unit test case and... | Ctrl + F5
for quick test.
The key combination keeps the console open until you close it.
|
6,137,124 | 6,137,203 | compiling error when erasing a STL std::set element by key | I have the following code, in which I hold a std::set of iterators to a STL container of ints, and erase an element by key (where the key is an iterator to the STL container). The code compiles and runs as expected (compiler is VC 2008) if the container is std::vector, but fails to compile if the container is a std::li... | The problem is caused by the fact list::iterator does not have a comparison defined. The value type of an std::set requires a strict weak ordering.
A vector supports random access iterators, which have an ordering. A list is only required to support bidirectional iterators, which do not have an ordering (of course, an ... |
6,137,148 | 6,676,577 | Is there a problem running a program using the framewave library under valgrind? | I have a set of unit tests, which are testing a program using the framewave library.
The problem occurs when I run these unit tests using valgrind to check if the code causes memory problems. It looks like the unit test enters an endless loop because it waits for some threads to be joined (although I disabled threads w... | These errors are actually result of a bug in valgrind (the version of valgrind I am using is 3.4.1) :
DWARF2 CFI reader: unhandled CFI instruction 0:10
http://valgrind.org/docs/manual/dist.news.html
Valgrind giving errors with getline()
https://bugs.kde.org/show_bug.cgi?id=197512
Updating the valgrind to the latest ve... |
6,137,341 | 6,137,381 | Why field inside a local class cannot be static? | void foo (int x)
{
struct A { static const int d = 0; }; // error
}
Other than the reference from standard, is there any motivation behind this to disallow static field inside an inner class ?
error: field `foo(int)::A::d' in local class cannot be static
Edit: However, static member functions are allowed. I have on... | Because, static members of a class need to be defined in global a scope, e.g.
foo.h
class A {
static int dude;
};
foo.cpp
int A::dude = 314;
Since the scope inside void foo(int x) is local to that function, there is no scope to define its static member[s].
|
6,137,573 | 6,137,734 | Overhead in unused code | I am wondering what the overhead is of having unused functions in your code.
Say for example you have some debug logging, and you then give most of your objects a ToString() function that is being used in the debug logs.
In a release build that debug logging is not being used. Is it then worth it removing the source co... | It depends on the compiler and, I guess, optimization level.
G++ and MSVC++ remove unused inline functions but keep unused non-inline functions.
For instance, you use only a small fraction of the STL in a normal program. All unused functions get removed, because they're defined as inline.
GCC on the other hand keeps al... |
6,137,921 | 6,137,953 | Semantic iterator declaration? | I'm sorry for the very vague title, I really didn't know how to title this question.
Let's say I have this:
std::list<std::string> msgs;
for (std::list<std::string>::iterator it = msgs.begin(); it < msgs.end(); it++) {
// ...
}
For me, this is hard to to read. The std::list<std::string>::iterator almost seems lik... | If you provide a typedef it will make life a lot easier:
typedef std::list<std::string>::iterator ListIterator;
for( ListIterator it = msgs.begin(); it != msgs.end(); ++it ){}
Other than that, c++0x does it for you by providing the auto keyword:
for( auto it = msgs.begin(); it != msgs.end(); ++it ){}
edit like 5 year... |
6,137,989 | 6,140,568 | UpdateRegistry compilattion error | I am getting the following errors when I build an ATL com with the WInCE device SDK provided by the customer. How can I resolve this issue? I created the workspace with the VS-2005.
1>f:\polycold\testapps\polycoldsmartdevice\polycoldsmartdevice\CmdParser.h(73) : error C2039: 'UpdateRegistry' : is not a member of 'CCmdP... | By doing a lot of guessing with my crystal ball I will asume that CmdParser is a new ATL COM class you are trying to create. If this is the case, I believe there is a bug in VS ATL wizard that makes WINCE ATL projects not valid. An easy workaround I use for this is to comment out the following:
//#ifndef _CE_DCOM
DECLA... |
6,138,060 | 6,138,166 | Decode binary coded decimal (BCD) to unsigned integer | The value used in my project is expressed with 4-bits binary coded decimals (BCD), which was originally stored in a character buffer (for example, pointed by a pointer const unsigned char *). I want to convert the input BCD char stream to an integer. Would you please show me an efficient and fast way to do that?
Data ... | unsigned int lulz(unsigned char const* nybbles, size_t length)
{
unsigned int result(0);
while (length--) {
result = result * 100 + (*nybbles >> 4) * 10 + (*nybbles & 15);
++nybbles;
}
return result;
}
length here specifies the number of bytes in the input, so for the example given by t... |
6,138,068 | 6,138,322 | Using both std::string and QString interchangeably | I use Qt extensively in a software system I'm working on for graphical and GUI components. However, for most internal algorithms and processing of data Qt plays a smaller role.
I'll often run into the need to convert from std::string to QString or visa versa. My inclination is to use std::string as much as possible and... | Yes, I've had this situation before. The program I worked on used Qt throughout, but I had to hook it up to a library that expected std::string. The benefit of QString is that it explicitly uses Unicode, while the C++ standard library makes no guarantees about encoding.
The solution was to convert at the boundary of th... |
6,138,299 | 6,142,381 | BK-Tree Implementation Insertion time is more how to reduce | Following is my attempt to write BK-Tree , for 150000 word file it takes around 8 seconds
Is there any way to reduce this time.
Following is my code
#include <stdio.h>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <sstream>
#include "Timer.h"
class BkTree {
public:
BkTre... | You can reduce the time by eliminating the I/O. To test your algorithm, remove as many objects out of the equation that are not directly under the control of your program. For example, the OS controls the I/O, it is out of your control. An array of constant text removes much OS involvement (the OS still may page the... |
6,138,461 | 6,138,603 | Why is there "no matching function" for my call to mem_fun_ref? | I have some code where classes inherit from a base class.
That base class has a function which, when run, ought to call functions to be implemented by the children. That is, the general algorithm is the same for all children, but the implementation of the steps should vary.
template<class T>
class Foo
{
public:
... | Following are the prorotypes for mem_fun_ref
template <class S, class T>
mem_fun_ref_t<S,T> mem_fun_ref (S (T::*f)());
template <class S, class T, class A>
mem_fun1_ref_t<S,T,A> mem_fun_ref (S (T::*f)(A));
template <class S, class T>
const_mem_fun_ref_t<S,T> mem_fun_ref (S (T::*f)() const);
template <class S, ... |
6,138,771 | 6,138,870 | convert from string to byte[] and add the result into a memorystream | how can i convert a string into a byte[] and them add the result using in a stream. THX. I am working in c++ code, ubuntu.
EDIT:
i have a std::string as a string value.
I need a method that takes as an input a std::string value and returns as an output the stream value.
| You can get a pointer to the string buffer by simply calling std::string.c_str(). That will return a const char* (where char is an int8_t) that you can effectively use as a byte[]. Keep in mind though that the pointer returned is pointing to memory managed by the string object, so if you change anything in the origin... |
6,138,895 | 6,138,931 | Weird linker problem with static const class members | Please tell me, why gcc linker gives me the following error: "test_class::test_struct::constVar", referenced from: __ZN12lu_test_class27test_struct6constVar$non_lazy_ptr in test_class.o ?
My code (test_class.h):
class test_class
{
struct test_struct
{
static const int constVar = 0;
};
};
All refer... | Provide the definition of the static member outside the class
const int test_class::test_struct::constVar;
This works for me.
|
6,139,188 | 6,139,245 | Can the compiler elide the following copy? | I'm still a rookie programmer, I know that premature optimization is bad, but I also know that copying huge stuff around is bad, as well.
I've read up on copy elision and it's synonyms but the examples on Wikipedia for example make it seem to me that copy elision can only take place if the object to be returned gets re... |
the examples on wikipedia for example make it seem to me that copy elision can only take place if the object to be returned gets returned at the same time it gets completely constructed.
That is misleading (read: wrong). The issue is rather that only one object is returned in all code paths, i.e. that only one constr... |
6,139,190 | 6,139,414 | Simple line-plane intersection on a fixed z-axis? | What is, and is there, a fast way to check where in the plane my line will intersect, if i know the plane is always in the same z-axis (so it cannot be rotated), and its width/height is infinite? Also, my "line" isn't actually a line, but a 3d vector, so the "line" can go to infinite distance.
Here is the code that rel... | You can implement a strait-forward solution like there http://paulbourke.net/geometry/planeline/, then apply your simplifications. In the algebraic solution (#2) A and B are zeros in your case (if i understand correctly this statement)
plane is always in the same z-axis (so it cannot be rotated)
Note: your line shou... |
6,139,240 | 6,139,311 | c++ inherit virtual functions | ok say we have the following classes
class A
{
public:
virtual void taco()
{
cout << "Class A" << endl;
}
};
class B: public A
{
public:
virtual void taco()
{
cout << "Class B" << endl;
}
};
class C : public A
{
public:
void taco()
{
cout << "Class C" << e... | You must store pointers in the deque, since polymorphism only works with reference & pointer types. When you insert those objects into the deque, copies are made of type A, "slicing" off the parts that made them B or C originally.
Similarly, A r = B() just creates a temporary B and copies the A part of it into an A cal... |
6,139,543 | 6,139,644 | Passing this by value | Silly question: what is the best way to pass this by value?
Background: Let's use cars and car options. I used to have constructors such as Ford(FordOptions), Honda(HondaOptions). All cars derive from Car, all options from CarOptions. I used to have a car factory that gets passed a pointer to a CarOption, checks the ty... | You just have to dereference the this pointer... And depending on the called method, you pass a reference (as in the example), or by value
Ford::Ford(const FordOption &o) {}
Ford FordOption::produceCar() {
return Ford(*this); // <-- Dereference this
}
|
6,139,573 | 6,139,629 | Win32 program compiler errors in class definition file | I am trying to Compile in Visual C++ and just added this config file loader/parser to my project. For some ever function defined in class CProfileData is receiving at least one of two errors:
missing type specifier - int assumed.
syntax error : missing ',' before '&'
When obviously this should just be a referenced st... | Include <string>:
#include <string>
And write std::string wherever you've written string.
Its not a good idea to do either of the following in a header file:
using namespace std; //avoid doing this
using std::string; //avoid doing this as well
|
6,139,753 | 6,139,961 | Publisher/Subscriber with changing subscriptions during loop | This is more of a general design query I had. I have implemented a publish / subscribe pattern by maintaining a list of subscribers. When an event to publish occurs, I loop through the subscribers and push the event to each one, of them in turn.
My problem occurs when due to that publication, somewhere in the depth of ... | You could either disallow subscription operations during publication, or you could use an appropriate data structure to hold your subscription list, or both.
Assuming that you keep your subscribers in a std::list, you could run your loop thus:
for(iterator_type it = subs.begin(); it != subs.end(); ) {
iterator_type... |
6,140,066 | 6,140,123 | Convert hostname to IPAddr | How do I convert from a hostname (e.g. 'myhost') to a type of IPAddr using Windows API. IPAddr is an unsigned long.
| Try this (edited):
hostent * record = gethostbyname(argv[1]);
if(record == NULL)
{
printf("%s is unavailable\n", argv[1]);
exit(1);
}
in_addr * address = (in_addr * )record->h_addr;
string ip_address = inet_ntoa(* address);
IPAddr dst_ip = ::inet_addr( ip_address.c_str() );
|
6,140,223 | 6,155,524 | C++ & Boost: encode/decode UTF-8 | I'm trying to do a very simple task: take a unicode-aware wstring and convert it to a string, encoded as UTF8 bytes, and then the opposite way around: take a string containing UTF8 bytes and convert it to unicode-aware wstring.
The problem is, I need it cross-platform and I need it work with Boost... and I just can't s... | Thanks everyone, but ultimately I resorted to http://utfcpp.sourceforge.net/ -- it's a header-only library that's very lightweight and easy to use. I'm sharing a demo code here, should anyone find it useful:
inline void decode_utf8(const std::string& bytes, std::wstring& wstr)
{
utf8::utf8to32(bytes.begin(), bytes.... |
6,140,282 | 6,140,314 | g++ error - expected unqualified-id before ')' token | When I go to compile this code it says it expected an unqualified-id before the ) in my constructor
analysis2.h:
#ifndef _ANALYSIS2_H
#define _ANALYSIS2_H
class Analysis2{
public:
Analysis2();
...
analysis2.cpp:
#include "analysis2.h"
using namespace std;
Analysis2()
{
Seconds_v = 0;
Seconds_t = 0;
}
... | In analysis2.cpp you need to tell the compiler that you are defining the constructor by giving it a scope:
Analysis2::Analysis2()
{
Seconds_v = 0;
Seconds_t = 0;
}
Scope Resolution Operator
|
6,140,348 | 6,141,028 | Convert Haskell ByteStrings to C++ std::string | I want to convert strict ByteStrings from Haskell into C++'s std::string to pass it to a C++ library via the FFI. As the ByteString may contain NULL characters, converting into a CString as an intermediate step is not viable. What is the right approach here?
current solution
Thanks for the answers so far. I hoped for a... | The documentation is great!
type CString = Ptr CChar
A C string is a reference to an array of C characters terminated by NUL.
type CStringLen = (Ptr CChar, Int)
A string with explicit length information in bytes instead of a terminating NUL (allowing NUL characters in the middle of the string).
If you use a CStri... |
6,140,438 | 6,140,708 | Is it possible to ensure copy elision? | Copy elision is a neat optimization technique and in some cases relying on copy elision can actually be faster than passing around references "by hand".
So, let's assume you have identified a critical code path where you rely on the fact that the copy elision is performed by your compiler for the code path for maximum ... | Not really, except putting an assert(false); in the copy constructor.
Otherwise use your favorite profiler to measure that the interesting parts of your app is fast enough.
|
6,140,537 | 6,140,569 | C++ vector issue - 'LNK2001: unresolved external symbol private: static...' | Before anyone calls me out for not looking at pre-existing questions, I have looked and realise that it is to do with declaration, but I still can't get it to work (might be something to do with me using vectors).
Manager.h:
#include "Flight.h"
#ifndef manager_h
#define manager_h
class Manager {
static vector<Airp... | You have to define them in the .cpp file:
vector<string> Manager::flights;
vector<string> Manager::airports;
|
6,140,691 | 6,140,729 | What's the matter with 'const Obj' and 'Obj &'? | I want to write a class that is compatible for std::set, so I overload the "less than" operator like this. It works.
bool Segment::SVertex::operator<(const SVertex &rhs) const
{
return id < rhs.id;
}
However, since I write Java more than C++, 'rhs.id' looks very uncomfortable to me. So I change it to 'rhs.getId()'... | the problem is your getter function isn't exactly 'normal'; your getter should be
long SVertex::getId() const
{return id;}
Note the const at the end: it tells the compiler/users that this method does not modify the class' internals. So, it's possible to use it in your operator < which is also const.
Const member funct... |
6,140,703 | 6,140,918 | With D3D, do I need to call release before I exit my process? | The tutorial that i'm taking for direct3d says this:
"... Basically, if you create Direct3D, but never close it, it will just keep on running in the background of the computer until your next reboot, even after the program itself closes. Bad. Especially bad if you have a lot of resources in your game. Releasing thes... | Simply put, no. That is not true. When your process terminates, all your DirectX resources will be freed and no GPU or system memory will be leaked.
|
6,141,574 | 6,182,240 | how to write a program in C++ which receives 10 numbers from input and checks whether these numbers are in ascending order or not? | I am a newbie. And I want to do this program without using array and only with 3 variables. Looking forward for your help. I stuck up here:
#include<iostream>
#include <math.h>
using namespace std;
int main()
{
float a,b,c;
cout << "Please Enter the numbers: " << endl;
for(float k=0; k<=9; k++)
{
... | You only need two variables, not three.
#include <iostream>
#include <limits>
using namespace std;
int main(int argc, char* argv[]){
float old = std::numeric_limits<float>::min(), current = 0.f;
for(int i = 0; i < 10; i++){
std::cin >> current;
if(current > old){
old = current;
}else{
... |
6,141,603 | 6,141,682 | How do I handle a large number of properties that initialize a class? | I have a class that requires a large number of properties for initialization:
Hand hand = new Hand();
hand->skinColor(Color(0.5, 0.5, 0.2));
hand->indexFingerLength(0.5);
hand->middleFingerLength(0.6);
hand->ringFingerLength(0.55);
...
hand->init(); // Builds the hand model
These properties are only valid to modify u... | struct structHandParms
{
param1;
param2;
param3;
...
};
structHandParms stParams;
Hand hand = new Hand(stParams)
|
6,141,651 | 6,141,727 | Polymorphism ambiguities, can we resolve them with a "default" base to use | I need a layer of abstraction involving QWidget that can be QGLWidget, and I wonder if there is a way to say to the compiler, "Any time you have a doubt (ambiguities) try to use the default base I give you", of course if there is ambiguities it can't resolve with the default choice it prompts errors just like it does. ... | I personally doubt that this kind of automatic disambiguation is feasible in C++ at the language level.
What is possible is, case-by-case, disambiguate by explicitly giving the class whose method should be executed, like this:
QGLWidget::ambiguous_method(...
This is not what you are asking for, I know, and I am sure y... |
6,141,724 | 6,141,959 | Will the compiler unroll this loop? | I am creating a multi-dimensional vector (mathematical vector) where I allow basic mathematical operations +,-,/,*,=. The template takes in two parameters, one is the type (int, float etc.) while the other is the size of the vector. Currently I am applying the operations via a for loop. Now considering the size is know... | You can do the following trick with disassembly to see how the particular code is compiled.
Vector<int, 16> a, b;
Vector<int, 65536> c, d;
asm("xxx"); // marker
a.Add(b);
asm("yyy"); // marker
c.Add(d);
asm("zzz"); // marker
Now compile
gcc -O3 1.cc -S -o 1.s
And see the disasm
xxx
# ... |
6,141,750 | 6,141,818 | How to monitor page for changes without polling? | I currently have an IRC bot written in C++ which monitors a page written in php for changes and then outputs these changes to the IRC channel.
However the current method is rather in-effective as it just constantly polls the page once every 10 seconds and compares it to the last seen version to check if anything has ch... | If the data generated by PHP isn't somehow pushed on a stream (broadcast or feed), you don't have any other choice than polling the page, unfortunately.
What you could do is push the data from PHP using broadcast, or make a persistent connection from the bot to the PHP script, or make the PHP calculate the differences ... |
6,142,142 | 6,142,175 | Usage of Smart Pointers as a Programming Standard? | More and more I hear, that I should use smart pointers instead of naked pointers, despite I have effective memory leak system implemented.
What is the correct programming approach on using smart pointers please? Should they really be used, even if I check memory leaks on allocated memory blocks? Is it still up to me? I... | You should use RAII to handle all resource allocations.
Smart pointers are just one common special case of that rule.
And smart pointers are more than just shared_ptr. There are different smart pointers with different ownership semantics. Use the one that suits your needs. (The main ones are scoped_ptr, shared_ptr, wea... |
6,142,206 | 6,142,455 | What is the proper way of handling a mouse drag? | I need to implement mouse drag events which look something like this:
class MouseDragEvent
{
public:
uint m_btn;
uint m_x, m_y;
uint m_delta_x, m_delta_y;
};
I think I will need to check for WM_LBUTTONDOWN and WM_LBUTTONUP messages and manually find the change in x and y. Is there a drag message or a better w... | Start by detecting WM_LBUTTONDOWN. Record the starting coordinates where the mouse button was pressed. Check for WM_MOUSEMOVE, and when the mouse has moved outside the rectangle determined by GetSystemParameters(SM_CXDRAG) and GetSystemParameters(SM_CYDRAG) use SetCapture to capture the mouse. At this point continue re... |
6,142,576 | 14,046,420 | Sample from multivariate normal/Gaussian distribution in C++ | I've been hunting for a convenient way to sample from a multivariate normal distribution. Does anyone know of a readily available code snippet to do that? For matrices/vectors, I'd prefer to use Boost or Eigen or another phenomenal library I'm not familiar with, but I could use GSL in a pinch. I'd also like it if th... | Since this question has garnered a lot of views, I thought I'd post code for the final answer that I found, in part, by posting to the Eigen forums. The code uses Boost for the univariate normal and Eigen for matrix handling. It feels rather unorthodox, since it involves using the "internal" namespace, but it works. ... |
6,142,595 | 6,142,638 | Newbie question on C++ array | I'm working through a demo program written by someone else, and I'm very confused about some of the statements they are using. I'm not very familiar with C++ (moreso with Obj-C) and I'm not sure if this is valid code or not. Take, for example, the following: (comments are mine)
int main(int argv, char** argc)
{
int... | All those examples are absolutely wrong. It looks like you lost [i] when you copied the code from wherever you got it from.
I have seen something similar with code sent over messenger programs that treat certain bits of text as emotes and replace them with images that don't get copied as text, but instead get dropped. ... |
6,142,735 | 6,142,761 | How to initialize c-strings array (no stl) | I want to initialize array of c-strings with zero pointers in MSVC2010
// Foo.h
#pragma once
class Foo {
int sz_;
char **arr_;
public:
Foo();
~Foo();
// ... some other functions
};
// Foo.cpp
#include "Foo.h"
#define INITIAL_SZ 20
Foo::Foo() : sz_(INITIAL_SZ) {
// there I have to initialize arr_ (dynamic... | arr = new char*[INITIAL_SZ](); will do - you can even put it in an initialization list.
|
6,142,818 | 6,142,951 | Container of type-unique items | I recognize the questions title is a bit vague, so thanks for at least reading it ;-)
My situation is this: I have got a set of classes CommandA, CommandB, ... derived from a common pure abstract base class ICommand. Now I need to keep instances of those derived classes in some kind of container but with the restircti... | If you cannot use template or RTTI you can do something like this
class ICommand
{
virtual void *getStaticId() = 0;
}
int bar;
void* CommandA::getStaticId()
{
return &bar;
}
int foo;
void* CommandB::getStaticId()
{
return &foor;
}
You can u... |
6,142,830 | 6,143,009 | How do I initialize a stl vector of objects who themselves have non-trivial constructors? | suppose I have the following class:
class MyInteger {
private:
int n_;
public:
MyInteger(int n) : n_(n) {};
// MORE STUFF
};
And suppose this class don't have a default trivial constructor MyInteger(). I must always supply an int to initialize it for some reason. And then suppose that somewhere in my code I need... | There are many ways to get there. Here are some of them (in no particular order of presence).
Use vector(size_type n, const T& t) constructor. It initializes vector with n copies of t. For example:
#include <vector>
struct MyInt
{
int value;
MyInt (int value) : value (value) {}
};
struct MyStuff
{
std::ve... |
6,143,297 | 6,143,327 | expected unqualified-id before numeric constant | template <int K>
class Wrap
{
// stuffs
};
What is wrong if I instantiate the template like Wrap < 5>4 > p;?
I get expected unqualified-id before numeric constant error. How to fix this?
|
What is wrong if I instanciate the template like Wrap < 5>4 > p;?
That should be intuitively obvious just by looking at the statement: it’s confusing even for humans! The compiler has no way of coping with the double meaning of > here: does it mean “greater than”? Does it mean “close the template argument list”? Turn... |
6,143,308 | 6,143,434 | Shorten static definitions | If I have a class named SomeClassName, can I avoid writing SomeClassName:: everytime I am referring to something in that class? I am thinking along the lines of namespace where I can enclose the definitions in using MyNamespace { ... }; and avoid writing the namespace the class is under every time (bad practice?).
One ... | No, but you can shorten the name with a typedef, if all you are after is less typing:
typedef SomeClassName SCN;
|
6,143,569 | 6,143,603 | How to get a local date-time from a time_t with boost::date_time? | I'm using boost::date_time and I got a time_t, that have been generated by a library using the time() function from the C standard library.
I'm looking for a way get a local time from that time_t. I'm reading the documentation and can't find any way to do this without providing a time zone, that I don't know about beca... | For this task, I'd ignore boost::date_time and just use localtime (or localtime_r, if available) from the standard library.
|
6,143,601 | 6,144,521 | C++ SQL Server connection and then read table in a particular way | How to read a table from SQL Server 2008 to a a vector in C++ in the following way:
SQL TABLE 2008 table
1att 2att 3att 4att 5att 6att 7att ... attn
--------------------------------------------
565 526 472 527 483 529 476 470 502
497 491 483 488 488 483 496 515 491
467 516 480 477 494 497 478 519... | There are many ways to do this:
Fetching single columns from
database
Fetching odd columns from database
Fetching entire table from database
Fetching Single Columns
In this method, you tell the data base to select one column. You fill in a single vector by iterating through the result set. Repeat for each column yo... |
6,143,619 | 6,146,170 | Code understanding Question | I was going through one code on net.
I did not understand following logic. This code works and works really fast.
for (int i = 0; i < typo_word_vec.size(); i++)
{
float each_typo_word_len = (float)typo_word_vec[i].size();
int start_range = each_typo_word_len - floor((each_typo_word_len / lower_bound_wor... | You really should have posted a few more lines - we definitely need to check the whole code to understand something.
As I understand it, the 'source' words are ordered by size. The 'candidate' words may be shorter or longer than their potential match. That is what start_range and end_range are used for.
Though I have a... |
6,143,640 | 6,143,804 | Code readability with c++11 lambdas | I REALLY love lambdas and having the ability to use them in C++ is a pleasure. But, as I'm used to Haskell, where lambdas fit really well into the syntax, I'm struggling with how to use them in C++ without writing unreadable cluttered long code lines.
So, as an example, suppose I'd write this:
vector<double> foo(10,0.... | I usually go for
for_each(foo.begin(), foo.end(), [](double x) {
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
I've written some several hundred line lambdas.
|
6,143,689 | 6,156,367 | is it possible to inject multiple Dlls with MS detours? | In c++ ,I want to hook more than one dll to a process. Right now I use CreateProcesswithdll() which can hook only one api at a time. What can I do to inject multiple dlls?
I came across this problem because MS detours requires us to name our custom dll the same as original dll in order to properly detour the api calls... | Seems like detourattach and detourdetach will do the trick for me. Thanks everyone!
I found this blog useful!
|
6,143,824 | 6,143,869 | Add leading zeroes to string, without (s)printf | I want to add a variable of leading zero's to a string.
I couldn't find anything on Google, without someone mentioning (s)printf,
but I want to do this without (s)printf.
Does anybody of the readers know a way?
| // assuming that `original_string` is of type `std:string`:
std::string dest = std::string( number_of_zeros, '0').append( original_string);
|
6,143,859 | 6,143,896 | Automatically Specify .LIB in Header for Visual Studio 2008 C++ | Is it possible to automatically link a c++ static library in Visual Studio 2008? Or, is there an improvement to use from the standard approach?
I am developing a set of c++ libraries and linking/testing them is quite a pain. The usual approach is to specify the .lib files in the test clients, but now the list has grown... | Use #pragma comment(lib, "name_of_the_library.lib"). Other useful options for #pragma comment can be found at the MSDN page.
With regard to Debug vs. Release configuration: usually a _DEBUG preprocessor macro is used to distinguish. Visual C++ header certainly use it for the same purpose as you want; e.g. this is from ... |
6,143,958 | 6,143,986 | I'm getting an undefined reference error to something that isn't there | When I try to compile this code
Analysis2::Analysis2() //line 13
{
Seconds_v = 0; //Seconds_v and Seconds_t are both of type int
Seconds_t = 0; //and declared in header
}
I get this error
analysis2.cpp:13: undefined reference to `FileParameters::FileParameters()'
Why is it giving me that undefined refe... | When you have constructor, every member variable is automatically default-constructed if you don't explicitly construct it in the initializer list. Your code above automatically expands to:
Analysis2::Analysis2() : mFileParams(), Seconds_v(), Seconds_t() // line 13
{
Seconds_v = 0; //Seconds_v and Seconds_t are ... |
6,143,964 | 6,144,004 | Interpolating Radian Angles? | If I'm given a start angle of 1.0f, and an end angle of 6.0f, then what I really want to interpolate is not the 5 in between 1 and 6, but the smaller portion. This will cause counter clockwise interpolation. How can I account of this when interpolating?
Essentially, when given 2 radian angles from 0 to 6.283, how can ... | Get the target angle minus starting angle. If that is greater than PI, go counterclockwise.
Invert the logic if the value is negative.
|
6,144,206 | 6,144,276 | Avoiding copies in exception handling | Can I avoid the copying of object in the following way?
MyClass Obj;
try {
throw &Obj;
}
catch(MyClass *a) {
}
| If the object is too expensive to copy, it should not be thrown as an exception - full stop. Exception classes should be fairly simple and light-weight. And you should always catch exceptions by reference (probably by const reference) - catching pointers is bad style. So your code should better be written:
try {
th... |
6,144,610 | 6,144,910 | MFC: Best place to handle context menu message? | Using C++ with MFC. I'm using a grid control which derives from CWnd (specifically the MFC Grid control on codeproject). I want to display a context menu when the user right clicks on a cell. My thinking is to handle the ON_WM_CONTEXTMENU() message.
However, where is the best place to handle this, in a OnContextMenu... | If there is a convention, I haven't noticed.
I would choose based on who has the information required to build the menu, and who will be processing the commands resulting from the menu selection.
|
6,144,673 | 6,145,060 | A good simple 3D environment simulation | I need to be able to load in a 3D environment (a possibly very large file), and have a single object traverse and be controlled through the environment. Physics are not explicitly needed, but collision detection and simulated motion are required. I also need to be able to specify locations of different viewpoints mount... | I personally suggest ogre, but I also found this article about irrlicht that seems particularly pertinent to your case.
|
6,144,682 | 6,144,745 | Should I use cstdint? | I have been pondering on whether or not I should use the typedefs inside <cstdint> or not.
I personally prefer writing uint32_t over unsigned int and int8_t over char etc... since it to me is alot more intuitive.
What do you guys think? Is it a good idea to use the typedefs from <cstdint> or not? Are there any disadva... | Actually, I would suggest using both.
If you want something that is definitely 32-bits unsigned, use uint32_t. For example, if you are implementing a "struct" to represent an external object whose specification defines one of its fields as 32 bits unsigned.
If you want something that is the "natural word size of the m... |
6,144,751 | 6,144,800 | Writing files with std on iOS | i added a save.txt to my iPhone resource in xCode, with a same text "..."
i write some strings to the file, and than read it, but when i read it, i only get the old content.. so there is nothing new written into it
NSString* resources = [ [ NSBundle mainBundle ] resourcePath ] ;
std::string respath( [ resources U... | You cannot write or modify files inside the application bundle, that file.open() call is surely failing but you aren't checking for errors. Instead, you should write to the Documents folder for your app.
Per your code sample, that would be:
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,... |
6,144,851 | 6,145,214 | Making a passthrough interface to library | Sorry if this question has been asked before. I'm really not sure how to search for it.
What I'm trying to do is build up a library of functions for myself to make life easier in my future school work. I built up a set of functions that handle Geometry based things, like 3D vectors and points and planes along with all ... | I'd suggest using namespaces for this:
namespace geometry {
class Vector3 {
...
};
}
namespace eigen {
using geometry::Vector3;
...
}
Basically this would allow you to define your basic geometry types & operations, and then use selected portions directly from within the other namespace.
|
6,145,112 | 6,145,301 | boost regular expression capture groups | After a days worth of hacking and reading, I have had no luck with boost's regex engine, hopefully someone here can help.
I want to grab the first field out of every line where the last field matching some input.
string input =
"449 a dingo ate my baby THING\n"
"448 a dingo ate my baby THING\n"
"445 a din... | acording to this articale you have to pass flag match_not_dot_newline to the matching algorithm. i think that would solve your case.
|
6,145,134 | 6,145,971 | compiling with o2 flag makes program to trow access violation | I know it may be some once in life time question but I've stuck with it and i cann't think of any possible problem that's cousing this, I've written a code in c++ (somthing around 500 lines in seperate classes and files) using visual studio and while I compile it without optimization flag (/od) it works fine, but when... | The reason you're seeing different behavior with and without optimizations is that your code (unintentionally) relies on undefined behavior. It just so happens to work if the compiler lays out data in one way, and breaks if the compiler lays it out differently.
In other words, you have a bug.
It may be in your already... |
6,145,247 | 6,146,086 | C++11 templates, determining return type | I am building a matrix library and I am trying to use the policy-based design.
So my base classes are classes that provide a storage method and some
access functions.
I also have a function matrix which provides the mathematical functions.
This works great, but there is a major problem with the operator*
because of the... | Picking up on the idea of @hammar, but with partial specialization to allow the normal syntax like the question shows:
template<class MatrixContainer>
class matrix;
template<
template<class,int,int> class MatrixContainer,
class T, int rows, int cols
>
class matrix< MatrixContainer<T,rows,cols> >{
typedef MatrixC... |
6,145,282 | 6,145,344 | How to display framerate in window title? | I think this is going to be an easy one for you guys :)
I am trying to get FPS displayed in the window title in my Directx application (written in C++). I do not really know how to do this as my app assigns title in this manner
any ideas how to do this (so that I can see the FPS when I minimise my app) ?
| I think you can use SetWindowText() to accomplish this, e.g.:
HWND window = CreateWindow(windowClass.lpszClassName, title, WS_OVERLAPPEDWINDOW, x, y, width, height, GetDesktopWindow(),NULL,windowClass.hInstance,NULL);
... then later ...
SetWindowText(window, "XXXX FPS");
See:
http://msdn.microsoft.com/en-us/library/a... |
6,145,548 | 6,145,585 | What is the purpose of the statement "(void)c;"? | Sorry for the vague title, but not really sure how to phrase it. So I was looking through the innards of boost::asio (trying to track down some ridiculous delays), and I notice code like this dotted about:
op_queue<operation> completed_ops;
task_cleanup c = { this, &lock, &completed_ops };
(void)c; // EH?
... | Maybe to avoid a compilation warning because c isn't used?
|
6,145,670 | 6,145,727 | Searching for string in vector of pointers | I understand how to find a specific value in a vector using find(vector.begin(), vector.end(), item)!=vector.end() however, I have a vector of pointers which points to objects of type Restaurant and I need to be able to search this vector for an attribute of the objects each element points to.
I'm not sure if I can con... | find_if is your friend. Here is an example:
struct Comparator {
const char* expected_name;
Comparator(const char* _expected_name)
: expected_name(_expected_name)
{}
bool operator()(const Restaurant* r1) const
{ return !strcmp(r1->getRestaurantName(), expected_name); } // Just an example using str... |
6,145,715 | 6,145,741 | Changing class variables by calling super | Is it possible to change a derived class' variable from the super in C++?
(Using an example may make my question more clear..)
Say I have the following classes and functions:
class SuperClass // super class
{
int myClassVariable;
public:
virtual void modify()
{
... | It's the super class, since the member is modified in the super class and a member can't be virtual, only methods can be virtual.
Also note that modify() isn't virtual in the derived class (with respect to the super class), it's only virtual to children of the derived class, since modify() wasn't declared virtual in th... |
6,145,738 | 6,145,864 | Cross platform _wtoi() implementation? | Hey everyone, I'm writing a piece of software that, due to my choice to use Qt, required me to rewrite a few hundred lines of code to be unicode compliant (qt forced my entire project _UNICODE). After nearly killing myself writing all this code and making it work I ran into a problem with _wtoi() - it's not cross platf... | If you want sheer runtime speed , I recommend Boost.Spirit.Qi:
#include <cwchar>
#include <boost/spirit/include/qi_int.hpp>
#include <boost/spirit/include/qi_parse.hpp>
int portable_wtoi(wchar_t const* const str)
{
using boost::spirit::int_;
using boost::spirit::qi::parse;
wchar_t const* p = str;
int ... |
6,145,910 | 6,146,232 | cross platform native open/save file dialogs | I'm writing a UI for my program using opengl with SDL in a combination of Lua and C++
What I need now is some library that will allow me to call a function that presents the user with a file select dialog for opening/saving a file. But if the OS offers native functionality for such a dialog, then I want to use that dia... | In my opinion, wxWidgets is the open source, battle tested, mature, cross platform, cross language, free, open source, GUI library. Beside wxWidgets, there are also many other such cross platform libraries, such as:
Tk
FLTK
FOX
XUL
AbiWord's cross platform layer
... and more.
You will most likely find you're looking ... |
6,145,965 | 6,145,983 | caching multiple key hash | I want to do some caching in my project.
Let my API is int foo(int a, float b, float c, int d, char e)
Now in my project, there is lot of calls to above time consuming API with repeating values of a, b, c ,d and e. Now I want to store return value of this function with these arguments as keys.
suppose my call sequence... | If you can use boost, look at boost::unordered_map, otherwise you can use a std::map. You will have to provide functor to generate the key.
|
6,145,995 | 6,146,078 | installing open cv for the Dev C++ | I want to install open cv library and i am using Dev c++ compiler. I tried several times to install open cv, but it doesnt work properly. i have read some documents which says, it is necessary to intall cmake first. but, i tried without it. can anyone guide me to install open cv please (please give me procedure, step b... | I wrote a procedure for Code::Blocks on Win32 a little while back.
|
6,145,997 | 6,148,768 | given abstract base class X, how to create another template class D<T> where T is the type of the class deriving from X? | I want to be able to accept a Message& object which references either a Message1 or Message2 class. I want to be able to create a MessageWithData<Message1> or MessageWithData<Message2> based on the underlying type of the Message& object. For example, see below:
class Message {};
class Message1 : public Message {};
cl... | As has been mentioned, it is not possible to build your template as is.
I do not see any issue with passing additional parameters, though I would perhaps pack them into a single structure, for ease of manipulation.
Certainly I find it more idiomatic to use a supplementary Data parameter, rather than extending a class h... |
6,146,025 | 6,146,083 | C++: dynamically allocating a member array of structs using non-default constructor | If I have:
struct a_struct
{
int an_int;
a_struct(int f) : an_int(f) {}
a_struct() : an_int(0) {}
};
class a_class
{
a_struct * my_structs;
a_class() {...}
};
I can do:
a_class() {my_structs = new a_struct(1)}
//or
a_class() {my_structs = new a_struct [10]}
But I cannot do:
a_class() {my_st... | If using the STL is an option, you could use std::vector instead of a dynamic array.
I think that this will work:
std::vector<a_struct> my_structs;
my_structs.assign(10, 1);
If not, this should:
my_structs.assign(10, a_struct(1));
|
6,146,053 | 6,146,214 | Decoding problems with Lempel-Ziv-Welch algorithm | I have to implement the LZW algorithm but I have found some trouble with the decoding part.
I think the code is right because it works with a example I've found somewhere on the web: if I initialize my dictionary as follows
m_dictionary.push_back("a");
m_dictionary.push_back("b");
m_dictionary.push_back("d");
m_diction... | It looks like you are outputting the dictionary indices as ASCII encoded numbers. How are you going to tell the sequence 1,2,3 from 12,3 or 1,23.
You need to encode the data in an unambiguous way using either 9-bit (10, 11 or whatever) numbers or some sort of prefix-free code like huffman coding.
|
6,146,348 | 6,146,495 | Making a GUI using Qt for a text-based game | Me and my fellow classmates decided to make a game over the summer. At first we decided to make it a text-based console app, but then I though that it would be possible to create a GUI for the game using Qt. I played around with it a bit, being able to create widgets and what-not, but was unable to do one thing. For an... | It's a good thing to let the main.cpp as lean as possible, it should not contain much code in your case.
If I understand correctly you have several windows (could be simple QWidgets with no parent or QMainWindows) running on the same QApplication and your want to share data between them ? Why not just share a Player po... |
6,146,359 | 6,146,459 | Searching a data file: coding in python vs c++ | First off , this isn't a homework assignment!!! :p What I want to do is this:
Given a data file(be it text or numbers) saved on the desktop i.e., I want to be able to search that file and pull out only the data I want and print it to the screen. I may want to do other stuff with it but I have no idea what options there... | This is a bit difficult to answer without knowing how you want to specify the data you want.
If you can specify the necessary data using regexes, Python will probably be about equally efficient, and a bit quicker to write -- but you may be able to do the job with something like grep even more easily.
If it'll take a lo... |
6,146,969 | 6,147,001 | Not sure why my program wont display | #include <iostream>
#include <string>
using namespace std;
class BookData
{
string Title;
int Qty;
public:
void setTitle(string in_title) { Title = in_title;}
string setQty(int in_qty) { Qty = in_qty; }
string getTitle() { return Title; }
int getQty() { return Qty; }
};
int main()
{
BookDa... | Change the return type of BookData::setQty() from string to void.
Without this change, it should still work fine. On my Linux machine, it crashes when setQty() is called with a return type of string and no string being returned.
|
6,147,188 | 6,147,218 | C++ console not showing menu | If the user selects 1 or 2, function doesn't run. Any suggestions?
#include <iostream>
using namespace std;
void getTitle();
void getIsbn();
int main()
{
int choice = 0; // Stores user's menu choice
do
{
// Display menu
cout << " Main Menu\n\n\n";
// Display menu... | The functions should certainly get called. What will happen, though, is that the newline generated when you press "Enter" to type the number will get returned by the getline(), and the function will return without really prompting you. You need to clear that newline. You can use ignore() to do this: add cin.ignore(); i... |
6,147,374 | 6,151,074 | How do I share objects between a closed QDialog and newly opened QMainWindow? | I have an application that opens a QDialog for some flow, and when it is closed, the QMainWindow is opened.
In the QDialog I create some objects that I'd like to pass as a pointer (or some other way) to the QMainWindow. For example I create a SysTray object that needs to change its state from the QMainWindow. What is t... | One approach is to allocate on the heap with the QMainWindow as a parent. The QObject-hierarchy will take care of freeing the memory and you will access the object for the lifetime of the QMainWindow.
If at any point you know for sure that you don't need the QDialog or the shared object anymore, you can call deleteLate... |
6,147,717 | 6,147,752 | how this auto_ptr program works and what it does? | I ran this program but I didn't get what this auto_ptr does and on which basics it shows the values?
int main(int argc,char **argv)
{
int *i= new int;
auto_ptr<int> x(i);
auto_ptr<int>y;
y=x;
count <<x.get()<<endl;
count <<y.get()<<endl;
}
| This code will print a NULL address for the first auto_ptr object and some non-NULL address for the second, showing that the source object lost the reference during the assignment (=).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.