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
7,705,772
7,705,820
How to know if my object is alive in C++?
Is there a way to know that my object is alive other than declaring a static private member in class and increment it in constructor, decrement it in destructor. Thanks in advance.
You can also do it non-intrusively to your class with STL using shared_ptr/weak_ptr. stl::shared_ptr<YourClass> p = stl::make_shared(...); // holds a strong reference to your type stl::weak_ptr<YourClass> wp(p); cout << wp.use_count(); // "1" p.reset(); cout << wp.use_count(); // "0"
7,705,773
7,705,812
Devise a formula inside a loop for x and y to satisfy these requirements
Given the following requirements, devise a formula to find x and y as given below given: length1 length2, assume length1 >= length2 total = length1 + length2 i = 0 : x = 0, y = 0 i = 1 : x = 0, y = 1 ... i = length2 -1 : x = 0, y = length2 -1 i = total...
if (i < length2) { x = 0; y = i; } else { x = i - length2; y = 0; }
7,705,783
7,709,292
Integrate LibRocket With SDL And OpenGL
I been currently involved in a game project and we reach the point we're want to added the GUI for menus and other stuff but the time that we maybe spent developing our own system could cost us a bit of time, and this is a part of the system that we don't want to lose too much time. So, we're reading about some UI Libr...
librocket is designed to work with any media libraries. You need to write a renderer that derives from Rocket::Core::RenderInterface. If you look in the example, they already provide both opengl and directx implementation of this renderer. For playing sound, there is no default support, but you can easily implement the...
7,706,182
7,706,213
While loop escape range
I have a while loop i wish to escape when i hit the number 1 through 5. What would be the best statement to put for that? I currently have this. while ( oneChoice!= 1 || oneChoice!= 2 || oneChoice!= 3 || oneChoice!= 4 || oneChoice!= 5 ) { cout << "Please make a selection" << endl; cout << "Choose once more: "; cin >...
Assuming oneChoice is an int (and thus can't have a value between 1 and 2, for example), just change the conditional to: while (!(1 <= oneChoice && oneChoice <= 5)) or, equivalently: while (oneChoice < 1 || oneChoice > 5) Additionally, if oneChoice has no real meaning or importance before entering the loop, it would ...
7,706,241
7,706,260
What is new Bytef[int] in C++?
I have a code snippet below, I'm not quite sure what the last line does. More specifically what's a Bytef[]? FILE* read_file_handle = fopen(read_filename, "rb"); fseek(read_file_handle, 0, SEEK_END); size_t no_bytes_to_read = ftell(read_file_handle); Bytef* read_buffer = new Bytef[no_bytes_to_read]; What is the Bytef...
new Bytef[no_bytes_to_read] simply allocates an array of Bytef objects with a length of no_bytes_to_read. If you are porting to PHP, as you say, you may want to review PHP arrays. I'm no PHP expert, but it appears that because arrays are implemented as ordered maps, you cannot preallocate - so there is no direct trans...
7,706,326
7,706,338
Global Variable Curiosity
Say i have a bunch of functions that will be using int = price; for instance. Can i set this outside int main and all the functions so they all call to it? For example here i called int price outside main but there will be more functions using it. Is this fine? int price; int main() { cout << price; return 0; }
Fine yes. Recommended DEFINITELY not. Try to avoid global variables at every turn. Also you should initialize your variables.
7,706,339
7,706,668
Grayscale to Red-Green-Blue (MATLAB Jet) color scale
I was given a data set that is essentially an image, however each pixel in the image is represented as a value from -1 to 1 inclusive. I am writing an application that needs to take these -1 to 1 grayscale values and map them to the associated RGB value for the MATLAB "Jet" color scale (red-green-blue color gradient)....
I hope this is what you're looking for: double interpolate( double val, double y0, double x0, double y1, double x1 ) { return (val-x0)*(y1-y0)/(x1-x0) + y0; } double blue( double grayscale ) { if ( grayscale < -0.33 ) return 1.0; else if ( grayscale < 0.33 ) return interpolate( grayscale, 1.0, -0.33, 0.0, 0.33 );...
7,706,354
7,707,531
Custom build environment/target libraries
I want to build an application that will be compatible with, say, Debian Lenny (libc, postgres, oracle and other libs) on a different Debian/Ubuntu release. Is this possible? If so, where can I read how to do it?
You can use the open build service for this. Create the Debian package description files for it (you can add also rpm spec files), select the target distributions and you will get it built on each platform and also get a specific download repository for each platform. Your package will be rebuilt automatically when nee...
7,706,369
7,706,463
Unable to push_back elements in a list
I'm facing a really peculiar problem with my code, I am unable to push elements into a list. I'm trying to implement a scan fill algorithm. I want the list of points that I have plotted on the screen so that I can check if a scan line intersects with them. In my Screen::plot_pixel function I push the Point into the plo...
You are passing the Screen object s into your functions, but they take the Screen object by value. They therefore take a copy of the object which they then modify. Your original Screen "s" is unchanged after the call to draw_shape(). You should probably modify them so they take a reference to a Screen object, such as: ...
7,706,391
9,205,996
How to calculate betweenness using boostlib for adjacency list?
I'm trying to write a simple program to calculate betweeness using brandes_betweenness_centrality from boostlib. I got stuck at getting an output (CentralityMap). I've been reading the documentation but I can't figure out how to put it all together. Here is my simple code: #include <iostream> // std::cout #include <ut...
The simplest way to fill in the missing parts is: boost::shared_array_property_map<double, boost::property_map<Graph, vertex_index_t>::const_type> centrality_map(num_vertices(g), get(boost::vertex_index, g)); then pass centrality_map as the centrality map to brandes_betweenness_centrality.
7,706,410
7,706,427
Accumulate algorithm incorrect sum
Just began learning about algorithms in c++. My book mentions a simple read-only algorithm defined in the numeric header. It takes three parameters, the first are iterators that specify a range or elements to sum and the third is the initial value of the summation. However when i try to do this: #include <iostream> #in...
http://www.cplusplus.com/reference/std/numeric/accumulate/ Your vector has elements 0-9 inside whose sum is 45. As an offset to your accumulator you add 1. Therefore you get the correct result 46.
7,706,592
7,706,994
Can I access to symbols of the host process from a shared object loaded in runtime? Any alternative?
In my scenario I want a plugin, which is a shared object loaded in runtime, to access symbols from the “host application” so I can add any functionality to my application. I have tried but have not found any way to do this and I have no clue on whether this is possible or not. So, can I do this somehow or is there any...
There are three main approaches: Pass a structure of function pointers to the DLL from the application, giving access to whatever symbols you want to share. This is the most portable method, but is kind of a pain to create all the function pointers. Something like: // In shared header struct app_vtable { void (*appF...
7,706,602
7,706,740
How to subtract one list of map keys from another and get new map (map A - mab B = map C)
So I have 2 std::maps <string, shared_ptr<file> > one is 'old' one is 'new' I want to get what files were removed and so be capable to iterate thrue differene and do some stuff to shared_ptr. Is such thing possible and how to do it?
While it's easy enough to write this yourself (iterate over A and check if the key is present in B), this looks like a job for std::set_difference. We'll need a lambda or some custom predicate to compare keys, though: #include <iterator> #include <map> #include <string> #include <algorithm> typedef std::map<std::strin...
7,706,817
7,706,831
Floating point in or out of range?
Both of these examples below have 8 significand digits, but the first case doesn't give any warning, while the second case does, why? float f1 = 11111111; float f2 = 99999999; Does the float data type have 7 or 8 significand digits?
Check out this article: The IEEE754 32-bit float has a 24-bit mantissa (cue the omitted leading 1). Now 224 is 16'777'216. That means that your first number, 11'111'111, fits nicely, but the second doesn't. Unfortunately binary isn't the same as decimal, so when discussing precision, most of the time we're really talki...
7,706,863
7,706,921
Using OpenGL 2.1 within VM
I recently switched over to the new Parallels Desktop Version from VMWare. I am working on MacOSX and develop with Visual Studio (C++), because I have to do an OpenGL Windows Game for my University Coursework. The problem is that the header/library files of OpenGL are only OpenGL 1.1, so I can't work on my FXAA GLSL Sh...
In order to use OpenGL>1.1 on Windows, you need to use GLee, GLEW or similar library.
7,706,883
7,706,963
Type Traits - Explicit template specialization. fails on xcode
I'm trying to use type traits like in "Modern C++ Design" using a template to determine if a type has a variable size or not. e.g. a string requires variable size storage, an int has fixed-size storage. This code works on Microsoft C++, now I'm porting to mac and I get the error: explicit specialization is not allowed...
The 2003 C++ standard only allows member template specialization outside of the enclosing class definition. Also, the out-of-definition specialization must be an explicit full specialization of the enclosing template. Microsoft C++ is non-standard in this regard. The fix is simple, just move the inner template out of t...
7,706,892
7,706,943
C++ application autorun on windows boot
I am developing an application in C++ that has an option "autostart". When user set that option, program should change something in Windows to be started by Windows on next Windows boot and user logon. Also when user unset this option, the program must put things back. I don't need to run app as a service, so it would ...
I'd suggest using registry keys like HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run. Create a string value here with the name of your software and value of your main executable path - this should suffice. Much easier then creating a .lnk file - and registry editing API is easily accessible from C++ UP...
7,707,136
7,707,167
How to include the qtsql module?
I am new to Qt and C++ (coming from the PHP world) and am stuck on something that is probably pretty obvious: including non-core Qt modules. I (understandably) get the compile error that QSqlDatabase does not name a type. I also get errors when I include either of the following: #include <QSqlDatabase> #include <QSql>...
Add QT += sql To your .pro file to enable this module. Be careful that you don't do QT = .. after the QT += sql Or simply put all the modules in one line: QT = core gui sql
7,707,137
7,707,261
Why will my toy example of multifile compilation not compile?
I have been using a makefile that I inherited from the internet for long enough! It is time that I learn to compile my own projects once and for all. So I've read some tutorials and thrown together a mock-up. It doesn't work, and I am at my wits end now (which is usually when I come to YOU). As usual, thank you all in...
The error message gives the command line: g++ project.cpp Note the lack of -c. That's apparently not in your makefile, in spite of what you think.
7,707,143
7,707,172
read space delimited number from file up to newline character
I have a text file that contains the following data. The first line is this: 5 4 3 2 1 The second line is this: 1 2 3 4 5 I am trying to read data from one line at a time because my first linked-list object is going to use the data from the first line and my second linked-list object is going to use data from the secon...
You don't say what a is, but never mind: If you want line based parsing, you need to have getline in the outer loop. Also, never use eof, as it doesn't do what you want. Rather use the implicit conversion to bool to check if an operation succeeded. Here's the typical gig: #include <sstream> #include <fstream> #include ...
7,707,315
7,707,373
Calling a C++ Function that takes pointers from C#
I have a function in C++ that returns pointer values​​: fPosFirst( int &aId, char *aNname, char *aDirectory ); But I have to pass this to C#. How can I do that?
This is VB.NET syntax, but you should be able to convert this to C# easily enough. Private Declare Ansi Sub fPosFirst lib "libraryname" (ByRef aId as Integer, byval aName as StringBuilder, byval aDirectory as StringBuilder) Now if aNname and aDirectory should have been const char *, you can use String instead of Strin...
7,707,371
7,714,571
OpenGL compiling issues
I am using Visual Studio C++ and GLEW. The Project Settings are all set (Includes/Libs). MenuState.obj : error LNK2001: unresolved external symbol __imp____glewUseProgramObjectARB MenuState.obj : error LNK2001: unresolved external symbol __imp____glewLinkProgramARB MenuState.obj : error LNK2001: unresolved external sym...
Make sure to #define GLEW_STATIC in the project before including GLEW in Windows. Then you can just include the entire source code in your project files. Otherwise, you need to have the proper GLEW DLL file in with your executable.
7,707,412
7,707,436
Using pointers for conditional while/for loops gives error when compiling
I'm wondering how to properly use pointers in for and while loops in C++. Usually I write using C instead of C++. The only reason I'm using the C++ std library this time is so I can use the complex number functions required by other mathematical functions in the code. As part of the assignment we were given the follow...
coeffs(i) is calling convention to a function that takes an integer argument. But in your case it is an pointer. So, you need to use [] operator to access the element at it's index. Also ((coeffs_end-1)-i) resolves to an address location. You need to dereference it to get the value at the location.
7,707,440
7,707,535
C++ Linked list implementation crashing
I am trying to implement a linked list for a data structures class and I am having some difficulty with the searching portion of the algorithm. Below is the offending code, which I have tried to implement following the pseudo-code in the MIT introduction to algorithms text: // // Method searches and retrieves a specifi...
Try this to construct the list: void List::addNode(int number) { newNode = new Node; newNode -> number = number; newNode -> next = m_listHead ; m_listHead = newNode; ++m_listSize; } It will add nodes to the head. Perhaps you may wish to store the pointer to the tail and insert the nodes there.
7,707,498
7,707,587
Using .dlls in my projects
Hello, Specs: VS 2010 C++ professional edition. I have a project with some statistical functions that I want to test. So I wrote a simple test console application which I added to the solution of the project with functions that I ...
If it's not included in the same directory as the console app (or in the path), then you'll need to include BASE as the runtime can't resolve the dependancy on BASE by ROC. Edit: Simply referencing ROC isn't enough; although there may be some build option that builds ROC and BASE and then links them into a single DLL; ...
7,707,604
7,707,631
Void vs Int Functions
What would be the different between void and int functions? When do i use which? Would void be used when just printing out a message or a variable value? like cout << value; Or would it just be text? And is int used when you actually do calculations within it?
void is used when you are not required to return anything from the function to the caller of the function. for eg. void no_return_fn() { cout<< "This function will not return anything" << endl; return; // returns nothing or void } int is used when you have to return an integer value from the function to the c...
7,707,653
7,707,663
How to locate MySQL header files to compile qt
From the qt documentation: You need the MySQL header files and as well as the shared library libmysqlclient.so. Depending on your Linux distribution you may need to install a package which is usually called "mysql-devel". [emphasis added] How do I get these? I tried apt-get install mysql-devel but apt-get told me...
Try using package: libmysqlclient-dev. You can use apt-cache search ... to find packages.
7,707,736
7,707,778
char array corruption in C++
I'm working on a project that makes me store an array of objects whose constructor is Item(char* item, int itemType){ char temp[200]; for(int i = 0; i < 200; i++){ temp[i] = '\0'; if(item[i] != '\0'){ temp[i] = item[i]; } } _item = item; _itemType = itemType; _twe...
In your Item constructor, you are setting what I presume is a member _item as such: _item = item; This just assigns the pointer value of the location pointed to by item into _item. It does not actually copy the string! The next time you go to read this location, it might be valid - chances are, though, it will be gar...
7,707,775
7,708,407
Convex Decomposition of a Complex Polygon?
With both my 2D physics system (box2D) and OpenGL, conplex polygons need to be decomposed into convex polygons. Ensuring models conform to this is easy. However, I would also like to edit the polygons as the simulation progresses, so I need a dynamic way of fracturing existing polygons into more polygons that are sti...
I think this is what you're looking for. As for finding the intersection, that's just a little algebra; for any two line segments it's easy to derive the corresponding lines ('rise over run', etc.), y = a1*x + b1 y = a2*x + b2 then the point of intersection (x', y') is x' = (b2 - b1) / (a1 - a2) y' = a1*x' + b1 Now...
7,707,805
7,707,934
C++ heapsort confusion
This might be a weird question but I'm trying to figure out why the following code works. It seems as though this code should be used where the heap elements index starts at 1 but it's starting at 0 and the sort is completed correctly. I say that because the left child is calculated as (element*2) and the right child i...
For the case when root = 0, there are two sub-cases: numbers[0] > numbers[1], or not. In the first, maxchild is set to 0. The next "if" clause - effectively "numbers[0] < numbers[0]" - necessarily evaluates to false, and so "done" is set to 1 and the loop terminates. If numbers[1] >= numbers[0], then maxchild is set to...
7,707,842
7,707,908
STL containers with reference to objects
I know STL containers copy the objects. So say I have a list<SampleClass> l; each time when I do SampleClass t(...); l.push_back(t); a copy of t will be made. If SampleClass is large, then it will be very costly. But if I declare l as a container of references, list<SampleClass&> l; When I do l.push_back(t); ...
Sadly no, it won't compile (with stlport at least). But the alternative, which is to store pointers to your objects in the container, will compile perfectly fine. This will leave you with a bit of extra syntactic noise around your code - you'll have to new things in order to insert them into your container. std::list<c...
7,707,876
7,707,885
New/delete[] and VirtualAlloc
#include <Windows.h> #include <iostream> using namespace std; int main(void) { unsigned char* pFoo = new unsigned char[1000]; pFoo = (unsigned char*)VirtualAlloc(NULL, 1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE); VirtualFree(pFoo, 0, MEM_RELEASE); delete[] pFoo; cin.ignore(); cin.get(); ...
You're using the same variable. So your first allocation gets leaked. After you free it with VirtualFree, the pointer is invalid. So delete on it is undefined. Furthermore: You can't mix VirtualAlloc and delete for the same reason you can't mix malloc with delete.
7,707,985
7,708,043
How to convert array<System::Byte> to char* in C++ CLR?
In my project, I pass a byte[] from C# to C++ CLR function. C++ CLR code: void TestByteArray(array<System::Byte>^ byteArray) { ... } C# code: byte[] bytes = new byte[128]; ... TestByteArray(bytes); In the TestByteArray() function, I need convert byteArray to char*, so that I can used it in native C++ code. How c...
void TestByteArray(array<System::Byte>^ byteArray) { pin_ptr<System::Byte> p = &byteArray[0]; unsigned char* pby = p; char* pch = reinterpret_cast<char*>(pby); // use it... }
7,708,110
7,708,142
Which situation will use clone in C++ and how to use it?
What is the difference between virtual clone and clone? I find the following example, it clone derived to base, what is it for? class Base{ public: virtual Base* clone() {return new Base(*this);} int value; virtual void printme() { printf("love mandy %d\n", value); } }; class Derived : publi...
Consider this: Base * b = get_a_base_object_somehow(); // now, b might be of type Base, or Derived, or something else derived from Base Base * c = b->clone(); // Now, c will be of the same type as b was, and you were able to copy it without knowing its type. That's what clone methods are good for.
7,708,479
7,708,546
deque<bool> iterator compile error
How to use deque to print its items? The below code results with a build error: fatal error LNK1000: Internal error during IncrCalcPtrs deque<bool> mandy3; mandy3.push_back(true); mandy3.push_back(false); mandy3.push_back(true); for(deque<bool>::iterator it=mandy3.begin(); it!=mandy3.end(); it++) printf("mandy3 ...
This is not a compiler error, it's a linker error. It occurs while using the incremental linking feature, so do a clean build (rebuild) to clear out old files.
7,708,633
7,708,650
C++: Function to handle different size arrays
I have 2 2D arrays that represent a maze const char maze1[10][11] and const char maze2[20][21] I'm trying to create 1 function to handle both mazes like so: void solveMaze(maze[][]) { } and just pass the maze like solveMaze(maze1); However, I have to supply a size for the array, which is different depending on which m...
C++ answer Use std::vector: // Initialize the vector with 11 rows of 10 characters std::vector<std::vector<char> > maze(11, std::vector<char>(10)); void solveMaze(const std::vector<std::vector<char> > &maze) { // note that you can access an element as maze[x][y] } The boost::multi_array is slightly more efficient...
7,708,644
7,711,593
undefined reference to std::hash<string>
I'm trying to write a simple factory function for std::unordered_map. The function takes in an iterable which has a begin and end method and whose value_type is a std::pair. The following is the code that I come up with. #include <string> #include <unordered_map> #include <cassert> #include <algorithm> template <class...
You're getting your type deduction mixed up. It's important to remove qualifiers from the deduced types, so declare your template like this: #include <functional> template <class Iterable> std::unordered_map<typename std::decay<typename Iterable::value_type::first_type>::type, typename Iterable::val...
7,708,915
7,709,509
C++: Function templates
I have 2 2D arrays that represent a maze const char maze1[10][11] and const char maze2[20][21] I'm trying to create 1 function to handle both mazes like so: void solveMaze(maze[][]) { } and just pass the maze like solveMaze(maze1); How would I do this with function templates? I recently asked this question already but...
There is no real support for multidimensional Arrays. You should consider using a class with proper support for the dimensions. The following does the trick template<int N, int M> void solveMaze(const char (&maze)[N][M]) { size_t n = N; size_t m = M; int x = 0; } int main(int argc, char *argv[]) { cons...
7,709,093
7,709,335
Can ADO on C++ platform be used to query a range of records? E.g. 100 records per query?
I am using c++ with ADO to connect to a mySql database, and I am using the standard ADO/C++ method to create a connection to the mySql database, and recordset is the pointer to the retrieved first record _RecordsetPtr recordset; recordset->Open("Select * from table",p_connection_.GetInterfacePtr(),adOpenForwardOnly,adL...
You will want to use limits on the query and cycle through them. //SELECT * FROM table LIMIT 0 OFFSET 100 int tlimit, blimit; std::string query; std::stringstream sstm; _RecordsetPtr recordset, count; count->Open("SELECT COUNT(*) FROM table",p_connection_.GetInterfacePtr(),adOpenForwardOnly,adLockReadOnly,adCmdText);...
7,709,259
7,709,272
Setting Char variables
For a char variable would i also set it to 0 as i would set and int or a float or any other variable? Such as char test = 0 would it be like that since int test = 0 would be like that?
Which do you want? The character '0', or the ascii 0? If you want to set it to the character '0', then you need: char test = '0'; If you want the ascii value 0, then it's fine the way it is.
7,709,372
7,709,402
will vector reallocate when push_back after shrink capacity to zero?
before push back, i shrink capacity to zero, then i push back item into vector, will it reallocate? is reallocate means slow down in performance? if so, why need to shrink capacity to zero or fit the size? vector<int> mandy2(5); vector<int>().swap(mandy2); printf("mandy2 size: %d\n", mandy2.size()); printf("mandy2 ca...
before push back, i shrink capacity to zero, then i push back item into vector, will it reallocate? Yes it will. Reference the doccumentation: void push_back ( const T& x ); Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x. Thi...
7,709,422
7,709,444
I saw this program. What is this - re(r), im(i) {} after constructor complex ( double r, double i )?
// operator_overloading.cpp // compile with: /EHsc #include <iostream> using namespace std; struct Complex { Complex( double r, double i ) : re(r), im(i) {} // what is this syntax? Complex operator+( Complex &other ); void Display( ) { cout << re << ", " << im << endl; } private: double re, im; }; // Op...
Those are member initializers. When the object is created with that constructor, the members are initialized according to those. So re gets set to r. And im gets set to i.
7,709,550
7,709,867
Is it safe to use std::bind with boost::signals2?
Is it safe to use std::bind to pass a member function to boost::signals2::signal::connect()? In other words, is boost::bind and std::bind interchangeable? It compiles with VC++ 2010 SP1, but the template code is way over my head and I'm afraid I might be venturing into undefined behaviour territory.
The connect function takes a boost::function object, which is basically a generic wrapper around anything that has an operator() defined for it. Therefore it is exactly as safe as what you are binding. For example, this is reasonably safe: boost::shared_ptr<ClassName> pValue = boost::make_shared<ClassName>(...); signal...
7,709,551
7,709,600
Polymorphism and data hiding: Does a base class override or ignore a derived class' access restrictions?
Please look at the following code listing: #include <iostream> using namespace std; class Base { public: virtual void Message() = 0; }; class Intermediate : public Base { }; class Final : public Intermediate { void Message() { cout << "Hello World!" << endl; } }; int main() { Final final; ...
How does that happen? Does a base class override or ignore a derived class' access restrictions? With Public Inheritance all public members of the Base class become public members of the derived class. So Yes Message() is public function in Intermediate. The function is called on a base class(Intermediate) pointer th...
7,709,703
7,709,750
Type not inherited in SFINAE for multiple inheritance?
I am using a SFINAE mechanism to deduce a type. Resolve<T>::type is deduced to T if class T doesn't contain yes and it's deduced to MyClass if it contains yes. class MyClass {}; template<typename> struct void_ { typedef void check; }; template<typename T, typename = void> struct Resolve { typedef T type; }; template...
Why would you expect a compiler error? You know SFINAE stands for Substitution Failure Is Not An Error right? When you substitute T by D3 the expression becames ambiguous. Due to SFINAE, this failure is not considered an error and your specialization is simply removed as a candidate. It's all about NOT getting a compil...
7,709,821
7,709,843
ofstream error at runtime
Hi I'm trying to write text to files with: ofstream #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstring> #include <stdlib.h> using namespace std; void init_log(ofstream* data_file, ofstream* incl_file, string algo){ stringstream datafilename; datafilename << "rep...
ofstream* data_file; ofstream* incl_file; You've declared these as pointers, and you're using them without allocating memory for them. That is the reason of the runtime error. I would suggest you to make then automatic objects, as: ofstream data_file; ofstream incl_file; and then pass them as reference type: void ini...
7,709,894
7,709,970
Using auto in a lambda function
#include <vector> #include <algorithm> void foo( int ) { } int main() { std::vector< int > v( { 1,2,3 } ); std::for_each( v.begin(), v.end(), []( auto it ) { foo( it+5 ); } ); } When compiled, the example above starts the error output like this : h4.cpp: In function 'int main()': h4.cpp:13:47: error: paramete...
auto keyword does not work as a type for function arguments, in C++11. If you don't want to use the actual type in lambda functions, then you could use the code below. for_each(begin(v), end(v), [](decltype(*begin(v)) it ){ foo( it + 5); }); The code in the question works just fine in C++ 14.
7,710,039
7,710,072
static constant members for array size
MyClass.h class MyClass { public: static const int cTotalCars; private: int m_Cars[cTotalCars]; }; MyClass.cpp #include "MyClass.h" const int MyClass::cTotalCars = 5; The above code doesn't work because it will say "expected constant expression" for the m_Cars array. class MyClass { public: static const int cTota...
Static const members of simple type are a exception to that rule, so you latter code is correct. This exception is a fairly modern one (from C++98, but not implemented by every compiler until a few years later) so many old-fashioned teachers are not yet aware of it. They prefer the idiom: class MyClass { public: enu...
7,710,409
7,716,959
boost::phoenix with VS2008
Simple example using boost::phoenix: #include <vector> #include <algorithm> #include <boost/phoenix.hpp> namespace ph = boost::phoenix; namespace place = boost::phoenix::placeholders; struct A { int val_; explicit A(int i) : val_(i) {} int foo() { return val_;} }; int main() { std::vector<A> coll; ...
It looks like the Boost devs decided that they weren't going to workaround this, perhaps since it was determined to be an error on the part of the compiler. Here's a link: https://svn.boost.org/trac/boost/ticket/1097 I think this is for general boost::bind(), but I'd bet that this probably won't be fixed. There's a w...
7,710,428
7,710,542
Warning -- Suspicious Truncation in arithmetic expression combining with pointer
I am doing static code analysis (Using Gimpel PC- Lint) of my source code. In code analysis, i am getting a warning 'Suspicious Truncation in arithmetic expression combining with pointer'. Here is the what analysis report says:: source\interp.cpp(142): error 679: (Warning -- Suspicious Truncation in arithmetic expressi...
It may be because your adding an int to an unsigned long with ulIndex+1 Try py[ulIndex] = y[ulIndex+UL1]-y[ulIndex]; Or it could depend on how you've defined py and y arrays.
7,710,598
7,710,682
Universal function pointer
There is some class which have methods like: int getSomething1(); std::string getSomething2(); someClass getSomething3(); There is structure which describes fields of this class like: {"name of field", pointer to getter, std::type_info} Then I would like to use it as follows: if(type == int){ field_int = (int)gett...
This answer of mine to another question addresses your problem pretty well. With some minor modifications, you get this: template<class C, class T> T get_attribute(const C& instance, T (C::*func)() const) { return (instance.*func)(); } Assuming the following: struct Foo { int getSomething1() const; std::st...
7,710,989
7,711,096
shared_pointer of a base class cannot be created using a polymorphic derived
I have a base polymorphic class ( with virtual methods ) and a derived from it. I am trying to use the following code boost::shared_ptr<base_class> ptr( new derived_class() ); but the compiler returns me the following error cannot convert ‘fpga_northwest*’ to ‘fpga*’ in initialization make: *** [../obj/ix...
boost::shared_ptr<base_class> ptr( new derived_class() ); This should work just fine. Perhaps those classes are not related after all? Perhaps those classes are incomplete at that point, so the compiler doesn't know that the classes are related? (This should produce other error as well, though.)
7,711,013
7,711,263
Boost Gzip filters: compile failes
I'm trying to compile example from Boost Gzip filters page: #include <fstream> #include <iostream> #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> int main() { using namespace std; ifstream file("hello.gz", ios_base::in | ios_b...
The problem is that you are not specifying the namespace in which to look up filtering_streambuf, input, or gzip_decompressor. Try: #include <fstream> #include <iostream> #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> int main() { ...
7,711,029
7,711,310
Boost C++ and Android 3
I tried to google and SO search. So far I was able to find only conflicting information. If it is too hard to marry Boost and Android, maybe there are replacements? I am especially interested in smart_ptr, threads, function, lexical_cast, string_algo and containers. Any input is appreciated. Thank you.
Have a look at this project: https://github.com/MysticTreeGames/Boost-for-Android Boost for android is a set of tools to compile the main part of the Boost C++ Libraries for the Android platform. To compile Boost for Android you may use the customized NDK r4b provided by Dmitry Moskalchuk aka CrystaX. Or you may d...
7,711,047
7,711,109
Split array string in c++
I am new to cpp and have a situation in which I want to split array string I have for( i = k = 0; i < points[1].size(); i++ ) { cout << points[1][k]; } Output >> [390.826, 69.2596] [500.324, 92.9649] [475.391, 132.093] [5.60519e-44, 4.62428e-44] I want 390.826 69.2596 ...
Assuming the type of point has public members x and y: for( i = k = 0; i < points[1].size(); i++ ) { cout << points[1][k].x << endl; cout << points[1][k].y << endl; } If the members are something else, say, X and Y (the uppercase), then use the uppercase instead (or whatever it is). The reason why you code pri...
7,711,112
7,711,213
How can I link with a directory which might not exist while running?
I'm writing a library for Linux which has some functionality which relies on the a shared library libfoo.so. I'm trying to case where libfoo.so doesn't exist into consideration. I have a well defined behavior for such a case, but I don't know how to properly implement it, linkage wise. Currently, my library is shipped ...
There are two different problems that kind of fit the description, depending on whether the presence of the library is to be detected at compile time or at runtime. At compile time you will have to use some tool to detect whether the library is present and modify the build scripts to pass that information down to the ...
7,711,171
7,711,592
How to optimize interpolation of large set of scattered points?
I am currently working with a set of coordinate points (longitude, latitude, about 60000 of them) and the temperature at that location. I need to do a interpolation on them to compute the values at some points with unknown temperature as to map certain regions. As to respect the influence that the points have between t...
Radial basis functions with infinite support is probably not what you want to be using if you have a large number of data points and will be taking a large number of interpolation values. There are variants that use N nearest neighbours and finite support to reduce the number of points that must be considered for each ...
7,711,205
7,717,542
How can I delete an object flagged as SFGAO_STREAM?
I have a file that I can reach by pidl via IShellFolder. This file has the flag SFGAO_CANDELETE and its parent folder has the flag SFGAO_STORAGEANCESTOR only. How can I delete the file? Conditions: Files and folders are on USB device (digital camera and a phone). A solution should work at least on WinXP (Win2000 suppo...
See the answer I posted to this very same question (from you?) on the C++Builder Journal forums last month. In short, the only documented way I can find anywhere is to retreive the parent folder's IContextMenu interface, and then invoke the delete verb on the desired file.
7,711,237
7,711,459
How to access protected base class function, from derived class through base class ptr
I have abstract class A, from which I inherit a number of classes. In the derived classes I am trying to access protected function in A trough A pointer. But I get a compiler error. class A { protected: virtual void f()=0; }; class D : public A { public: D(A* aa) :mAPtr(aa){} void g(...
Relying on private access works on unrelated instances of the same type. Relying on protected access works on unrelated instances of the same type (and of more derived types). However, relying on protected access does not work on unrelated instances of a base type. [n3290: 11.5/1]: When a friend or a member function o...
7,711,540
7,711,861
Catching a Request to Open or Create a File and Rerouting it
I downloaded some flash games some time ago to play offline at school if I find myself with no work to do and have a spare. The only problem is that they always attempt to save/load from the application data, and I don't believe the files are created at all, let alone loaded next time I would play it again. Instead of...
I hope some of these help: WinAPIOverride32 is an advanced api monitoring software. Deviare API Deconstructing the Poker Client, Part 1
7,711,638
7,714,153
How to "disconnect" an accelerator , key-press-event or mouse-press-event in a GTK+ Widget?
Say I have a custom GTK+ widget obtained from a third party library. It has an accelerator, e.g it hides itself when I press 'h' or click it, and shows itself when I press 'h' again or double-click it. I want disable this particular functionality of the GTK+ widget. How can I do this without changing the source code of...
I'm guessing now, but how about gtk_widget_can_activate_accel () ? http://developer.gnome.org/gtk/2.24/GtkWidget.html#gtk-widget-can-activate-accel
7,711,682
7,711,791
Convert server response (std::string) into a png file
I'm getting a response from a server using boost::asio. The result is stored in a std::string. I want to convert this std::string into a .png image and write it to file. I'm having awful trouble with this. Here is my code: CURL *curl; CURLcode res; std::string errorBuffer[CURL_ERROR_SIZE]; std::string url="http://www.g...
binary_file.write(reinterpret_cast<const char*>(&p_Data),sizeof(std::string)); Right, this is why reinterpret_cast is poor in many scenarios: it promotes guesscoding. This is when you've thrown away your reference materials and just assumed that you need to pass a pointer to an std::string somewhere, and decided that ...
7,711,697
7,713,962
Spawn a redis instance programmatically
I have a program (call it x, written in c++) which will run using a job scheduler to spawn instances of x to process work units sent from a server. Part of the processing x does is to split the work into multiple smaller units which it processes in a queue. I would like to use redis to manage the queue for x, but every...
This is still "via the shell", but from within your program: you could fork-exec, use popen, or system (with a & at the end) to interact with a shell to execute Redis.
7,711,714
7,711,773
Why are some many OpenCL examples written in C++ and not in C?
Disclaimer: the author is at the beginner level in C/C++. Wikipedia says that "OpenCL includes a language (based on C99) for writing kernels". But if you look at any example of code in the OpenCL Programming Guide book, you will see that alongside with the kernel .cl file there is always a .cpp file (or even few of the...
Does that mean that the kernels are written in C-like language, while all the other stuff (like memory objects management) is written in C++? OpenCL itself is an extension of C99, so the .cl files are written in that. You'd have to check what's in the C++ files to see what's implemented in them. Why everything is no...
7,711,739
7,712,130
Netbeans insert new line at end of file c/c++
When I use nebeans formatter it is removing new line from end of file while using gcc I am getting warning warning: no newline at end of file How can I force netbeans to insert new line at end of file ?
Netbeans supports the concept of code templates - you'll find the option to modify the templates under "Tools>Templates". Edit the C++ code templates, and insert a new line at the end of the templates. Then when you select to create a new C++ file, it will use the template - which will contain the new line you require....
7,711,960
7,712,428
CryptoAPI and XMLDSIG c, c++, delphi
I'm trying to sign a xml document (http://www.w3.org/TR/xmldsig-core/) with an enveloped signature, I managed to calculate the signed info part but I'm struggling to get a meaningful result from the cryptoapi, unfortunately I have to stick to the crypto api (no external libs, no XmlXec). The signature method is rsa-sha...
There is an article in the MSDN about XML signatures: http://msdn.microsoft.com/en-us/library/ms757845(v=VS.85).aspx
7,711,965
7,711,981
STL vector and pointers to elements of vector
There are two STL vectors, one with objects and second with pointers to objects. v_objects = [obj1, obj2, obj3, obj4] v_ptr = [ptr_to_obj1, ptr_to_obj2, ptr_to_obj3, ptr_to_obj4] Vector v_ptr is used to sort elements in v_objects. Let's say that something is added to v_objects so it looks like: v_objects = [obj1, obj2...
I don't think so. You could probably save yourself the trouble by just using a single vector with shared_ptrs to your objects, or just use a ptr_vector.
7,711,974
7,714,933
Options for Windows service communication
I'm developing a service which will run as System and will process long-running tasks in the background. I now need to display some feedback to the user in the form of a tasktray icon and I would also like to be able to pause/resume the tasks from the tasktray icon so my requirement is to send a message in either direc...
COM is the best solution for RPC in windows. It is very powerful and easy to write. Raw MS-RPC is good too. With both you can return arbitrary length data, see size_is MIDL attribute: HRESULT Proc7( [out] long * pSize, [out, size_is( , *pSize)] my_type ** ppMyType); /* Specifies a pointer ...
7,712,075
7,712,211
When is it safe to free a FP * in a Excel XLL?
MSDN states: ... Therefore, when returning a DLL-created string or floating-point array, you have the following choices: Set a persistent pointer to a dynamically allocated buffer, return the pointer. On the next call to the function (1) check that the pointer is not null, (2) free the resources allocated on the ...
FP is declared like this: typedef struct _FP { unsigned short int rows; unsigned short int columns; double array[1]; /* Actually, array[rows][columns] */ } FP; You are assuming that FP is packed and contains no padding. I don't know how XLLs are meant to be compiled but I think it is very likely tha...
7,712,568
7,716,467
IContextMenu::QueryContextMenu being called, but IContextMenu::InvokeCommand doesn't
In my implementation of IContextMenu COM server, the QueryContextMenu gets called (can see it with logging) but InvokeCommand doesn't. Here is the QueryContextMenu: HRESULT ContexMenuImp::QueryContextMenu(HMENU hmenu,UINT indexMenu,UINT idCmdFirst, UINT idCmdLast,UINT uFlags) { if (uFlags & CMF_DEFAULTONLY) { ...
You forgot to honor the idCmdFirst when you inserted the menu. globals.menuItemInfo.wID = idCmdFirst; globals.menuItemInfo.fMask |= MIIM_ID; (So I was right: You added your menu items with the wrong ID.) Note that since each context menu may have a different ID, you should not use a global.
7,712,584
7,712,696
Performance difference between mutex and critical section in C++
I was reading this post on performance differences in C# between critical sections and mutexes for a given test case. I'm womdering if there is any further documentation out there that gives performance overheads for the various locking classes for a C++ application, specifically MFC running on a Windows 32 or 64 bit ...
As far as I can understand, a Win32 Mutex is a full blown kernel object. This means that any call to a Mutex will involve a system call. This will often invalidate the cache and therefore can be quite expensive. Critical Sections are Userside objects that make no use of the kernel in cases where there is no contention....
7,713,266
7,713,317
How can I change the variable to which a C++ reference refers?
If I have this: int a = 2; int b = 4; int &ref = a; How can I make ref refer to b after this code?
This is not possible, and that's by design. References cannot be rebound.
7,713,283
7,713,417
const array vs static const array in a function
For example there is a function doing something. How should i declare and define an array inside the function i'd like to be allocated/initialized only once? void someclass::somefunction(/*parameters here*/) { static const my_array[4] = {1,2,3,4}; // #1 /*or just*/ const my_array[4] = {1,2,3,4}; // #2 } As far a...
Declare and define it the most logical and clear way, and only if profiling shows it to be a bottleneck would I suggest changing the code. In this case some compilers may very well generate the same code. Others may generate different code due to the slightly different initialization semantics (for example in some case...
7,713,540
7,713,618
C++ template class and return type as a constraint
Sorry for this foolish question, but I'm quite new to C++. I have a base class called AlertInfoBase in my project. It has some dozens of subclasses. Now I want to have a class template, which will have a method filter(). This method will always return a reference to AlertInfoBase. Here's the code: template <class T> cl...
You can think of templates as a code generation mechanism. A particular instantiation of a template is identical in most ways to manually written code that just substituted the template argument where appropriate. In your example, if you instantiated AlertInfoFilter with a std::string (as an example of a class that doe...
7,713,608
7,713,890
Unresolved external symbol with x64 flag c++
I have a VS2008 C++ project which currently I compiled on VS2010. it contains a dll and execution GUI project. With x64 flag the dll is build without any errors but the GUI has some LNK errors to function that are in the dll. "unresolved external symbol..." (error LNK 2019 and 2001) with Win32 flag there is no LNK erro...
As I understand it your problem is as follows: Your solution contains a class library project and an application project of somesort that provides the user interface. Your solution compiles without problem when set for win32 bit environment, but shows linker errors when compiled for x64 bit environment. It is likely th...
7,713,934
7,714,921
Classification Library
I need to test various famous classification methods like kNN, ID3 and ... on a huge data-set of a project, and choose one for future use. I have no limitation on language but performance and readable code both in learning and classification phase are very important. therefore, I'm looking for a good library with follo...
Take a look at RapidMiner which comes with a Java-API and graphical tools for data mining. The community edition is free, I think. I used the predecessor of this tool/library as a student but do not have professional experience with it, though.
7,713,983
7,714,396
Segfault with libssl/libcrypto
This is more of a hypothetical whilst I'm debugging some code. Lets say I have an application (called X) that calls out to a lib to send an email over a TLS encrypted SMTP connection, whilst at the same time X is talking to another lib which is establishing another TLS socket through the same libcrypto lib, what's the ...
Quite genrally speaking it could be possible - but well written library should be robust to multiple access. You might want to look through documentation to see if their API is reentrant (or even thred-safe). If it is thread-safe, then (assuming that libcrypto authors didn't make mistake) you can be sure that it's not ...
7,714,024
7,714,177
Vector of objects that contain references
I have the following struct: struct Transaction { Transaction(Book& bb, Patron& pp, Date dd) : b(bb), p(pp), d(dd) { } Book& b; Patron& p Date d; }; When I try to put an object of type Transaction into a vector<Transaction>v_t with a push_back, it won't work. A screenful of errors b...
You'll need an assignment and copy operator for the type since it contains a reference. STL container objects must be copyable AND assignable (and this won't be possible with your reference unfortunately). Check this thread: http://cboard.cprogramming.com/cplusplus-programming/106779-copy-constructor-class-const-refere...
7,714,087
7,716,699
Where is the grouped list of classes in the Qt Documentation?
In previous versions of Qt, there used to be a list of classes grouped by function (e.g. http://doc.trolltech.com/4.1/groups.html). This was very useful when looking for a class to perform a function but not knowing the name of the class. For example, there's a short list of basic widgets at http://doc.trolltech.com/...
It's not exactly the same as before but I think it is a pretty good organization. Starting at the main index, notice the second section to the left titled Qt Topics. The first item, Programming with Qt is a close approximation of the former "Grouped Classes" Clicking on the third item under Qt Topics, UI Design with Qt...
7,714,220
7,714,355
How race conditions will caused by context switching
I want to know how race condition will happen during context switching, and where and how this happens. I know about race condition can occur when accessing shared resource, I just need to understand it better. Can someone help me grasp this?
Here's a classic example: int global_int = 0; void update () { ++ global_int; /* generated assembly is something like register = global_int increment register global_int = register */ } Say the first thread starts running, calls update(), but gets interrupted (by a signal, context switch...
7,714,345
7,714,388
forward declaration with vector of class type - pointer to incomplete class type not allowed
I have two classes, foo and bar. foo.h #includes bar.h and contains a std::vector of pointers to bar objects. At some point during runtime, bar has to access this vector of pointers to other bar objects. Therefore, foo contains a method named getBarObjects() that returns the array of pointers. Therefore, I forward decl...
You can't forward declare members. Instead, bar.cpp should #include both foo.h and bar.h. Problem solved. In general, if you use the sequence: Forward declare all class types Define all class types Bodies of class members everything will be fine.
7,714,357
7,714,376
Simple Constructor Initialization List
I want to initialize one of the class variables to max of unsigned long long with something like this: ClassA(): maxvalue(std::numeric_limits<unsigned long long>::max()) { } Is it ok to do this? Can I use std::numeric_limits<unsigned long long>::max() in the intialization list?
Yes. This will work as long as maxvalue is able to be constructed from std::numeric_limits<unsigned long long>::max().
7,714,561
7,714,741
No O(1) operation to join elements from two forward_lists?
When reading about forward_list in the FCD of C++11 and N2543 I stumbled over one specific overload of splice_after (slightly simplified and let cit be const_iterator): void splice_after(cit pos, forward_list<T>& x, cit first, cit last); The behavior is that after pos everything between (first,last) is moved to this. ...
Your algorithm fails when you pass in end() as last because it will try to use the one-past-end node and relink it into the other list. It would be a strange exception to allow end() to be used in every algorithm except this one. Also I think first.next = &last; needs to be first.next = last.next; because otherwise las...
7,714,685
7,715,145
Offer optimised algorithm to work with timestamped values
Possible Duplicate: C#. Need to optimise counting positive and negative values I need to maximize speed of the following functionality: a. a value comes in. value has 2 properties - int value and long timestamp in ticks. b. need to count previously stored values which are younger than 1ms (from the current). c. nee...
Maintaining 2 buffers to keep the positives separated from the negatives sounds like a pain and inefficient. You could instead have a single buffer with all the values, and use std::accumulate to count up the positives and negatives. If you start with a collection of all the tuples (each of which has an age and a valu...
7,714,728
7,714,768
Unicode character for superscript shows a square box: ࠚ
Using the following code to create a Unicode string: wchar_t HELLO[20]; wsprintf(HELLO, TEXT("%c"), 0x2074); When I display this onto a Win32 Control like a Text box or a button it gets mapped to a [] Square. How do I fix this ? I tried compiling with both Eclipse(MinGW) and Microsoft Visual C++ (2010). Also, UN...
The font you are using does not contain a glyph for that character. You will likely need to install some new fonts to overcome this deficiency. The character you have picked out is 'SAMARITAN MODIFIER LETTER EPENTHETIC YUT' (U+081A). Perhaps you were after U+2074, i.e. 'SUPERSCRIPT FOUR' (U+2074). You need hex for that...
7,714,908
7,715,274
MODBUS TCP answer convert to a float C++
I got a Problem. I've got a MODBUS TCP answer, which is hex coded like this: 0 0 0 0 0 7 1 4 4 41 B8 66 64. For explanation: the first five zeroes are a specification of Modbus, the 7 are the numbers of bytes following after it. the 1 is the client address in the Modbus network and not relevant. the first 4 is the func...
You're almost there. Unfortunately, conversion occurs automatically during promotion - the most "straightforward" way of circumventing this is through dereferencing a float pointer cast of an int, as so: int ival = (ibuf[9]<<24)+(ibuf[10]<<16)+(ibuf[11]<<8)+ibuf[12]; float fval = *(float*)&ival; For the data supplied...
7,714,938
7,715,024
2D array bounds checking using std::vector and .at()
I've a quite simple question but for witch I cannot find the answer. How can I use the .at(i) in a 2D array of vector < vector <type> > ? I want to have bounds checking - witch .at(i) function provides automatically, but I can only access my array using the array[i][j] witch doesn't provide for bounds checking.
Use vec.at(i).at(j) and must use this in try-catch block since at() will throw std::out_of_range exception if the index is invalid: try { T & item = vec.at(i).at(j); } catch(const std::out_of_range & e) { std::cout << "either index i or j is out of range" << std::endl; } EDIT: As you said in the comment: I...
7,715,371
7,715,486
What's the point of const pointers?
I'm not talking about pointers to const values, but const pointers themselves. I'm learning C and C++ beyond the very basic stuff and just until today I realized that pointers are passed by value to functions, which makes sense. This means that inside a function I can make the copied pointer point to some other value ...
const is a tool which you should use in pursuit of a very important C++ concept: Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean. Even though it doesn't change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. I...
7,716,040
7,716,097
Migrate function C++ with pointers to C#
I have a function in C++ that returns pointer values​​: fPosFirst( int &aId, char *aNname, char *aDirectory ); My syntax in c# is: fPosFirst(ref int aId, String aNname, String aDirectory); the function returns the id but not the string parameters that anyone knows?
Assuming that the native function does not "return pointers" but writes characters to the memory locations specified by aNname and aDirectory, you should be able to pass a StringBuilder with a proper capacity to the native function: void fPosFirst(ref int aId, StringBuilder aNname, StringBuilder aDirectory); Usage: va...
7,716,074
7,716,298
How to make it so the user can't delete a dynamic array?
In writing a response, I wrote some code that challenged my assumptions on how const pointers work. I had assumed const pointers could not be deleted by the delete function, but as you'll see from the code below, that isn't the case: #include <new> #include <string.h> class TestA { private: char *Array; ...
If your users are using delete[] on pointers they didn't get from new[], hit them upside the head with a clue bat. There are so many reasons a pointer can be dereferenced but mustn't be passed to delete: Someone else will delete it. It's not the beginning of the block. It came from malloc or some other non-new allocat...
7,716,861
7,722,331
How to get text from TextInput in a special container [Nokia Qt Qml]
I'm trying to program a sudoku game on Symbian using Qt Creator. My sudoku game is made with a Grid (QML element) of 9 x 9 rectangles in which there are some TextInput elements limited to one character (the number). If its needed, I can paste the code here. I don't know how I can get all values from the sudoku grid...
Just read the values of each TextInput element. I hope you created an array of TextInput so you could use loop to obtain them. If not then read this: How to make an Array of Widgets You can also check How to access your child widgets at runtime.
7,716,869
7,716,894
Any script to strip out the compiled source in C++
In my C++ file, I have #ifdef DEBUG then blah #else blooh. I want to strip out all text that does not get compiled after preprocessing, so that if DEBUG is not defined, then all statement of the form: #ifdef DBUG /* some debug code */ #endif gets stripped out of the source. EDIT: Here is an example ...
Is just running the preprocessor not good enough? For example g++ -E?
7,716,923
7,716,988
What's the best way to access the internal data structure within a class?
I have a class A consisting of a bunch of internal data structures (e.g. m_data) and a few objects (e.g. ClassB): class A { public: ... private: int m_data[255]; ClassB B[5]; } What's the best way for B to access m_data? I don't want to pass m_data into B's function.. // updated: Many thanks for the ...
Ideally, you don't allow external access the data structure at all. You should rethink your approach, considering more the question "What are the functional requirements / use cases needed for ClassB to access instances of A" rather than offloading the management of the internal members to methods not managed within c...
7,717,529
7,717,593
What does OpenCV's cvAcc() do?
Could someone please explains in simple, non-technical and non-mathematical terms what exactly does cvAcc do? I read that it it "accumulates", but have no idea what accumulates means. Thanks
Accumulation is the result of adding (or summing). It's kind of what the += does in C/C++. So cvAcc(image, accumulation, mask); Is like accumulation += image; // with the mask applied so only a region might be affected
7,717,650
7,717,704
change the inside of a loop without testing
let's say I have the following loops: for(int i=left; i < right; i++) { for(int j=top; j < bottom; j++) { if(tilesMap[i][j]) (tilesMap[i][j])->Draw(window) ; } } and for(int i=left; i < right; i++) { for(int j=top; j < bottom; j++) { (tilesMap[i][j])->Draw(window) ; } } Is ...
You can use a pointer to a function(i,j). Or an object. If you use C++, you can do it object oriented way i.e. with a virtual method and inheritance. It will need a lot of source lines, but it will be clean code. :-)
7,717,747
7,722,009
How to effectively use git repositories / submodules for a C++ product that has many dependencies?
I'm very new to Git and still figuring things out... I think I'm finally understanding the whole branching/merging aspects. But I'm still not sure what the best solution for handling project dependencies are. What is best practice? This has got to be a common problem and yet I can't find a good tutorial or best pra...
Normally this is a bad idea, but why don't you check the binaries into the submodules as well as the compiled code for submodules that don't change often? That way, the fetch will pull down the bins, and when you compile a new version of a dependency with changed binaries, you will see the binaries show up in the git s...
7,718,116
7,718,145
Simple c++ constructor don't work (very basic)
Ok, so I've decided to read a little c++ now and then, just to get a basic understanding of the syntax. I am familiar with Java, and a little bit of Python. I have 'read' through a c++ for dummies book, and I thought I had the grip - until I tried to create the simplest class. The idea was very simple: a class (named ...
You are assigning a value to a variable that doesn't exist. Change: ape::ape(int num) { tall = num; } To: ape::ape(int num) : number(num) { } Moreover, I don't know why you wrote a destructor, and why you decided to make it virtual. By default, the compiler will generate an empty destructor (similar to yours, b...
7,718,214
7,718,249
Why does this compile and is there any compiler switch that can make the compiler report it as an error or warning?
I found this example when I ran PCLint on the source code of the project I am working on. Here is the code snippet: QString foo() { return false; } I compiled the code and verified that it returns an empty string. The real example is a large method in a large class, and somewhere in some remote if branch, there wa...
false equates to zero. Zero is a special case that represents the NULL pointer, and will be cast to any pointer type without warning. I'm quite surprised that the compiler allowed this as a one-step conversion, and didn't consider it a two-step conversion from boolean to int, then int to char* - two-step conversions ar...
7,718,240
7,718,300
Initializing C++ array in constant time
char buffer[1000] = {0}; This initializes all 1000 elements to 0. Is this constant time? If not, why? It seems like the compiler could optimize this to O(1) based on the following facts: The array is of fixed size and known at compile time The array is located on the stack, which means that presumably the executable ...
It will never be constant time, global or not. its true the compiler initializes that, but the operating system must load all the file into memory, which takes O(n) time.
7,718,331
7,718,614
Referencing the same variable that you're declaring
I've seen the following type mistake a couple of times while working with C++ code: QString str = str.toUpper(); This can be a fairly easy mistake to make and yet it compiles and executes (sometimes with crashes, sometimes without). I can't see any circumstances under which it would be something that you'd actually wa...
Technically the object str is defined when you reach the equal sign, so it can be used at that point. The error is in trying to initialize the object with itself, and the compiler is allowed to warn about that (if it is able to detect it). However, as the detection is not possible in every case, the compiler is not req...