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 |
|---|---|---|---|---|
142,602 | 142,683 | How to revive C++ skills | I was a C++ developer (mostly ATL/COM stuff) until, as many of us, I switched to C# in 2001. I didn't do much C++ programming since then.
Do you have any tips on how to revive my C++ skills? What has changed in C++ in the last years? Are there good books, articles or blogs covering the language. The problem is that mos... | I personally find that syntax is where i mostly need to catch up when i wander back to a language i havent used in a long time. But the concepts and what the language is about stays the same in memory.
Assuming its the same with you, i would say its a good idea to relook at the texts you remember to have been useful t... |
142,804 | 143,131 | Network Multithreading | I'm programming an online game for two reasons, one to familiarize myself with server/client requests in a realtime environment (as opposed to something like a typical web browser, which is not realtime) and to actually get my hands wet in that area, so I can proceed to actually properly design one.
Anywho, I'm doing t... | The easiest thing
for you to do, would be to simply invoke the windows API QueueUserWorkItem. All you have to specify is the function that the thread will execute and the input passed to it. A thread pool will be automatically created for you and the jobs executed in it. New threads will be created as and when is requ... |
142,877 | 142,921 | Can the C preprocessor be used to tell if a file exists? | I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore.
There are several places in the codebase where it would clean up the cod... | Generally this is done by using a script that tries running the preprocessor on an attempt at including the file. Depending on if the preprocessor returns an error, the script updates a generated .h file with an appropriate #define (or #undef). In bash, the script might look vaguely like this:
cat > .test.h <<'EOM'
#in... |
143,006 | 143,007 | Why does my MFC app hang when I throw an exception? | If you throw an exception from inside an MFC dialog, the app hangs, even if you have a catch block in your code. It refuses to respond to the mouse or keyboard, and the only way to shut it down is to use Task Manager.
Why I'm posting this question
To my shame, there is a popular shrink-wrapped application that hangs ... | The code for CDialog::DoModal makes the dialog modal by disabling the parent window. When the dialog code returns, the window is reenabled. There is an explicit catch for CException* errors, but not for any other kind of thrown exception; thus the parent window never gets reenabled.
Change your code to throw a pointe... |
143,073 | 206,081 | Debugging C++ STL containers in Windbg | Windbg fans claim that it is quite powerful and I tend to agree. But when it comes to debugging STL containers, I am always stuck. If the variable is on the stack, the !stl extension sometimes figures it out, but when a container with a complex type (e.g. std::vector<TemplateField, std::allocator<TemplateField> >) is o... | You might also want to give this debugger extension a try. It is a library called SDbgExt, developed by Skywing.
|
143,174 | 198,099 | How do I get the directory that a program is running from? | Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)
(If there's no platform/filesystem-agno... | Here's code to get the full path to the executing app:
Variable declarations:
char pBuf[256];
size_t len = sizeof(pBuf);
Windows:
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
Linux:
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
r... |
143,233 | 143,239 | How to redirect data to stdin within a single executable? | I am using cxxtest as the test framework for my C++ classes, and would like to figure out a way to simulate sending data to classes which would normally expect to receive it from standard input. I have several different files which I would like to send to the classes during different tests, so redirection from the com... | The appropriate method is to rewrite your classes so that they are testable. They should accept as a parameter the handle, stream or file from which they are supposed to read data - in your test framework, you can then mock in the stream or supply the path to the file containing the test data.
|
143,285 | 143,298 | How much memory do Enums take? | For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++
| In Java, an enum is a full-blown class:
Java programming language enum types
are much more powerful than their
counterparts in other languages. The
enum declaration defines a class
(called an enum type). The enum class
body can include methods and other
fields.
In order to see the actual size of each enum... |
143,788 | 143,806 | when to pass function arguments by reference and when by address? | Could anyone explain with some examples when it is better to call functions by reference and when it is better to call by address?
| Pass your arguments to function using reference whenever possible.
Passing arguments by reference eliminate the chance of them being NULL.
If you want it to be possible to pass NULL value to a function then use pointer.
|
143,808 | 145,386 | How to improve link performance for a large C++ application in VS2005 | We have fairly large C++ application which is composed of about 60 projects in Visual Studio 2005. It currently takes 7 minutes to link in Release mode and I would like to try to reduce the time. Are there any tips for improving the link time?
Most of the projects compile to static libraries, this makes testing easier ... | If you're using the /GL flag to enable Whole Program Optimization (WPO) or the /LTCG flag to enable Link Time Code Generation, turning them off will improve link times significantly, at the expense of some optimizations.
Also, if you're using the /Z7 flag to put debug symbols in the .obj files, your static libraries ar... |
143,850 | 143,853 | How does Multiple C++ Threads execute on a class method | let's say we have a c++ class like:
class MyClass
{
void processArray( <an array of 255 integers> )
{
int i ;
for (i=0;i<255;i++)
{
// do something with values in the array
}
}
}
and one instance of the class like:
MyClass myInstance ;
and 2 threads which call the processArray m... | i is allocated on the stack. Since each thread has its own separate stack, each thread gets its own copy of i.
|
144,285 | 144,336 | State of C++ Standard | I haven't kept up lately with the C++ world. Exactly where do things stand these days regarding the standard?
Is TR1 adopted?
Is there a TR2?
How do these relate to C++0x? Are the subsumed?
Has a decision been reached on threading yet?
| You can find an extensive article about the upcoming C++0x on wikipedia and the current state of C++ evolution here. It is also worth giving a look at the current GNU implementation in gcc
|
144,583 | 144,655 | Windows C++ dialog resizer class | I'm looking for a really good dialog resizer class that will stretch and shrink individual items as needed as the screen is resized. Stephan Keil has a good one (DlgResizeHelper) which basically resizes everything by a set ratio, but I'm looking for something smarter.
For example:
Icons should not resize
Single-line ... | You can use wxWidgets. It completely replaces MFC, is multi-platform, and gives you a layout-based dialog mechanism.
|
144,761 | 144,804 | How to remove accents and tilde in a C++ std::string | I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string clas... | First, this is a really bad idea: you’re mangling somebody’s language by removing letters. Although the extra dots in words like “naïve” seem superfluous to people who only speak English, there are literally thousands of writing systems in the world in which such distinctions are very important. Writing software to mut... |
145,096 | 145,098 | Is it true that there is no need to learn C because C++ contains everything? | I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this?
| Overview:
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++ doe... |
145,110 | 145,122 | C++ performance vs. Java/C# | My understanding is that C/C++ produces native code to run on a particular machine architecture. Conversely, languages like Java and C# run on top of a virtual machine which abstracts away the native architecture. Logically it would seem impossible for Java or C# to match the speed of C++ because of this intermediate... | Generally, C# and Java can be just as fast or faster because the JIT compiler -- a compiler that compiles your IL the first time it's executed -- can make optimizations that a C++ compiled program cannot because it can query the machine. It can determine if the machine is Intel or AMD; Pentium 4, Core Solo, or Core Duo... |
145,270 | 145,436 | Calling C/C++ from Python? | What would be the quickest way to construct a Python binding to a C or C++ library?
(I am using Windows if this matters.)
| You should have a look at Boost.Python. Here is the short introduction taken from their website:
The Boost Python Library is a framework for interfacing Python and
C++. It allows you to quickly and seamlessly expose C++ classes
functions and objects to Python, and vice-versa, using no special
tools -- just your ... |
145,563 | 145,576 | Finding Frequency of numbers in a given group of numbers | Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.
example:
int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
the output is 4 because 2 occurs 4 times. That is the maximum number... | Sort the array and then do a quick pass to count each number. The algorithm has O(N*logN) complexity.
Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorith... |
145,570 | 145,604 | Existing Standard Style and Coding standard documents | The following have been proposed for an upcoming C++ project.
C++ Coding Standards, by Sutter and Alexandrescu
JSF Air Vehicle C++ coding standards
The Elements of C++ Style
Effective C++ 3rd Edition, by Scott Meyers
Are there other choices? Or is the list above what be should used on a C++ project?
Some related lin... | I really think it does not matter which one you adopt, as long as everyone goes along with it. Sometimes that can be hard as it seems that some styles don't agree with peoples tases. I.e. it comes down to arguing about whether prefixing all member variable with m_ is pretty or not.
I have been using and modifying the G... |
145,586 | 145,763 | What continuous integration tool is best for a C++ project? | Cruisecontrol and Hudson are two popular continuous integration systems. Although both systems are able to do the automated continuous builds nicely, it just seems a lot easier to create a batch or bash build script, then use Windows scheduler or cron to schedule builds.
Are there better continuous integration systems... | We have been using CruiseControl for CI on a C++ project. While it is the only thing we use ant for, the ant build script for CruiseControl just starts our normal build script, so it is very simple and we haven't really needed to update it in a long while. Therefore the fact that CrusieControl is Java based has not rea... |
145,621 | 145,648 | What are some recommendations for porting C++ code to the MacOS? | For a upcoming project, there are plans to port the existing C++ code that compiles on Windows and Linux to the MacOS(leopard). The software is command line application, but a GUI front end might be planned. The MacOS uses the g++ compiler. By having the same compiler as Linux, it does not seem like there would be an... | Does your app have a GUI, and which one (native / Qt / Gtk+)?
If not, the issues to watch out for (compared to Linux) are mainly in the dynamic linkage area. OS X uses '-dylib' and '-bundle' and in fact has two kinds of dynamic libraries (runtime loadable and the normal ones). Linux has only one kind (-shared), and is ... |
145,814 | 145,944 | Compile-time type based dispatch | Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:
template<class T, template <class> class Manager = DefaultManager> c... | Overloading can be useful to implement compile-time dispatching, as proposed by Alexandrescu in his book "Modern C++ Design".
You can use a class like this to transform at compile time a boolean or integer into a type:
template <bool n>
struct int2type
{ enum { value = n}; };
The following source code shows a possible... |
145,838 | 145,841 | Benefits of inline functions in C++? | What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what adva... | Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough... |
146,275 | 146,309 | Function pointer to template class member functions | I have a templated class defined (in part) as
template <class T> MyClass
{
public:
void DoSomething(){}
};
If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type... | Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.
Something like this:
class Base {
public:
virtual ~Base(){}
virtual void DoSomething() = 0;
}
template <class T> class MyClass : publi... |
146,381 | 146,419 | Visual Studio support for new C / C++ standards? | I keep reading about C99 and C++11 and all these totally sweet things that are getting added to the language standard that might be nice to use someday. However, we currently languish in the land of writing C++ in Visual Studio.
Will any of the new stuff in the standard ever get added to visual studio, or is Microsoft ... | MS has a series of public replies to this, most of them blaming their users. Like this one:
https://devblogs.microsoft.com/cppblog/iso-c-standard-update/
Now, the Visual C++ compiler team receives the occasionally question as to why we haven’t implemented C99. It’s really based on interest from our users. Where we’v... |
146,387 | 149,814 | What is the best way to produce random double on POSIX? | I'd like to get uniform distribution in range [0.0, 1.0)
If possible, please let the implementation make use of random bytes from /dev/urandom.
It would also be nice if your solution was thread-safe. If you're not sure, please indicate that.
See some solution I thought about after reading other answers.
| This seems to be pretty good way:
unsigned short int r1, r2, r3;
// let r1, r2 and r3 hold random values
double result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);
This is based on NetBSD's drand48 implementation.
|
146,452 | 146,454 | What are POD types in C++? | I've come across this term POD-type a few times.
What does it mean?
| POD stands for Plain Old Data - that is, a class (whether defined with the keyword struct or the keyword class) without constructors, destructors and virtual members functions. Wikipedia's article on POD goes into a bit more detail and defines it as:
A Plain Old Data Structure in C++ is an aggregate class that contain... |
146,480 | 146,509 | How do I get the resolution of the main monitor in Mac OS X in C++? | I have a graphical app that needs to test the resolution of the display it is starting up on in Mac OS X to ensure it is not larger than the resolution. This is done before the window itself is initialized.
If there is more than one display, it needs to be the primary display. This is the display that hardware acce... | Using CoreGraphics:
CGRect mainMonitor = CGDisplayBounds(CGMainDisplayID());
CGFloat monitorHeight = CGRectGetHeight(mainMonitor);
CGFloat monitorWidth = CGRectGetWidth(mainMonitor);
More information at Apple's Quartz Display Services Reference.
|
146,795 | 146,932 | How to read config file entries from an INI file | I can't use the Get*Profile functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.
[section]
name = some string
I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is pre... | What I came up with:
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
WCHAR _line[256];
file.getline(_line, ELEMENTS(_line));
std::wstringstream lineStm(_line);
std::wstring &line=lineStm.str();
if (line.empty()) continue;
switch (line[0]... |
146,850 | 146,886 | Is D a credible alternative to Java and C++? | Is the D language a credible alternative to Java and C++? What will it take to become a credible alternative? Should I bother learning it? Does it deserve evangelizing?
The main reason I ask is that with the new C++ standard (c++0x) almost here, it's clear to me that the language has gone well past the point of no retu... | What determines the success and popularity of a programming language for real-world software development is only partially related to the quality of the language itself. As a pure language, D arguably has many advantages over C++ and Java. At the very least it is a credible alternative as a pure language, all other t... |
146,873 | 147,031 | How does the UTF-8 support of TinyXML work? | I'm using TinyXML to parse/build XML files. Now, according to the documentation this library supports multibyte character sets through UTF-8. So far so good I think. But, the only API that the library provides (for getting/setting element names, attribute names and values, ... everything where a string is used) is thro... | First, utf-8 is stored in const char * strings, as @quinmars said. And it's not only a superset of 7-bit ASCII (code points <= 127 always encoded in a single byte as themselves), it's furthermore careful that bytes with those values are never used as part of the encoding of the multibyte values for code points >= 128... |
146,924 | 146,934 | How can I tell if a given path is a directory or a file? (C/C++) | I'm using C and sometimes I have to handle paths like
C:\Whatever
C:\Whatever\
C:\Whatever\Somefile
Is there a way to check if a given path is a directory or a given path is a file?
| Call GetFileAttributes, and check for the FILE_ATTRIBUTE_DIRECTORY attribute.
|
146,943 | 147,169 | Help improve this INI parsing code | This is something simple I came up with for this question. I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
std::wstring line;
std::getlin... |
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
I would use boost::regex to match for every different type of element, something like:
boost::smatch matches;
boost::regex name_value("(\S+)\s*=\s*(\S+)");
if(boost::regex_match(line, matches, name_value))
{
name ... |
147,130 | 147,137 | Why doesn't C++ have a garbage collector? | I'm not asking this question because of the merits of garbage collection first of all. My main reason for asking this is that I do know that Bjarne Stroustrup has said that C++ will have a garbage collector at some point in time.
With that said, why hasn't it been added? There are already some garbage collectors for ... | Implicit garbage collection could have been added in, but it just didn't make the cut. Probably due to not just implementation complications, but also due to people not being able to come to a general consensus fast enough.
A quote from Bjarne Stroustrup himself:
I had hoped that a garbage collector
which could be op... |
147,298 | 147,465 | Multithreaded Memory Allocators for C/C++ | I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator.
So far I'm torn between:
Sun's umem
Google's tcmalloc
Intel's threading building blocks allocator
Emery Berger's hoard
From what I've found hoard might be the fastest, but I hadn't heard of ... | I've used tcmalloc and read about Hoard. Both have similar implementations and both achieve roughly linear performance scaling with respect to the number of threads/CPUs (according to the graphs on their respective sites).
So: if performance is really that incredibly crucial, then do performance/load testing. Otherwise... |
147,323 | 149,352 | CScrollView and window size | (MFC Question) What's the best way to determine the current displayed client area in a CScrollView? I only need the size of the visible portion, so GetClientRect() won't work here.
| You do need to use GetClientRect(), but I think you're asking the wrong question. It is not so that in a scrolled view there is a very big client window that is physically scrolled. Instead, when you scroll, the DC's viewportext and mapping mode are adjusted, which make it seem like your view is bigger than it actually... |
147,372 | 147,374 | How does this C++ function use memoization? | #include <vector>
std::vector<long int> as;
long int a(size_t n){
if(n==1) return 1;
if(n==2) return -2;
if(as.size()<n+1)
as.resize(n+1);
if(as[n]<=0)
{
as[n]=-4*a(n-1)-4*a(n-2);
}
return mod(as[n], 65535);
}
The above code sample using memoization to calculate a recursive formula based on some... | if (as[n] <= 0) is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test if (as[n] == 0). This makes your code easier to write, because by default vectors of ints are filled with zeroes.
|
147,378 | 225,281 | Options for refactoring bits of code away from native C++? | So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++.
But, what if you're starting with a native C++ app? What options do you have if you want to write t... | As Aaron Fischer suggests, try recompiling your C++ application with the /clr option turned on and then start leveraging the .Net platform.
CLI/C++ is pretty easy to pick up if you know C# and C++ already and it provides the bridge between the .Net world and native C++.
If your current C++ code can't compile cleanly wi... |
147,391 | 147,406 | Using boost::random as the RNG for std::random_shuffle | I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.
I tried something like this:... | In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).
This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0... |
147,572 | 147,589 | Will the below code cause memory leak in c++ | class someclass {};
class base
{
int a;
int *pint;
someclass objsomeclass;
someclass* psomeclass;
public:
base()
{
objsomeclass = someclass();
psomeclass = new someclass();
pint = new int();
throw "constructor failed";
a = 43;
}
}
int main()
{
b... | Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one).
This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get dest... |
147,902 | 147,915 | Linux configuration file libraries | Are there any good configuration file reading libraries for C\C++ that can be used for applications written on the linux platform. I would like to have a simple configuration file for my application. At best i would like to steer clear of XML files that might potentially confuse users.
| You could try glib's key-value-file-parser
|
147,920 | 147,954 | Can you create collapsible #Region like scopes in C++ within VS 2008? | I miss it so much (used it a lot in C#). can you do it in C++?
| Yes, you can. See here.
#pragma region Region_Name
//Your content.
#pragma endregion Region_Name
|
148,003 | 148,030 | Algorithm for finding the maximum difference in an array of numbers | I have an array of a few million numbers.
double* const data = new double (3600000);
I need to iterate through the array and find the range (the largest value in the array minus the smallest value). However, there is a catch. I only want to find the range where the smallest and largest values are within 1,000 samples ... | The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonable is to use O(N*log(N)) algorithm the following way:
* create sorted container (std::multiset) of first 1000 numbers
* in loop (j=1, j<(3600000-1000); ++j)
- calculate range
- remove from the set... |
148,024 | 149,641 | Why is my parameter passed by reference not modified within the function? | I have got a C function in a static library, let's call it A, with the following interface :
int A(unsigned int a, unsigned long long b, unsigned int *y, unsigned char *z);
This function will change the value of y an z (this is for sure). I use it from within a dynamic C++ library, using extern "C".
Now, here is what ... | First of all, I am very grateful to everyone for your help.
Thanks to the numerous ideas and clues you gave me, I have been able to finally sort out this problem. Your advices helped me to question what I took for granted.
Short answer to my problem : The problem was that my C++ library used an old version of the C lib... |
148,071 | 174,086 | Problem using large binary segment in OOXML | System Description
A plotting component that uses OOXML to generate a document.
Plotting component consists of several parts.
All parts are written in C++ as exe + dll's, with the exception of the interface to the OOXML document.
The latter component is a COM component that was created in C#/.NET. The main reason for... | You might try to unzip the package yourself (instead of using the .NET package API), write directly to the file which represents the binary segment and zip it again.
|
148,225 | 148,230 | How to extract four unsigned short ints from one long long int? | Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.
Particular order doesn't matter much here.
I generally know that I need to shift bits and truncate to the size of unsigned short int. But I think I may make some weird mistake somewhere, so I ask.
| #include <stdint.h>
#include <stdio.h>
union ui64 {
uint64_t one;
uint16_t four[4];
};
int
main()
{
union ui64 number = {0x123456789abcdef0};
printf("%x %x %x %x\n", number.four[0], number.four[1],
number.four[2], number.four[3]);
return 0;
}
|
148,281 | 150,158 | Eclipse C++ pretty printing? | The output we get when printing C++ sources from Eclipse is rather ugly.
Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?
| I also use enscript for this. Here's an alias I often use:
alias cpp2ps='enscript --color --pretty-print=cpp --language=PostScript'
and I use it like this:
cpp2ps -P main.ps main.cpp
There are several other great options in enscript including rotating, 2-column output, line numbers, headers/footers, etc. Check ou... |
148,298 | 148,302 | How to check for equals? (0 == i) or (i == 0) | Okay, we know that the following two lines are equivalent -
(0 == i)
(i == 0)
Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='.
My question is - in today's generation of pretty slick IDE's and intellig... | I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, "Are you 21 or older?", not, "Is 21 less than or equal to your age?"
|
148,373 | 148,408 | Restrict Template Function | I wrote a sample program at http://codepad.org/ko8vVCDF that uses a template function.
How do I retrict the template function to only use numbers? (int, double etc.)
#include <vector>
#include <iostream>
using namespace std;
template <typename T>
T sum(vector<T>& a)
{
T result = 0;
int size = a.size();
... | The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have.
So, you construct with an int, use + and +=, call a copy constructor, etc.
Any type that has all of these will work with your function -- so, if I create a new type that has these featu... |
148,407 | 148,423 | Why does the code below return true only for a = 1? | Why does the code below return true only for a = 1?
main(){
int a = 10;
if (true == a)
cout<<"Why am I not getting executed";
}
| When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to:
main(){
int a = 10;
if (1 == a)
cout<<"y i am not getting executed";
}
This is part of the C++ standard, so it's something you would expect to happen with every C++ standards compliant compiler.
|
148,511 | 148,551 | Limiting range of value types in C++ | Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such:
LimitedValue< float, 0, 360 > someAngle( 45.0 );
someTrigFunction( someAngle );
so that 'someTrigFunc... | You can do this using templates -- try something like this:
template< typename T, int min, int max >class LimitedValue {
template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other )
{
static_assert( min <= min2, "Parameter minimum must be >= this minimum" );
static_assert( max >=... |
148,540 | 149,207 | Creating my own Iterators | I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.
I want some help working out how to create an iterator for a class I have created.
I have a class 'Shape' which has a container of Points.
I have a class 'Piece' which ... | You should use Boost.Iterators. It contains a number of templates and concepts to implement new iterators and adapters for existing iterators. I have written an article about this very topic; it's in the December 2008 ACCU magazine. It discusses an (IMO) elegant solution for exactly your problem: exposing member collec... |
148,807 | 152,642 | How to find unused attributes/methods in Visual C++ 2008 | Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated.
Thanks,
Florian
Edit: nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applications.
| Try PC-Lint. It's pretty good at finding redundant code.
I haven't tried version 9 yet. Version 8 does take some time to configure.
Try the online interactive demo.
|
148,881 | 1,617,173 | How do I append a large amount of rich content (images, formatting) quickly to a control without using tons of CPU? | I am using wxWidgets and Visual C++ to create functionality similar to using Unix "tail -f" with rich formatting (colors, fonts, images) in a GUI. I am targeting both wxMSW and wxMAC.
The obvious answer is to use wxTextCtrl with wxTE_RICH, using calls to wxTextCtrl::SetDefaultStyle() and wxTextCtrl::WriteText().
How... | Derive from wxVListBox. From the docs:
wxVListBox is a listbox-like control with the following two main differences from a regular listbox: it can have an arbitrarily huge number of items because it doesn't store them itself but uses OnDrawItem() callback to draw them (so it is a Virtual listbox) and its items can ha... |
149,268 | 149,305 | Benefits and portability of Boost Library | Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library?
| Boost is organized by several members of the standard committee.
So it is a breeding ground for libraries that will be in the next standard.
It is an extension to the STL (it fills in the bits left out)
It is well documented.
It is well peer-reviewed.
It has high activity so bugs are found and fixed quickly.
It is pla... |
149,336 | 149,377 | Practical Uses for the "Curiously Recurring Template Pattern" | What are some practical uses for the "Curiously Recurring Template Pattern"? The "counted class" example commonly shown just isn't a convincing example to me.
| Simulated dynamic binding.
Avoiding the cost of virtual function calls while retaining some of the hierarchical benefits is an enormous win for the subsystems where it can be done in the project I am currently working on.
|
149,488 | 151,612 | Disk-backed STL container classes? | I enjoy developing algorithms using the STL, however, I have this recurring problem where my data sets are too large for the heap.
I have been searching for drop-in replacements for STL containers and algorithms which are disk-backed, i.e. the data structures on stored on disk rather than the heap.
A friend recently ... | I have implemented some thing very similar. Implementing the iterators is the most challenging. I used boost::iterator_facade to implement the iterators. Using boost::iterator_facade you can easy adapt any cached on disk data structures to have a STL container interface.
|
149,500 | 149,514 | What does the comma operator do? | What does the following code do in C/C++?
if (blah(), 5) {
//do something
}
| Comma operator is applied and the value 5 is used to determine the conditional's true/false.
It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.
Note that the , operator could be ... |
149,710 | 149,717 | Interlocked equivalent on Linux | In a C++ Linux app, what is the simplest way to get the functionality that the Interlocked functions on Win32 provide? Specifically, a lightweight way to atomically increment or add 32 or 64 bit integers?
| Upon further review, this looks promising. Yay stack overflow.
|
149,995 | 150,009 | Getting different header size by changing window size | I have a C++ program representing a TCP header as a struct:
#include "stdafx.h"
/* TCP HEADER
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| So... | See this question: Why isn't sizeof for a struct equal to the sum of sizeof of each member? .
I believe that compiler takes a hint to disable padding when you use the "unsigned int wWindow:16" syntax.
Also, note that a short is not guaranteed to be 16 bits. The guarantee is that: 16 bits <= size of a short <= size of a... |
150,186 | 150,249 | How to order headers in .NET C++ projects | I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project.
this forum thread
IDataObject : ambiguous symbol error answers a problem I've seen multiple times.
Post #4 states
"Move all 'using namespace XXXX' from .h to .cpp"
this looks like a good idea but no... | It's a good idea to always use fully qualified names in header files. Because the using statement affects all following code regardless of #include, putting a using statement in a header file affects everybody that might include that header.
So you would change your function declaration in your header file to:
void loa... |
150,294 | 150,300 | How to programmatically get the CPU cache page size in C++? | I'd like my program to read the cache line size of the CPU it's running on in C++.
I know that this can't be done portably, so I will need a solution for Linux and another for Windows (Solutions for other systems could be usefull to others, so post them if you know them).
For Linux I could read the content of /proc/cpu... | On Win32, GetLogicalProcessorInformation will give you back a SYSTEM_LOGICAL_PROCESSOR_INFORMATION which contains a CACHE_DESCRIPTOR, which has the information you need.
|
150,355 | 150,971 | Programmatically find the number of cores on a machine | Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?
| C++11
#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();
Reference: std::thread::hardware_concurrency
In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifde... |
150,726 | 150,768 | C++ having cin read a return character | I was wondering how to use cin so that if the user does not enter in any value and just pushes ENTER that cin will recognize this as valid input.
| You will probably want to try std::getline:
#include <iostream>
#include <string>
std::string line;
std::getline( std::cin, line );
if( line.empty() ) ...
|
150,803 | 150,874 | Side effects of calling RegisterWindow multiple times with same window class? | I'm working on a little test application at the minute and I have multiple window objects floating around and they each call RegisterWindowEx with the same WNDCLASSEX structure (mainly because they are all an instance of the same class).
The first one registers ok, then multiple ones fail, saying class already register... | You can test if the window class was previously registered calling GetClassInfoEx.
If the function finds a matching class
and successfully copies the data, the
return value is nonzero.
http://msdn.microsoft.com/en-us/library/ms633579(VS.85).aspx
This way you can conditionally register the window class based on th... |
151,046 | 151,078 | How can I detect the last iteration in a loop over std::map? | I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following:
for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
bool last_iteration;
// do something for all iterations
if (!last_iteration) {
// do so... | Canonical? I can't claim that, but I'd suggest
final_iter = someMap.end();
--final_iter;
if (iter != final_iter) ...
Edited to correct as suggested by KTC. (Thanks! Sometimes you go too quick and mess up on the simplest things...)
|
151,124 | 151,126 | Which is correct? catch (_com_error e) or catch (_com_error& e)? | Which one should I use?
catch (_com_error e)
or
catch (_com_error& e)
| The second. Here is my attempt at quoting Sutter
"Throw by value, catch by reference"
Learn to catch properly: Throw exceptions by value (not pointer) and
catch them by reference (usually to const). This is the combination
that meshes best with exception semantics. When rethrowing the same
exception, prefer jus... |
151,299 | 151,445 | Embedding SVN Revision number at compile time in a Windows app | I'd like my .exe to have access to a resource string with my svn version. I can type this in by hand, but I'd prefer an automated way to embed this at compile time. Is there any such capability in Visual Studio 2008?
| I wanted a similar availability and found $Rev$ to be insufficient because it was only updated for a file if that file's revision was changed (which meant it would have to be edited and committed very time: not something I wanted to do.) Instead, I wanted something that was based on the repository's revision number.
F... |
151,418 | 151,758 | Calling a C++ function pointer on a specific object instance | I have a function pointer defined by:
typedef void (*EventFunction)(int nEvent);
Is there a way to handle that function with a specific instance of a C++ object?
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler(1); }
};
cla... | I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
|
151,728 | 151,751 | Developing for different platforms individually, does anyone recommend it? | I know it is easy to recommend several cross platform libraries.
However, are there benefits to treating each platform individually for your product?
Yes there will be some base libraries used in all platforms, but UI and some other things would be different on each platform.
I have no restriction that the product mu... | I would say that the benefits of individual development for each platform are:
- native look and feel
- platform knowledge acquired by your developers
-... i'm out of ideas
Seriously, the cost of developing and maintaining 3 separate copies of your application could be huge if you're not careful.
If it's just the GUI ... |
151,841 | 151,847 | High-level Compare And Swap (CAS) functions? | I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives...
E.g., WIN32 on x86 has a family of functions _InterlockedCompareExchange in the <_intrin.h> header.
| I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the
atomic_compare_exchange()
operation in the new "Atomic operations library".
|
151,919 | 151,998 | When should I use __forceinline instead of inline? | Visual Studio includes support for __forceinline. The Microsoft Visual Studio 2005 documentation states:
The __forceinline keyword overrides
the cost/benefit analysis and relies
on the judgment of the programmer
instead.
This raises the question: When is the compiler's cost/benefit analysis wrong? And, how am... | The compiler is making its decisions based on static code analysis, whereas if you profile as don says, you are carrying out a dynamic analysis that can be much farther reaching. The number of calls to a specific piece of code is often largely determined by the context in which it is used, e.g. the data. Profiling a ... |
152,005 | 152,020 | How can currying be done in C++? | What is currying?
How can currying be done in C++?
Please Explain binders in STL container?
| In short, currying takes a function f(x, y) and given a fixed Y, gives a new function g(x) where
g(x) == f(x, Y)
This new function may be called in situations where only one argument is supplied, and passes the call on to the original f function with the fixed Y argument.
The binders in the STL allow you to do this fo... |
152,064 | 152,332 | How to measure performance in a C++ (MFC) application? | What good profilers do you know?
What is a good way to measure and tweak the performance of a C++ MFC application?
Is Analysis of algorithms really neccesary? http://en.wikipedia.org/wiki/Algorithm_analysis
| I strongly recommend AQTime if you are staying on the Windows platform. It comes with a load of profilers, including static code analysis, and works with most important Windows compilers and systems, including Visual C++, .NET, Delphi, Borland C++, Intel C++ and even gcc. And it integrates into Visual Studio, but can a... |
152,084 | 154,267 | Fixed point combinators in C++ | I'm interested in actual examples of using fixed point combinators (such as the y-combinator in C++. Have you ever used a fixed point combinator with egg or bind in real live code?
I found this example in egg a little dense:
void egg_example()
{
using bll::_1;
using bll::_2;
int r =
fix2(
... | Here is the same code converted into boost::bind notice the y-combinator and its application site in the main function. I hope this helps.
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
// Y-combinator compatible factorial
int fact(boost::function<int(int)> f,int v)
{
if(v == 0)
retu... |
152,216 | 3,308,176 | Boost Range Library: Traversing Two Ranges Sequentially | Boost range library (http://www.boost.org/doc/libs/1_35_0/libs/range/index.html) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz:
given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to defin... | I needed this again so I had a second look. There is a way to concat two ranges using boost/range/join.hpp. Unluckily the output range type is not included in the interface:
#include "boost/range/join.hpp"
#include "boost/foreach.hpp"
#include <iostream>
int main() {
int a[] = {1, 2, 3, 4};
int b[] = ... |
152,318 | 152,343 | Learning C++ Templates | Can anyone recommend any good resources for learning C++ Templates?
Many thanks.
| I've found cplusplus.com to be helpful on numerous occasions. Looks like they've got a pretty good intro to templates.
If its an actual book you're looking for, Effective C++ is a classic with a great section on templates.
|
152,387 | 152,476 | What technologies do C++ programmers need to know? | C++ was the first programming language I really got into, but the majority of my work on it was academic or for game programming. Most of the programming jobs where I live require Java or .NET programmers and I have a fairly good idea of what technologies they require aside from the basic language. For example, a Java ... | As for every language, I believe there are three interconnected levels of knowledge :
Master your language. Every programmer should (do what it takes to) master the syntax. Good references to achieve this are :
The C++ Programming Language by Bjarne Stroustrup.
Effective C++ series by Scott Meyers.
Know your librar... |
152,436 | 152,461 | Do you recommend Native C++ to C++\CLI shift? | I have been working as a native C++ programmer for last few years. Now we are starting a new project from the scratch. So what is your thoughts on shifting to C++\CLI at the cost of losing platform independent code. Are there are any special advantages that one can gain by shifting to C++\CLI?
| I would recommend the following, based on my experience with C++, C# and .NET:
If you want to go the .NET way, use C#.
If you do not want .NET, use traditional C++.
If you have to bridge traditional C++ with .NET code, use C++/CLI. Works both with .NET calling C++ classes and C++ calling .NET classes.
I see no sense ... |
152,555 | 152,671 | *.h or *.hpp for your class definitions | I've always used a *.h file for my class definitions, but after reading some boost library code, I realised they all use *.hpp. I've always had an aversion to that file extension, I think mainly because I'm not used to it.
What are the advantages and disadvantages of using *.hpp over *.h?
| Here are a couple of reasons for having different naming of C vs C++ headers:
Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically
Naming, I've been on projects w... |
152,643 | 152,665 | Idiomatic C++ for reading from a const map | For an std::map<std::string, std::string> variables, I'd like to do this:
BOOST_CHECK_EQUAL(variables["a"], "b");
The only problem is, in this context variables is const, so operator[] won't work :(
Now, there are several workarounds to this; casting away the const, using variables.count("a") ? variables.find("a")->se... | template <typename K, typename V>
V get(std::map<K, V> const& map, K const& key)
{
std::map<K, V>::const_iterator iter(map.find(key));
return iter != map.end() ? iter->second : V();
}
Improved implementation based on comments:
template <typename T>
typename T::mapped_type get(T const& map, typename T::key_type... |
152,745 | 152,784 | Optimising C++ 2-D arrays | I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead.
I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as:
vector<vector<double> > matrix(n,vector<double>(n));
and accessed through matrix[i][j] is be... | If you're using GCC the compiler can analyze your matrix accesses and change the order in memory in certain cases. The magic compiler flag is defined as:
-fipa-matrix-reorg
Perform matrix flattening and
transposing. Matrix flattening tries
to replace a m-dimensional matrix with
its equivalent n-dimensional matr... |
153,046 | 153,058 | Launch web page from my application | Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more port... | #include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://yourwebpage.com",
NULL, NULL, SW_SHOWNORMAL);
}
|
153,065 | 153,077 | Converting a pointer into an integer | I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example:
void function(MESSAGE_ID id, void* param)
{
if(id == FOO) {
int real_param = (int)param;... | Use intptr_t and uintptr_t.
To ensure it is defined in a portable way, you can use code like this:
#if defined(__BORLANDC__)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
#else
... |
153,074 | 153,122 | Tool to visualise code flow (C/C++) | Do you have any sugestions of tools to ease the task of understanding C/C++ code? We just inherited a large piece of software written by others and we need to quickly get up to speed on it. Any advice on tools that might simplify this task?
| SourceInsight and Understand for C++ are the best tools you can get for c/c++ code analysis including flow charts.
|
153,134 | 153,239 | How do I get a multi line tooltip in MFC | Right now, I have a tool tip that pops up when I hover over an edit box. The problem is that this tool tip contains multiple error messages and they are all in one long line. I need to have each error message be on its own line. The error messages are contained in a CString with a new line seperating them.
My existi... | Creating multiline tooltips is explained here in the MSDN library - read the "Implementing Multiline ToolTips" section. You should send a TTM_SETMAXTIPWIDTH message to the ToolTip control in response to a TTN_GETDISPINFO notification to force it to use multiple lines. In your string you should separate lines with \r\n.... |
153,257 | 153,525 | Random MoveFileEx failures on Vista | I noticed that writing to a file, closing it and moving it to destination place randomly fails on Vista. Specifically, MoveFileEx() would return ERROR_ACCESS_DENIED for no apparent reason. This happens on Vista SP1 at least (32 bit). Does not happen on XP SP3.
Found this thread on the internets about exactly the same p... | I suggest you use Process Monitor (edit: the artist formerly known as FileMon) to watch and see which application exactly is getting in the way. It can show you the entire trace of file system calls made on your machine.
(edit: thanks to @moocha for the change in application)
|
153,559 | 154,190 | What are some good profilers for native C++ on Windows? | I'm looking for a profiler to use with native C++. It certainly does not have to be free, however cost does factor into the purchase decision. This is for commercial work so I can't use personal or academic licensed copies.
The key features I'm looking for are:
Process level metrics
Component level metrics
Line-level ... | On Windows, GlowCode is affordable, fairly easy to use, and offers a free trial so you can see if it works for you.
|
153,676 | 153,704 | GUIDs in a C++ Linux GCC app | I've got a bunch of servers running this Linux app. I'd like for them to be able to generate a GUID with a low probability of collision. I'm sure I could just pull 128 bytes out of /dev/urandom and that would probably be fine, but is there a simple & easy way to generate a GUID that is more equivalent to the Win32 on... | This Internet Draft describes one type of UUID in great details and I have used a similar approach with great success when I needed a UUID implementation and could not link to an existing library for architectural reasons.
This article provides a good overview.
|
153,685 | 153,738 | Managing Window Z-Order Like Photoshop CS | So I've got an application whose window behavior I would like to behave more like Photoshop CS. In Photoshop CS, the document windows always stay behind the tool windows, but are still top level windows. For MDI child windows, since the document window is actually a child, you can't move it outside of the main window. ... | I would imagine they've, since they're not using .NET, rolled their own windowing code over the many years of its existence and it is now, like Amazon's original OBIDOS, so custom to their product that off-the-shelf (aka .NET's MDI support) just aren't going to come close.
I don't like answering without a real answer, ... |
153,707 | 153,830 | Inheriting from protected classes in C+++ | Suppose I have the following declaration:
class Over1
{
protected:
class Under1
{
};
};
I know that I could do the following:
class Over2 : public Over1
{
protected:
class Under2 : public Under1
{
};
};
But is there a way to declare Under2 without Over2?
Since you woul... | Using templates and explicit specializations you can do this with just one additional class declaration in Over1.
class Over1
{
protected:
class Under1
{
};
template <typename T>
class UnderImplementor;
};
struct Under2Tag;
struct Under3Tag;
struct Under4Tag;
template <>
class Over1::UnderImplementor<Under... |
154,060 | 708,982 | Overriding namespaces in gSOAP | I am using gSOAP as a Web Service toolkit and have generated the stub and proxy classes through soapcpp2 from multiple WSDLs all at once. Thus all the namespace bindings are in a single .nsmap file.
Now the problem is that all the namespace bindings are being sent with all the method calls I make. The HTTP POST pack... | Check soapcpp2 and its -q flag, it will help you.
Other than that, the -penv flag will pack basic gSOAP-related methods within the executable, not including any service objects.
Therefore the files generated with -penv can be shared across multiple namespaces, pertaining to different generated gSOAP Web Services.
|
154,136 | 154,138 | Why use apparently meaningless do-while and if-else statements in macros? | In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples.
#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
I can't see what the do while is doing. Why not just write this without it?
#define FOO(X) f(X); g(X)... | The do ... while and if ... else are there to make it so that a
semicolon after your macro always means the same thing. Let's say you
had something like your second macro.
#define BAR(X) f(x); g(x)
Now if you were to use BAR(X); in an if ... else statement, where the bodies of the if statement were not wrapped in cur... |
154,245 | 155,098 | Editing a text buffer | Ok, this is a bit of a cheeky question. I want to build a simple text editor (using my own text mode screen handling). I just want a good example of data structures that can be used to represent the text buffer, and some simple examples of char/text insertion/deletion. I can handle all the rest of the code myself (file... | This is 2008. Don't write a text editor; you're reinventing fire.
Still here? I'm not sure if this applies or what platforms you plan to support, but the Neatpad series of tutorials is a great place to start thinking about writing a text editor. They focus on Win32 as the basic platform, but many of the lessons learned... |
154,365 | 154,379 | search 25 000 words within a text | I need to find occurrences of ~ 25 000 words within a text. What is the most suitable algorithm/library for this purpose?
target language is C++
| build a hashtable with the words, and scan throuhgt the text, for each word lookup in the wordtable and stuff the needed info (increment count, add to a position list, whatever).
|
154,469 | 154,482 | Unnamed/anonymous namespaces vs. static functions | A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:
namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace
You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outsid... | The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:
The use of the static keyword is
deprecated when declaring objects in a
namespace scope, the unnamed-namespace
provides a superior alternative.
Static only applies to names of objects, functions, and anonymous unions, not to type declaration... |
154,547 | 156,115 | Control for getting hotkeys like tab and space | I have a dialog box that allows users to set hotkeys for use in a 3d program on windows. I'm using CHotKeyCtrl, which is pretty good, but doesn't handle some keys that the users would like to use - specifically, tab and space.
The hotkey handling is smart enough to be able to fire on those keys, I just need a UI to l... | One workarounds option would be to use a stock standard edit control with a message hook function.
This would allow you to trap the keyboard WM_KEYDOWN messages sent to that edit control.
The hook function would look something like this:
LRESULT CALLBACK MessageHook(int code, WPARAM wParam, LPMSG lpMsg)
{
... |
154,730 | 154,809 | Capturing video out of an OpenGL window in Windows | I am supposed to provide my users a really simple way of capturing video clips out of my OpenGL application's main window. I am thinking of adding buttons and/or keyboard shortcuts for starting and stopping the capture; when starting, I could ask for a filename and other options, if any. It has to run in Windows (XP/Vi... | There are two different questions here - how to grab frames from an OpenGL application, and how to turn them into a movie file.
The first question is easy enough; you just grab each frame with glReadPixels() (via a PBO if you need the performance).
The second question is a little harder since the cross-platform solutio... |
154,780 | 154,833 | Is there a way to handle a variable number of parameters in a template class? | I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each p... | Not yet in the language itself but C++0x will have support for variadic templates.
|
155,191 | 155,213 | Windows API commctrl.h using application doesn't work on machines without the Platform SDK | I have written something that uses the following includes:
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <commctrl.h>
This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean installs of ... | Use Dependency Walker. Download and install from http://www.dependencywalker.com/ (just unzip to install). Then load up your executable. The tool will highlight which DLL is missing. Then you can find the redistributable pack which you need to ship with your executable.
If you use VS2005, most cases will be covered... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.