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
2,572,540
2,572,594
Errors not printing correctly..Is this logic flow correct? c++
Example user input: PA1 9 //correct PJ1 9 //wrong, error printed "Invalid row" because it is not between A and I PA11 9 //wrong, error printer "Invalid column" because it is not between 1 and 9. The problem I am having is that it should clear the remaining input and then ask for the user to enter the "move" again, a...
cin's clear member function doesn't clear the remaining input, it resets the error flags on the stream (which could get set e.g. because you tried to read an integer but there were non-digit characters in the input). I guess you really want to discard the input up to the next newline; one way to do this would be to ca...
2,572,678
2,574,408
C++ STL Map vs Vector speed
In the interpreter for my experimental programming language I have a symbol table. Each symbol consists of a name and a value (the value can be e.g.: of type string, int, function, etc.). At first I represented the table with a vector and iterated through the symbols checking if the given symbol name fitted. Then I th...
You effectively have a number of alternatives. Libraries exist: Loki::AssocVector: the interface of a map implemented over a vector of pairs, faster than a map for small or frozen sets because of cache locality. Boost.MultiIndex: provides both List with fast lookup and an example of implementing a MRU List (Most Recen...
2,572,891
2,572,897
How are FFTs different from DFTs and how would one go about implementing them in C++?
After some studying, I created a small app that calculates DFTs (Discrete Fourier Transformations) from some input. It works well enough, but it is quite slow. I read that FFTs (Fast Fourier Transformations) allow quicker calculations, but how are they different? And more importantly, how would I go about implementing ...
If you don't need to manually implement the algorithm, you could take a look at the Fastest Fourier Transform in the West Even thought it's developed in C, it officially works in C++ (from the FAQ) Question 2.9. Can I call FFTW from C++? Most definitely. FFTW should compile and/or link under any C++ compiler. Mo...
2,572,985
2,573,156
How can I use Qt to get html code of the redirected page?
I'm trying to use Qt to download the html code from the following url: http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=nucleotide&cmd=search&term=AB100362 this url will re-direct to www.ncbi.nlm.nih.gov/nuccore/27884304 I try to do it by following way, but I cannot get anything. it works for some webpage such as www....
That page appears to have a redirect. From the Qt docs for 4.6: Note: When the HTTP protocol returns a redirect no error will be reported. You can check if there is a redirect with the QNetworkRequest::RedirectionTargetAttribute attribute.
2,572,994
2,573,049
opengl color quadrangle
i have a programm that creates a black border an white corner (quadrangle). now i want to make the corner of the quadrangle in an different color. i don't know where exactly to write the code, and i don't know much a but color4f, i searcherd on google, but didn't get it. (is there a good description somewhere?) #includ...
First of all, you probably want glColor3f. glColor4f also takes an alpha (transparency) value, which you probably don't care about yet. The range of parameters is 0 for no intensity and 1 for max intensity of red, green and blue. So you could do something like: glColor3f( 1.0f, 0.0f, 0.0f ); // red glVertex3f( -...
2,573,142
2,573,168
c++ shorthand operator-> operator()
Suppose I have: Foo foo; is there a shorthand for this? foo.operator->().operator()(1, 2);
Assuming you actually meant foo.operator->().operator()(1, 2), and that you have control over the class Foo, a simpler form would be (*foo)(1, 2). It requires the operator* to that defined though, but since we usually expect foo->bar to be equivalent to (*foo).bar, it seems reasonable. If your Foo is a smart pointer cl...
2,573,242
2,573,334
How can I create objects based on dump file memory in a WinDbg extension?
I work on a large application, and frequently use WinDbg to diagnose issues based on a DMP file from a customer. I have written a few small extensions for WinDbg that have proved very useful for pulling bits of information out of DMP files. In my extension code I find myself dereferencing c++ class objects in the sam...
Interesting idea, but this would have a hope of working only on the simplest of objects. For example, if the object contains pointers or references to other objects (or vtables), those won't copy very well over to a new address space. However, you might be able to get a 'proxy' object to work that when you call the pr...
2,573,325
2,573,387
std::for_each on a member function with 1 argument
I'm wondering how to implement what is stated in the title. I've tried something like... std::for_each( a.begin(), a.end(), std::mem_fun_ref( &myClass::someFunc ) ) but I get an error saying that the "term" (I"m assuming it means the 3rd argument) doesn't evaluate to a function with 1 argument, even though someFunc doe...
Even though someFunc is a member with one parameter, mem_fun_ref uses an implicit first argument of "myClass". You want to use the vector's items as the 2nd argument . And there are probably no negative performance implications of using for_each and mem_fun_ref. The compiler will generate comparable code. But, the o...
2,573,433
2,573,441
Vectors of Pointers, inheritance
Hi I am a C++ beginner just encountered a problem I don't know how to fix I have two class, this is the header file: class A { public: int i; A(int a); }; class B: public A { public: string str; B(int a, string b); }; then I want to create a vector in main which store either class A or...
The reason this won't work is because the objects in your vector are of (static) type A. In this context, static means compile-time. The compiler has no way to know that anything coming out of vec will be of any particular subclass of A. This isn't a legal thing to do, so there is no way to make it work as is. You ...
2,573,435
2,574,787
Clearing cin input: is cin.ignore not a good way?
What's a better way to clear cin input? I thought cin.clear and cin.ignore was a good way? Code: void clearInput() { cin.clear(); cin.ignore(1000,'\n'); //cin.ignore( std::numeric_limits<streamsize>::max(), '\n' ); } My teacher gave me this reply: this is basically saying that your clearInput doesn...
Your teacher’s reply are a bit unclear (at least to me). Concerning ignore, your teacher is wrong in principle: ignore is the standard idiom of how to clear a stream (as shown by Potatocorn, this is even mentioned in the standard). However, it’s important to notice that cin.ignore(1000) is indeed a bad way of doing thi...
2,573,653
2,574,095
Given a 1 TB data set on disk with around 1 KB per data record, how can I find duplicates using 512 MB RAM and infinite disk space?
There is 1 TB data on a disk with around 1 KB per data record. How do I find duplicates using 512 MB RAM and infinite disk space?
Use a Bloom filter: a table of simultaneous hashes. According to Wikipedia, the optimal number of hashes is ln(2) * 2^32 / 2^30 ≈ 2.77 ≈ 3. (Hmm, plugging in 4 gives fewer false positives but 3 is still better for this application.) This means that you have a table of 512 megabytes, or 4 gigabits, and processing each r...
2,573,701
2,591,117
llvm clang struct creating functions on the fly
I'm using LLVM-clang on Linux. Suppose in foo.cpp I have: struct Foo { int x, y; }; How can I create a function "magic" such that: typedef (Foo) SomeFunc(Foo a, Foo b); SomeFunc func = magic("struct Foo { int x, y; };"); so that: func(SomeFunc a, SomeFunc b); // returns a.x + b.y; ? Note: So basically, "magic" ne...
If you really want to do this kind of stuff, you have to link in the whole CLang, and learn how to use its complicated and constantly changing API. Are you so sure you actually need it?
2,573,726
2,573,749
How to use boost::crc?
I want to use boost::crc so that it works exactly like PHP's crc32() function. I tried reading the horrible documentation and many headaches later I haven't made any progress. Apparently I have to do something like: int GetCrc32(const string& my_string) { return crc_32 = boost::crc<bits, TruncPoly, InitRem, FinalXo...
Dan Story and ergosys provided good answers (apparently I was looking in the wrong place, that's why the headaches) but while I'm at it I wanted to provide a copy&paste solution for the function in my question for future googlers: #include <boost/crc.hpp> uint32_t GetCrc32(const string& my_string) { boost::crc_32_...
2,573,817
2,573,830
Is a control tree cached after the first call to FindWindowEx/EnumChildWindows?
I noticed that if you call FindWindowEx or EnumChildWindows against a hWnd that belongs to a window that's not in the foreground, i.e. minimized, then they don't report any children. On the other hand if I first call SetForegroundWindow against the window I'm querying, and after that FindWindowEx or EnumChildWindows, t...
Is this a window in your own application, or are you investigating what a third-party application does? I would guess that the application only creates its child windows the first time it is brought into the foreground; this would explain the behaviour you are seeing. To my knowledge, EnumChildWindows does not perform ...
2,574,041
2,574,106
Binary Search Tree node removal
I've been trying to implement a delete function for a Binary Search Tree but haven't been able to get it to work in all cases. This is my latest attempt: Node* RBT::BST_remove(int c) { Node* t = get_node(c); Node* temp = t; if(t->get_left() == empty) *t = *t->get_left(); else if(t->get_right() ...
First, your last else if conditional clause is redundant. Swap it with an else clause. Secondly, I think it would make things easier for you if you'd take as parameter a pointer to the node to remove. You can write a find() function which would find a node given its key. I'm assuming of course that you can change the f...
2,574,060
2,574,065
C++ min heap with user-defined type
I am trying to implement a min heap in c++ for a struct type that I created. I created a vector of the type, but it crashed when I used make_heap on it, which is understandable because it doesn't know how to compare the items in the heap. How do I create a min-heap (that is, the top element is always the smallest one i...
Add a comparison operator: struct DOC{ int docid; double rank; bool operator<( const DOC & d ) const { return rank < d.rank; } }; Structures can almost always usefully have a constructor, so I would also add: DOC( int i, double r ) : docid(i), rank(r) {] to the struct as well.
2,574,183
2,581,497
How can I load an MP3 or similar music file for display and analysis in wxWidgets?
I'm developing a GUI in wxPython which allows a user to generate sequences of colours for some toys I'm building. Part of the program needs to load an MP3 (and potentially other formats further down the line) and display it to the user. That should be sufficient to get started but later I'd like to add features like id...
After a little more googling, I think PyMedia might well be a good place to start at least as far as a Python implementation goes.
2,574,350
2,574,360
gluLookAt doesn't work
i'm programming with opengl and i want to change the camera view: ... void RenderScene() //Zeichenfunktion { glClearColor( 1.0, 0.5, 0.0, 0 ); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glLoadIdentity (); //1.Form: glBegin( GL_POLYGON ); //polygone glColor3f( 1.0f, 0.0f, 0.0f ); /...
gluLookAt modifies the current transform matrix, so it only has effect on things rendered after the call. Try putting gluLookAt before your rendering code.
2,574,358
2,574,365
if i want to build logger class in c++ or java what should it be singletone or static
general question is i like to build logger class that writes to single log file from different classes in my application what should the logger class be singletone or static class
In C++ you'll want a singleton rather than a static. C++ does not allow you to control the order static objects are constructed and destructed, and if you tried to log before the static was constructed behaviour would possibly be undefined. I'm not sure about Java.
2,574,416
2,574,473
Testing of coding and naming conventions of C/C++ code
I'm looking for a script/tool that can be customized to check and enforce coding/naming conventions on a C/C++ code. It should check for example: Code lines are wrapped at some length. Private variables have prefix _ Code is indented properly. All functions are documented. Many of the projects I'm working on are out...
The GNU indent tool can do some of what you're asking for. Not sure if it can check for documentation, but the rest sounds doable
2,574,458
2,574,471
Parsing/executing C# code in C++ (on Linux)?
I want to be able to add scripting functionality to my application. One of the language bindings I am considering is C# (and possibly VB.Net). The challenge is this: My application is developed in C++ My application runs on Linux I am aware of Mono, but I dont know (as yet), what is required to allow my C++ appliacti...
The Mono framework has an option specifically designed to allow embedding in C / C++ application. My suggestion would be to spend some time reading the documentation.
2,574,547
2,574,574
C++ setting up "flags"
Example: enum Flags { A, B, C, D }; class MyClass { std::string data; int foo; // Flags theFlags; (???) } How can I achieve that it is possible to set any number of the "flags" A,B,C and D in the enum above in an instance of MyClass? My goal would be something like this: if ( MyClassInst.I...
// Warning, brain-compiled code ahead! const int A = 1; const int B = A << 1; const int C = B << 1; const int D = C << 1; class MyClass { public: bool IsFlagSet(Flags flag) const {return 0 != (theFlags & flag);} void SetFlag(Flags flag) {theFlags |= flag;} void UnsetFlag(Flags flag) {theFlags &= ~...
2,574,549
2,575,145
Forward declare HINSTANCE and friends
Is there a way to forward-declare the HINSTANCE type from the WinAPI without including the full (and big) windows.h header? For example, if I have a class RenderWindow which owns an HINSTANCE mInstance, i will have to include windows.h in RenderWindow.h. So everything that needs RenderWindow also has to include windows...
HINSTANCE is declared in WinDef.h as typedef HINSTANCE__* HINSTANCE; You may write in your headers: #ifndef _WINDEF_ class HINSTANCE__; // Forward or never typedef HINSTANCE__* HINSTANCE; #endif You will get compilation errors referencing a HINSTANCE when WinDef.h is not included.
2,574,904
2,574,932
How to speed-up a simple method (preferably without changing interfaces or data structures)?
I have some data structures: all_unordered_m is a big vector containing all the strings I need (all different) ordered_m is a small vector containing the indexes of a subset of the strings (all different) in the former vector position_m maps the indexes of objects from the first vector to their position in the second...
vector lookups are blazing fast. size() calls and simple arithmetic are blazing fast. map lookups, in comparison, are as slow as a dead turtle with a block of concrete on his back. I have often seen those become a bottleneck in otherwise simple code like this. You could try unordered_map from TR1 or C++0x (a drop-in ha...
2,574,915
2,575,677
Question on multi-probe Local Sensitive Hashing
sorry to be asking this kind noob question, but because I really need some guidance on how to use Multi probe LSH pretty urgently, so I did not do much research myself. I realize there is a lib call LSHKIT available that implemented that algorithm, but I have trouble trying to figure out how to use it. Right now, I ha...
Let me instead point you to spectral hashing which kicks LSH's butt big time. Bonus: They have matlab code on their website, which you can either use or verify your own implementation against. Also, it's much easier to implement.
2,575,002
2,575,045
C++ Template Classes and Copy Construction
Is there any way I can construct an new object from the given object if the template parameters of both objects are identical at run-time? For example: I have a template class with the declaration: template<typename _Type1, typename _Type2> class Object; Next, I have two instantiations of the template: template class ...
What you have should work, the problem is that the compiler is doing a type check on the return *this part, even if the types aren't equal (hence the compile error). Just use return (Object<char, int>)(*this); and you should be fine -- the only time that code will be executed is when the types are the same anyway, so t...
2,575,059
2,575,076
Book on C++ for understanding advanced concepts
What is good book for industry level C++ programming? I am not looking for a beginners C++ book that talks about datatypes and control structures. I am looking for a more advanced book. For example, how to build system applications using C++. Any kind of guidance will be very helpful.
Modern C++ Design by Andrei Alexandrescu is probably the most advanced C++ book out there. It's more about very advanced design patterns rather than building software.
2,575,095
2,575,394
Why aren't these shared_ptrs pointing to the same container?
I have a class Model: class Model { ... boost::shared_ptr<Deck> _deck; boost::shared_ptr<CardStack> _stack[22]; }; Deck inherits from CardStack. I tried to make _stack[0] point to the same thing that _deck points to by going: { _deck = boost::shared_ptr<Deck>(new Deck()); _stack[0] = _deck; } I...
This example - derives from @Neil's answer, tries to emulate what you say is happening. Could you check that it works as expected (A and B have the same count) on your system. Then we could try and modify this code or your code until they match. #include <boost/shared_ptr.hpp> #include <iostream> class A { public:...
2,575,128
2,575,134
Calling a method of a constant object parameter
Here is my code that fails: bool Table::win(const Card &card) { for (int i = 0; i < cards.size(); i++) if (card.getRank() == cards[i].getRank()) return true; return false; } Error message is: passing 'const Card' as 'this' argument of 'int Card::getRank()' discards qualifiers. When I get a copy of the car...
Is getRank a const-method? It should be declared like this": int getRank( ) const; Assuming the return type is int.
2,575,265
2,575,490
Distinct rand() sequences yielding the same results in an expression
Ok, this is a really weird one. I have an MPI program, where each process has to generate random numbers in a fixed range (the range is read from file). What happens is that even though I seed each process with a different value, and the numbers generated by rand() are different in each process, the expression to gener...
Ok, apparently I'm retarded. After initializing the RNG, I spawned a new thread and generated the random numbers there, without initialization. Calling srand() in the new thread fixed the problem. So yeah, the lesson here is that srand() and rand() work per thread, not per process. I also need to start posting more inf...
2,575,293
2,575,316
Other test cases for this openFile function?
I am trying to figure out why my function to open a file is failing this autograder I submit my homework into. What type of input would fail here, I can't think of anything else? Code: bool openFile(ifstream& ins) { char fileName[256]; cout << "Enter board filename: "; cin.getline(fileName,256); cout << endl << ...
Well, you do know what the input is that they use. It appears in your program's output! The first input file name is test.txt, the second is not a fileName. Anyway, it seems that you're printing the filename after you receive it. But no printed filename appears in the correct output. Just stop printing it might help. (...
2,575,296
2,575,309
C++ polymorphism and slicing
The following code, prints out Derived Base Base But I need every Derived object put into User::items, call its own print function, but not the base class one. Can I achieve that without using pointers? If it is not possible, how should I write the function that deletes User::items one by one and frees memory, so that...
You need to use pointers, and you need to give your base class a virtual destructor. The destructor does not have to do anything, but it must exist. Your add function then looks like: void add_item( Base * item ){ item->print(); items.push_back( item ); } where items is a vector<Base *>. To destroy the items (...
2,575,373
2,575,431
Codechef practice question help needed - find trailing zeros in a factorial
I have been working on this for 24 hours now, trying to optimize it. The question is how to find the number of trailing zeroes in factorial of a number in range of 10000000 and 10 million test cases in about 8 secs. The code is as follows: #include<iostream> using namespace std; int count5(int a){ int b=0; f...
Use the following theorem: If p is a prime, then the highest power of p which divides n! (n factorial) is [n/p] + [n/p^2] + [n/p^3] + ... + [n/p^k], where k is the largest power of p <= n, and [x] is the integral part of x. Reference: PlanetMath
2,575,468
2,575,483
string to byte array
How do I input DEADBEEF and output DE AD BE EF as four byte arrays?
void hexconvert( char *text, unsigned char bytes[] ) { int i; int temp; for( i = 0; i < 4; ++i ) { sscanf( text + 2 * i, "%2x", &temp ); bytes[i] = temp; } }
2,575,510
2,575,648
GUI options for emulator c++
I want to create a Gameboy emulator which runs directly from the exe file, in a similar fashion to visualboy advance. I was wondering in terms of creating a GUI interface for the emulator what would be the best option to accomplish this ?
Do you just want a way to do 2D rendering? If so there are numerous ways. wxWidgets (as suggested), QT or SDL provide easy cross platform options. Otherwise you could do it in any number of platform specific ways from using Windows GDI to using D3D11 or whatever platform rendering choices you have available.
2,575,581
2,575,598
Visual Studio CLR project
so I wanted to try my first CLR project in Visual C++. So I created console project, but since every tutorial I found about CLR programming was using C#, or windows forms, I just tried writing standart c++ Hello Word app using iostream (I think code isnt needed in this case) but I though it will give me some compile e...
can any native console C++ app be compiled into MSIL and run by .NET? Most code can see http://msdn.microsoft.com/en-us/library/aa712815.aspx for the exceptions. Your application will still use native code thought. There's also /clr:pure if you want to ensure only CLR code is used.
2,575,684
2,575,703
Interpreter in C++: Function table storage problem
In my interpreter I have built-in functions available in the language like print exit input, etc. These functions can obviously be accessed from inside the language. The interpreter then looks for the corresponding function with the right name in a vector and calls it via a pointer stored with its name. So I gather all...
In each module (io, string, etc.), define a method that registers the module with the interpreter, e.g.: void IOModule::Register(Interpreter &interpreter) { interpreter.AddFunc( "print", print ); //... } This can also be a normal function if your module is not implemented in a class. Then in your application's...
2,575,745
2,575,753
c++ link temporary allocations in function to custom allocator?
I am currently working on some simple custom allocators in c++ which generally works allready. I also overloaded the new/delete operators to allocate memory from my own allocator. Anyways I came across some scenarios where I don't really know where the memory comes from like this: void myFunc(){ myObj tes...
(myObj testObj(); declares a function named testObj which returns a myObj. Use myObj testObj; instead.) The memory comes from the stack. It will be auto-matically destroyed when leaving the scope. To use your new and delete you must of course call new and delete: myObj* p_testObj = new myObj; ... delete p_testObj; B...
2,575,748
2,575,792
Applying policy based design question
I've not read the Modern C++ Design book but have found the idea of behavior injection through templates interesting. I am now trying to apply it myself. I have a class that has a logger that I thought could be injected as a policy. The logger has a log() method which takes an std::string or std::wstring depending on i...
To actually be using a policy class, the policy needs to be a template parameter. One example is the char_traits parameter to basic_string, even though that's implemented differently than MC++D's policies, which use inheritance to make use of the empty base class optimization and to allow easy addition to a class's pu...
2,575,866
2,575,901
Dynamic creation of a pointer function in c++
I was working on my advanced calculus homework today and we're doing some iteration methods along the lines of newton's method to find solutions to things like x^2=2. It got me thinking that I could write a function that would take two function pointers, one to the function itself and one to the derivative and automate...
You can't dynamically create a function in the sense that you can generate raw machine code for it, but you can quite easily create mathematical expressions using polymorphism: struct Expr { virtual double eval(double x) = 0; }; struct Sum : Expr { Sum(Expr* a, Expr* b):a(a), b(b) {} virtual double eval(double x...
2,575,973
2,575,977
Overload assignment operator for assigning sql::ResultSet to struct tm
Are there exceptions for types which can't have thier assignment operator overloaded? Specifically, I'm wanting to overload the assignment operator of a struct tm (from time.h) so I can assign a sql::ResultSet to it. I already have the conversion logic: sscanf(sqlresult->getString("StoredAt").c_str(), "%d-%d-%d %d:%d:%...
The assignment operator must be a member function (of struct tm in this case), so the only way of doing this would be to modify the standard library itself, something you should definitely not do. You can of course write a named free function to do whatever you want.
2,576,004
2,576,025
Any C/C++ to non-native bytecode compiler/interpreters?
As the title indicates, are there any C/C++ bytecode compilers/interpreters? I'm writing an application in an interpreted language that depends on certain libraries that are fully cross-compilable (there are no special flags to indicate code changes during compilation for a certain platform) but are written in C and C+...
Which interpreted language are you using? If it has a .NET based implementation (e.g. IronPython) you could possibly use it with the C++/CLI compiler to produce byte code for the .NET CLR and Mono. This is only likely to be feasible if you have full control over your C++ libraries.
2,576,022
2,576,207
efficient thread-safe singleton in C++
The usual pattern for a singleton class is something like static Foo &getInst() { static Foo *inst = NULL; if(inst == NULL) inst = new Foo(...); return *inst; } However, it's my understanding that this solution is not thread-safe, since 1) Foo's constructor might be called more than once (which may or ma...
Your solution is called 'double checked locking' and the way you've written it is not threadsafe. This Meyers/Alexandrescu paper explains why - but that paper is also widely misunderstood. It started the 'double checked locking is unsafe in C++' meme - but its actual conclusion is that double checked locking in C++ can...
2,576,117
2,640,405
How to set QNetworkReply properties to get correct NCBI pages?
I try to get this following url using the downloadURL function as follows: http://www.ncbi.nlm.nih.gov/nuccore/27884304 But the data is not as what we can see through the browser, now I know it's because some correct information (such as browser type) is needed. How can I know what kind of information I need to set, a...
Close, but you aren't setting the correct header. You need to do: request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)" );
2,576,121
2,576,133
Shift from Java to c++
I have been developing applications based on C# (.net) and Java (J2EE) for the last 3 years. But now I feel, Java, C# makes you lame (from learning point of view) and you can develop your apps quickly but you fail to understand the basic underlying concepts of programming. So, I am trying to learn C++, but I find it a ...
In my opinion, you should learn C first in order to properly understand the base upon which C++ is built. Pick up a copy of "The C Programming Language" by Kernighan and Ritchie, widely considered the best reference on the language, and start reading through it. Once you fully understand C, you'll have the low-level ba...
2,576,122
2,576,155
Advice for keeping large C++ project modular?
Our team is moving into much larger projects in size, many of which use several open source projects within them. Any advice or best practices to keep libraries and dependancies relatively modular and easily upgradable when new releases for them are out? To put it another way, lets say you make a program that is a fork...
With clones of open source projects one of your biggest headaches will be keeping in sync/patched according to the upstream sources. You might not care about new features, but you will sure need critical bug fixes applied. My suggestion would be to carefully wrap such inner projects into shared libraries, so you can mo...
2,576,251
2,576,280
Algorithm for count-down timer that can add on time
I'm making a general timer that has functionality to count up from 0 or count down from a certain number. I also want it to allow the user to add and subtract time. Everything is simple to implement except for the case in which the timer is counting down from some number, and the user adds or subtracts time from it. Fo...
Your code is unnecessarily complex. The following is equivalent: float Timer::GetElapsedTime() { if ( m_forward ) { m_elapsedTime = m_clock.GetElapsedTime(); } else { m_elapsedTime = m_startingTime - m_clock.GetElapsedTime(); } return m_elapsedTime; } and hopefully illustrates why AddTime() doesn't wor...
2,576,368
2,576,395
Use abstract within base expecting it to be a derived class?
take this simple code: class A{ public: virtual void foo() = 0; void x(){ foo(); } }; class B: public A{ foo(){ ... } }; main(){ B b; b.x(); } What I want is to build an abstract class that will have a function that will call a function expecting it to be implemented in the derived class The question is ...
There is nothing preventing you from doing that: struct A { virtual ~A() {} virtual void f() = 0; virtual void g() { f(); } }; struct B : A { void f() { std::cout << "B::f()" << std::endl; } }; // ... A* a = new B; a->g(); // prints "B::f()" As for calling a pure virtual function from the destructor...
2,576,620
2,576,627
Const unsigned char* to char*
So, I have two types at the moment: const unsigned char* unencrypted_data_char; string unencrypted_data; I'm attempting to perform a simple conversion of data from one to the other (string -> const unsigned char*) As a result, I have the following: strcpy((unencrypted_data_char),(unencrypted_data.c_str())); However, ...
You can't write to a const char *, because each char pointed to is const. strcpy writes to the first argument. Hence the error. Don't make unencrypted_data_char const, if you plan on writing to it (and make sure you've allocated enough space for it!) And beware of strcpy's limitations. Make sure you know how big your b...
2,576,688
2,576,701
What's the future of std::valarray look like?
Up until fairly recently I hadn't been keeping up with the C++11 deliberations. As I try to become more familiar with it and the issues being worked, I came across this site which seems to be advocating for deprecating or removing std::valarray since most people are using Blitz++ instead. I guess I'm probably one of ...
std::valarray is included in C++11. It has not been deprecated or removed. It has been updated to include move operations std::valarray is defined in §26.6[numarray] of the C++11 language standard.
2,576,766
2,576,775
should std::auto_ptr<>::operator = reset / deallocate its existing pointee?
I read here about std::auto_ptr<>::operator= Notice however that the left-hand side object is not automatically deallocated when it already points to some object. You can explicitly do this by calling member function reset before assigning it a new value. However, when I read the source code for header file...
If the auto_ptr being assigned to already holds a pointer, that pointer must be deleted first. From the 2003 standard (§20.4.5.1): auto_ptr& operator=(auto_ptr& a) throw(); 7 Requires: The expression delete get() is well formed. 8 Effects: reset(a.release()). 9 Returns: *this. So, assigning to an auto_ptr has the sa...
2,576,812
2,587,322
How to see the contents of std::map in Visual C++ .NET (Visual Studio 2003) while debugging?
I need to see the contents of a std::map variable while debugging. However, if i click on it in the Autos/Locals Tab, I see implementation specific stuff, instead of the keys and its contents which I want to look at. Is there a work-around i'm missing ?
I have no VS2003 nearby at the moment. But you could try to add in "autoexp.dat" the following section (I was sure that in VS2003 there are already included sections for all standard types): ;------------------------------------------------------------------------------ ; std::map ;------------------------------------...
2,576,868
2,576,914
Detect when multiple enum items map to same value
Is there a compile-time way to detect / prevent duplicate values within a C/C++ enumeration? The catch is that there are multiple items which are initialized to explicit values. Background: I've inherited some C code such as the following: #define BASE1_VAL (5) #define BASE2_VAL (7) typedef enum { MsgFoo1A = ...
There are a couple ways to check this compile time, but they might not always work for you. Start by inserting a "marker" enum value right before MsgFoo2A. typedef enum { MsgFoo1A = BASE1_VAL, MsgFoo1B, MsgFoo1C, MsgFoo1D, MsgFoo1E, MARKER_1_DONT_USE, /* Don't use this value, but leave it here....
2,576,919
2,584,309
c++ sdl: can i have an sdl-opengl window inside a menu and buttons i created with glade?
I used glade to create some gtk buttons. is it possible to add an sdl-opengl window to a glade application ? if so, how ? how can I interact between the gtk events and the sdl events inside the gtk window ? thanks
There are at least two extensions to GTK that might help you: GtkGLExt and Gtksdl. Gtksdl appears to be abandoned, but may contian some useful code. GtkGLExt is great if you're not relying on much SDL functionality beyond core OpenGL and events handling.
2,576,983
2,576,988
An array of LPWSTR pointers, not working right
Declare: LPWSTR** lines= new LPWSTR*[totalLines]; then i set using: lines[totalLines]=&totalText; SetWindowText(totalChat,(LPWSTR)lines[totalLines]); totalLines++; Now I know totalText is right, cause if i SetWindowText using totalText it works fine. I need the text in totalLines too. I'm also doing: //accolating mor...
LPWSTR is already a pointer, so you're creating a 2D array of pointers - is that what you wanted? I think not, because this: SetWindowText(totalChat,(LPWSTR)lines[totalLines]); Casts LPWSTR* to LPWSTR. Isn't your compiler complaining?
2,577,402
2,577,670
g++/clang ultra fast parse but not compile mode?
Is there some ultra fast "syntax check my code, but don't compile mode" for g++/clang? Where the only goal is to just check if the code I have is valid C++ code?
-fsyntax-only for GCC, this should probably work for Clang as well since they emulate GCC's command line options. Whether or not it's significantly faster, you'll have to time.
2,577,437
2,577,457
Exposing boost::scoped_ptr in boost::python
I am getting a compile error, saying that the copy constructor of the scoped_ptr is private with the following code snippet: class a {}; struct s { boost::scoped_ptr<a> p; }; BOOST_PYTHON_MODULE( module ) { class_<s>( "s" ); } This example works with a shared_ptr though. It would be nice, if anyone knows the ans...
The semantics of boost::scoped_ptr prohibit taking copies, while shared_ptr is intended to be copied. The error you are getting is the compiler telling you that some of the code (macro expansion?) is trying to copy the scoped_ptr but that the library does not allow the copy to be made.
2,577,473
2,577,548
Use Ribbon Interface in Open Source Applications
Are there any open source implementations of the Ribbon interface available? I need to use them in a GPL licensed software, so the library should be compatible with GPL. The software is in VC++ 2005.
wxWidgets supports ribbon interfaces as well.
2,577,557
2,577,890
Restricting `using` directives to the current file
Sorry for this silly question, but is there any way to restrict using directives to the current file so that they don't propagate to the files that #include this file?
Perhaps wrapping the code to be included inside its own namespace could achieve the behavior you want, since name spaces have scope affect. // FILENAME is the file to be included namespace FILENAME_NS { using namespace std; namespace INNER_NS { [wrapped code] } } using namespace FILENAME_NS::INNER_NS; a...
2,577,702
2,577,751
Better variant of getting the output dynamically-allocated array from the function?
Here is two variants. First: int n = 42; int* some_function(int* input) { int* result = new int[n]; // some code return result; } int main() { int* input = new int[n]; int* output = some_function(input); delete[] input; delete[] output; return 0; } Here the function returns the memor...
I think second variant is better, because you have "balanced responsibility over pointer". That makes code more readable, because you see where you allocate and where you free your memory. If you want to use first variant, I'd suggest you to make dual funnction some_function_free(). As for malloc/free, new/delete, new[...
2,577,822
2,577,851
I am looking for an actual functional web browser control for .NET, maybe a C++ library
I am trying to emulate a web browser in order to execute JavaScript code and then parse the DOM. The System.Windows.Forms.WebBrowser object does not give me the functionality I need. It let's me set the headers, but you cannot set the proxy or clear cookies. Well you can, but it is not ideal and messes with IE's set...
Have you seen Watin?
2,577,911
2,577,926
C++ vector pointer/reference problem
Please take a look at this example: #include <iostream> #include <vector> #include <string> using namespace std; class mySubContainer { public: string val; }; class myMainContainer { public: mySubContainer sub; }; void doSomethingWith( myMainContainer &container ) { container.sub.val = "I was modified"; ...
You're making a copy of the vector here: current = vec.at( i ); and modifying current, but printing the original, vec.at(i). Instead, modify the object directly, e.g. doSomethingWith(vec[i]); // or vec.at(i) for checked access.
2,577,934
2,577,947
Bitwise setting in C++
enum AccessSource { AccessSourceNull = 0x00000001, AccessSourceSec = 0x00000002, AccessSourceIpo = 0x00000004, AccessSourceSSA = 0x00000008, AccessSourceUpgrade = 0x00000010, AccessSourceDelta = 0x00000020, AccessSourcePhoneM = ...
The value of AccessSourceAll is (int)0xFFFFFFFF since enum is of type int in C. The unset just AccessSourceE use: x & ~AccessSourceE // to assign: x &= ~AccessSourceE; To add, use x | AccessSourceE // to assign: x |= AccessSourceE; To test, if (x & AccessSourceE) { ... }
2,578,079
2,578,088
Index strings by other strings
I need to index specific strings with other strings and I can't really find a good way to do so. I tried to use tr1::unordered_map, but I'm having some difficulties using it. If someone could tell me what is the best way to do that I'd be really grateful :) I also need to index objects by a number (numbers are not in o...
What about std::map? std::map<std::string, std::string> foo; Then you can add elements, foo["bar"] = "baz"; cout << foo["bar"] << std::endl; // baz
2,578,365
2,578,388
c++ signatures, pointers
what's the difference between these signatures? T * f(T & identifier); T & f(T & identifier); T f(T & identifier); void f(T * identifier); void f(T & identifier); void f(T identifier); I met pointers in c, but the amperstand in function signature is new for me. Can Anyone explain this?
An ampersand in a type declaration indicates a reference type. int i = 4; int& refi = i; // reference to i int* ptri = &i; // pointer to i refi = 6; // modifies original 'i', no explicit dereferencing necessary *ptri = 6; // modifies through the pointer References have many similarities with pointers, but they're e...
2,578,387
2,578,398
Where to Declare Structures, etc?
Should all structs and classes be declared in the header file? If I declare a struct/class in a source file, what do I need to put in the header file so that it can be used in other files? Also, are there any resources that show some standard practices of C++ out there?
Should all structs and classes be declared in the header file? Yes. EDIT: But their implementations should be in cpp files. Sometimes users coming from C# or Java don't realize that the implementation in C++ can be completely separate from the class declaration. If I declare a struct/class in a source file, what do I n...
2,578,638
2,578,662
C++ Vector at/[] operator speed
In order to give functions the option to modify the vector I can't do curr = myvec.at( i ); doThis( curr ); doThat( curr ); doStuffWith( curr ); But I have to do: doThis( myvec.at( i ) ); doThat( myvec.at( i ) ); doStuffWith( myvec.at( i ) ); (as the answers of my other question pointed out) I'm going to make a hell...
You can use a reference: int &curr = myvec.at(i); // do stuff with curr The at member function does bounds checking to make sure the argument is within the size of the vector. Profiling is only way to know exactly how much slower it is compared to operator[]. Using a reference here allows you to do the lookup once a...
2,578,866
2,578,899
strftime doesnt display year correctly
i have the following code below: const char* timeformat = "%Y-%m-%d %H:%M:%S"; const int timelength = 20; char timecstring[timelength]; strftime(timecstring, timelength, timeformat, currentstruct); cout << "timecstring is: " << timecstring << "\n"; currentstruct is a tm*. The cout is giving me the date in the corre...
When you put the year into your currentstruct, you're apparently putting in 2010, but you need to put in 2010-1900. If you retrieve the time from the system and convert to a struct tm with something like localtime, you don't need to do any subtraction though, because what it puts into the struct tm is already the year ...
2,578,944
2,578,995
python challenge, but for C++
Does anyone know any site or book that presents problems like python challenge, but for C++? When I think python challenge, I do not mean only a set of problems to be solved with C++ (for that I could probably use the same problems of python challenge), but rather problems that will probably be best solved using C++ ST...
Google Code Jam problems frequently have analyses with snippets of C++ code, probably because C++ is by far the most popular language used for solving code-jam problems. The latter also allows you to see many C++ constructs cleverly employed, as code-jam allows you to download the solutions by all the competitors. As m...
2,578,994
2,579,003
Value get changed even though I'm not using reference
In code: struct Rep { const char* my_data_; Rep* my_left_; Rep* my_right_; Rep(const char*); }; typedef Rep& list; ostream& operator<<(ostream& out, const list& a_list) { int count = 0; list tmp = a_list;//----->HERE I'M CREATING A LOCAL COPY for (;t...
I assume list is meant to be the same as Rep. You are only copying the the pointer to the first node in the list. You are not copying the data, nor the rest of the nodes of the list. You are doing a shallow copy of the first node of the list. If you would also copy the objects themselves it would be deep copy.
2,579,020
2,579,044
GDB skips over my code!
So, I've defined a class like DataLoggingSystemStateReceiver { DataLoggingSystemStateReceiver() : // initializer list { // stuff } // ... other functions here }; In main, I instantiate DataLoggingSystemStateReceiver like so: int main() { // ... run stuff Sensor sensor(port, timer); DataLoggingSys...
This: DataLoggingSystemStateReceiver dlss(); does not declare an automatic variable. It declares a function named dlss that takes no arguments and returns a DataLoggingSystemStateReceiver. You want: DataLoggingSystemStateReceiver dlss; The object will be default initialized, so for your class type, the default const...
2,579,230
2,579,250
Signedness of enum in C/C99/C++/C++x/GNU C/GNU C99
Is the enum type signed or unsigned? Does the signedness of enums differ between: C/C99/ANSI C/C++/C++x/GNU C/ GNU C99? Thanks
An enum is guaranteed to be represented by an integer, but the actual type (and its signedness) is implementation-dependent. You can force an enumeration to be represented by a signed type by giving one of the enumerators a negative value: enum SignedEnum { a = -1 }; In C++0x, the underlying type of an enumeration can...
2,579,511
2,579,749
Incorrect logic flow? function that gets coordinates for a sudoku game
This function of mine keeps on failing an autograder, I am trying to figure out if there is a problem with its logic flow? Any thoughts? Basically, if the row is wrong, "invalid row" should be printed, and clearInput(); called, and return false. When y is wrong, "invalid column" printed, and clearInput(); called and re...
It's hard to know without seeing the input, but here's a couple of possible issues: (1) The way you detect that the column read failed is by examining the value of y - but are you sure that it's set to a value outside the range 1-9 by the calling code? Otherwise even if the read fails you might think it succeeds. You...
2,579,588
2,582,888
Incorrect emacs indentation in a C++ class with DLL export specification
I often write classes with a DLL export/import specification, but this seems to confuse emacs' syntax parser. I end up with something like: class myDllSpec Foo { public: Foo( void ); }; Notice that the "public:" access spec is indented incorrectly, as well as everything that follows it. When I ask emacs to describ...
From http://www.emacswiki.org/emacs/IndentingC#toc13 you can set up a "microsoft" style. Drop this into your .emacs: (c-add-style "microsoft" '("stroustrup" (c-offsets-alist (innamespace . -) (inline-open . 0) (inher-cont . c-lineup-multi-inhe...
2,579,642
2,579,660
How to free memory from a list of classes
Say I have two classes created work and workItem. CWorker *work = new CWorker(); CWorkItem *workItem = new CWorkItem(); The work class has a public list m_WorkList and I add the work item to it. work->m_WorkList.push_back(workItem); If I just delete work if(work != NULL) delete work; Do I need to lo...
Yes you need to delete each item. If you call new N times, then you need to call delete exactly N times as well. There is no shortcut for bulk deleting items. Also when you're done with it you need to call delete on work. You can use new[] and delete[] if you want to create an array of items on the heap and release t...
2,579,657
2,579,665
Ctor not allowed return type
Having code: struct B { int* a; B(int value):a(new int(value)) { } B():a(nullptr){} B(const B&); } B::B(const B& pattern) { } I'm getting err msg: 'Error 1 error C2533: 'B::{ctor}' : constructors not allowed a return type' Any idea why? P.S. I'm using VS 2010RC
You're missing a semicolon after your struct definition. The error is correct, constructors have no return type. Because you're missing a semicolon, that entire struct definition is seen as a return type for a function, as in: // vvv return type vvv struct { /* stuff */ } foo(void) { } Add your semicolon: struct B { ...
2,579,702
2,580,782
graphics programming
I would like to program some graphic figures such as line, circle,etc. I have used turboc++ 3.0 for dos graphics. I would like to do the same with the compilers dev c++ or code blocks or vc++. I would like to implement dda and bresenhems line and circle drawing algorithm. how should I go about implementing these progr...
If you're wanting to play around with graphics code to draw objects and do things with them may I suggest that you skip the whole Windows/GDI/DirectX/ thing completely and take a look at Processing? It's basically Java, so you won't have to jump too far for the language, but more specifically it's designed for playing ...
2,579,874
2,579,909
Lifetime of a string literal returned by a function
Consider this code: const char* someFun() { // ... some stuff return "Some text!!" } int main() { { // Block: A const char* retStr = someFun(); // use retStr } } In the function someFun(), where is "Some text!!" stored (I think it may be in some static area of ROM) and what is its scope life...
The C++ Standard does not say where string literals should be stored. It does however guarantee that their lifetime is the lifetime of the program. Your code is therefore valid.
2,580,123
2,580,261
Possible to have C++ anonymous functions with boost?
I'm trying to solve a problem that anonymous functions make much, much easier, and was wondering if this was possible in c++. What I would like to do is (essentially) template<typename T> T DoSomething(T one, function<T(T)> dosomething) { return one + dosomething(5); } void GetMyVal(...) { DoSomething<int>(1, /...
As Anders notes in his answer, boost::lambda can be useful, but the code can become hard to read in some cases. It thus depends on what you want to do in your anonymous function. For simple case like the p => p * 5 you mention in your question, it seems to me that using Lambda or Bind would be reasonable, though: DoSom...
2,580,189
2,581,671
How to initialise a STL vector/list with a class without invoking the copy constructor
I have a C++ program that uses a std::list containing instances of a class. If I call e.g. myList.push_back(MyClass(variable)); it goes through the process of creating a temporary variable, and then immediately copies it to the vector, and afterwards deletes the temporary variable. This is not nearly as efficient as I ...
C++0x move constructors are a partial workaround: instead of the copy constructor being invoked, the move constructor would be. The move constructor is like the copy constructor except it's allowed to invalidate the source argument. C++0x adds another feature which would do exactly what you want: emplace_back. (N3092 §...
2,580,680
2,580,700
Does a c/c++ compiler optimize constant divisions by power-of-two value into shifts?
Question says it all. Does anyone know if the following... size_t div(size_t value) { const size_t x = 64; return value / x; } ...is optimized into? size_t div(size_t value) { return value >> 6; } Do compilers do this? (My interest lies in GCC). Are there situations where it does and others where it doesn...
Even with g++ -O0 (yes, -O0!), this happens. Your function compiles down to: _Z3divm: .LFB952: pushq %rbp .LCFI0: movq %rsp, %rbp .LCFI1: movq %rdi, -24(%rbp) movq $64, -8(%rbp) movq -24(%rbp), %rax shrq $6, %rax leave ret Note the shrq $...
2,580,729
2,580,749
C++ Return by reference
Say, i have a function which returns a reference and i want to make sure that the caller only gets it as a reference and should not receive it as a copy. Is this possible in C++? In order to be more clear. I have a class like this. class A { private: std::vector<int> m_value; A(A& a){ m_value = a.m_value; } p...
You can do what you want for your own classes by making the class non copyable. You can make an class non copyable by putting the copy constructor and operator= as private or protected members. class C { private: C(const C& other); const C& operator=(const C&); }; There is a good example of making a NonCopyab...
2,580,916
2,648,170
Intellisense fails for boost::shared_ptr with Boost 1.40.0 in Visual Studio 2008
I'm having trouble getting intellisense to auto-complete shared pointers for boost 1.40.0. (It works fine for Boost 1.33.1.) Here's a simple sample project file where auto-complete does not work: #include <boost/shared_ptr.hpp> struct foo { bool func() { return true; }; }; void bar() { boost::shared_ptr<foo> pf...
I also recently ran into this and went searching for an answer. All I found was people saying Intellisense is going to be improved in VC10 or that I should improve it now using Visual Assist. I didn't like these answer so I experimented a bit. Here's the solution that fixes most of the issues (at the very least it fixe...
2,581,025
2,581,339
How are VST Plugins made?
I would like to make (or learn how to make) VST plugins. Is there a special SDK for this? how does one yield a .vst instead of a .exe? Also, if one is looking to make Audio Units for Logic Pro, how is that done? Thanks
Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page). The n...
2,581,250
2,581,306
Precision of cos(atan2(y,x)) versus using complex <double>, C++
I'm writing some coordinate transformations (more specifically the Joukoswky Transform, Wikipedia Joukowsky Transform), and I'm interested in performance, but of course precision. I'm trying to do the coordinate transformations in two ways: 1) Calculating the real and complex parts in separate, using double precision, ...
I think that in 1) it should be Z.y = 0.5*(si*sq - si/sq); If you want really good performance you may want to go back to first principles and observe that 1/(a+ib) = (a-ib)/(a*a+b*b) No sqrt(), atan2() or cos() or sin().
2,581,377
2,581,708
Pass C++ object to Lua function
I have a C++ project, where 1 method of a 1 class changes very often. So I want to take that code from C++ to Lua. Note, I'm novice to Lua. The whole task: Bind some class methods to Lua state machine; Pass reference to class object to a function, written in Lua; Operate with passed C++ object in Lua function. I've f...
//This has a large number of steps, but I'm gonna post them all. This is all using native Lua 5 and the lua CAPI. int CreateInstanceOfT(lua_State* L) { new (lua_newuserdata(L, sizeof(T))) T(constructor args); return 1; } int CallSomeFuncOnT(lua_State* L) { if (lua_istable(L, 1)) { // If we're passed a table...
2,581,416
2,581,430
recognise @param in Eclipse for c++?
I am using Eclipse (3.5.1), on Ubuntu 9.10 to write some C++ code. I was searching through endless settings but didnt find what I as looking for... How can I force eclipse to make @param,(@see, @return etc) to be bold in the comments? All the documentation will be generated with the doxygen so I dont really need anyth...
When I do /** * @param foo ... In Eclipse (Version: 3.5.1) I get comment http://ploader.net/files/b39ff20600cf04990b80d3ef2f6e6592.png With the doxygen plugin enabled for the project. Note the double asterisks.
2,581,424
2,581,462
How to check for C++ copy ellision
I ran across this article on copy ellision in C++ and I've seen comments about it in the boost library. This is appealing, as I prefer my functions to look like verylargereturntype DoSomething(...) rather than void DoSomething(..., verylargereturntype& retval) So, I have two questions about this Google has virtua...
I think this is a very commonly applied optimization because: it's not difficult for the compiler to do it can be a huge gain it's an area of C++ that was a commonly critiqued before the optimization became common If you're just curious, put a debug printf() in your copy constructor: class foo { public: foo(): x(...
2,581,485
2,583,659
Is there an alternative to libusb-win32 for 64bit windows?
I've been developing some software which uses the libusb-win32 library to interact with some USB hardware I've been developing. Now I'm trying to run the same software on windows 64 but the drivers don't seem to work (understandably). Are there any alternatives for 64 bit Windows I've overlooked?
Looks like there may be some 64-bit pre-compiled version available here and here. [Edit] Oops. Looks like this is already provided for in libusb-win32 in the latest release. 64bit and 32bit are both provided in the device driver package.
2,581,493
2,581,509
C++ Newbie: Passing an fstream to a function to read data
I have a text file named num.txt who's only contents is the line 123. Then I have the following: void alt_reader(ifstream &file, char* line){ file.read(line, 3); cout << "First Time: " << line << endl; } int main() { ifstream inFile; int num; inFile.open("num.txt"); alt_reader(inFile, (char*)&n...
The first time you printed the variable, you printed it as a char *, printing treating the file as a text file (And you're lucky you didn't crash). The second time you printed it, you reinterpreted it as an int, making the representation completely different. Whenever you cast pointers from one type to another type you...
2,581,578
2,581,602
If statement not effective
void spriteput(int x,int y, int stype) { char sprite1[5]="OOOO"; char sprite2[5]="OOOO"; char sprite3[5]="OOOO"; char sprite4[5]="OOOO"; if (stype == 1) { char sprite1[5] = " OO "; char sprite2[5] = "OOOO"; char sprite3[5] = "OOOO"; char sprite4[5] = " OO "; ...
Your declarations inside the if statement are shadowing the declarations outside it; once the if-statement exits, those shadowed declarations are out of scope and gone forever. To work around this, you could do something like if (stype == 1) { sprite1[0] = ' '; sprite1[3] = ' '; // ... Or you could use a f...
2,581,752
2,581,775
How do I compile for windows XP under windows 7 / visual studio 2008
I'm running Windows 7 and Visual Studio 2008 Pro and trying to get my application to work on Windows XP SP3. It's a really minimal command line program so should have any ridiculous dependencies: // XPBuild.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR*...
What you have missed is most likely that VC++ programs require a runtime to be installed (unless you link statically, which is not the default) - the error message you show is exactly the one you get if they're not in order. Try installing the Microsoft Visual C++ 2008 SP1 Redistributable Pack on the XP machine - you w...
2,581,761
2,581,766
How to read a file line by line to a string type variable?
I'm trying to read a file line by line to a string type variable using the following code: #include <iostream> #include <fstream> ifstream file(file_name); if (!file) { cout << "unable to open file"; exit(1); } string line; while (!file.eof()) { file.getline(line,256); cout<<line; } file.close(); i...
Use std::getline: std::string s; while (std::getline(file, s)) { // ... }
2,581,794
2,581,805
Skip lines in std::istream
I'm using std::getline() to read lines from an std::istream-derived class, how can I move forward a few lines? Do I have to just read and discard them?
Edit: You can also use std::istream::ignore, see https://stackoverflow.com/a/25012566/492336 Do I have to use getline the number of lines I want to skip? No, but it's probably going to be the clearest solution to those reading your code. If the number of lines you're skipping is large, you can improve performance by...
2,581,869
2,581,874
for_each but for setting each element to a value in C++
I have the following code to assign a value to all the elements of a vector: x = 100; for (int i=0;i<vect.size();i++) { vect[i] = x; } It's straightforward enough, but I'm wondering if there is a function in the STL that does the same thing; something like for_each, but for assignment.
Use std::fill: std::fill(vect.begin(), vect.end(), 100); Note if you want to initialize a vector to have all the same value, you can use the appropriate constructor: std::vector<int> v(5, 100); // 5 elements set to 100 assign can be used to "reset the vector", but if you're just making the vector, use the constructo...
2,581,898
2,581,919
PHP to C/C++ through CGI script
I realize it's probably something strange, but here is what I have. I have an application (handwriting recognition engine) written in C/C++. This application has Perl wrapper which was made by application's authors using SWIG. My website is written in PHP, so I'm looking for some ways to make PHP work with C/C++ applic...
Do you think it could be done this way? Yes, no reason it can't be done. Are there any better solutions? May be. If you intend to execute the perl wrapper as a system call to a separate Perl script, you don't need a separate CGI perl script. You can just do system calls from PHP in your site directly. Not a big dif...
2,581,993
2,582,015
What the reasons for/against returning 0 from main in ISO C++?
I know that the C++ standard says that return 0 is inserted at the end of main() if no return statement is given; however, I often see recently-written, standard-conforming C++ code that explicitly returns 0 at the end of main(). For what reasons would somebody want to explicitly return 0 if it's automatically done by ...
Because it just looks weird to not "return" something from a function having a non-void return type (even if the standard says it's not strictly necessary).
2,582,001
2,582,016
GDB not breaking on breakpoints set on object creation in C++
I've got a c++ app, with the following main.cpp: 1: #include <stdio.h> 2: #include "HeatMap.h" 3: #include <iostream> 4: 5: int main (int argc, char * const argv[]) 6: { 7: HeatMap heatMap(); 8: printf("message"); 9: return 0; 10: } Everything compiles without errors, I'm using gdb (GNU gdb 6.3.50-200508...
You need to instantiate HeatMap as: HeatMap heatMap; HeatMap heatMap(); declares a function that returns HeatMap.
2,582,032
2,582,087
Find max integer size that a floating point type can handle without loss of precision
Double has range more than a 64-bit integer, but its precision is less dues to its representation (since double is 64-bit as well, it can't fit more actual values). So, when representing larger integers, you start to lose precision in the integer part. #include <boost/cstdint.hpp> #include <limits> template<typename T...
Just a little predicate: #include <limits> template <typename T, typename U> struct can_fit { static const bool value = std::numeric_limits<T>::digits <= std::numeric_limits<U>::digits; }; #include <iostream> int main(void) { std::cout << std::boolalpha; std::cout << can_fit<...
2,582,103
2,582,318
Smoothing Small Data Set With Second Order Quadratic Curve
I'm doing some specific signal analysis, and I am in need of a method that would smooth out a given bell-shaped distribution curve. A running average approach isn't producing the results I desire. I want to keep the min/max, and general shape of my fitted curve intact, but resolve the inconsistencies in sampling. In sh...
A "quadratic" curve is one thing; "bell-shaped" usually means a Gaussian normal distribution. Getting a best-estimate Gaussian couldn't be easier: you compute the sample mean and variance and your smooth approximation is y = exp(-squared(x-mean)/variance) If, on the other hand, you want to approximate a smooth curve ...