question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,557,141
4,557,238
Static polymorphism definition and implementation
I have some questions about the concept of static polymporhism I somethimes hear about; you may interpret them primarily in the context of C++, but I'd appreciate language-agnostic answers where applicable (hence tagging both C++ and language-agnostic). How do we define static polymorphism in general? As an example, I...
Static polymorphic behavior is type polymorphism that occurs at compile time rather than run time. Yes. UML is about how classes interact at runtime -- I don't believe there's a UML format for describing templates, but I could be wrong. As far as I am aware it is C++ specific, but I'm not positive given that I've not ...
4,557,244
4,557,307
Hash table with two keys
I have a large amount of data the I want to be able to access in two different ways. I would like constant time look up based on either key, constant time insertion with one key, and constant time deletion with the other. Is there such a data structure and can I construct one using the data structures in tr1 and mayb...
Use two parallel hash-tables. Make sure that the keys are stored inside the element value, because you'll need all the keys during deletion.
4,557,264
4,557,865
COM port read - Thread remains alive after timeout occurs
I have a dll which includes a function called ReadPort that reads data from serial COM port, written in c/c++. This function is called within an extra thread from another WINAPI function using the _beginthreadex. When COM port has data to be read, the worker thread returns the data, ends normaly, the calling thread clo...
Don't use WaitCommEvent. You can call ReadFile even when there is no data waiting. Use SetCommTimeouts to make ReadFile itself timeout, instead of building a timeout on the inter-thread communications.
4,557,272
4,561,918
Copy QuickTime audio to another QuickTime movie
I'm trying to copy a section of audio from one QuickTime movie to another one but without success; the audio doesn't seem to be copied. C++ basic code: // Copy from another QT movie, *src, to this one soundTrack = NewMovieTrack(myMovie, 0, 0, kFullVolume); soundMedia = NewTrackMedia(soundTrack, SoundMediaType, ...
The code is good, I can get sound using it. I made some mistake in another part and ended up selecting the wrong source sequence for the sound. Sorry about that.
4,557,356
4,557,541
Tips on reducing c++ linking time
I have a project that takes about 8 seconds to link with g++ and ld. It uses a bunch of static libraries, most of the code is c++. I'm interested in a general list of tips on how to reduce link time. Anything from "dont include debug symbols" to "make your code less spagetti"
I dealt with this for years at a previous job. The GNU linker simply has serious performance problems when linking large numbers of static libraries. At one point, link time was on par with compile time, which we found so strange we actually investigated this and figured it out. You can try to merge your static librari...
4,557,723
4,557,732
C++ Template Iterator error
I am going over some code i wrote in 2006 as an undergrad. It's a simple genetic algorithm library written in C++ using templates. It use to work in 2006 when i coded it with visual studio, but now when i am trying to run it in xcode i get compile errors. This function is giving me errors: friend bool operator==(const ...
Use typename when declaring variables whose class is a member of a template-dependent type: typename vector<T>::iterator it_t1; A good description of the need for the typename keyword can be found at A Description of the C++ typename Keyword.
4,557,907
4,560,361
How to remember a previous image with OpenCV in a loop?
I have about 300 images which I want to process in a loop. In every iteration I want to compare an image with an image from the previous loop. I am trying to hold the current image in: fIplImageHeader The image from the previous iteration is stored in: lastFIplImageHeader This is how I am doing it and it is giving...
I suggest you load the first image outside the loop and iterate from i=1. You did not show how (if at all) you initialized lastFIplImageHeader and fIplImageHeader outside the loop. In the line if ( NULL != lastFIplImageHeader->imageData ) there is no test that lastFIplImageHeader itself is not null. I suggest you add ...
4,557,929
4,648,110
JGroups equivalent library in C++
at work we have been using JGroups and I have to say that I really like it, however, at home I primarily build with C/C++. I'm wondering if anyone knows of any good/solid ports of JGroups to C++ or any other equivalent software library for C++. I'm interested in hearing pros/cons of various libraries out there. Though ...
I don't know of any ports of JGroups to C++. Some folks run JGroups as a daemon and then talk to it from other languages via a protocol. I recently created a STOMP protocol, which allows for messages sent by clients written in different languages to be processed by JGroups, and for those clients to receive messages as ...
4,558,471
4,561,673
How to control master volume in linux/c++?
Specifically, I'm using Fedora 13 but I believe the code would be similar across any Gnome-ish flavor of Linux. I just need to be able to adjust the master volume using C++, and accomplish the exact same effect as if I had moved the slider up and down on the speaker icon in the "system tray." What's the best and easi...
You just have to use the Alsa library. Or you could cheat and subprocess the amixer program.
4,558,473
4,575,861
Compacting garbage collector implementation in C++0x
I'm implementing a compacting garbage collector for my own personal use in C++0x, and I've got a question. Obviously the mechanics of the collector depend upon moving objects, and I've been wondering how to implement this in terms of the smart pointer types that point to it. I've been thinking about either pointer-to-p...
This is a pretty straight-forward question so here's a straight-forward answer: Mark-and-sweep (and occasionally mark-and-compact to avoid heap fragmentation) is the fastest when it comes to allocation and access (avoiding double de-refs). It's also very easy to implement. Since you're not worried about collection per...
4,558,587
4,558,691
I am getting the below mentioned error in my program. what will be the solution?
// Finaldesktop.cpp : Defines the entry point for the console application. // #include <iostream> #include <string> #include <vector> #include <windows.h> #include <conio.h> using namespace std; int SearchDirectory(vector<string> &refvecFiles, const string &refcstrRootDirectory, ...
Without seeing the code I can tell you one way to cause this would be to do something like this: WCHAR wstr[260]; std::string temp; temp + wstr; You'll get lots of errors including the one above that you mentioned. However the problem in this case is that the binary operator for addition has no way to convert the WCH...
4,558,606
24,992,596
C++ non-iterator based range library?
I've been frustrated by the unhandiness of stl iterators and am looking for something more usable. In particular, a concept that is easier to map and filter, and one that is easier to implement too: basically C#/python/ruby/everything-but-C++ style enumerations. I came across Andrei Alexandrescu's Iterator's must go! ...
It's been a few years, but it looks like there's a library out there that implements proper functional style sequences now: C++ Streams. Code sample from the project's homepage: Summing the first 10 squares: int total = stream::MakeStream::counter(1) .map([] (int x) { return x * x; }) .limit(10) .sum();
4,558,787
4,558,801
Resolving C++ Name Collision
InitializeQTML is a function in QTML.h. I'm writing a wrapper and I would like to use the name InitializeQTML for the wrapper function: #include <QTML.h> public class QuickTime { public: static void InitializeQTML(InitializationFlags flag) { InitializeQTML((long)flag)); }; }; How can I reference...
You can qualify the name. If the QTML library's InitializeQTML function is in the global namespace, you can use this in your QuickTime::InitializeQTML static member function to refer to it: ::InitializeQTML((long)flag); ^ look in the global namespace
4,559,078
4,559,231
Qt: How to use Leptonica?
I need to write a program which will deskew scanned images. I've chosen Qt due to easy UI creation. I've tried to create deskew algorithm by myself, but then found interesting and well-known (to others) "Leptonica". And i have 2 problems (googling dont help): How i can include Leptonica lib to my Qt project? I can't ...
To use Leptonica from C++, simply call it like you would in C. You can use the existing Leptonica samples as a starting point for calling the routines. You will want to look at ...\leptonlib-1.xx\prog\skewtest.c for a pretty complete example of how the skew routines are used. In fact, you could probably just compile th...
4,559,137
4,559,186
Help Me Understand C++ Header files and Classes
OK, So I am trying to transition from intermediate Delphi to C++ Object Oriented programing. I have read Ivar Horton's book on visual C++ 2010. I can pull off the simple console applications no problem. I get the language itself (kinda). Where I am struggling is with headers and classes. I also understand what header ...
I also understand what header files and classes do in general. What I am not getting is the implementation when do I use a header or a class? Do I need to create classes for everything I do? Do my actual work functions need to be in header files or in CPP files? I'm lost on the proper uses of these and...
4,559,219
4,562,584
Refactor Decision: Message Queue Library, synchronize callers or offload create dedicated read/write threads in library
I'm refactoring a project that I did not design. It is written in C/C++ for linux. The project has a major client component that looks like this: Client -> Output Queuing Library (OQL) -> Controller Client Messy semi-complex code, poorly designed (hodgepodge of OOP approximations using singletons/namespaces, just weir...
You could change the Controller to use a second thread to do the reading from the message queue (and just post the data to a much larger buffer, internal to the Controller, to be read by the main Controller thread).
4,559,319
4,559,389
How do you declare an allocator?
I'm trying to recreate the inbuilt vector class in cpp to get a bit more practice with classes and memory management. I keep getting an error that says 'ISO C++ forbids declaration of ‘allocator’ with no type' and I can't figure out why for the life of me. Is there something I'm missing? #include <cstddef> #include <me...
It should be, std::allocator<T> alloc;, everything in the standard library is contained within the namespace std.
4,559,397
4,562,808
clock_t does not work on Linux?
This is what I have been using in WIndows: #include <ctime> #include <iostream> int main( void ) { using namespace std; clock_t lastT; lastT = clock(); cin.get(); cin.get(); return 0; } In Linux I get the error: 'clock_t' was not declared in this scope Is there some other data type for this...
Ok. I have solved it by using: int lastT; instead. The rest works the same way.
4,559,608
4,559,624
Should I make OR operator to return const reference or just reference
class error_code { public: error_code() : hi(0), lo(0) {} error_code(__int64 lo) : hi(0), lo(lo) {} error_code(__int64 hi, __int64 lo) : hi(hi), lo(lo) {} error_code& operator|=(const error_code &e) { this->hi |= e.hi; this->lo |= e.lo; return *this; } __int64 hi; __int64 lo; }; error_code operator|(con...
It should return non-const error_code&. Generally, an overloaded operation/equals operator should mirror integral type semantics and return a non-const reference. The OR-equals operation is modifying the object, so it doesn't really make sense to return a const reference. Returning a non-const reference also allows ...
4,559,648
4,559,932
Write to memory buffer instead of file with libjpeg?
I have found this function which uses libjpeg to write to a file: int write_jpeg_file( char *filename ) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; /* this is a pointer to one row of image data */ JSAMPROW row_pointer[1]; FILE *outfile = fopen( filename, "wb" ); if ( !outf...
You can define your own destination manager quite easily. The jpeg_compress_struct contains a pointer to a jpeg_destination_mgr, which contains a pointer to a buffer, a count of space left in the buffer, and 3 pointers to functions: init_destination (j_compress_ptr cinfo) empty_output_buffer (j_compress_ptr cinfo) ter...
4,559,707
4,559,891
What are the differences in the meaning of "static" in C++ and Objective C?
Objective-C and C++ belong to the C family, so in terms of "static", there are static variables, static functions, static classes etc. Static has static storage, lifecycle, scope. Here is the question: What are the big differences in the meaning of "static" in C++ and Objective C?
static has the exact same meaning in Objective-C that it would have in C. It does not mean the same thing as in C++. In C++, static is additionally used to declare and define class methods (methods which can only be called on the class itself) and variables, but Objective-C distinguishes class and instance methods with...
4,559,945
4,559,960
Linking errors when compiling code with OpenCV Libraries
I'm trying to compile a sample program after installing Opencv with the command: g++ hello-world.cpp -o hello-world -I /usr/local/include/opencv -L /usr/local/lib -lm -lcv -lhighgui -lcvaux however, I'm getting an error that says: /usr/bin/ld: cannot find -lcv /usr/bin/ld: cannot find -lhighgui /uer/bin/ld: cannot...
You need to add another -L argument specifying the actual location of the OpenCV libraries.
4,560,174
4,560,392
what SDL and OpenGL version and implementation I'm using
I downloaded SDL 1.2.14 on Windows 7 and I have Mobility Radeon X1800 driver installed. I'm using Microsoft Visual C++ 2010 Express. I added the SDL include and library directories in the "VC++ Directories" I added the following Additional Dependencies: opengl32.lib; glu32.lib; SDL.lib; SDLmain.lib; I added the...
call glGetString Here is Microsoft's documentation for glGetString. It just repeats the SGI doc and tells you the function is found in gl.h and opengl32.lib.
4,560,246
4,560,488
Going through members of a C++ class
As far as I know, if I have a class such as the following: class TileSurface{ public: Tile * tile; enum Type{ Top, Left, Right }; Type type; Point2D screenverts[4]; // it's a rectangle.. so.. TileSurface(Tile * thetile, Type thetype); }; There's no easy...
No. There are no easy way. If to put "easy way" aside then with C++ you can do anything imaginable. If you want just to dump your data contents run-time then simplest way is to implement operator<<(ostream&,YourClass const&) for each YourClass you are interested in. Bit more complex is to implement visitor pattern, but...
4,560,372
4,561,806
how boost::~shared_ptr works?
when reading "Beyond the C++ Standard Library: An Introduction to Boost " ,I got a very interesting example: class A { public: virtual void sing()=0; protected: virtual ~A() {}; }; class B : public A { public: virtual void sing( ) { std::cout << "Do re mi fa so la"<<std::end...
Surprisingly, the key here is not boost::shared_ptr destructor but its constructor(s). If you look into boost/shared_ptr.hpp, you will see that shared_ptr<T> does not 'simply' have a constructor expecting a T * but : template<class Y> explicit shared_ptr( Y * p ); In //3 when you construct a boost::shared_ptr from a B...
4,560,423
4,560,502
String Table Resource in Native Executable
Using C#, can I modify the string table resource of a native windows executable?
As far as I know, there's no support for doing that in the .NET Framework. You'll probably have to p/invoke BeginUpdateResource(), UpdateResource() and EndUpdateResource() from your code. You can find an example of modifying resources in unmanaged code here. Although it involves dialog boxes instead of string tables, i...
4,560,673
4,560,737
Using TagLib (C++ Library) in Objective-C Mac App
I'm looking to use TagLib, a C++ library for getting tagging information from a variety of audio files, in a new Objective-C project. Does anyone have experience using a C++ library such as this in an Objective-C project? What kind of roadblocks should I expect? Can anyone point me a good tutorials or guides for this ...
It is very easy to mix Objective-C and C++; there is practically no problem. Read this documentation at Apple. As described there, there is something called Objective-C++, which allows you to mix C++ and Objective-C++ in the same file. In XCode, just use a file extension .mm to use Objective-C++. It does not attempt t...
4,560,797
4,560,817
Why is the size of a class object different based on order of members?
class CHaraICICCC { int i; char c1; int j; char c2; char c3; char c4; }; class CHaraIICCCC { int i; int j; char c1; char c2; char c3; char c4; }; void fun() { CHaraICICCC eici; CHaraIICCCC eiicc; int icic = sizeof(eici); // -> output of icic is 16. int iicc = sizeof(eiicc); // -> output of icic is 12...
Because of alignment. x86 compilers tend to align int types on 4 bytes boundary (for faster memory access) so CHaraICICCC would probably be laid out as this: byte 0: \ byte 1: | <--- int i byte 2: | byte 3: / byte 4: <----- char c1 byte 5: \ byte 6: | <--- Padding (wasted bytes) byte 7: / byte 8: \ byte 9:...
4,560,808
4,561,096
Looking for a C++ database library that works with Visual Studio 2008/2010
I'm looking for a C++ libraries that can work with Visual Studio 2008/2010, but not MS-SQL. Since MySql is the first database application that I used, it would be much helpful if it also can work with MySql. I had a bad experience with setting up MySqlConnector in Visual Studio. It was such a nightmare, it was so diffi...
If MySQL is what you are familiar with, then perhaps you should use MySQL++. The FAQ section discusses using it on VC++. It seems to fit all your requirements except possibly "Easy to set up with Visual Studio" since that is entirely subjective, but download the code - compile the code - link the code seems fairly s...
4,560,931
4,564,898
C++ STL type_traits question
I was watching the latest C9 lecture and noticed something interesting.. In his introduction to type_traits, Stephan uses the following (as he says, contrived) example: template <typename T> void foo(T t, true_type) { std::cout << t << " is integral"; } template <typename T> void foo(T t, false_type) { std::cou...
The example below should illustrate the difference. Let's add struct X: struct X { X(int) { } }; and modify one foo as below: template <typename T> void foo(T t, true_type) { std::cout << t << " is integral"; X x(t); } template <typename T> void foo(T t, false_type) { std::cout << t << " is not integ...
4,560,981
4,561,001
preallocation and vector
In c++, for vector, why preallocation is so important even if vector alocates space dynamically
First, it's unlikely to be "so important" for 99% of cases. It's basically an optimization. Since vector doesn't have any idea how many elements you are going to add to it, it assumes a small default, and will have to grow if you try to add a new element and there is not enough space for a new element to be added. The...
4,561,140
4,561,152
Need to create http webserver using Qt 4.7 in C++
I need to create a http web server which responds to http clients using Qt 4.7 I have gone through the API and found few servers, but how to create a http server using the API Any hints and guidance on this please....i am totally new to this also what is .pro in Qt 4.7 and is it the same as doing in Visual studio
You should use QTcpServer , check this example.
4,561,210
4,561,509
Are these pointer conversions using static_cast ok?
Suppose we have the following code: #include <iostream> struct A { virtual void f() { std::cout << "A::f()" << std::endl; } }; struct B: A { void f() { std::cout << "B::f()" << std::endl; } }; void to_A(void* voidp) { A* aptr = static_cast<A*>(voidp); aptr->f(); } void to_B...
Your first code example invokes undefined behaviour. You can use a static_cast to reverse a standard conversion of pointer to object type to pointer to void but the result is only guaranteed if the value of the pointer to void being converted back to the original object type is the result of the standard conversion of ...
4,561,286
4,561,339
Nested templates in C++
I want to template one function for code reuse and specialization. The function signature is something along the lines int DoStuff(FooBar &a); where FooBar is Foo<BarX>, that is, an instance of template that I cannot typedef beforehand. I tried to do template <class T> int DoStuff(Foo<T> &a); and template <class T> int...
The code you suggested: template <class T> int DoStuff(Foo<T> &a); should work. Note that as with templated structs/classes, the code for the function must be visible where the function is used (i.e., the code for the function must typically be in a header).
4,561,334
4,561,497
Random access and update of an stl::set
I'm using a stl::set to keep elements sorted as they are inserted. My question is about the random access. If I have a complex class(difficult to init, for example), I found that is easy to insert, because I define the less operator into class. But if the key is the class itself, how do I need to access to the class? W...
I don't think it is possible : as you already noticed, the std::set<>::find member function expects a const key_type & (which, in a std::set is identical to value_type). If you object is expensive to construct, chances are that you should better use a std::map (which also is a sorted container), possibly with values be...
4,561,605
4,561,647
accessing members of boost:: tuple
I am trying to implement a vector like vector< boost::tuple<int,int,int> >day; I want to acess tuple's first element to check a condition. can someone please tell me how to do it? I am new to boost. Thanks in advance.
#include <boost/tuple/tuple.hpp> #include <iostream> #include <vector> int main() { std::vector< boost::tuple<int, int, int> > v; v.push_back(boost::make_tuple(1, 2, 3)); std::cout << boost::get<0>(v[0]) << std::endl; std::cout << boost::get<1>(v[0]) << std::endl; std::cout << boost::get<2>(v[0]) <...
4,561,641
4,561,677
Is there a way to detect what application receives focus?
Is there a way to detect what application receives focus and so is currently using from user ? For instance, I can know when a user is using Firefox, notepad, vlc, ecc. The intent is to tie it into a timetracking tool so that I can keep track of how much time the user spend being unproductive.
http://msdn.microsoft.com/en-us/library/ms633505(v=vs.85).aspx this is what you're looking for. BTW, I'm making the same thing. There are several existing solutions for this though, but they just don't meet some of my specific demands. Check this out, maybe you don't need to make it, if you find what you need http://en...
4,561,699
4,816,479
Single-Reader-Single-Writer Queue for Win32
Hallo, I am looking for a Single-Reader-Single-Writer queue for Win32. Best regards, Friedrich
Waitfree single-producer/single-consumer linked-list-based queue: http://www.1024cores.net/home/lock-free-algorithms/queues/unbounded-spsc-queue
4,561,878
4,561,927
Why can't I pass template parameters on to another template?
Okay I'm going to give a simple example of my problem: void Increment(Tuple<int, int>& tuple) { ++tuple.Get<0>(); } int main() { Tuple<int, int> tuple; tuple.Get<0>() = 8; Increment(tuple); printf("%i\n", tuple.Get<0>()); // prints 9, as expected return 0; } This compiles just fine, and ...
It should be: ++tuple.template Get<0>(); In the same way you need typename to specify a type qualified from a dependent type, you need template to specify a template function qualified from a dependent type.
4,562,135
4,562,250
how to get error line number in C++ program
I want to handle errors in my c++ program, so I created some exception classes to manage those errors, but I want to specify at which line in my program the error occurred. I passed LINE macro to the constructor of my exception class. For example: void f(int i){ // LINE A if(i<0) throw(OutOfRange("message", __LIN...
You are looking for a stack trace and there's no portable way to get it. Something somewhat similar can be achieved with: struct SourcePoint { const char *filename; int line; SourcePoint(const char *filename, int line) : filename(filename), line(line) { } }; std::vector<SourcePoint> callstack; s...
4,562,420
4,563,300
Combining std::string and std::vector<char>
This is not the actual code, but this represents my problem. std::string str1 = "head"; char *buffer = "body\0body"; // Original code has nullbytes; std::string str2 = "foot"; std::vector<char> mainStr(buffer, buffer + strlen(buffer)); I want to put str1 and str2 to mainStr in an order: headbody\0bodyfoot So the bin...
You cannot use strlen as it uses '\0' to determine the end of string. However, the following will do what you are looking for: std::string head = "header"; std::string foot = "footer"; const char body[] = "body\0body"; std::vector<char> v; v.assign(head.begin(), head.end()); std::copy(body, body + sizeof(body)/sizeof...
4,562,485
4,563,708
GDB breakpoints stop working after asio socket->connect call
I am using Eclipse + Mingw + Boost on Windows. The problem I have appears when the debugger gets to this code fragment in Eclipse: int YarpInterface::connect_to_port(std::string ip, std::string port, tcp::socket* socket) { boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::reso...
The issue seems to be resolved for the time being. Useful tips for other poor souls debugging with gdb in Eclipse under Windows: 1) Be VERY careful about (Watch) Expressions. It seems that gdb tries to interpret these on every step. Provide wrong values here and you'll have a very unstable debugging experience. 2) Be c...
4,562,678
4,562,719
C++ virtual + protected?
In C++, I have a base class A, a sub class B. Both have the virtual method Visit. I would like to redefine 'Visit' in B, but B need to access the 'Visit' function of each A (and all subclass to). I have something like that, but it tell me that B cannot access the protected member of A! But B is a A too :-P So, what can...
It is corrected in the "example". Now B is subclass of A.
4,562,750
4,562,771
std::map iterator output order will be constant if map keys/values don't change?
is the output order of a map::iterator guaranteed if I don't change the keys/values in that map? E.g., I initialize a map with some keys/values then do a sequence of loops and in each loop iterate over the map and perform read-only actions, will the output of each iteration be equal? for(i=0;i<5;i++) for(it=map.begin(...
std::map is an ordered collection. Iterating from begin() to end() will always return map entries in order. The order is determined by the comparison operator of the map which is std::less<Key> by default. In a word: yes.
4,563,094
4,563,146
Managing a log stream in C++ in a cout-like notation
I have a class in c++ in order to write log files for an application of mine. I have already built the class and it works, it is something like this: class Logger { std::string _filename; public: void print(std::string tobeprinted); } Well, it is intuitive that, in order to print a line in the log file, for an ...
Yes, this is the right way. But you'll have to add << operator overloads for every data type that you need to log.
4,563,126
4,563,136
error: expected ')' before '<' token|
I was implementing a String and was giving the definition in .h file. The code in String.h is the following: #include<list> class String { public: String();//Constructor String(char * copy);//For converting CString to String const char *c_str(const String &copy);//For converting String to Cstring St...
You are missing a std:: in front of list<char> : String(std::list<char> &copy);
4,563,340
4,565,181
What are the differences between g++ version 4.0.0.8 and 4.3.2?
What's the difference between g++ 4.0.0.8 and g++ 4.3.2? These two are the most common C++ compilers that I have seen used in various programming competitions. I tried to google it, but found nothing.
It's really not such a 'huge list', considering you're interested in the C++ changes between the two. 4.0.0.8 is just a patch revision of 4.0, whose release notes are here: http://gcc.gnu.org/gcc-4.0/changes.html 4.3.2 is a patch revision of 4.3, whose release notes are here: http://gcc.gnu.org/gcc-4.3/changes.html If ...
4,563,356
4,563,397
Did `#pragma once` make it into C++0x?
The title says it all. Have #pragma once been standardized for C++0x? I don't know any compiler that doesn't provide an implementation of it, with almost always the same semantics and name.
All #pragma directives cause the implementation to behave in an implementation defined way. This hasn't changed between C++03 and the latest C++0x draft (n3225.pdf). Include guards are the portable alternative.
4,563,421
4,563,449
/dev/dsp windows alternative
in Linux playing or recording some audio is just read or write /dev/dsp But how to do the same in windows ? (with C)
There is no static device name, you should use waveOut* functions, here is a nice example of using those APIs.
4,563,617
4,563,663
How to terminate a program with Ctrl-D?
I am trying to write a simple program that simulates a calculator. I would like the program to exit or turn-off when the Ctrl+D keystroke is made. I searched through stackoverflow and saw other examples of Ctrl+C or Ctrl+A but the examples are in java and C. for C: (scanf("%lf", &var); for java, a SIGINT is raised whe...
Ctrl+D will cause the stdin file descriptor to return end-of-file. Any input-reading function will reflect this, and you can then exit the program when you reach end-of-file. By the way, the C example should work verbatim in C++, though it may not be the most idiomatic C++. Is this homework, by the way? If so, please ...
4,563,693
4,563,803
OpenGL voxel engine slow
I'm making a voxel engine in C++ and OpenGL (à la Minecraft) and can't get decent fps on my 3GHz with ATI X1600... I'm all out of ideas. When I have about 12000 cubes on the screen it falls to under 20fps - pathetic. So far the optimizations I have are: frustum culling, back face culling (via OpenGL's glEnable(GL_CULL_...
You should profile your code to find out if the bottleneck in your application is on the CPU or GPU. For instance it might be that your culling/octtree algorithms are slow and in that case it is not an OpenGL-problem at all. I would also keep count of the number of cubes you draw on each frame and display that on scre...
4,563,700
4,563,747
Is 0x000001, 0x000002, etc. ever a valid memory address in application level programming?
Or are those things are reserved for the operation system and things like that? Thanks.
While it's unlikely that 0x00000001, etc. will be valid pointers (especially if you use odd numbers on many processors) using a pointer to store an integer value will be highly system dependent. Are you really that strapped for space? Edit: You could make it portable like this: char *base = malloc(NUM_MAGIC_VALUES); #d...
4,564,101
4,637,491
Anything like Watin available for C++?
I'm wondering if there are any projects like Watin available for C++ (on Windows), or if I just have to use QtWebkit. Does anyone know of any good IE automation libraries that work well in C++ and provide a nice layer above MS's WebBrowser control? Thanks.
You could try using Mozilla's Gecko/FireFox engine in C++. https://developer.mozilla.org/en/Embedding_Mozilla
4,564,267
4,565,880
c++ how to copy range from vector using two iterators
I have this example code that doesn't compile: #include <iostream> #include <vector> using std::endl; using std::cin; using std::cout; using std::vector; int main() { vector<int> vi, seg; vi.push_back(3); vi.push_back(4); vi.push_back(5); vi.push_back(6); vi.push_back(7); vector<int>::con...
int main() { vector<int> vi; vi.push_back(3); vi.push_back(4); vi.push_back(5); vi.push_back(6); vi.push_back(7); //the end of the sequence vector<int>::iterator seq_end = vi.begin() + 1; while (seq_end != vi.end()) { cout << "......" ; for (vector<int>::itera...
4,564,273
4,564,302
C++ -- Which one is supposed to use "new Car" or "new Car()"?
Possible Duplicate: Do the parentheses after the type name make a difference with new? Hello all, class Car { public: Car() : m_iPrice(0) {} Car(int iPrice) : m_iPrice(iPrice) {} private: int m_iPrice; }; int _tmain(int argc, _TCHAR* argv[]) { Car car1; // Line 1 Car car2(); // Line 2, th...
In this case the lines are equivalent; there's no difference in operation. However, please be careful - this does not mean that such lines are ALWAYS equialent. If your data type is a POD (i.e. a simple struct: struct Foo { int a; float b; }; Then new Foo produces a uninitialized object, and new Foo() calls a ...
4,564,322
4,564,375
Some good example for using enums
I learned enums when I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is due to the fact I never use it in my programming,my programming interest concentrate around algorithmic problem solving so I am not sure where could...
Imagine that you are programming a depth first search and you want to tag your edges with whether they are tree, back, forward, or cross. You could create an enum EDGE_TYPE with the four possibilities and use it to tag your edges.
4,564,713
4,564,750
How can I avoid threading + optimizer == infinite loop?
In a code review today, I stumbled across the following bit of code (slightly modified for posting): while (!initialized) { // The thread can start before the constructor has finished initializing the object. // Can lead to strange behavior. continue; } This is the first few lines of code that runs in a new thr...
Calling a function won't help at all; even if a function is not declared inline, its body can still be inlined (barring something extreme, like putting your isInitialized() function in another library and dynamically linking against it). Two options that come to mind: Declare initialized as an atomic flag (in C++0x, y...
4,564,792
4,564,893
getline in istream and getline in basic_string
string text; getline(text.c_str(),256); 1) I am getting an error "error: no matching function for call to 'getline(const char*, int)" What's wrong in the above since text.c_str() also returns a pointer to array of characters. If I write like this char text[256] cin.getline(text, 256 ,'\n'); it works fine. What's th...
text.c_str() returns a const char *. You may not use it to modify the contents of the string, in any way. It only exists so that you can pass the string data to old C API functions without having to make a copy. You are not allowed to make changes because there is no way that the string object that holds the data could...
4,564,850
4,564,877
strlen was not declared in this scope - C++
I need to install a simulator in my ubuntu. It is written in C++ and when I try to run make, I get this error strlen was not declared in this scope. Any solution to overcome this error?
This should do it : #include <cstring>
4,565,272
4,565,290
Why use div or ldiv in C/C++?
Is there a specific reason to use ldiv or div instead of '/' or '%' to divide/modulus two variables?
Yes. C99 §7.20.6.2/2 says: The div, ldiv, and lldiv, functions compute numer / denom and numer % denom in a single operation.
4,565,364
4,565,807
removing first line of a file and inserting it back in the output
I've a csv file and I read the file as follows: #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <numeric> using namespace std; typedef vector <double> record_t; typedef vector <record_t> data_t; data_t data; istream& operator >> ( istream& in...
What about read the first line first, and then put the stream buffer into this function? It seems like you don't want to change the function. ifstream infile( "2010.csv" ); string header; std::getline(infile, header); infile >> data;
4,565,532
4,565,586
I can't go to a directory with C++
I need to change working directory of my project, so that output files go to a certain folder, not where all the project files are. I'm using system("cd secretdir/"); system("ls"); However, what I get, is the list of files in current project directory, not the "secretdir" one. I'm on Mac OS X 10.6/Qt Creator 4.7 64 b...
Your current code will spawn a subshell that will change its current directory to ./secretdir, then proceed to exit() without doing anything else. Only then will ls run in another subshell, whose current directory is, of course, completely independent of what you did during your previous call to system(). That's probab...
4,565,689
4,566,216
how open in eclipse ".pro File Editor"
i'm need in eclipse the qt and openCV library. i'm found the tutorial http://www.welding.iat.uni-bremen.de/cms/index.php?view=article&catid=14%3Aimage-processing&id=14%3Aa-tutorial-on-integrating-eclipse-qt-and-opencv&format=pdf&option=com_content&Itemid=24 where writen last step " We make sure that the Advance Mode ...
If I understand correctly: Right click on .pro file and go to 'Qt Project Editor', if it is not there then you can use the text editor option (or something is wrong with your Eclipse Qt installation).
4,565,739
4,565,812
CString error, 'CString': is not a member of 'ATL::CStringT<BaseType, StringTraits>'
I am trying to do this: #include <atlstr.h> CHAR Filename; // [sp+26Ch] [bp-110h]@1 char v31; // [sp+36Ch] [bp-10h]@1 int v32; // [sp+378h] [bp-4h]@1 GetModuleFileNameA(0, &Filename, 0x100u); CString::CString(&v31, &Filename); But I am getting the compiler error C2039:'CString': is not a member of 'ATL::CStringT' ...
That's not how constructors are invoked in C++. CString s = CString(&v21,&File); Note that GetModuleFilename expects a pointer to an array of characters (which it fills), not a pointer to a single character. Your code is therefore doomed to crash at runtime.
4,566,030
4,566,049
Small doubt in for-loops
How many times 'x' value will be tested in the following code snippet ? int x; for(x=0;x < 10; x++) printf("%d",x); To me it seems that the answer is 11 but my module says it is 10 ?! what am I missing?
Eleven, as the condition is tested at the beginning of each loop iteration, before printf is called: 0 < 10 == true 1 < 10 == true 2 < 10 == true 3 < 10 == true 4 < 10 == true 5 < 10 == true 6 < 10 == true 7 < 10 == true 8 < 10 == true 9 < 10 == true 10 < 10 == false // exit from loop (printf not executed)
4,566,210
4,567,010
Converting integers with different capacity
I have the following code: // ---- third party library code ---- struct Point { int16_t x, y; }; void third_party_library__getPoint(Point*); void third_party_library__setPoint(const Point*); // ---- my library code ---- void move_point(int dx, int dy) { Point pt; third_party_library__getPoint(&pt); pt.x +=...
For me there are 3 related but different points here: A. Deal with the overflow In fact, there are two parts here: conversion overflow and addition overflow. Even if you take int16_t as the input, there could still be an overflow at the += stage, and you have to decide what to do with it (of course you can simply ignor...
4,566,480
4,566,505
What does "statically typed" and "free-form" mean for C++?
In the C++ tag wiki, it is mentioned that C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. Can someone please explain the terms "statically typed" and "free-form"? Thanks.
A statically-typed language is a language where every variable has a type assigned to it at compile-time. In C++, this means that you must tell the compiler the type of each variable - that is, whether it's an int, or a double, or a string, etc. This contrasts with dynamically-typed languages like JavaScript or PHP, ...
4,566,722
4,566,742
Is construction of static function-scope object thread-safe?
Suppose I have a function that tries to protect a global counter using this code: static MyCriticalSectionWrapper lock; lock.Enter(); counter = ++m_counter; lock.Leave(); IS there a chance that two threads will invoke the lock's constructor? What is the safe way to achieve this goal?
The creation of the lock object itself is not thread safe. Depending on the compiler, you might have multiple independent lock objects created if multiple threads enter the function at (nearly) the same time. The solution to this problem is to use: OS guaranteed one time intialization (for the lock object) Double-chec...
4,566,747
4,567,025
performance of Intel TBB memory allocator?
once I tried TBB memory allocator in the project I was working on (MMORPG cluster, linux 2.6, recent gcc, 8 cores Intel Xeon) and was surprised when received worse performance. what can be a reason? I expected at least not better performance (all cores were loaded and allocation happens regularly). can anybody share ow...
You can probably get the best answers at TBBs forums, they have excellent support. I have been using TBB for a little over a year and I have been quite satisfied with TBB in general and its allocator. You will need to provide more information, e.g. use case, numbers etc... otherwise it is impossible to tell what is ca...
4,566,833
4,566,869
Is it possible to avoid C++ compiler error (C2757) where 2 different header files contain same symbol for namespace & class?
I am facing a problem when implementing some new code to an existing library. This library already references a class with a name say 'foo'. The same name is used as a namespace in the other header file which has to be included to implement the new functionality. Since both the header files are a part of legacy code li...
You can try the following workaround: namespace bar { #include "HeaderA.h" } #include "HeaderB.h" ... bar::foo fooObject; foo::ABC abcObject;
4,567,096
4,567,156
how to mix two audio channels?
I have two mono audio channels (pcm format) of audio call, incoming and outgoing. how to mix them? how to position them in space? (e.g. incoming channel sounds slightly on the left and outgoing on the right)
Mixing is just a weighted addition of both signals. So if you want them to be equal in one mono signal, lower both signals by a factor of 2 and add them. If you want to position them in the stereo space, use different weighting on the left and right channel. For example 0.6 of signal 1 and 0.4 of signal 2 on the left c...
4,567,226
4,567,399
Examples of implementetional composite pattern for graphic primitives
Can you tell me where I can see some examples (articles, opensource projects) of implementetional composite pattern on C++ (desirable full source code), on an example of problem: graphic primitives - rectangle, ellipse, arc and etc. This primitives may be to unite in one object.
Maybe this one: http://sourcemaking.com/design_patterns/composite/cpp/2
4,567,232
4,567,277
Win32 asynchronous sockets basic question
I've done a client-server voice chat (like ventrilo) in C# and am now doing it in unmanaged win32 c++. I've got a question about how asynchronous reads/writes are handled in c++. In C#, you had a function that got called (EndSend/EndRecieve) once BeginSend/BeginRecieve were done. How is this done in c++? I've looked at...
and if you don't want to deal with Asio, here's good tutorial about asynchronous sockets: http://www.gamedev.net/reference/programming/features/asyncsock/
4,567,321
4,567,357
How can i get HWND of external application's listview? In Windows Api using c++
So i am trying to make app to get content of my explorer listviews and get item text etc.. from it but here are the problems... If i inspect windows explorer folder(using spy++) with listview, just for testing purposes i will use random folder. It shows me that caption of the window is "FolderView" with class "SysList...
If you got a handle to main window (using FindWindow for example), you can enumerate its child windows using EnumChildWindows.
4,567,394
4,567,414
Is there a way, or what is the 'accepted' way to get all the windows running under the current process?
From the process address space of another app how would you get a handle to each window that it is using/displaying? I know you can get a snapshot of all the current threads running within a process http://msdn.microsoft.com/en-us/library/ms686701(v=vs.85).aspx but I am wondering if there is a way, using the THREAD ID ...
You can use EnumThreadWindows to enumerate all nonchild windows associated with a thread, and then use EnumChildWindows to get all their child windows. Alternatively, you can use EnumWindows to get all top-level windows on the desktop, and use GetWindowThreadProcessId to filter to only those associated with the process...
4,567,535
4,567,562
Native CheckedListBox?
In .NET land, there's the tremendously useful System.Windows.Forms.CheckedListBox class. What is the equivalent in Windows Common Controls land? (if any)
Turn a list view into one with checkboxes. If you want it similar to a ListBox, only use 1 column. ListView_SetExtendedListViewStyle (handle, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT);
4,567,585
4,567,593
Get alternative filename in windows
I'm running my program on windows that will enumerate the files in a directory and pass it on to some other library that processes the files. While my program does support unicode, the library doesn't, so I have to convert the unicode file path and name to ANSI. That works just fine, as long as there are no unicode cha...
GetShortPathName() It should be noted that shortname generation can be turned off (fsutil)
4,567,767
4,567,815
How to get readable classname and title from HWND handle? in WinApi c++
I am using the following enumchild proc to get hwnd of each window, the problem is that i am unable to somehow detect any info from each hwnd so i can do what i want with the ones that are detected as the ones i need. For example, how could i get window class name and the title of each window in the enum bellow? I tri...
Isn't it Unicode build? Check again with below: TCHAR className[MAX_PATH]; GetClassName(hwnd, className, _countof(cName)); _tprintf(cName);
4,567,875
4,568,205
How would I load a PNG image using Win32/GDI (no GDI+ if possible)?
Is it possible to load a PNG from a file into an HBITMAP using Win32 GDI functions? If not, what would be the lightest solution without using external libraries (like libpng)?
You can use the Windows Imaging Component to load PNG files (on Windows XP SP2 and later). See MSDN Magazine for an introduction on how to use the API and my blog post for a code sample that loads a PNG from an IStream and converts it to an HBITMAP.
4,567,974
4,567,981
C++ -- What is the meaning of this statement?
I saw the following class definition and cannot figure out the meaning of the line 1. class Noisy { public: Noisy() throw(); ~Noisy() throw(); Noisy& operator= (const Noisy&) throw(); Noisy (const Noisy&) throw(); // Line 1 }; What is the meaning of this line and what is the usage of this line? Thank...
It isn't a statement. It is a declaration of a copy constructor that is specified as throwing no exceptions. You can find out more in your favorite good introductory C++ book.
4,567,976
4,567,991
C++ static member, a little confused here
//static member in classes #include <iostream> using namespace std; class CDummy { public: static int n; CDummy() {n++;}; ~CDummy(){n--;}; }; int CDummy::n =0; int main(){ CDummy a; CDummy b[5]; CDummy *c = new CDummy; cout << a.n << endl; delete c; cout << CDummy::n << endl; ...
CDummy b[5]; This declares an array of five CDummy objects. It ends up calling the CDummy default constructor five times (once for each object in the array). You create seven CDummy objects: a, five in the array b, and the one pointed to by c. n then has a value of 7. Then you destroy one CDummy object (the one po...
4,568,057
4,568,066
How would I draw a PNG image using LoadImage and StretchDIBits?
(This is related to the question on How would I load a PNG image using Win32/GDI (no GDI+ if possible)?.) Hi all, I was wondering, given that you have a PNG resource embedded in a binary file with the ID IDB_PNG1, and an LPDRAWITEMSTRUCT to draw into (so that means you have the HDC and the rectangle for your target), h...
I think the PNG support inside bitmaps is only really for use by printer drivers. For screen display, you will probably have to decompress the PNG data yourself using some code such as libpng.
4,568,093
4,568,190
want to find a good online Library Manual of C++
I am new to c++ from C. When I need to find something about c. I always type "man *" on google then I can get what I want. But how can I find nice c++ library documentation? Thanks..
If you just want a reference, try: http://cplusplus.com/reference/ http://www.cppreference.com/wiki/
4,568,187
4,568,206
Error loading shared libraries of boost
I am working on centos. I installed boost version 1.45.0 on my system. The programs are compiled correctly but whenever I type command to see output it gives following error: ./a.out: error while loading shared libraries: libboost_thread.so.1.45.0: cannot open shared object file: No such file or directory
How did you install the boost libraries? The problem you're likely having is that the linker can not find the libraries, and when you built your program, you had to manually specify additional library paths to search for libraries. A quick fix you can do is to set LD_LIBRARY_PATH to include the directory where the boo...
4,568,215
4,568,391
I'm using tcp for very many small sends, should I turn off Nagles algorithm? (People also know this as TCP_NODELAY)
I remade this post because my title choice was horrible, sorry about that. My new post can be found here: After sending a lot, my send() call causes my program to stall completely. How is this possible? Thank you very much everyone. The problem was that the clients are actually bots and they never read from the connect...
TCP_NODELAY might help latency of small packets from sender to receiver, but the description you gave points into different direction. I can imagine the following: Sending more data than receivers actually consume - this eventually overflows sender's buffer (SO_SNDBUF) and causes the server process to appear "stuck" i...
4,568,352
4,568,368
C++ Pointers to functions
using namespace std; int addition (int a, int b) { return (a+b); } int subtraction (int a, int b) { return (a-b); } int operation (int x, int y, int (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return(g); } int main() { int m,n; int (*minus)(int,int) = subtraction; m = ope...
"minus" is a name of a variable which is a pointer to a function taking two int arguments and returning another int. The function called "operation" takes 3 arguments: 2 ints and a pointer to a function which operates on 2 ints and return another one. When invoked, the operation function applies argument 3 to the arg...
4,568,364
4,569,375
Any tips on reducing wxWidgets application code size?
I have written a minimal wxWidgets application: stdafx.h #define wxNO_REGEX_LIB #define wxNO_XML_LIB #define wxNO_NET_LIB #define wxNO_EXPAT_LIB #define wxNO_JPEG_LIB #define wxNO_PNG_LIB #define wxNO_TIFF_LIB #define wxNO_ZLIB_LIB #define wxNO_ADV_LIB #define wxNO_HTML_LIB #define wxNO_GL_LIB #define wxNO_QA_LIB #defi...
You can additionally set MSVC to compile for small binary size (but this might impact performance of course) by using the flag /01. See here. Also remember that wxWidgets will need to be compiled as such for this to have any impact. And I think that 2.4 MB for a statically linked app is pretty decent IMHO... UPDATE: th...
4,568,374
4,568,416
Question about inserting assembly code in C++
I am working on VC++ compiler. I want to accomplish the following The variables s.AddrFrame.Offset and s.AddrStack.Offset contain the value of EBP and ESP respectively. Offset is a 64 bit unsigned integer. My machine is little-endian. typedef unsigned __int64 DWORD64; I want to extract the value of old EBP and the re...
You cannot use two memory operands for mov; one must be a register. So, in your case, you need to have two mov instructions: mov eax, [s.AddrFrame.Offset + 1] mov old_ebp, eax and analogously for ret_addr.
4,568,389
4,568,470
After sending a lot, my send() call causes my program to stall completely. How is this possible?
So basically I'm making an MMO server in C++ that runs on linux. It works fine at first, but after maybe 40 seconds with 50 clients it will completely pause. When I debug it I find that basically the last frame its on before it stops responding is syscall() at which point it disappears into the kernel. Once it disappea...
The kernel keeps a finite buffer for sending data. If the receiver isn't receiving, that buffer will fill up and the sender will block. Could that be the problem?
4,568,645
4,568,650
Printing 1 to 1000 without loop or conditionals
Task: Print numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times. How would you do that using C or C++?
Compile time recursion! :P #include <iostream> template<int N> struct NumberGeneration{ static void out(std::ostream& os) { NumberGeneration<N-1>::out(os); os << N << std::endl; } }; template<> struct NumberGeneration<1>{ static void out(std::ostream& os) { os << 1 << std::endl; } }; int main(){...
4,568,666
4,568,679
What are your techniques of optimizing your code in c++?
What are your techniques of optimizing your code in c++?
Write code Profile code Tweak performance hot spots If still not fast enough, go to step 2
4,568,677
4,568,773
Generic Container in C++
I'm attempting to create a generic container type to provide a single common interface, as well as hide the internal containers I'm using as they are subject to change. Basically I have plugins that return collections of items and I don't wish the plugins to be aware of the type of container my code is using. Can anyon...
I have plugins that return collections of items and I don't wish the plugins to be aware of the type of container my code is using. Have your plugins provide begin and end iterators into their collections of items and then consume the range as you see fit. The greatest advantage of iterators is that they allow comple...
4,568,789
4,569,724
Will Linux prevent the stack and heap from growing into each other?
all I write this cpp code to test the stack and head. And I find Linux doesn't prevent that event. (Linux devlinux11 2.6.9-78.ELsmp #1 SMP Wed Jul 9 15:39:47 EDT 2008 i686 i686 i386 GNU/Linux gcc version 3.4.6 20060404 (Red Hat 3.4.6-10)) And is there any way to prevent that event? #include <iostream> using name...
Your version of Linux is either outdated or unmaintained. That is fixed in a more recent release, because that introduced a security flaw in Xorg. If your distribution hasn't backported this patch, then your should stay away from it. see http://git.kernel.org/linus/320b2b8de12698082609ebbc1a17165727f4c893 for the patch...
4,568,973
4,569,014
Turning on whole program optimization in some static library increases dramatically the library size !
In Visual Studio 2010, I have a C/C++ static library project. When I turn on the option whole program optimization in release mode, I obtain a .lib file exceeding 90 MB ! When I turn off this option the size is reduced to 24 MB. This library contains hundreds of classes generated with proto-buffer. I'm wondering why th...
Whole program optimization means things are not optimized until the link stage. The size of a static library is not the thing to look at. When in this mode, the static library may be full of extra information needed for the final optimization/link stage. If you weren't doing whole program optimization then that informa...
4,569,517
4,569,539
Stack walk with inline asm for VC++
I have inserted the following asm code in my C++ code. I am using a VC++ compiler. char c; curr_stack_return_addr = s.AddrFrame.Offset; //I am doing a stack walk __asm{ push bx mov eax, curr_stack_return_addr mov bl, BYTE PTR [eax - 1] mov c,bl pop bx ...
I see two problems here: push bl and pop bl don't exist. You can only push and pop word or dwords. The compiler warns by the way. How do you know that eax points to a legal address?
4,569,591
4,569,639
Windows DLL on Linux System
I wonder if you can load a DLL, of Windows operating system (for example, user32.dll), in an application (in any programming language) with a Linux operating system. The DLL would be in a directory on the Linux file system. Thanks for the help. Greetings!
No. The architectures are fundamentally different. I note your question is tagged C++. If it was a .net DLL (built with CLR bytecode) then you could reference it via an application running under Mono.
4,569,730
4,569,777
Converting integer to a character pointer in c++ and then appending it to another chacter pointer
I have the following code for converting the integer(a score) into the character and then appending it with the player's name (player1). It gets displayed after that. It is a part of a bigger project : #include <iostream> #include <string.h> using namespace std; char* convertIntTochar(int number) { char t[3]; ...
char str11[] = "Player1: "; This is the problem. There is not enough room for string concatenation. Try this: char str11[100] = "Player1: "; Better yet, use std::string instead of C-like char*. Smallest possible changes that fix string problems are these (because there exist using namespace std then std:: part ...
4,569,756
4,569,944
Help with code optimization
I've written a little particle system for my 2d-application. Here is raining code: // HPP ----------------------------------- struct Data { float x, y, x_speed, y_speed; int timeout; Data(); }; std::vector<Data> mData; bool mFirstTime; void processDrops(float windPower, int i); // CPP -------------...
In loop introduce reference Data& current = mData[i] and use it instead of mData[i]. And use this reference instead of index also in procesDrops. BTW I think that consulting mFirstTime in processDrops serves no purpose because it will never be true. Hmm, I missed processDrops in initialization loop. Never mind this.
4,569,928
4,569,975
Why code using local struct as parameter for STL function does not compile in g++?
I have such code which works well: #include <algorithm> #include <iostream> char x[11]= "ABCDEFGHIJ"; char y[11]; struct F { char operator () (char c) const { return c+1; } }; int main() { std::transform(x, x+10, y, F()); y[10] = 0; std::cout <<y <<std::endl; } But if I change it to this style: #in...
In C++-98/03 the second code is not valid, since F is a local type; in facts, at §14.3.1.2 it's stated that A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter. [Example: template <class T> class X { ...
4,569,983
4,569,999
mouse click position in c++
Is there way to get mouse click postion (x & y) in c++ console application?
Assuming Windows: use ReadConsoleInput(). That gets you an array of INPUT_RECORD with keyboard and mouse events. Use GetStdHandle() to get the stdin handle you'll need to call this function.