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,785,640
4,786,152
Template argument deduction (using both explicit and implicit arguments in same call)
I have three template arguments to a function and am having troubles with (I think) the compiler deducing which template argument is which. The template function is: #include <structures/partition.h> #include <vector> namespace cliques { template <typename P, typename T, typename QF> P find_optimal_partition_l...
I hate to answer my own question but problem was that cliques::DisjointSubsetForest is actually a templated class so cliques::find_optimal_partition_louvain<cliques::DisjointSetForest<int> >(my_new_graph, cliques::find_linearised_stability(current_markov_time)); works
4,785,678
4,786,040
C++ class declarations and namespaces
I'm having an issue with a C++ library I'm trying to write. It's the usual setup, one cpp file, one header file. I want the header file to only expose the parts that are meant to be used (I have an abstract base class for instance, I don't want in the header file). So far, I'm just working with a single file (I assume ...
There are two problems with .cpp files you are dealing here: I. If you want to put an instance of that class on the stack (like you do in your main()) the compiler needs to know the size of the class (to allocate enough memory). For that it needs to know the members and by that the complete declaration. The only way to...
4,785,760
4,786,244
C++ Generic Abstract Factory Design Question
I'm currently trying to design an generic Abstract Factory and have the following class design sketched out: template <typename T> class TFactory { public: template <typename A> static T* create(A a); template <typename A, typename B> static T* create(A a, B b); template <t...
You can find this kind of work already done in Boost libraries such as Bind and Lambda. Here is a list of Lambda expressions that wrap constructors/destructors and new/delete. You can either use those, or get inspired by them to write your own. For example, using Lambda constructor, you could have the following: templa...
4,785,765
4,785,823
How to include a C/C++ lib (e.g. libcurl) in a C++ project (IDE: Eclipse)?
I have a problem, I'm working on a C++ project (I'm using Eclipse as my IDE). Now I want to make use of a C/C++ library, for example libcurl, so I download curl and don't know what to do next. Must I only include the .h and .c files I need or must I compile it before?
A typical way to use a library (this, of course might differ from library to library) is to include all of the header files from the library, include them as needed, use functions that they provide. Then, when building the application, link the objects with the library object (.a, .lib, whatever the extension). If you ...
4,785,884
4,785,905
C++ Download file from internet with Winhttp
Possible Duplicate: How to download a file with WinHTTP in C/C++ ? Hello! I have a simple question. How can you download a file from specific http page with the help of Winhttp in C++? Note: I want to use this function for a console application.
You should try to read the API or a tutorial
4,785,900
4,785,944
How to find the minimal element of a BST?
I'm a beginner to c++ and am having problems with finding the minimal element of a BST. The BST is implemented in this way: class Tree{ struct Node { int Element; Node *Left, *Right; Node(int Element) : Element(Element), Left(0), Right(0){} }; Node *Root; void InOrder(void(*Action)(int&), Node *Current); void Destro...
The minimal value would be the first value that calls Action in the above code. Go left as far as you can, and the minimal value you shall find...
4,785,928
4,786,030
Class function member not depending on the class members
Is there a good reason why should a class function member be part of the class if it does not depend on any of the members of the class?
No. In fact, you should prefer free-functions over member functions. Only functions that really need to operate on the members should be member functions, the rest should use them to provide functionality.
4,786,292
4,786,441
Converting unicode strings and vice-versa
I'm kind of new to using Unicode string and pointers and I've no idea how the conversion to unicode to ascii and versa-versa works. Following is what I'm trying to do, const wchar_t *p = L"This is a string"; If I wanted to convert it to char*, how would the conversion work with converting wchar_t* to char* and vice-ve...
The solutions are platform-dependent. On Windows use MultiByteToWideChar and WideCharToMultiByte API functions. On Unix/linux platforms iconv library is quite popular.
4,786,334
4,786,403
C++ function that takes an OutputIterator and writes to it
I'm trying to write a C++ function that takes an OutputIterator and writes values to it, but I'm getting various problems. When I pass in a list<> iterator, the list is not filled, and when I pass in a vector<> iterator, I get a segmentation fault (on Linux). I followed the discussions from "populating an std::[contain...
Your code breaks, because neither the list nor the vector have enough elements. Note that an output iterator doesn't add elements, it simply writes to existing elements. Thus, you could rewrite it as follows: template<typename Container> void insertValues(Container &result) { for (int i = 0; i < 10; i++) { ...
4,786,364
4,786,400
Pointer arithmetic and const qualifier in C
In the following piece of code, to calculate strlen, int s(const char* str) { int count=0; while(*str++) count++; return count; } You can see that the argument str is const. But, the compiler does not complain when I do a str++. My question is When passing pointers as arguments to a C function, ...
const char* str; means a non-const pointer to a const data. char* const str; means a const pointer to a non-const data. const char* const str; means a const pointer to a const data. The reason for this is that in C++ the variable type declarations are parsed from right to left, which results in that the word "const"...
4,786,448
4,786,472
How does less take over to the console?
I want to take over the console like less does, to make a more interactive app. It seems like they have complete control over what gets drawn where. How can I do that?
It uses the ncurses library for handling the terminal.
4,786,481
4,786,617
What's wrong with my switch-case?
It automatically does the default and not any of my cases. Any idea what I'm doing wrong? #include <stdio.h> #include <math.h> int main () { float x,y,z,p,a,h; int d; printf ("\n This program calculates Perimeter, Area, or Hypotenuse of a right triangle based on user choice\n\n\n\n"); /* Prompt user...
It looks like your scanf() call: scanf ("%f,%f,%f",&p,&a,&h); should be: scanf ("%c",&d); Why would you ever think accepting three float inputs makes sense given the text of the prompt!? However doing that will cause you problems with the subsequent input calls, so what you should actually do is: scanf ("%c",&d); wh...
4,786,521
4,788,440
Check if thread is a boost thread
For purposes of thread local cleanup I need to create an assertion that checks if the current thread was created via boost::thread. How can I can check if this was the case? That is, how can I check if the current thread is handled by boost::thread? I simply need this to do a cleanup of thread local storage when the t...
The premise for your question is mistaken :) boost::thread_specific_ptr works even if the thread is not a boost thread. Think about it -- how would thread specific storage for the main thread work, seeing as it's impossible for it to be created by boost? I have used boost::thread_specific_ptr from the main thread fine,...
4,786,644
4,786,670
C/C++ pointers, ptr+1 = ptr +1 byte or ptr+1*sizeof(pointer_type)?
Having any_type *ptr = (any_type*)malloc(sizeof(any_type)*size); my_ptr = ptr+1; memcpy(dst, my_ptr, sizeof(any_type)); Will my_ptr be pointed to 1 byte after ptr, or to sizeof(any_type) bytes after ptr? How alignment options may affect the answer? Is it different for signed/unsigned types?
Pointer arithmetic is performed on the size of the static type[*] of the pointer, so it will effectively add sizeof *ptr. Alignment of the members will be accounted for in the size of the object, as the alignment of the type (padding at the end of the object). struct test { int a; char b; }; The size of test wil...
4,786,649
4,786,671
Are Variadic macros nonstandard?
For debugbuilds, I usually use Clang, as it formats warnings and errors better, and makes it a little easier to track them down, and fix them. But recently after adding a Macro with variadic arguments, Clang told me the following (from a dummy project): main.cpp:5:20: warning: named variadic macros are a GNU extension ...
Quote Wikipedia: Variable-argument macros were introduced in 1999 in the ISO/IEC 9899:1999 (C99) revision of the C language standard, and in 2011 in ISO/IEC 14882:2011 (C++11) revision of the C++ language standard. So it's standard from C99 and C++11 onwards, but a GNU extension in C++03.
4,786,764
4,786,930
linking in library that contains reference to cuda kernel
I am trying to figure out how to use a CUDA kernel as part of a library so that I can just add the library to my existing C++ source files, and be able to use the cuda kernel. So how do you go about doing this? I tried to create a wrapper, like so: .h file: #ifndef __reductions2d_H_ #define __reductions2d_H_ #include <...
include .h into .cu as well. nvcc is c++ compiler and mangles names. compile as: nvcc -c file.cu // compile cuda kernel nvcc file.o main.cpp // compile and link I would change you code as: .hpp #ifndef __reductions2d_H_ #define __reductions2d_H_ void getMean_wrapper(); // c++ linkga #endif .cu: #include "...hpp" #...
4,786,861
4,787,006
CMAKE link external c library
Hi basicly i am trying to use the svm from here . It is written in C and gives instructions how to use it in c++: Compile "svm_learn.c", "svm_common.c", and "svm_hideo.c" as C code. The C++ program you want to call svm_learn/8 and classify_example/2 (or classify_example_linear/2) from needs to inclu...
The best way would be to add those C files to your project: SET(SVM_LIGHT_SRC_DIR "E:/framework/svm_light") INCLUDE_DIRECTORIES(${SVM_LIGHT_SRC_DIR}) ADD_LIBRARY( svm_lib_light ${SVM_LIGHT_SRC_DIR}/svm_learn.c ${SVM_LIGHT_SRC_DIR}/svm_common.c ${SVM_LIGHT_SRC_DIR}/svm_hideo.c ) ADD_EXECUTABLE ( MYPro...
4,786,991
4,787,062
C++ How do I pass a list of non-consts to a function wanting a list of consts
I have a function with a signature void Foo(list<const A*>) and I want to pass it a list<A*> How do I do this? (plz note - the list isn't constant, only the member of the list)
The problem you have is that even though T * can be implicitly converted to a T const *, the template system isn't "aware" of that, so a whatever<T *> and whatever<T const *> are completely unrelated types, and there's no implicit conversion from one to the other. To avoid the problem, I'd probably avoid passing a coll...
4,787,612
5,009,990
Dynamically Creating WebView From C++ Through JNI
In my C++ code, I create an instance of a Java class through JNI. That Java class's job is to create a WebView dynamically that should go on top of the application's views. My current strategy is to retrieve the application's main activity, dynamically create a WebView and attach it to the main activity's list of view...
In the end, my Java class has a static method Init that is called by my activity to store the reference to the activity. Later, when my C++ code creates an instance of the Java class it retrieves that reference and uses it.
4,787,934
4,787,939
Returning a long long value
#include <stdio.h> int main(void) { long long x = test(); printf("%lld\n", x); return 1; } long long test() { return 1111111111111111111; } The output is 734294471 . If I replace the call to test() by a the number, the output is as I expect. I checked the value of x using a debugger and it wasn...
You need to declare test before you call it, otherwise C assumes it returns int.
4,788,013
4,788,039
What is the appropriate way to retrieve the value of a C++ variadic template constant argument at position N?
I would like to know what is the correct way to retrieve the value of a variadic template constant argument at position N (N is known at compile time). For instance, let's say you have a template that receives a variadic number of function pointers as arguments, and you need to retrieve the second function pointer. For...
You can use something along these lines, I think: template <int Index, int... Args> struct LookupAtIndex; template <int Index, int First, int... Rest> struct LookupAtIndex<Index, First, Rest...> { static constexpr int result = LookupAtIndex<Index - 1, Rest...>::result; }; template <int First, int... Rest> struct Lo...
4,788,016
4,788,669
SOCI Undefined Reference Error During Compilation
I'm trying to get soci working, and am basing my code on their documentation here. I'm getting an error that I can't decipher. My code: // relevant imports using namespace soci; using namespace std; int main(int argc, char** argv) { string dbName = "mysql"; string options = "dbname=db user=root password=abc"; ...
You need to link against the soci library and the appropriate backend. Add "-lsoci" to your linker command line. Update: Based on comments, you need to add: -L/usr/local/lib -lsoci_core -lsoci_mysql to your linker command line.
4,788,112
4,788,247
Re: reference access with boost::make_transform_iterator
I'm trying to use boost::make_transform_iterator to create an iterator for a custom class whose data is held in a map and where the iterator uses the vector of keys to access the values. In my problem, the values of the map are containers which hold large data. Since I can't afford to copy the data, I would like to acc...
This is me just guessing, but transform_iterator is a wrapper around the function object and the base iterator. I wouldn't be surprized if its dereference operator's return type is the same as the typedef for result_type of your functor. Have you tried using a reference type as result_type-typedef? In other words chang...
4,788,177
4,788,481
QFiledialog returns the incorrect directory
A snippet of what i'm using looks like this QDir lastDir; QFileDialog dial(this); dial.getOpenFileName(this, tr("Open File"), QString("/home"), tr("Raw Images (*.nef *.NEF *.dng *.DNG)")); lastDir = dial.directory(); qDebug() << lastDir; The output, is c...
getOpenFileName() is a static function which immediately opens a "file picker" dialog and returns, once the user is finished with the dialog, "an existing file selected by the user". You use it like this (note the use of :: and the class name QFileDialog instead of the object name): QString fileName = QFileDialog::getO...
4,788,375
4,788,403
Should I Return This Memory Block?
template < typename ArrayType > ArrayType *VectorToArray( ArrayType **p_ppThisBlock = NULL, vector< ArrayType > *p_vThisVector = NULL ) { // Check to see if both parameters are valid. if( p_ppThisBlock == NULL || p_vThisVector == NULL ) { return NULL; } else if( p_ppThisBlock != NULL && p_v...
Eventually; failure to do so would cause a memory leak. If the function is allocating the array and leaving it up to the caller to free the memory, this is fine. If the caller assumes the memory is freed later (and it isn't from what we see here), memory leak. Why not return a vector< vector< ArrayType > >? EDIT: Try ...
4,788,470
4,794,302
boost::spirit::qi and out-of-sequence variables
I'm writing a lexigraphical analyser. It takes an English string, and converts it into a set of latitude/longitude co-ordinates. It's a bit like Google Earth. Anyway, I've written my symbol tables and grammar, and it's happily parsing formatted data. struct LatLongDegrees { std::string dirLat_; double degLat_; s...
You have several possibilities. The easiest is to adapt your struct into a Fusion sequence in the required order: BOOST_FUSION_ADAPT_STRUCT( LatLongDegrees, (std::string, dirLong_) (double, degLong_) (std::string, dirLat_) (double, degLat_) ); (yes, the order of adaptation does not have to match th...
4,788,693
4,796,684
Where are the limits for Qt types?
Regularly, I could reference limits.h to see what the max is for a certain type, like an int or long. In Qt, there are types like qlonglong. Is there a header file and/or documentation that can be used in a similar way to manually or programmatically reference the limits of these types?
There's a high likelihood the Qt types distill down to one of the basic types for which numeric_limits are defined. Have you tried calling e.g., std::numeric_limits<qlonglong>::max()? As MSalters points out, too, if the types are not builtin numeric_limits can still be specialized for them. If that were the case one wo...
4,788,695
4,788,947
Disable warning about explicitly initializing base constructor inside copy constructor of derived class
I'm using g++ version 4.2.1 with -Wextra enabled. I'm including a header from a library, and I keep getting the following warning about a class in the library, which is enabled by -Wextra (I've replaced the class's actual name with BaseClass): warning: base class ‘class BaseClass’ should be explicitly initialized in th...
According to http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html (search for Wextra) that is an inherent part of -Wextra and can't be disabled separately (e.g. it isn't listed separately by its own -W option). It looks like the best you can do is either isolate the use of the library to one file on which you disable...
4,788,721
4,788,791
How can I resolve missing symbols when compiling C++ code with clang 2.8 on Mac OS X 10.6?
The following code, compiled on OS X with clang 2.8 from macports gives the missing symbol errors below. #include <iostream> int main() { std::cout << "hello world" << std::endl; } jonathancoe@MacBookCoe:/tmp$ clang HW.cpp Undefined symbols: "__ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_P...
Try: $ clang++ test.cpp If that doesn't do the trick, show the command line you're using.
4,788,991
4,789,024
Using variables globally throughout all files set up in a header file
Hey everyone! I've recently started using header files in my c++ programs (fairly new to it) and was wondering what the best way to initialize global variables across all your files. I currently have a header file outlining a program class with: init(), render(), loop(), event()... (etc) Each of these is set up within ...
Do not use global variables. Until you have learned to do without global variables, declare the variables as extern in the header file, e.g extern int pi. This tells the compiler: "An integer named pi exists, don't care where it is, the linker will know where to find it". That way you can initialize them anywhere you w...
4,789,192
4,796,160
Reimplemented resizeEvent() is not called
Please check the following implementation: BoardView.h #include <QGraphicsView> class BoardView : public QGraphicsView { protected: void resizeEvent(QResizeEvent* event); public: BoardView(); }; BoardView.cpp BoardView::BoardView() { } void BoardView::resizeEvent(QResizeEvent* event) { QGraphicsV...
Why a BoardView::resizeEvent() is not called, yet the QGraphicsView was showing the QGraphicsScene correctly? The reason is a silly mistake, instead of BoardView _board_view; I wrote QGraphicsView _board_view; Sorry for posting such a silly question!
4,789,193
4,789,423
C++: Using boolalpha
I am using a function (TinyXML's TiXmlElement::QueryValueAttribute(const std::string &name, T * outValue) that attempts to read a string into the data type that is passed. In my case I am passing a bool. So I want to use the boolalpha flag so that the input can be true or false instead of 0 or 1. How do I do this? Than...
TiXmlElement::QueryValueAttribute uses a std::istringstream to parse the value. So, you can create a wrapper class around bool that overloads operator >> to always set boolalpha before extraction: class TinyXmlBoolWrapper { public: TinyXmlBoolWrapper(bool& value) : m_value(value) {} bool& m_value; }; std::is...
4,789,255
4,789,287
Calculation Problem C++
I'm really new to C++, and this is homework. I don't understand what's going on. When I run this, everything works fine if I put in 60000 for current salary and .05 for pay increase, but if I put in something like 52000 for current salary and .23 for pay increase, then the retroactive pay comes out as 5982.00 instead o...
currentAnnual / 12 The division of two integers in C is an "integer division" (it gives an integer), and I think you dont want that. One solution is to change it to currentAnnual / 12.0. Anyway, it's important that you understand what is happening here.
4,789,346
4,789,416
How can I make cout faster?
Is there any way to make this run faster and still do the same thing? #include <iostream> int box[80][20]; void drawbox() { for(int y = 0; y < 20; y++) { for(int x = 0; x < 80; x++) { std::cout << char(box[x][y]); } } } int main(int argc, char* argv[]) { drawbox()...
As Marc B said in the comments, putting the output into a string first should be faster: int box[80][20]; void drawbox() { std::string str = ""; str.reserve(80 * 20); for(int y = 0; y < 20; y++) { for(int x = 0; x < 80; x++) { str += char(box[x][y]); } } st...
4,789,400
4,789,433
Convert string to int and get the number of characters consumed in C++ with stringstream
I am new to C++ (coming from a C# background) and am trying to learn how to convert a string to an int. I got it working by using a stringstream and outputting it into a double, like so: const char* inputIndex = "5+2"; double number = 0; stringstream ss(inputIndex); ss >> number; // number = 5 This works great. The pr...
You can use std::stringstream::tellg() to find out the current get position in the input stream. Store this value in a variable before you extract from the stream. Then get the position again after you extract from the stream. The difference between these two values is the number of characters extracted. double x = ...
4,789,670
4,789,846
Need some help with template-programming
I am trying to expand my template programming skills and I am facing a problem to which I don't see the right solution for. This is a personal training execise only to do some more advanced templating. This the goal : write a template to convert any integer type (using sprintf or swprintf) to either string or wstring d...
Frankly, this is the only solution I can think of: template <typename T> struct Dft { static const T* value; }; template <> const char* Dft<char>::value = "%i"; template <> const wchar_t* Dft<wchar_t>::value = L"%i"; template < typename T ,typename I > inline std::basic_string< T ,std::char_traits < T > > to_string...
4,789,910
4,789,929
what is the size of empty class in C++,java?
What is the size of an empty class in C++ and Java? Why is it not zero? sizeof(); returns 1 in the case of C++.
Short Answer for C++: The C++ standard explicitly says that a class can not have zero size. Long Answer for C++: Because each object needs to have a unique address (also defined in the standard) you can't really have zero sized objects. Imagine an array of zero sized objects. Because they have zero size they would all ...
4,789,912
4,790,555
1>LINK : fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_36.lib'
I have created a application for using the libtorrent. In that I am using the boost library. I tried the sample example given in http://www.rasterbar.com/products/libtorrent/examples.html & tried it in my MSVC 9.0 but I am getting this error 1>LINK : fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_3...
Right click the project, and choose "Properties" --> "Linker" --> "General" --> "Additional Library Directories", add your path of libboost_system-vc90-mt-gd-1_36.lib in it. "Properties" --> "Linker" --> "Input" --> "Additional Dependencies", add libboost_system-vc90-mt-gd-1_36.lib in it. I am using MSVC 10.0, but I th...
4,790,369
4,790,580
Need to pick a library for compression (Using c++ 64 bit environment windows)
I need to create archive files out of a stream of data. The program should be written in C++ and should be run as a 64 bit program on Windows OS. I am looking into Zlib and 7-Zip libraries but have no experience working with them. Any suggestions about which one to pick? Regards, Lalith
It really depends on what you intend to be compressing, and any related requirements you may have. Generally, the main trade-off is compression speed vs effectiveness (output file size). It isn't exactly clear from your question, but if you're compressing images, video, audio -- you should be looking at other options ...
4,790,425
4,790,431
simple code notation
I have never seen this notation.... CreateProcess (L"c:\s2.exe", NULL, NULL, NULL, false, 0, NULL, NULL, &s, &po) The first parameter has L"c:\s2.exe", what exactly is that L? Thanks
This stands for a wide character string, e.g. Unicode.
4,790,515
4,790,565
Advantage of macro over in-line in C++
We know that in-line are favorable as they are checked by the compiler and same operation ( like ++x ) does not evaluate more than once when passed as an argument as compared to macros. But in an interview I was asked the specific advantages or the circumstances when a macro is more favorable to inline in C++. Does any...
The only thing I can think of is there are some tricks that you can do with a macro that can't be done with an inline function. Pasting tokens together at compile-time, and that sort of hackery.
4,790,550
4,790,581
does anything on the lines of friend function exist in java?
Hi I want to implement a method on the lines of friend function in C++. How can I go about it?If it does not, why java doesn't need it?Please suggest how to implement it.. as in a sample: public class A {//some variables and methods..private and protected to be used by methods in Class B} public class B {}
Yes, something does exist. Java classes declared in the same package can have access to their package-mates less-than-private members. This is one of the places where Java and C++ really diverge and you need to get a specific understanding of the Java way to keep from shooting yourself in the foot.
4,790,607
4,790,616
Get the ascii value for a char, Ord equivalent in C++
In delphi exist a function called Ord which Returns the ordinal value of an ordinal-type expression. for example you can retrieve the Ascii value for a char in this way Ord('A') return 65 Ord('a') return 97 in C++ which function i must use to get the ascii value for a Char.?
A simple int a = c; where c is a char should work.
4,790,721
21,626,087
C++ type registration at compile time trick
I have the following situation: suppose I have a bunch of types (functors) which I want to register/compile in during compilation, preferably into something like boost::mpl::vector. Do you know any trick to do so nicely? My desire is to have hpp file which implements functor type and registration file, where a macro br...
There is a way to register types one by one and then retrieve all of them in the form of mpl::vector or similar. I've learned this trick on the boost mailing lists (perhaps from Dave Abrahams, although I can't recall for sure). Edit: I learned it from slide 28 on https://github.com/boostcon/2011_presentations/raw/maste...
4,790,751
4,791,237
error LNK2019: unresolved external symbol "public:
I am creating an torrent application using libtorrent in VS 2008. I tried the example given in the link http://www.rasterbar.com/products/libtorrent/examples.html BUt it is showing me these error....how to solve them? Linking... main.obj : error LNK2019: unresolved external symbol "public: __thiscall libtorrent::torren...
The .lib is not included in your project. Make sure you are linking it in; Configuration Properties -> Linker -> Input -> Additional Dependencies Another altnerative is to simply copy the .lib to your project folder but don't, it's bound to create problems later on. Sometimes the .lib is not shipped with the library, ...
4,791,370
5,079,151
Template function overload not called as expected
My situation is the following: I have a template wrapper that handles the situation of values and object being nullable without having to manually handle pointer or even new. This basically boils down to this: struct null_t { // just a dummy }; static const null_t null; template<class T> class nullable { public: n...
Well, since no real answer was found so far, I've made a workaround. Basically, I put the aforementioned Add functions in a seperate detail namespace, and added two template wrapper functions: template<class T> xml_iterator Add(xml_iterator parent, const char* name, const T& value) { ...
4,791,788
4,791,973
QTest - Unable to pass Qt::Enter to QPushButton
I'm creating an automated test application using QTest Library. I'm able to simulate key presses on the application except when it gets to a window having QDialogButtonBox (Save, and Cancel). Here's my sample code: std::auto_ptr<MainForm> myForm( new MainForm( 3, 3 )); myForm->show(); QTest::keyPress(myForm.get(), Qt...
in QDialogButtonBox you may get needed button with QPushButton * QDialogButtonBox::button ( StandardButton which ) and then call it's SetFocus method. If you can't access QDialogButtonBox directly, you may get it with QList<T> QObject::findChildren ( const QString & name = QString() ) or even get buttons themself wi...
4,791,804
4,792,002
assignment operator for classes having a non copyable boost::mutex
I am reading here this old Boost Thread FAQ where there is a guideline to implement copy-construction and assignment operator for classes having a boost::mutexnon-copyable object as member. I am fine with the copy constructor but I have some doubt on the assignment operator. Is still valid the instruction below? //...
First of all, I assume the question is about avoiding deadlock when locking multiple arbitrary mutexes. The important thing is to always use the same ordering convention throughout the code using a set of mutexes. If you can guarantee that mutex A will always be locked before B, B will always be locked before C, and A ...
4,791,982
4,792,158
how can we tell if the remote server is multi-threaded?
My customer did not gave me details regarding the nature of it's application. It might be multithreaded it might be not. His server serves SOAP messages (http requests) Is there any special trick in order to understand if the peer is single or multi threaded? I don't want to ask the customer and I don't have access to ...
It's irrelevant. Why do you feel it matters to you? A more useful question would be: Can the server accept multiple simultaneous sessions? The answer is likely to be 'yes, of course' but it's certainly possible to implement a server that's incapable of supporting multiple sessions. Just because a server supports mu...
4,792,032
4,792,054
Reducing time complexity
int main() { int n ; std::cin >> n; // or scanf ("%d", &n); int temp; if( n ==1 ) temp = 1; // if n is 1 number is power of 2 so temp = 1 if( n % 2 != 0 && n!= 1) temp =0; // if n is odd it can't be power of two else { for (;n && n%2 == 0; n /= 2); if(n > 0 && n!= 1) temp = 0; // if ...
Try if( n && (n & (n-1)) == 0) temp = 1; to check whether a number is power of two or not. For example : n = 16; 1 0 0 0 0 (n) & 0 1 1 1 1 (n - 1) _________ 0 0 0 0 0 (yes) A number which is power of 2 has only one bit set. n & (n - 1) unsets the rightmost set bit. Running time O(1) ;-) As @GMan noticed n needs ...
4,792,400
4,792,490
Detecting connection requests without looping
I need to implement some kind of server which first waits for users to connect. I use C++ and SDL_Net, and my code currently checks socket activity in a loop. The problem is that is consumes a lot of CPU performance doing nothing actually, so I'm wondering if there's a way to detect connection request/socket activity w...
You can use an SDLNet_SocketSet, create one, then check with SDLNet_CheckSockets and SDLNet_SocketReady
4,792,449
4,793,662
C++0x has no semaphores? How to synchronize threads?
Is it true that C++0x will come without semaphores? There are already some questions on Stack Overflow regarding the use of semaphores. I use them (posix semaphores) all the time to let a thread wait for some event in another thread: void thread0(...) { doSomething0(); event1.wait(); ... } void thread1(...) { ...
You can easily build one from a mutex and a condition variable: #include <mutex> #include <condition_variable> class semaphore { std::mutex mutex_; std::condition_variable condition_; unsigned long count_ = 0; // Initialized as locked. public: void release() { std::lock_guard<decltype(mutex_)>...
4,792,596
4,795,217
Creating installer for a c++ windows service Dynamically
I have created a windows service which checks for the status of the printer. The user can download this service from a website. I need to query for the status of printers used by this user. So when the user clicks on the download button I want to store the user information in a file which my service can use. The servic...
In WiX you can create custom actions which are arbitrary code you write (You provide the .dll which can be built using C++). In the custom action you can generate your user/location customization file.
4,792,607
4,792,703
Get vector of pointers from vector in C++
Is there an easy way of creating a vector of pointers to the elements of a vector? i.e. easier than the below std::vector<T*> fn(std::vector<T> &v) { std::vector<T*> r; for (int i = 0; i < v.size(); i++) { r.push_back(&v[i]); } return r; } EDIT: Incoming vector by reference
As @Benoit suggested, it is a bad idea to store these pointers. But if you really want to do it, you can use std::transform like this: template<class T> struct Address { T* operator()(T& t) const { return &t; } }; template<class T> vector<T*> fn(vector<T>& v) { vector<T*> r; transform(v.begin...
4,792,614
4,792,783
Making classes public to other classes in C++
If I have two classes for example as follows: class A {...} class B {...} If I want to make class A public to class B, do I just make the members of class A public or I can just use public class A {...}? Is there a way to tell class B for example that only class A is public for you? In other words, can I make public ...
There's a substantial difference between making the class public and making its contents public. If you define your class in an include file (.h file) then you are making your class public. Every other source file that includes this include file will know about this class, and can e.g. have a pointer to it. The only w...
4,792,618
4,794,792
Include another CMake Project as Library
I have decided to make a C++-Qt-GUI for a C program (both languages I don’t know), using KDevelop, which in turn uses CMake. The C source has no header, so I made one, and migrated some structs into it, as well as the declaration of the only function in the C source i need to call. The problem is that I can’t call it, ...
I'm a bit rusty on this, but could you do something along the lines of: In oregengui.c #if !defined MYGUIPROJ int main() { ... } #endif In your CMakeLists that you want both in: add_definitions( -DMYGUIPROJ ) The compiler should then ignore your second main function.
4,792,753
4,792,784
Memory allocation order in c++
I've written the following code trying to solve a challenge which requests an array-like structure without using them: #include <iostream> int main(){ int x = 132,y = 33,z = 87; int *i = &x; std::cout << x << " " << y << " " << z << "\n"; std::cout << &x << " " << &y << " " << &z << "\n"; std::co...
This practice is as bad as it can get. The stack layout is not specified; even if the variable actually has a on-stack representation (which it may not have, if you don't take the variable address and the optimizer moves it to registers), the order between variables and the padding (i.e. the difference between pointers...
4,792,819
4,792,860
Connecting the C++ class with the LUA table
I am trying to connect my 3d engine to a lua (5.1) parser. For example, I have a LUA class of a vec3 and I have a C++ class of a vec3. I want them to work with eachother. This is (part) of my C++ class: class vec3 { public: vec3() {} vec3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} vec3 operator...
What you need to do is create a userdata on the Lua stack in C++ and use that as the object. You can fairly simply placement new into it and arrange the metatable from C++. Of course, this is hideously type-unsafe, amongst the other huge holes in the Lua system.
4,792,823
4,793,042
Java packages vs. C++ libraries
In Java, there is what is called package. Does library in C++ represent the same meaning, especially in terms for example of containg relative classes and the use of protected members? Thanks.
There are different dimensions of what a package means in Java. As a container that differentiates the names of the classes inside from the names of classes in other packages, its equivalent would be c++ namespaces. As a unit that guarantees access to non-private members to classes in the same block, there is no equiva...
4,792,865
4,792,959
Semaphores, Critical section, Mutex Examples in MFC & C#
can any one tell me or give me a link saying about detailed description of Critical section, Mutex,semaphores with some sample example of how to use them in MFC & C#
I might explain but documentation on MSDN is already pretty excellent. Consider visiting Following Links. Here is the link to Semaphores in C# with Example -- http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx Mutex and Locks -- http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx CM...
4,792,936
4,792,994
TinyXML #include problem... Using libraries
Hey, i'm really trying to get TinyXML to at least read a file but it says "main.cpp:8: error: ‘TiXMLDocument’ was not declared in this scope" This is the code im using: TiXMLDocument("demo.xml"); Ideally i want to read able to read files and output the XML so i also tried this code i found online in a tutorial #includ...
It's called TiXmlDocument, not TiXMLDocument You can't call a function that you haven't declared yet. Since you're trying to call an undeclared overload of dump_to_stdout, the compiler assumes you want to call the version that takes const char * and fails.
4,792,957
4,793,039
Suppose i created three or four object of a class study then memory will be created seperatly or not?
Here class study { some data member; some member function; }; main() { study s1, s2, s3; } It will create three object of class study then memory created seperatly for seperate object or not in c++
Not quite sure what you're asking here but... Obviously s1,s2 and s3 will each occupy different areas of memory. However, the memory allocated for them is on the stack, so there will be no calls to malloc()/new() to actually 'allocate' memory. Allocating memory off the stack is fast (just a subtraction from the stack p...
4,792,974
4,793,000
"integer constant is too large for ‘long’ type" when finding largest prime factor
I am working on solving Euler project 3: Description: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? This is my code to generate the answer. However I need an integer type to hold 600851475143. When I compile this on GCC on a Mac I get: inte...
Check this question. You have to specify your literal like this: 600851475143LL
4,793,011
4,793,026
C++ destructor: when the memory gets freed?
If I delete an object which causes its destructor to be called, does the memory get freed before or after the destructor has finished doing whatever there is in the function?
Memory is only freed once the least derived class subobject has been destroyed. So if you have: class Base { }; class Derived : public Base { public: ~Derived(); }; then first Derived is destroyed, then Base is destroyed and only then memory is deallocated.
4,793,072
4,793,189
C++ newbie question--basic error handling using try, throw, catch
I'm trying to understand error handling in C++. I have read that using try, throw, catch is better style and less complicated than using if statements with return values. But I'm not sure I really understand how try, throw, catch works. I made a simple example below and it would be great to get feedback about any probl...
Well that's a lot of questions. I will try to give you some hints : (1) Do not include the try-catch in your function. Throwing an exception is done to tell the outer world that something happened. If you can handle the problem in your function, do not throw at all ^^ A good error handling is generally to catch the err...
4,793,193
4,793,255
Howto call external program and get it's output from another program
Howto do this in c++: Suppose that program A is a command line tool with some inputs (for example file paths and a number), according to it's inputs, it may get some other parameters during runtime. (if(condithin) cin<<something) I'd like to call A from another program B and want to see complete output of A during it's...
Since you use Qt, using QProcess is probably the best way to do it.
4,793,199
4,793,225
Boost. Multithreading
class accel{ public: accel(int threads, string params); private: void getfile(int from, int to); void download(int threads); }; void accel::download(int threads){ boost::thread g(&getfile(0, 1)); //<<<< } Gives an error '&' requires l-value. I have been doing this by example. How to make it work?
boost::thread g (boost::bind(&accel::getfile, this, 0, 1));
4,793,824
4,794,362
Export Visual Studios 08 project to PDA
I have got a visual studios 2008 application which is deisnged for a PDA. How do i export the project to run on the PDA. The PDA is running windows mobile 6.
Create and deploy a CAB file using an Installer project in Studio.
4,794,298
4,794,312
How can i delete data store in a file?
Delete some specific data present in a file.What ever user want to delete that will be deleted from file in c++ Suppose file contain 5 6 9 10 numbers I want to delete 9 number which is present in a file Please give code for it if any one know.
First read the file, and then overwrite it with the data you just read. While overwriting, just make sure that you don't write the "specific" data which you want to delete. That way you'll have a file that wouldn't contain the "specific" data anymore!
4,794,729
4,794,767
failed to link example program using id3 library
i am trying to use lib id3 to access mp3 tags with the ultimate aim of accessing album art from mp3 music files. The problem is that i have even failed to compile the example programs that come with the id3 library. problem 1. trying to compile an example program in my project first generates this error 1>*** NOTICE ...
Don't link in msvcprtd.lib which is a default library already included in the id3lib.lib. You definitely want to link in id3lib.lib
4,794,754
4,795,145
DCOM: How to close connection in server on client crash?
I have a rather old project: DCOM client and server, both in C++\ATL, only Windows platform. Everything works fine: local and remote clients connect to server and work simultaneously without any problem. But when remote client crashes or being killed by Task Manager or by "taskkill" command or power switch off - I hav...
I'm not sure about the DCOM ping system, but one option for you would be to simply farm off the notifications to a separate thread pool. This will help mitigate the effect of having a small number of blocking clients - you'll start having problems when there are too many though, of course. The easy way to do this is to...
4,794,755
4,794,984
StlSoft - how to use their file system functionality?
I'm trying to add portability to the file system in an application I wrote. To this end, I'm using stlsoft, but I can't figure out how to use anything. Is there a tutorial somewhere, or a relevant example? They have samples on the site, but as far as I can see none relating to the filesystem module.
...Eh, looks like I'll be using Boost instead.
4,794,836
4,795,856
error LNK2005: _sprintf already defined in ntdll.lib(ntdll.dll)
I'm linking against ntdll.lib to use ZwQueryInformationProcess and am using the Multi-threaded runtime library. ntdll seems to define some of the crt functions. So, when I link against it and also use the runtime library, I get linker errors. Can I force the linker to use the crt functions and to ignore the ntdll symbo...
Changing the link order seems to solve it. To change the order of automatically linked libs, you need to ignore them by adding to "Ignore Specific Library" and then re-add them to "Additional Dependencies" in the order you want them linked. The error message was this: 1>libcmt.lib(wcstol.obj) : error LNK2005: _wcstoul ...
4,794,922
4,794,963
Which are the best practices for data intensive reading and writing in a HD?
I'm developing a C++ application (running in a Linux box) that is very intensive in reading log files and writing derived results in disk. I'd like to know which are the best practices for optimizing these kind of applications: Which OS tweaks improve performance? Which programming patterns boost IO throughput? Is pre...
Compression may certainly help a lot and is much simpler than tweaking the OS. Check out the gzip and bzip2 support in the Boost.IOStreams library. This takes its toll on the processor, though. Measuring these kinds of jobs starts with the time command. If system time is very high compared to user time, then your progr...
4,795,108
4,795,195
Unmangling C++ DLL Function Names
Possible Duplicate: How do I stop name-mangling of my DLL's exported function? I have a DLL that is written in C++. The exported function names need to be unmangled. For example, int MyFunc( int Param1, int Param2 ); needs to appear to an outside application trying to call the library function simply as MyFunc. H...
Ways to get rid of mangling: (assuming MSVC is the build environment) Export via a .DEF file. Export as extern "C" ensuring that the __cdecl calling convention is used. __stdcall prepends the _ and postpends the @ on dll exported functions even when extern "C" is used. extern "C" __declspec(dllexport) int __cdecl MyFun...
4,795,169
4,795,271
Handling CPU exceptions in C++
is there a cross-platform way to handle the CPU exceptions like segmentation faults, or division by zero? Lets say, I need to call some potentially unsafe functions (for example from a plug-in file), that can cause a segfault, or some other problems that I cannot test before I execute it. I know, that the C standard li...
libsigsegv is a cross-platform library for handling segmentation faults and stack overflows. However, in the vast majority of cases, when you detect a segmentation fault, the right thing to do is to terminate execution as fast as possible instead of trying to recover from it. A segfault is usually indicative of a bug...
4,795,391
4,795,855
using the find_if() function in c++
I get errors where i use the find_if function. It says no matching function. I did find that others have come through this error, but i couldn't quite understand the replies. Please can some one correct this & explain what the mistakes are? Any help would be greatly appreciated. Thanks in advance. //Another way to spli...
Aside from the using std::find_if as mentioned by John Dibling, and a whole host of other issues (look at getWords method and what it's doing with the passed in stream, and return type? etc.) Your main problem is that you are passing in two different iterator types to find_if, the first iterator is a const_iterator - b...
4,795,512
4,796,227
How can I use Boost.Bind on compound types?
I have std::map<int, std::pair<short, float> >, and I need to find the minimal short in this map. How can I use boost::bind with std::min_element() for this? boost::lambda?
The map iterator will give you a pair where first is the int key and second is the map's pair value, so if you had an iterator it, you'd want the minimum of all the it->second.first values. The min_element function expects a comparison function for its third argument, so you need to build a comparison function that pro...
4,795,715
4,799,856
Drawing any rectangle to a GTK+ DrawingArea fills the whole DrawingArea
I have a GTK+ DrawingArea that should display a rectangle in the top left corner. When I draw the rectangle using Cairo, the whole drawing area is filled with the color of the rectangle. How can I prevent that? Why does Cairo do that? What am I doing wrong? #include <gtkmm.h> class Window : public Gtk::Window { priv...
context->paint() paints the current source everywhere within the current clip region. The proper method to call is Gtk::Context::fill.
4,795,757
4,796,057
Is there a better way to wordwrap text in QToolTip than just using RegExp?
So the question is in the title. QToolTip doesn't seem to provide the wordwraop feature. It is possible, however, to replace the Nth space with an \n using regexps, but I was wondering if anyone has a suggestion for a better sollution. Specifically, my problem with my approach is that it doesn't take the length of tex...
If the text in a tooltip is rich text, it is automatically word-wrapped. Here's a trivial example, where setting the font to black makes it "rich text" and so it gets word wrapped. Leaving out the font declarations means the tooltip will be plain text and extend the whole length of the screen. QString toolTip = QStrin...
4,795,775
4,804,262
Pattern to share data between objects in C++
I have started a migration of a high energy physics algorithm written in FORTRAN to an object oriented approach in C++. The FORTRAN code uses a lot of global variables all across a lot of functions. I have simplified the global variables into a set of input variables, and a set of invariants (variables calculated once...
Well, in C++ the most suitable solution, given your constraints and conditions, is represented by pointers. Many developers told you to use boost::shared_ptr. Well it is not necessary, although it provides a better performance especially when considering portability and robustness to system faults. It is not necessary ...
4,796,063
4,796,180
How to determine if an existing class can be unit-tested?
Recently, i took ownership of some c++ code. I am going to maintain this code, and add new features later on. I know many people say that it is usually not worth adding unit-tests to existing code, but i would still like to add some tests which will at least partially cover the code. In particular, i would like to add ...
While Martin Fowler's book on refactoring is a treasure trove of information, why not take a look at "Working Effectively with Legacy Code." Also, if you're going to be dealing with classes where there's a ton of global variables or huge amounts of state transitions I'd put in a lot of integration checks. Separate out...
4,796,195
4,796,222
What is the value of private members here?
If I have two classes A and B, such that B inehrits A. In other words, A is the base class, and B is the derived class. Now, suppose that class A has private members. Since class B inherited class A, the private data members became part of class B. As we know, private members are said not to be accessed even by derived...
They aren't usable in any way by member functions of B, but they will be useful to member functions of A, which B in turn will rely on. It's simply another level of encapsulation (B shouldn't care how the functionality of A is implemented).
4,796,270
4,796,308
Sequence points, conditionals and optimizations
I had an argument today with one of my collegues regarding the fact that a compiler could change the semantics of a program when agressive optimizations are enabled. My collegue states that when optimizations are enabled, a compiler might change the order of some instructions. So that: function foo(int a, int b) { if...
If the compiler can verify that there is no observable difference between those two, then it is free to make such optimizations. Sequence points are a conceptual thing: the compiler has to generate code such that it behaves as if all the semantic rules like sequence points were followed. The generated code doesn't ac...
4,796,590
4,807,830
Window C/C++ Crypto API Examples and tips
I'm asking this question because I've spent the best part of a day trawling through msdn docs and other opaque sources for simple straightforward guidelines on how to get started with the Windows C/C++ Crypto API. What I'd like to see is some example code, typical include paths, linking guidelines, etc, anything useful...
Here's a bunch of examples I've found.... Example C Program: Listing the Certificates in a Store Example C Program: Using CryptAcquireContext Example C Program: Enumerating CSP Providers and Provider Types Example C Code for Opening Certificate Stores Example C Program: Sending and Receiving a Signed and Encrypted Mes...
4,796,745
4,796,995
OpenMP and STL-style for
I'm trying to parallelize my program with openMP. The program is using STL-iterators heavily. It is said that openMP 3.0 can deal with this: std::vector<int> N(2*N_max+1); std::vector<int>::const_iterator n,m; #pragma omp parallel for for (n=N.begin(); n!=N.end(); ++n){ //Task to be in parallel }; But I got the ...
Standard OpenMP doesn't bear with C++ iterators in general. The standard requires iterators to be random access iterators with constant time for random access. It also only permits < and <= or > and >= in test expressions of for loops, but not !=. If you are using iterators and STL heavily, you might be better off wi...
4,796,777
4,797,337
how to create a triangle in c++ without using opengl, directx, or other api
I want to know if it possible for me to create a line or a triangle or any shape with only c++ code.
Based on the OP comments elsewhere in this thread, it sounds like he wants to do this by direct manipulation of the low-level instructions on the various pieces of hardware used for rendering images. To do this: Understand the hardware you have for performing this. This means doing exensive research into how the har...
4,796,789
4,797,014
Default inheritance access specifier
If I have for example two classes A and B, such that class B inherits A as follows: class B: public A In this case, I'm doing public inheritance. If I write the previous code as follows: class B: A What type of inheritance will I be doing here (i.e; public)? In other words, what is the default access specifier? Just a ...
Just a small addition to all the existing answers: the default type of the inheritance depends on the inheriting (derived) type (B in the example), not on the one that is being inherited (base) (A in the example). For example: class A {}; struct B: /* public */ A {}; struct A {}; class B: /* private */ A {};
4,796,943
4,796,981
Open method opens files with full path only C++
File opens if I write the full path (full-path/roots.txt). File fails to open if I write the filename only (roots.txt) And yet, roots.txt is in the same folder as the main.cpp. Is there any settings I should check on XCode? Here's the code: string line; ifstream infile; infile.clear(); // infile.open("roots.txt")...
If it works when you attempt to open a file with an absolute path and fails with just the filename, your relative path is likely incorrect. Ensure roots.txt is placed in the current working directory. Look into the getcwd function declared in unistd.h.
4,797,213
4,839,618
How to create TitleAreaDialog using WTL or Windows SDK (no MFC)?
I am trying to create a TitleAreaDialog using WTL or Windows SDK (please no MFC). From the google I am able to find these two links: http://www.codeproject.com/KB/dialog/dialogheader.aspx (MFC article) http://www.codeproject.com/KB/dialog/taskdialogs.aspx (doubtful.. how to use it) The desired output is like the ec...
Finally able to solve it using the Dialog Header link. Just went through the code twice or may be thrice :) and then ported it for WTL. There is another very good example in pure c++/win sdk: xmessagebox. Its about replacing default windows messagebox with something good (although there is a mode which uses title area...
4,797,359
4,797,409
qt: undefined reference to 'mysql_something@nr'
I am really stuck right now, everytime I try to compile my c++ programm I get output like this: release/dialog.o:dialog.cpp:(.text+0x9e): undefined reference to `mysql_init@4' release/dialog.o:dialog.cpp:(.text+0xe1): undefined reference to `mysql_real_connect@32' Browsing the whole day to find workarounds, tutorials,...
It sounds like you need to add the mysql library to the build process. If you're using Qt's qmake system, something like: LIBS += -L/wherever/the/mysql/lib/is -lmysql in the .pro file for the project.
4,797,483
4,797,537
Immutable container with mutable content
The story begins with something I thought pretty simple : I need to design a class that will use some STL containers. I need to give users of the class access to an immutable version of those containers. I do not want users to be able to change the container (they can not push_back() on a list for instance), but I want...
The simplest option would probably be a standard STL container of pointers, since const-ness is not propagated to the actual objects. One problem with this is that STL does not clean up any heap memory that you allocated. For that take a look at Boost Pointer Container Library or smart pointers.
4,797,657
4,797,712
Stopping destructor being called
I have a class on which I am overloading new and delete (these fetch and return memory from and to a memory pool). What's frustrating me is that the class on which I have overloaded still has it's destructor called before the delete overloaded function get's called. How can I stop this? class Message { ~Message() {...
Destruction and de-allocation are two orthogonal things, one should not inhibit the other. What would you do with instances of your class that were created on the stack? Not cleanup their resources? You are trying to break a very useful concept of RAII.
4,797,747
4,797,827
C++ compiler error with stringbuf / ifstream
I cannot understand why my compiler (MSVC++2010) doesn't like this code: // get_sum(filename as c-string) returns sum from file int get_sum(const char* const s) { stringbuf bill_buf; ifstream bill_file; bill_file.open(s); bill_file.get(bill_buf, '\0'); // read whole file ...
You're missing an include. Here's your code, this time without using streambuf: #include<fstream> #include<string> #include<iterator> int get_sum(const char* const s) { std::ifstream bill_file(s); std::string contents((std::istreambuf_iterator<char>(bill_file)), std::istreambuf_iterato...
4,797,781
4,972,045
Setting up SCons to Autolint
I'm using google's cpplint.py to verify source code in my project meets the standards set forth in the Google C++ Style Guide. We use SCons to build so I'd like to automate the process by having SCons first read in all of our .h and .cc files and then run cpplint.py on them, only building a file if it passes. The issue...
One way to do this is to monkey patch the object emitter function, which turns C++ code into linkable object files. There are 2 such emitter functions; one for static objects and one for shared objects. Here is an example that you can copy paste into a SConstruct: import sys import SCons.Defaults import SCons.Builder O...
4,797,847
4,797,903
How can I do some code work just like a singleton?
Possible Duplicate: C++ Singleton design pattern. How can I create only one instance of a class and share that instance with all my header and source files without using a singleton? Can you provide a simple example?
You can do this: class Sample { /*** your code **/ public: Sample(); void DoWork(); int GetValue(); /*** other functions ***/ }; Sample & OneInstance() { static Sample instance; return instance; } //Use OneInstance everywhere like this OneInstance().DoWork(); Note Sample is not a Singlet...
4,797,908
4,798,431
Handling very large images in Qt
I can't get Qt to work on images beyond 10,000X10,000. I'm dealing with huge satellite images that are around 2GB each. I considered using memory mapping but the image still occupies space in memory. QFile file("c://qt//a.ras"); file.open(QIODevice::ReadOnly); qint64 size = file.size(); uchar *img=file.map(0,size); QI...
Qgraphicsview and a set of image tiles, the view handles all the scrolling and world coords for you. Then you just have to either pre-chop the images into tiles in advance or pull a section of image data on the fly
4,798,169
4,800,368
Is there a way to break out of boost::mpl for_each?
Simple question really, let me give some background: I have a mpl::vector of types where each type has an id, at run time I use the mpl::for_each to iterate through this vector and find the matching type for the given id. But once found, there is no point in continuing the loop, so - question is, is there a way to brea...
To implement something like find_if I changed the for_each (calling it exec_if) to take a bool template argument. The bool indicates if execution should with the next sequences, or in affect return early. #include <iostream> #include <boost/mpl/vector.hpp> #include <boost/mpl/is_sequence.hpp> #include <boost/mpl/begi...
4,798,262
4,798,452
Is a letter compare slower than number compare?
Bear with me here. A couple months ago I remember my algorithms teacher discussing the implementation of bucket sort with us (named Distribution sort in my algorithms book) and how it works. Basically, instead of taking a number at face value, we start comparing by the binary representation like so: // 32 bit integers....
In C or C++, a char is simply a one-byte integer (though "one byte" may or may not be 8 bits). That means that in a typical case, the only difference you have to deal with is whether a single-byte comparison is faster than a multi-byte comparison. At least in most cases, the answer is no. Many RISC processors don't hav...
4,798,400
4,798,524
Understanding of the objects creation in c++
If i have a class name app and a class name manager. I want to create inside manager class an app class, I've seen two options but I didn't understand the difference. choice 1: //..... class app; //writing this line outside the declaration of the func class manager{ //.. private: app *a; //... } or choice 2: clas...
The class app; outside your class manager { ... } is a forward declaration. It tells the compiler, "app is a class. I'm not going to tell you what it looks like, but trust me, it is." Think of your compiler as only knowing about this particular file (which I am assuming is a .h file) when it compiles. You have said th...