question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,918,396
4,918,411
Precompiled headers: do's and don'ts?
I know precompiled headers are used for speeding up compilations, but are there any do's and don'ts to what files I should include in them? For example, I have a project that uses a lot of boost libs so I just include the boost header files in stdafx.h (I'm using VS2008). Should I include every standard header file in ...
Pre-compiled headers don't affect the size of your executable, only the compilation speed. Since they are pre-compiled, they don't have to be re-compiled all the time. Windows.h is the primary beneficiary of this feature.
4,918,437
4,918,476
How to make such construction return values form 0 to 1?
It give me only 1s int maxVal; int minVal; int wh = w*h; int values[1000]; for(x=0;x<w;x++){ for(y=0;y<h;y++){ double RealColor = cvGetReal2D(source, y, x); values[x*y + y] = RealColor; } } minVal = *min_ele...
The values array is an array of int, so it can only contain integers rather than floating-point numbers. Does changing it to float or double fix the problem? Also, your indexing expression x*y + y is incorrect: it should be x*h + y or w*y + x.
4,919,035
4,919,103
Problem with using functions in 1 cpp file in another
I have 1 cpp file with main(). It relies on structs and functions in another (say, header.hpp). The structs are defined in header.hpp, along with function prototypes. The functions are implemented in header.cpp. When I try to compile, I get an error message saying: undefined reference to `see_blah(my_thing *)` So to g...
Your code is fine. You're just compiling it wrong. Try: g++ main.cpp header.cpp
4,919,181
4,919,227
Which memory allocation algorithm suits best for performance and time critical c++ applications?
I ask this question to determine which memory allocation algorithm gives better results with performance critical applications, like game engines, or embedded applications. Results are actually depends percentage of memory fragmented and time-determinism of memory request. There are several algorithms in the text books...
It all depends on the application. Server applications which can clear out all memory relating to a particular request at defined moments will have a different memory access pattern than video games, for instance. If there was one memory allocation algorithm that was always best for performance and fragmentation, woul...
4,919,209
5,552,465
errors compiling project with boost asio
I have created a separate project to connect my server component to clients using TCP/IP with boost::asio. I first created and tested this project separately first and tested these classes, everything worked fine. Adding this to my server component it now no longer compiles and I get following compiler errors about co...
The Windows SDK activates various operating-system specific release's additional API calls by using Preprocessor #defines. This allows you to build applications for any version of Windows, while preventing you from inadvertently building an application that won't run on, say, Windows 98. ::CreateWaitableTimer was added...
4,919,216
4,919,246
What is the benefit of constructors in C++?
Constructors initialize the data members of a class when an object is created. My question is, what is the benefit of this initialization process? Why wouldn't we let every object determine its initial value without a constructor to be called? And, also, what is the benefit of the default constructor? At the end, it is...
The constructor is the way to have every object determine its initial value. When you create a new object in C++, initially all of its data members have a completely indeterminate value. If you want to have the object determine its own default, it needs to have some code to execute in order to set its fields to meani...
4,919,264
4,942,485
Gtk+: How to set the cursor of a window from a Cairo context?
I have written the following code to set the cursor of a Gtk::Window from a Cairo::Context. When I run the program and move the cursor into the window, the cursor changes to a horizontal black line at the top, followed by some undefinable white shape at the bottom. I was expecting the cursor to change into a black 16×1...
I did not figure out the cause of the problem, but a way to work around it: Create an empty Gdk::Pixbuf. Create a Cairo::ImageSurface using the Gdk::Pixbuf's pixels as data buffer. Create a Cairo::Context from the Cairo::ImageSurface. Clear the Cairo::Context (this is important, because Gdk::Pixbuf's pixel data seem n...
4,919,303
4,919,321
C++ random number generation
For example, the following expression: r = (rand() % 10)+1; Generates a random number from 1-10. How can we make it generate random numbers from 0-10? Thanks.
You're almost there! The rand() function returns a random value in a pretty large range (0 to RAND_MAX). The use of the modulus operator wraps this down into a smaller range (from 0 to 9, since you're modding by 10) and then the +1 moves this to be from 1 to 10. To get values between 0 and 10, you can take rand and m...
4,919,308
4,919,419
Callback in C++ to a class member
We have a simple communication library for our customers. My problem is: How can I save a pointer to a method from a class of our customer? Library.h is the header file with all the methods our customer need to establish a communication. library.cpp is our code. Somewhere here i have to save the pointers to the method ...
The basic idea is, you define an abstract Callback class, which actually gets passed to your interface. This one calls back to a function passing a single int parameter: struct Callback { virtual ~Callback(){} virtual void operator()(int param)=0; }; This class allows YOUR implementation to be free from knowledge ...
4,919,322
4,919,355
C++ template class and inheritance
Possible Duplicates: [FAQ] Why doesn't a derived template class have access to a base template class' identifiers? Problem with protected fields in base class in c++ cannot access data member in a class template Following code gives me compilation error. What is wrong? struct Base { int amount; }; template<class...
The problem here has to do with how names are looked up in template classes that inherit from template base classes. The actual rules behind it are pretty arcane and I don't know them off the top of my head; I usually have to consult a reference to learn precisely why this doesn't work. The way to fix this is to expli...
4,919,440
4,919,491
Database creation error in Qt
I am using this code to create a database. But I am getting "false" in debug. I tried a lot but its not working. What is the error in this? QSqlQuery query; qDebug() << query.exec("CREATE TABLE glucose (id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER, date TEXT, time TEXT, duration TEXT, note TEXT"); qDebug() ...
you forget to close your CREATE TABLE query with ")"
4,919,460
4,920,288
C++ access specifiers
I just want to make sure I got the idea of public and private right. Regarding the private access specifier, does it mean: Only accessed inside the class Cannot be accessed from the object of the class unless there are public class methods that can be used to access them (Can other objects use those public functions?)...
I think there is an issue of vocabulary to begin with. In C++ (and most languages) a class is a type. You can think about it as a blueprint to actually build something. it describes the attributes that are held it describes the methods to operate on those attributes it describes the restrictions that apply: this is th...
4,919,720
4,921,002
Benchmarking an application in a fully loaded machine
I need to "time" or benchmark a number crunching application written in C/C++. The problem is that the machine where I run the program is usually full of people doing similar things, so the CPUs are always at full load. I thought about using functions from time.h liket "get time of the day" (don't remember the exact s...
From your other recent questions, you seem to be using MPI for parallelisation. Assuming this question is within the same context, then the simplest way to time your application would be to use MPI_Wtime(). From the man page: This subroutine returns the current value of time as a double precision floating point nu...
4,919,953
4,921,402
Why does RWDBManager::database need shared library name?
I am using Roguewave library to connect to Sybase database from C++. I understand that database object is constructed as: RWDBManager::database("accessLib", "", "", "", "", "XA=lrm_name"); http://www2.roguewave.com/support/docs/sourcepro/edition8/html/dbxaug/5-3.html says All arguments are of type RWCString. Note th...
It is probably because they dynamically load the library using it's name and a standard call like dlopen() on POSIX systems. There is an equivalent in windows, I think it is LoadLibrary(). With such a system you are able to load a library and get symbols from it. Very convenient to build plugin systems or things like t...
4,920,032
4,920,055
Can I change the access modifiers of any parent function in Child class?
Can I change the access modifiers of any parent function in Child class?
Child classes may only "loosen" the visibility, e.g. class ParentClass { protected function foo() {} } can be class ChildClass extends ParentClass { public function foo() {} } but not class ChildClass extends ParentClass { private function foo() {} } Apart from that, you can use the Reflection...
4,920,066
4,920,992
how to use c/cpp library/functions in android
I want to use c/cpp functions/library in an Android application using jni. any suggestion / links / tutorials /example ? my problem with pointer/structure return in c/cpp. how to use pointer/structure in android? actually, I am trying to develop a remote desktop application through which I should be able to access m...
The Android NDK is a toolset that lets you embed components that make use of native code in your Android applications. What is the NDK Following are some link which help you to work in Android NDK Using NDK to Call C code from Android Apps Android Beginners: NDK Setup Step by Step Writing applications using the Andro...
4,920,068
4,920,487
Partially specializing member-function implementations
I'm currently refactoring some code the explicitly specializes a member function of a class template with two template parameters. template <class S, class T> class Foo { void bar(); }; template <class S, class T> void Foo<S, T>::bar() { /* Generic stuff */ } template <> void Foo<SomeType, SomeType>::bar() { /* Som...
You are correct, it is not possible. What you can do is create a helper member class template inside the new Foo, and place the specialized function inside it as a non-template member function. Specialize the helper class instead of the function. Another alternative is to turn the specialization into a non-template ove...
4,920,424
4,920,567
Problems when using strtok function
Good morning to everybody, :) I have writen a code in C++ that reads information from a txt file. It takes the information in the first row saving it in a string and then I want to work with this info. I want to read this string and when it finds a "|" character it must jump to a new line. Its something quite easy but ...
strtok works with char*, not string*. That's probably why you're experiencing issues. Since you're implementing this with c++, I suggest you use the string functions instead of strtok: int main() { ifstream ifs( "C:\\a\\text.txt" ); string temp; getline( ifs, temp ); cout<<temp<<endl; size_t tok...
4,920,457
4,920,525
how can we determine our program well working?
Can we determine if a program is well working by considering the following questions? Memory is succesfully reclaimed by the Operating system There is no Stack Overflow after writing and running some code to determine whether there is any overflowing going on? Our assistant give us feedback after running our program...
You say that person has the source code - that means he can analyze the program - either by reading and thinking or by using some clever program. For example he could see the following: void someCleverFunction() { char* buffer = new char[100]; if( someCondition ) { //do something with the buffer del...
4,920,530
4,920,600
Typecast operator overloading problem
For example i have two classes A and B, such that for two objects a and b, i want to be able to do : A a; B b; a = b; b = a; for this i have overloaded the = operator, and the typecast operators as: class A{ -snip- operator B()const { return B(pVarA); } }; class B{ -snip- operator A()const { return A(pVarB); } ...
Try forward declaring then supplying the actual function definitions later on: class B; class A{ -snip- operator B()const; }; class B{ -snip- operator A()const; }; inline A::operator B() const { return B(pVarA); } inline B::operator A() const { return A(pVarB); }
4,920,610
4,920,649
C++ class function in assembly
Hello Community I am look at C++ assembly, I have compiled a benchmark from the PARSEC suite and I am having difficulty knowing how do they name the class attribute functions in assembly language. for example if I have a class with some functions to manipulate it, in cpp we call them like test.increment(); After some...
It's called name mangling, is necessary because of overloads and templates and such (i.e. the plain chars-and-numbers name isn't enough to identify a chunk of code unambiguously; embedding spaces or <> or :: in names usually isn't legal; copying the additional information in uncondensed, human-readable form would be wa...
4,920,661
4,920,947
Setting stdout/stderr text color in Windows
I tried using system("color 24"); but that didn't change the color in the prompt. So after more Googling I saw SetConsoleTextAttribute and wrote the below code. This results in both stdout and stderr both getting colored red instead of stdout being green and stderr being red. How do I solve this? My prompt is also now ...
According to the MSDN GetStdHandle() documentation, the function will return handles to the same active console screen buffer. So setting attributes using these handles will always change the same buffer. Because of this you have to specify the color right before you right to the output device: /* ... */ HANDLE hConso...
4,920,706
4,920,792
C++, add/remove rows from a QTableWidget
I'm creating a simple app with a table and an "Add row" button. Using Qt Creator I thought I can do something like this: QObject::connect(ui->addRowButton, SIGNAL(clicked()), ui->moneyTableWidget, SLOT(insertRow(1))); But I can't. I'm really new to Qt and I could be wrong, but think the problem is...
Insert the row in a method of your class. Try this class TableDialog : public QDialog { Q_OBJECT public: TableDialog(QWidget *parent = 0); private slots: void addRow(); private: QTableWidget *tableWidget; QDialogButtonBox *buttonBox; }; And the (partial) implementation: TableDialog::TableDialog(QW...
4,920,730
4,921,353
Cross platform and language plugin system
I'm looking for a good, cross platform and cross language plugin system in C++. I'm currently using Qt as a framework. I need the plugins to be cross platform, and to be able to be created in different scripting languages (python, ruby, etc.) and Java. Anyone here knows a good system for that? Thx, bl00dshooter.
Here a great article on how to write a portable plugin management system for C/C++. It demonstrates that such a system is hard to develop. It should have links in it ...
4,920,783
4,922,366
Combining Enum Value using Bitmask
I understand it's possible to use bitmasks in enum values, but I don't know how to create it. I have a simple enum : enum State { minimizing = 0, maximizing, minimized, maximized }; A state is always State.minimized or State.maximized, and can have additional state on resize. So something can be Maxim...
I am going to assume that myState has the type of your enum State. The traditional use of enum is to create the constant values that a variable of this type can take. You wish to set you variable myState to a combination of the values defined in the enum. The enum defines 1, 2, 4, and 8 as valid values, yet you want to...
4,921,071
4,921,452
String to Date in C++ [Using Anjuta IDE]
I'm writing a program and I need to read date from file. In date is year, month and day. How I need to read all date information?? Can you give some examples??
Firstly you'd probably need a struct to hold the values. There is a standard struct, tm, but this one has a lot of members, some of them depending on the others, and it would be confusing when the yday would not be conformant with wday and mday. struct Date { int year; int month; int day; }; Then you need ...
4,921,150
4,921,310
When to use static member function?
Possible Duplicates: Where would you use a friend function vs a static function? C++: static member functions When is it appropriate to use a static member function in C++? Please give me a real world example.
Good uses of static member functions: Meta-programming. Real-world example is template std::char_traits. All member functions are static Making it a static member function gives it access to private members of the class, although a friend would suffice here too A protected static member function thus is accessible onl...
4,921,392
4,921,469
Is there any software for recompiling a CMake-based software project on file changes?
I'm working on a C++ software project which uses CMake as its build system. The software is built on Mac OS/X, Linux as well as Windows. In order to improve my usual hack/compile/test cycle, I was wondering whether there is maybe some daemon-like software which is aware of all the source files considered by a CMake pro...
I've used JNotify for sucessfully monitoring file changes without much hassle. It works for all operating systems you mentioned and file change detection is almost instantanious. It can detect file creation, deletion, modification, etc. A nice code sample can be found here. You can do something like this: class CMakeLi...
4,921,549
4,923,663
Getting the broadcast source ip address with boost::asio
I'm currently struggling with a basic socket problem using boost::asio. A server is sending broadcasts in my LAN to discover client machines. The broadcast is successfully read on the client, but now I'm stuck with the question of how to get the IP address of the server, to be able to establish a regular connection to ...
try using the recieve_from or async_recieve_from methods for the UDP socket... they take an endpoint parameter that is filled in when the data is recieved.
4,921,592
4,921,767
Pimpl with smart pointers in a class with a template constructor: weird incomplete type issue
When using smart pointers with the pImpl idiom, as in struct Foo { private: struct Impl; boost::scoped_ptr<Impl> pImpl; }; the obvious problem is that Foo::Impl is incomplete at the point where the destructor of Foo is generated. Compilers usually emit a warning there, and boost::checked_delete, which is use...
This is the destructor of boost::shared_ptr<> that requires the object to be complete when using boost::checked_deleter<> deleter. Because you put the range constructor Bar::Bar(I begin, I end) in the header file the compiler must generate code that destroys already constructed members if your constructor throws, hence...
4,921,683
4,922,323
Visual Studio 2008 C++. Problem Referencing DLL Project
I've got a solution with two projects in it: one is a simple dll with a simple class (dll_test). The second project references the dll project and is supposed to be used to test the dll project (dll_tester). The dll project builds fine, but the tester project always complains about not being able to find dll_test.lib...
Ah, the joys of DLLs and dependencies in Visual Studio. I swear, C# coders have it easy :) Are you certain that the LIB file is actually created? If your DLL project does not export any symbols you won't get a lib file, and ergo you won't have anything to link to. So you need to make sure that: Your DLL Project def...
4,921,741
4,922,047
Question about std::less behavior
What is happening there? #include <functional> namespace A { struct Class { }; } bool operator<(const A::Class& a, const A::Class& b) { return false; } int main() { std::less<A::Class>()(A::Class(), A::Class()); return 0; } This is compiled ok. But if I use. #include <set> I got errors: g++ test.c...
The reason that the lookup fails is that set introduces an operator< for std::set in the std namespace that hides all other global operator<. The lookup of < in the instantiation of std::less happens inside a scope inside the std namespace. The only way that any operator< outside of std namespace will become visible is...
4,921,753
4,921,790
how to create a process which will run in kernel level in windows?
I want to create a kernel level of process for windows (Ring 0) but i don't know where to start from. I want to know which SDK is required and any tutorial showing its implementation would be helpful.
The SDK is the Windows Driver Kit and documentation here. As a correction to your question, at kernel mode you can't use processes, since kernel-mode drivers run as part of the operating system's executive. You can create kernel threads though.
4,921,817
4,921,950
Get screen resolution programmatically in OS X
I'd like to launch a fullscreen 3D C++ application in native resolution on mac. How can I retrieve the native screen resolution ?
If you don't wish to use Objective C, get the display ID that you wish to display on (using e.g. CGMainDisplayID), then use CGDisplayPixelsWide and CGDisplayPixelsHigh to get the screen width and height, in pixels. See "Getting Information About Displays" for how to get other display information. If you're willing to u...
4,922,048
4,922,128
Specialized partialization with template parameters
I have a template class ,MyClass<class E,class T>,and i want to use : std::unary_function<T,bool> _predicate; std::binary_function<T,E,void> _swaper; as template template parameters in my class , notice the bool and the void which is partial template specialization .... can someone tell how MyClass decleration and c...
depends if you need to use the parameters only in the constructor or not. Could be: class MyClass { template <class T, class E> MyClass(std::unary_function<T,bool> p, std::binary_function<T,E,void> s) { ... } ... } or template <class T, class E> class MyClass { MyClass(std::unary_function<T,boo...
4,922,191
4,922,597
C++ newbie: template function problem--getting string and numerical data from text file, putting it in vector
I am a newbie. I have tried to write a template function that gets string AND numerical data (for example, douubles) from a text file, then puts it in a vector. Each element of the vector is a different name or number. Last week I asked whether overloading or a template might be best for this. I would like to go w...
I had to do a bunch of work to make this a fully compilable code snippet. Here is what I came up with: #include <string> #include <vector> #include <istream> #include <fstream> #include <iterator> #include <sstream> #include <algorithm> template<typename T> void readFile(const std::string& name, const st...
4,922,325
4,922,425
Conditional operator "?:" in C++
Why this statement : int a = 7, b = 8, c = 0; c = b > a? a > b? a++: b++: a++ ? b++:a--; cout << c; is not equal to : int a = 7, b = 8, c = 0; c = (b > a? (a > b? a++: b++): a++)? b++: a--; cout << c; and is equal to : int a = 7, b = 8, c = 0; c = b > a? (a > b? a++: b++): (a++? b++: a--); cout << c; Please give me ...
Just put it on multiple lines to see the differences : c = b>a // true ? a>b // false ? a++ : b++ // b is incremted = 9; c = 8 (post increment) : a++ ? b++ : a--; is not equal to : c = ( b>a // true ? ( a>b // false ? a++ : b++ ) // b is incremted =...
4,922,404
4,922,433
boost::variant and void* pointers
I need a variant type that holds instances of any user-defined class. So I use void*: typedef boost::variant<void*, int, float, std::string> Tvariant; I've created a wrapper class with a map: typedef std::map<std::string, Tvariant> Tvalues; Example of usage: int x = 123; attributes.set("int_var", x); x = attributes.g...
Have you look at Boost::Any? This is something that carries with it compile time knowledge of the casting of the type while hiding what type it really is via the Any.
4,922,575
4,923,238
Class that inherits std::ostream and operator<< for QString
Hell ! I'm trying to make a class that would help me with outputting text to stdout ... Anyway, everything is working, except for one thing. Let's say that I've create object of my class called out. When I do this, everything works prefectly: out<<"test test"<<std::endl; And it also works when I do this: out<<QString(...
This compiles for me (with the command line from your third link): #include <iostream> #include <sstream> #include <QString> class Output: public std::ostream { friend std::ostream& operator<<(std::ostream &out, const QString var); private: class StreamBuffer: public std::stringbuf { private: ...
4,922,639
4,922,671
C++ boost::bind/lambda and operator bool()
How do I bind a conversion-to-bool operator using boost::bind or boost::lambda? For example, suppose I have a class C, with an operator bool(), and a list<C>. How do I use remove_if and bind/lambda to remove all elements that, when converted to bool, evaluate to false?
You don't need to use std::bind or std::remove_if for this; std::remove will suffice: std::vector<T> v; // Assuming T provides some conversion to bool // Remove all elements that evaluate to 'false': v.erase(std::remove(v.begin(), v.end(), false), v.end()); Or, you can use the std::logical_not function object with st...
4,922,820
4,923,050
Efficiently creating lots of small c++ objects that need access to "global" object
A question about c++ design and efficiency... Imagine this code - Database db; class SmallObject { private: /* Some small amount of data and functions */ public: /* Constructor, more functions */ void fn1() { /* Code that uses global db to do it's job */ } void fn2() { /* Code that uses global db to do...
If you are looking for efficiency it may well be the way you are allocating large numbers of small objects and might want to use some kind of pool. With regards to the database, I would question your coupling and what users of your classes are doing and seeing. Ideally you do not want them to see your implementation de...
4,922,875
4,922,978
How to prepare a codebase for compiling on both Windows and Unix-based systems
I am wondering about different solutions to easily compile my cross-platform application for both windows and unix. Right now I am using a makefile on Ubuntu, but before my codebase grows larger I'd like to perform the steps necessary to compile it on Windows, and then continue doing so regularly to see that it still w...
I will point you to CMake which is used by high-profile projects, such as MySQL, KDE, or Compiz. It has the ability to generate native build files for the target system, such as Makefiles for Unix-based platforms, and Visual C++ project and solution files for Windows. In order to deal with platform differences, I invit...
4,923,108
4,923,144
predicate for a map from string to int
I have this small program that reads a line of input & prints the words in it, with their respective number of occurrences. I want to sort the elements in the map that stores these values according to their occurrences. I mean, the words that only appear once, will be ordered to be at the beginning, then the words that...
std::map is always sorted according to its key. You cannot sort the elements by their value. You need to copy the contents to another data structure (for example std::vector<std::pair<string, int> >) which can be sorted. Here is a predicate that can be used to sort such a vector. Note that sorting algorithms in C++ sta...
4,923,270
4,923,639
Is operator-> "chained" for pointers?
Possible Duplicate: Overloading operator -> Hi, I've seen that operator->() is chained (re-applied) after it is evaluated, for example: struct Bar { Bar() : m_str("Hello world!") {} const string* operator->() const { return &m_str; } string m_str; }; struct Foo { const Bar& operator->() const { return m_bar...
C++98 standard §13.5.6/1 "Class member access": An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator-> exists and if the operator is selected at the best match function by the overload resolution mechanism (13.3). What this means in practice is that when x is a pointe...
4,923,384
4,923,531
Conversion of boost::optional to bool
How I can prevent the last line of this code from compiling? #include <boost/optional.hpp> int main() { typedef boost::optional<int> int_opt; int_opt opt = 0; bool x = opt; // <- I do not want this to compile } The last line doesn't examine opt's contained int value, but instead compiles as a type conver...
The whole point of boost::optional is to enable code like this: void func(boost::optional<int> optionalArg) { if (optionalArg) { doSomething(*optionalArg); } } So the implicit conversion to bool is a feature, and should not be prevented from compiling.
4,923,512
4,927,803
c++, insert only numbers (double) in a QTableWidget
I'm creating a sort of little spreadshirt and I need to insert only numbers in all the cells of a column. Is there anyway to do this just with the tablewidget or do I need to "fill" table with LineEdit and then restict on some way the LineEdit input? Can someone point me to the right direction?
After perusing some of the documentation, it looks like you might have to use QLineEdit widgets and setValidator to a QDoubleValidator. This is a fairly simple way to accomplish what you want, but for more complex spreadsheets you might need to get into something like a QTableView and get down and dirty in Qt's Model/V...
4,923,541
5,083,344
Bullseye vs MS code coverage tool
I need to select code coverage tool between Bullseye and MS code coverage tool. I found some positive feedback for Bullseye, and I can use MS code coverage tool free. The price for Bullseye is not that much ($800/1copy for buying, and $100/1copy+1year for later years), so it will not be a problem of licensing some copi...
Bullseye, is so much easier to use than the MS tool. To get the MS tool to work, is painful, especially for hundreds of projects you have to build.
4,923,608
4,923,655
overload operator<< for class template
let's take this code to implement the operator<< for two classes: #include <iostream> using std::cout; using std::endl; class A { int a1_; public: A(int a1) : a1_(a1){} std::ostream& print(std::ostream& os) const { return os << "a1_ : " << a1_ << endl; } }; class B { int b1_; doub...
Same as above: template< class T> std::ostream& operator<<(std::ostream& os, const T& in) { return in.print(os); } However, a "catch all" overload like that is a bit like dynamite fishing. You can constrain the range of the operator to all T's which define a suitable "print" member using SFINAE (http://en.wikipedi...
4,923,629
4,923,856
Printing Rich Layout Like Spreadsheets
I'm looking for a solution that would allow me to print from a C++/Qt app content like an invoice. To be clear, I'm not asking how I can manipulate excel spreadheets. I am looking to take my app data and PRINT OUT [to paper] something like an invoice that is nicely formatted. I need good formatting/layout capability. ...
QGridLayout can be used to create Excel-like "spreadsheet" form. You have control on where each of your info/widgets goes. To print the layout, place the layout and its content in a QWidget then use render to paint it onto a QPrinter, which is a QPaintDevice.
4,923,726
4,923,784
Line Break means something in C/C++?
I´m merging two branches of a software, and in the process of merging, some code stayed like that: if (b_flag) DoSomething(); //MERGE else //ENDMERGE DoOtherThing(); See the disconnection of the if/ else block ? This works like supposted to do ? Compilers take line breaks in consideration ?
Yes, it will work like it's supposed to. When you have an if or else with no curly braces ({}), the next statement is treated as being the body of the if. Inserting line breaks or comments doesn't change the fact that DoSomething(); or DoOtherThing(); are these statements.
4,923,748
4,923,889
C++ string constants and static variable initialization (or just use macros?)
I am writing a library and wanted to be as C++ centric as possible, remembering the old adage "Macros are evil". In a source file, I had the following definitions: const std::string DATA_DIR_ENV_STR = "DATADIR" const std::string DFLT_DATA_DIR = "../data" /* #define DATA_DIR_ENV_STR "DATADIR" #define DFLT_DATA_DIR "...
Yes, this is the static initialization fiasco biting your behind. A way to avoid it is the "construct on first use" idiom (brain-compiled code): // In the header class mySingleton { private: static mySingleton *s_instance; mySingleton(); public: mySingleton &instance() { if (...
4,923,878
4,923,971
decimal to 8 bit binary conversion in c++
I am working on decimal to binary conversion. I can convert them, using char bin_x [10]; itoa (x,bin_x,2); but the problem is, i want answer in 8 bits. And it gives me as, for example x =5, so output will be 101, but i want 00000101. Is there any way to append zeros in the start of array? or is it possible to get a...
In C++, the easiest way is probably to use a std::bitset: #include <iostream> #include <bitset> int main() { int x = 5; std::bitset<8> bin_x(x); std::cout << bin_x; return 0; } Result: 00000101
4,923,956
4,924,139
Starting programs from C++, exchanging info with pipes and then shared memory
I am currently developing a modular framework using shared memory in C & C++. The goal is to have independent programs in both C and C++, talk to each other through shared memory. E.g. one program is responsible for reading a GPS and another responsible for processing the data from several sensors. A master program w...
Pipes are not reroutable -- they go where they go when they were created. What you need to do is have the slave close the pipe when its done with it, and then reopen its stdout elsewhere. If you always want output to the terminal, you can use freopen("/dev/tty", "w", stdout), but then it will always go to the termina...
4,924,053
4,924,108
inserting subclasses into a superclasses array in c++
This is one of those things where i just know im doing it wrong. My assignment is simple. Create 3 classes in c++, product ,software ,book. product is super, book and software are product. then make an array of pointers and fill the array with software and books. so i've done the following int main() { Product *produ...
As the array is of type Product, you should declare pSoftware as a pointer to Product: Product *pSoftware = new Software(5); // ... productList[0] = pSoftware;
4,924,082
4,924,318
Static template data members storage
First I'll write example to properly address the question. First of all, I'll declare template to be used to create singleton object (not auto-created): singleton_base.h template <class Derived> class SingletonBase { public: static Derived* instance() { assert(s_instance); return dynamic_cast<Derived*>(s_instance...
The answer to this is the same as with any other template-based or inline function - the only difference is in this case the variable ends up being marked for placement in a read-write section. In most compilers, the compiler will instantiate any needed template functions and static member variables in every compilatio...
4,924,157
4,924,183
iterator of template based container
template<class A,class B> void tmp(){ set<int,int>::iterator it; //works set<A,B>::iterator it; // doesn't work }
Due to some rather annoying limitations in C++'s grammar, you must explicitly tell C++ that set<A,B>::iterator is a type name, rather than a static member identifier, using the typename keyword. For example, this code compiles just fine: #include <set> template<class A, class B> void tmp() { std::set<int,int>::ite...
4,924,212
4,924,369
C++ - What does this double pointer/array structure really mean? I have trouble picturing it
This is within C++ code YInterface ** Y_list; int numberofYInterfaces; then numberofYInterfaces=1; Y_list = new YInterface *[numberofYInterfaces]; //What ?????? I have a very hard time picturing the structure of Y_list? And then imagine my confusion when and if the numberofYInterfaces becomes more than one, ...
When you declare Y_list, you get a single variable with an unspecified value in it: Y_list +-------+ | | +-------+ When you assign it with new[], it points to whatever new[] allocated, which in this case is an array of pointers: Y_list array +-------+ +-------+ | o---+---->| | +-------+ ...
4,924,249
4,924,878
The fastest minimum spanning tree algorithm
http://en.wikipedia.org/wiki/Minimum_spanning_tree I'm looking to benchmark my minimum spanning tree algorithm against the best of the best. Does someone know where I can find a C++ implementation of these algorithms? I binged and googled the and didn't find anything. If these algorithms are the best, surely there must...
When the Wikipedia page says "the fastest minimum spanning tree algorithm," what they mean is the algorithm with the lowest asymptotic bounds -- in this case, O(m α(m,n)), with m, n, and α defined as in the quote you pasted. Put simply, this means that for very large input values, the amount of time taken will always ...
4,924,785
4,924,804
Will function dispatch via vtable if calling non-virtual implementation?
Say I have the following: struct Base { virtual void callback() { /* */ } }; struct Derived : public Base { void callback() { /* */ } }; Base* obj = new Derived; static_cast<Derived*>(obj)->callback(); Will the call to callback invoke via the vtable or a straight function call as it's not marked as virtual i...
Derived::callback is implicitly virtual because the Base::callback function with a the same return type and parameters is declared as virtual. That said, whether or not the vtable is used depends on the compiler and what optimizations it performs. Since the compiler can know here that obj points to a Derived object, i...
4,924,912
4,925,602
Inline qualifier stems from prototype or definition?
I'm not quite sure about this in the standards. Say I have three files like this: foo.h #include <iostream> inline void foo(); void foo() { std::cout << "Foo" << std::endl; } foo.cpp: #include "foo.h" void baz(); int main() { baz(); foo(); } bar.cpp #include "foo.h" void baz() { foo(); } Now, the de...
C++0X draft N3225 says in 7.1.2 Function specifiers: clause 2: A function declaration with an inline specifier declares an inline function clause 4: An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case. So, to me, it looks lik...
4,925,012
23,131,842
Can I get a report of ALL the libraries linked when building my C++ executable (gcc)? (including statically linked)
I have a C++ application that I inherited, which consists of: My main app Several app-specific libraries (libapp1, libapp2, etc...) Several "third party" libraries (most "third partis are just other teams in the company") linked from both the main app, from the app-specific libappX libraries, and from other 3rd part l...
I had similar problem and found solution: add -Wl,--verbose option when linking. It will switch linker to verbose mode: gcc -o test main.o -ltest -L. -Wl,--verbose Here is example output: GNU ld (GNU Binutils) 2.23.52.20130604 Supported emulations: i386pep i386pe using internal linker script: =================...
4,925,028
4,925,067
Can you specify the order of thread termination, i.e. thread dependencies?
I am making a video game and I have a main thread which takes care of the graphics, and a separate worker thread which takes care of the networking (synchronous UDP sockets). The problem is that when I close the game, I get an "Access violation" error, and the debugger points me to one of several lines of code--each of...
Before cleaning up shared resources, the main thread should wait for the networking thread to complete. In Boost, the boost::thread::join() function should do the trick. Be sure to deal with boost::thread_interrupted as well! (N.B. This is sort of a generic answer; I have no experience with Boost threading in particula...
4,925,131
4,929,672
Interaction between Bluetooth and a computer
I'm developing a device and writing the software for it under Windows (MFC with Visual Studio). I would like to start a measurement with a remote. It would be nice if it worked over Bluetooth, but I don't have a clue where to start. What book can recommended or is there a site where such things are described? Is it eve...
As Dan wrote in the comment when it comes to Microsoft the best place to start is with MSDN. For me his link didn't work, but I guess he wanted to point here. MFC does not offer you support for Bluetooth, instead you have to work with a Bluetooth driver stack API. On Windows there are more stacks, but most widely used ...
4,925,150
4,925,210
Redirect cin to a string
I want to have cin read input from a string. Is there a way to have it do this? Something like this: const char * s = "123 ab"; cin.readFrom(s);//<---- I want something like this int i; cin>>i; cout<<i; //123
Like this: #include <sstream> #include <iostream> std::istringstream stream("Some string 123"); streambuf* cin_backup = std::cin.rdbuf(stream.rdbuf()); You might want to back up the original rdbuf of std::cin, if you want to use it again.
4,925,191
4,925,248
How to get around inability to overload on return type in C++
I have function which can create a number of different templated types; an simple example of the problem would be: EncodedMsg<?>* encode(const Msg& msg) { if(msg.qty < 100) return new EncodedMsg<short>(...); else if(msg.qty < 100000) return new EncodedMsg<int>(...); else return new...
You are attempting to use templates in a dynamic fashion, which isn't possible. The template's type must be known at compile time, so you can't differentiate based on a series of conditionals. To change type at runtime, you'll need polymorphism from classes and inheritance.
4,925,233
4,926,150
Global variable has multiple copies on Windows and a single on Linux when compiled in both exec and shared libaray
* Question revised (see below) * I have a cpp file that defines a static global variable e.g. static Foo bar; This cpp file is compiled into an executable and a shared library. The executable may load the shared library at run time. If I am on Linux there seem to be two copies of this variable. I assume one comes from...
I strongly suggest you read the following. Afterwards, you will understand everything about shared libraries in Linux. As said by others, the quick answer is that the static keyword will limit the scope of the global variable to the translation unit (and thus, to the executable or shared library). Using the keyword ext...
4,925,253
4,941,633
Do any boost::asio async calls automatically time out?
I have a client and server using boost::asio asynchronously. I want to add some timeouts to close the connection and potentially retry if something goes wrong. My initial thought was that any time I call an async_ function I should also start a deadline_timer to expire after I expect the async operation to complete. No...
So I did some testing. Based on my results, it's clear that they depend on the underlying OS implementation. For reference, I tested this with a stock Fedora kernel: 2.6.35.10-74.fc14.x86_64. The bottom line is that async_resolve() looks to be the only case where you might be able to get away without setting a deadline...
4,925,300
4,926,696
Program compiled on Linux not getting code in #ifdef section
I have a cross platform program I am working on that has several files with #ifdef WIN32 ...inclues #endif #ifdef LINUX ..inlcudes #endif when I went to compile on LINUX I keep getting errors about not finding functions and such, but if i comment out the #ifdef LINUX blocks (still keeping the includes uncommented) it...
Your make file actually does work for c files, but not for c++ files. This is because you invoke your custom compile command line for c compilation but your cpp files are going directly into what is effectively your link command line which does not specify compilation flags.
4,925,390
4,925,412
C# - stream question
When I was writing some I/O routine in C++, I would usually make it as generic as possible, by operating on the interfaces from <iostream>. For example: void someRoutine(std::istream& stream) { ... } How should the same be done in C#? I suspect I could write my routines based on the System.IO.TextReader or System.IO.T...
If you want to work with strings, you should take a TextReader or TextWriter. If you want to work with bytes, you should take a Stream. These classes are inherited by concrete implementations such as FileStream, StringWriter, and NetworkStream.
4,925,394
4,925,434
why prepend namespace with ::, for example ::std::vector
I have seen production code such as ::std::vector<myclass> myvec; I have no idea what the prepending :: mean however - and why is it used? For an example see: C++: Proper way to iterate over STL containers
The leading "::" refers to the global namespace. Suppose you say namespace foo { .... Then std::Bar refers to foo::std::Bar, while ::std::Bar refers to std::Bar, which is probably what the user meant. So always including the initial "::" can protect you against referring to the wrong namespace, if you're not sure which...
4,925,639
4,925,879
va_arg with a list of void*
I would like to create a function that takes a variable number of void pointers, val=va_arg(vl,void*); but above doesn't work, is there portable way to achieve this using some other type instead of void*?
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> void myfunc(void *ptr, ...) { va_list va; void *p; va_start(va, ptr); for (p = ptr; p != NULL; p = va_arg(va, void *)) { printf("%p\n", p); } va_end(va); } int main() { myfunc(main, myfunc, printf, ...
4,925,647
4,925,722
C++ array creation problem specific to gcc 4.5
The following code works under gcc versions 2.9 through 4.4 but not version 4.5: struct Pass { }; int main(void){ Pass **passes = new ( Pass (*[ 10 ]) ); } The specific error message with gcc 4.5 is: prob.cc: In function ‘int main()’: prob.cc:6:31: warning: lambda expressions only available with -std=c++0x or -...
Pass** passes = new Pass*[10];
4,925,665
4,925,773
Using qsort() with class pointers
I am using the in-built function qsort() to sort a vector of class item pointers. class item { int value; vector<char> c; ... ... }; //Declaration of vector vector<item*> items; //Function Call qsort(&items, items.size(), sizeof(item*), value_sort); int value_sort(const void* a, const void* b) { item* pa = *(item**...
I agree with the answers that advise using std::sort. But ignoring that for the moment, I think the reason for your problem is that you're passing the address of the vector object, not the contents of the vector. Try this: //Function Call qsort(&items[0], items.size(), sizeof(item*), value_sort); Then after you try t...
4,925,818
4,925,947
Getting input into a process
While talking with a friend over yahoo messenger, I told him would be really cool to make a bot to answer with generic messages when someone starts a conversation. Upon thinking about what I told him, I realized it would be quite interesting to do something like that. The problem is that I don't know much about win32. ...
http://pinvoke.net/ seems to be the website you are looking for. The site explains how to use Windows API functions in higher level languages. Search on pinvoke for any of the functions I've listed below and it gives you the code necessary to be able to use these functions in your application. You'll likely want to us...
4,926,105
4,926,163
What is forward declaration in c++?
This answer says: … Finally, typedef struct { ... } Foo; declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also can't be forward-declared. If you want to make a forward declaration, ...
Chad has given a pretty good dictionary definition. Forward declarations are often used in C++ to deal with circular relationships. For example: class B; // Forward declaration class A { B* b; }; class B { A* a; };
4,926,287
4,926,372
Is it possible to truncate an array of derived classes into an array of base classes in C++?
I'm making an application which uses OpenGL and currently store an array of objects that should be rendered each frame which look something like this: class Object { private: float x; float y; public: void func1(); void func2(); ... }; I'd like to be able to create a vertex buffer object from t...
The functions in your class Object don't actually contribute anything to the object's layout. Although the spec doesn't guarantee this, on all major compilers the in-memory representation of an object is just its fields. (If you add a virtual function into the mix, though, this isn't true). In your case, your Object...
4,926,435
4,926,724
C++ preprocessor and overloading issues
I have the following problem: Let's consider we have #define SET callMe #define COLUMN(x) #x and in our main block of our program we have the following line: SET(COLUMN(price)="hi"); which after the preprocessor running is translated to: #callMe("price"="hi"); I need function callMe signature to be callMe(string st...
Is this any good to you? #define SECOND_PASS(x) callMe(#x) #define COLUMN(x) x #define SET(x) SECOND_PASS(x) which results in: callMe("price=\"hi\""); This essentially gets the preprocessor to remove COLUMN before converting to a string.
4,926,436
4,926,474
About C++ STL list class method erase()
The documentation of list::erase() says, "call destructor before", what does this mean? If I want to erase(it) a item and then push_back(*it) the item again, will that be illegal since it was destructed already?
Yes, this will result in undefined behavior. Once you erase a list iterator you invalidate the iterator, meaning that the object it references is no longer guaranteed to be valid. This means that if you then try to use the iterator in any context, including trying to dereference the value to add it to the list again,...
4,926,517
4,926,545
Does it matter whether I put an #include directive in my cpp file or in an included header file?
My c++ program is using a separate header file (Let's call it myHeader.h) and therefore includes it (#include "myHeader.h"). In my program I need to use another header file (Let's call it another.h). Does it make a difference whether I put the #include "another.h" directive in the cpp file or in myHeader.h?
If it's not used in the .h file, then there will be no difference in compilation success/failure. However, it is recommended to put include for header files you only need in the implementation in the .cpp files for the following reasons: for encapsulation reasons - no one needs to know what you include solely for the ...
4,926,622
4,926,654
How to generate different random numbers in a loop in C++?
Is it possible to generate different random number, every time loop runs. For example, i have: for (int t=0;t<10;t++) { int random_x; srand ( time(NULL) ); random_x = rand() % 100; cout<<"\nRandom X = "<<random_x; } But the problem is, it generates same random number everytime. Is it possible to gener...
Don't use srand inside the loop, use it only once, e.g. at the start of main(). And srand() is exactly how you reset this.
4,926,674
4,931,251
Unpacking Argument List with Variadic Template
I'm trying to create a C++ convenience wrapper around an old C-API that uses an opaque data type. There's one particular C-function which takes a format string, along with a variable number of arguments using the C <stdarg.h> facilities. As part of my wrapper, I want to be able to pass an arbitrary number of argument...
I think you need the same syntax as when you do perfect forwarding : template <class... Args> void apply(OPAQUE* object, const char* fmt_string, Args&&... args) { C_API_Function_Call(object, fmt_string, Convert(std::forward<Arg>(args))...); } The ellipsis ... can be placed at the right of an expression containing t...
4,926,784
4,926,851
C++ std::string problem using VC10
I'm using C++, Visual Studio 2010 Premium on Windows 7, and in my application I have a std::string variable that fails on append :( ... The situation is, the string variable contains a huge amount of chars appended at different times, first time I add for example 7609 bytes, second time 8184 and finally 1463, somethin...
Is this snippet your actual code? What do you mean with "taking care of the char 0"? do { bytesRead = ReadChars(buffer, BUFFER_SIZE); if (bytesRead > 0) str += buffer; // I'm already taking care of the char 0 at the end :) } while (bytesRead > 0); In your example, you always append the whole buffer to ...
4,926,800
4,927,141
Testing concurrent data structure
What are some methods for testing concurrent data structures to make sure the data structs behave correctly when accessed from multiple threads ?
All of the other answers have focused on actually testing the code by putting it through its paces and actually running it in one form or another or politely saying "don't do it yourself, use an existing library". This is great and all, but IMO, the most important (practical tests are important too) test is to look at ...
4,926,935
4,927,181
Find what bodies are colliding in Box2D using C++
I have a basic class for detecting collisions but I can't figure out how to see what bodies are colliding to trigger the appropriate event. Lets say I have a pong game and in it a ballBody and topwallBody. How would I figure out if these are colliding or not. Here is the class I'm using just to give you an idea. class ...
When you create the bodies, set the userdata to something meaningful, but be consistent :) A good tip is to always have the same kind and type of data in there, an entity id or reference to an actor. Straight from the documentation: b2BodyDef bodyDef; bodyDef.userData = &myActor; So if you went this road you would ge...
4,926,990
4,935,661
Build Boost 1.45 using MinGW
Try to compile Boost 1.45 on Windows XP using MinGW. I did it a year ago and almost forgot how to repeat it. %PATH% contains MinGW path. user-config.jam contains using gcc ; bjam (the ntx86 one) from here. Output: <path> > bjam --build-dir="E:\Boost" --build-type=complete toolset=gcc stage <path>/tools/build/v2/build\...
Downloaded previous release of Boost - 1.44. The same bjam (3.1.18-1-ntx86) with Boost 1.44 works just great.
4,927,007
4,927,099
setting breakpoints when array value changes in cuda-gdb
Is there a way to set a breakpoint in GDB for when a particular index of an array changes? That is, can I make it stop when array[25] changes? This would be happening in the kernel, of course.
If it follows the same commands as gdb, the command would be something like watch array[25] Edit: As of September 2010 watchpoints were not implemented, and you need a watchpoint to do this. http://forums.nvidia.com/index.php?showtopic=180367
4,927,114
4,927,366
New thread on invocation of timer_create()
I am investigating how to get thread ID when the function timer_create() is called. I observed that everytime the timer_create() is called, a new thread (child thread of main process) is created. I verified this with ps -eL|grep I need to get the same TID (child thread ID) displayed by ps -eL inside my program which u...
Whether a thread even exists before the timeout handler gets called is unspecified. Certainly a conformant implementation could defer creation of the thread until the timer expires. The existence of numeric thread ids that look like pids is also an implementation detail, one which you should not use. Could you explain ...
4,927,154
4,927,436
C++ string array char questions
why when i try to compile this code: TenStrings::TenStrings() { char str1[10] = "String 1"; char str2[10] = "String 2"; char str3[10] = "String 3"; char str4[10] = "String 4"; } ; i get error: unused variable str1, str2, str 3, str4? I am trying to make a char array that will fit "string 1", "string 2", etc
For the assignment that you're working on, you do not want to be declaring variables named str1, str2, etc. You want your TenStrings class to have a single data member (call it strings) which is an array of ten char pointers. This array would be initialized in your constructor. You have spent so much time asking questi...
4,927,531
4,927,661
How can you assert that all std::vector<std::string> are a given size in a one-liner?
I have a method which accepts a std::vector of sha1 hashes as strings which must exactly 20 characters long. It would be great to assert in a one-liner that this precondition is respected.. void MyClass::setSha1Sums(const std::vector<std::string>& sha1Sums) { assert(magic_oneliner_which_verifies_that_all_strings_are...
C++03, with boost (>= 1.33): std::find_if( sha1Sums.begin(), sha1Sums.end() , boost::bind( &std::string::size, _1 ) != 20U ) == sha1Sums.end(); Note that the != is an overloaded operator that boost supplies to make building more complex binds which use basic relational and logical operators...
4,927,595
4,927,642
C++ whats going on here
Lets say i have a class TwoWayList that holds Records , and GetRec actually creates a new list on the heap, here is the method void GetRec(TwoWayList<Record> &rec) { TwoWayList<Record>* list= new TwoWayList<Record>(); Record r; list->Insert(&r); } Now i have the follow two scenarios, the first one dies when ...
Your first main creates record on the stack -- not the heap. So your attempt to delete the address of a stack variable crashes. Your second main never allocates record at all. So when you try to use the pointer, it segfaults. Also, your function allocates memory, but then forgets about it and leaks it. By that I mea...
4,927,682
4,927,711
Help compiling with gcc/g++
If I have a directory structure such as the tree below, what should my g++ command look like that would successfully compile the .cpp file that is in the taglib/bin dir, with all my .h files sitting in the taglib/include/taglib directory. Anyones help would be greatly appreciated. Thank you! -taglib --bin .cpp file...
The -I and -L options specify search directories for includes and libraries respectively. Therefore, you command should be something like: g++ -o <xyz> taglib/bin/*.cpp -Iinclude/taglib -Llib man gcc and even gcc --help gives great information on these particular command line options (and the GCC manual is fairly frien...
4,927,748
4,927,765
Does the implicitly defined copy constructor in C++ call copy constructor for members too right?
Just want to double check that the default (implicitly defined by compiler) copy constructor for C++ classes performs the copy constructor on each member variable as well using the old value to get the copied value for each member and for atomic objects just uses a bit copy (e.g. ints and floats)
Yes, that is exactly what it does.
4,927,956
4,928,342
cygwin doesnt recognize >> operator? C++
cout and the << operator work fine in compiling c++ program in CYgwin but as soon as i try the cin >> operator, compiler breaks says cygwin doesnt recognize >>? wt is that about? source code: #include "TenStrings.h" #include <iostream> using namespace std; using std::cin; //Default Constructor TenStrings::TenStrings(...
Ok, now we see the problem. You shouldn't use endl with cin. Say just cin >> numAlter; and it will automatically wait for the enter key to be pressed. You don't need both using namespace std; and using std::cin;. That was just a wild guess because I couldn't be sure of your problem without seeing the code. My crysta...
4,928,203
4,928,321
undefined reference to 'readline'
I'm trying to use the readline library in my c++ project using netbeans, so I've installed libreadline6-dev and add it to my project Properties -> Linker -> Additional Library directories -> and add (usr/include/readline). But while compiling I get this error : undefined reference to 'readline'. I found that I need to ...
You are on the good way, the problem you got is about the linker. You have to specify the library(readline) here: Project properties -> Build -> Linker -> Libraries. and you also need to specify the path of the library: Properties -> Linker -> Additional Library directories But, like nos said, it is not the include dir...
4,928,242
4,928,558
Use PHP functions in PHP extension
Can I use a PHP function such as explode() when creating an extension in C++?
Here it is: PHP_FUNCTION(explode) expands to zif_explode with these parameters. That's the function you should call. Read this for more details.
4,928,276
4,935,555
image color conversion
I need to convert 24bppRGB to 16bppRGB, 8bppRGB, 4bppRGB, 8bpp grayscal and 4bpp grayscale. Any good link or other suggestions? preferably using Windows/GDI+ [EDIT] speed is more critical than quality. source images are screenshots [EDIT1] color conversion is required to minimize space
I received acceptable results (preliminary) by GDI+, v.1.1 that is shipped with Vista and Win7. It allows conversion to 16bpp (I used PixelFormat16bppRGB565) and to 8bpp and 4bpp using standard palettes. Better quality could be received by "optimal palette" - GDI+ would calculate optimal palette for each screenshot, bu...
4,928,296
4,928,344
Efforts or plans to port gson to C++
Does anyone know if there have been any efforts or plans to create a C++ version of gson? The library is very helpful and one the easiest to use and it would be great if there was something similar for C++/
You mean the google project to convert json into java objects and back? There are c++ json libraries but from what I understand, the advantage of gson is the ability to automatically serialize objects. The problem that makes this difficult, and impossible to do as well as in other languages is that C++ doesn't support ...
4,928,404
4,928,405
Returning a flexible datatype from a C++ function
I'm developing for a legacy C++ application which uses ODBC for it's data access. Coming from a C# background, I really miss the ADO style of data access. I'm writing a wrapper (because we can't actually use ADO) to make our data access less painful. This means no char arrays, no manual text blob streaming, and no decl...
I used OTL (http://otl.sourceforge.net/) in some one-off projects back in the day for interfacing C++ and some SQL Server databases. It's streams-based, so it can do type conversion for you. I did find the streams paradigm a bit confusing at times, as I had to unstream the values in the query order - I never quite fi...
4,928,411
4,930,725
Changing QPushButton Color when Pressed
Is there a way to change the background color of a QPushButton which is pressed by modifying its QPalette object? I realize it can be done with style sheets but would like a way to do it by modifying the QPalette. Something similar to how one changes the background color of the button when not pressed: QPushButton my...
Connect to QPushButton's pressed() signal and update the palette with your desired color and then connect to released() signal and switch back the color to the old color. That should do it. You may want to run update() after settings the colors or in extreme cases repaint().
4,928,417
4,928,827
SWIG: private typedefs used in public functions
I often give my classes a private typedef to refer to themselves, as follows: class MyClass { private: typedef MyClass Self; public: void DeepCopyFrom(const Self& other); ... }; I'm now wrapping my C++ code using SWIG, which complains about such typedefs: error: ‘typedef class MyClass MyClass::Self’ is...
I suggest keeping it simple(r): just remove the typedefs and write the class name instead. If you really hate that, you could tell SWIG to %ignore the "broken" methods and then %extend the classes with wrapper methods calling the real ones. Unless the number of classes and methods you are binding is small relative to ...