question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,971,275 | 2,989,974 | Word automation - SaveAs | I try to write a simple MFC - Word Automation to save for every 1 minute.
I follow this article : http://www.codeproject.com/KB/office/MSOfficeAuto.aspx
And this is what Im trying to implement , I'm new to COM so I think there's problem here:
my VBA is generated by Word 2010:
ActiveDocument.SaveAs2 FileName:="1.docx",... | The VBA syntax uses named parameters where the order and count of the parameters do not matter. However, when calling from C++ you need to pass the required number of parameters in the right order.
SaveAs2 is defined as:
void SaveAs2(
ref Object FileName,
ref Object FileFormat,
ref Object LockComments,
... |
2,971,386 | 2,987,731 | How do I write a std::codecvt facet? | How do I write a std::codecvt facet? I'd like to write ones that go from UTF-16 to UTF-8, which go from UTF-16 to the systems current code page (windows, so CP_ACP), and to the system's OEM codepage (windows, so CP_OEM).
Cross-platform is preferred, but MSVC on Windows is fine too. Are there any kinds of tutorials or a... | I've written one based on iconv. It can be used on windows or on any POSIX OS.
(You will need to link with iconv obviously).
Enjoy
The answer for the "how to" question is to follow the codecvt reference. I was not able to find any better instructions in the Internet two years ago.
Important notices
theoretically ther... |
2,971,518 | 2,971,566 | Polygon Chain - Conversion to non-crossing while preserving shape? | I have polygon chains similar to the following...
...given the chain in the image, how would I go about calculating a chain that defines the same shape but without crossing paths?
Specifically, in the case of the image's input chain, the result I want looks like this:
A1,
A2,
Intersect between A2 and A3,
Intersect bet... | Here's a simple algorithm:
for each line segment in the chain:
Identify any segments which cross this segment
If crossings > 0
Follow the branch to the right, if this doesn't lead back to the
current intersection follow the branch to the left
go to the next line segment
If following a br... |
2,971,670 | 2,971,689 | Member access syntaxes for pointer to a structure | #include <iostream>
typedef struct _person
{
std::string name;
unsigned int age;
}Person;
int main()
{
Person *pMe = new Person;
pMe->age = 10;
pMe->name = "Larson";
std::cout << "Me " << (*pMe).age << " " << (*pMe).name.c_str() << std::endl;
return 0;
}
Consider the above code. The mem... | This is just a syntactic difference and the reason for the difference can be found here
Because the syntax for access to structs and class members through a pointer is awkward, C++ offers a second member selection operator (->) for doing member selection from pointers. Hence both lines are equivalent.
The -> operator i... |
2,971,730 | 2,971,803 | Is there a way find out which second event will happen in MFC | I stumbled upon a curious problem with MFC. I have a Dialog where I check every Edit field on ON_EN_KILLFOCUS if it's valid. If validation doesn't go through I set focus back and show error message. This would be fine, if only I would close the dialog. I mean if I leave wrongly entered field and press close button or X... | In general, you cannot know what event comes after the focus changed event.
However, it is possible to solve this, you change the conditions when the validation logic is fired - validate an edit control when
focus is lost
and the focus is lost to another edit control
By checking that the focus is lost to another cont... |
2,971,782 | 2,971,794 | Why does this program hang? | I have the following code which is seems to be lead to the infinite loop:
struct X
{
void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};
struct X2 : X
{
void my_func( char value ) { my_func(value); }
};
What is the problem with it?
| The second bit is infinitely recursive:
struct X2 : X
{
void my_func( char value ) { my_func(value); } //calls itself over and over again
};
Prefix my_func with the name of the base class and you will be OK
struct X2 : X
{
void my_func( char value ) { X::my_func(value); }
};
EDIT Just realised that base class my_... |
2,971,845 | 2,974,272 | Learning C++ from AS3 | I'm a decent AS3 programmer. I work in games, and that is my reason for programming. While there is much I can accomplish with Adobe AIR, my understanding at this point is that learning C++ is probably a good direction to take. I would learn a lot of valuable lower level programming if I needed it down the road, and I ... | About Haxe: I personally see no risk in using it. I completely switched to Haxe from AS3 about 9 months ago, and I feel it was a very good decision. AS3 has completely stalled since its release. Sure, the player API has grown, but the language itself hasn't evolved, except for the introduction of typed vectors.
While ... |
2,971,918 | 2,971,927 | Unable to run native C++ application on different machine | I wrote a simple 'Hello, world' application in C++ using Visual Studio 2008. I am able to run the app successfully on my local machine. BUt when I copy the exe onto another machine and run, it does not run. It gives the error that 'Application has failed to start because application configuration is incorrect'. The ano... | Probably the CRT DLL is missing. Compile your app using static CRT - /MT (/MTd for debug). More info.
In Visual studio go to Project properties > C/C++ > Code Generation > Runtime Library.
|
2,972,020 | 2,972,065 | C++ warning: suggest parentheses around arithmetic in operand of | | I have a code like
A = B|C|D|E;
Throwing the warning "suggest parentheses around arithmetic in operand of |"
Expecting that expression needs high priority paranthesis for operators, tried the following ways:
A=(B|C)|(D|E);
one more as :
A=(((B|C)|D)|E);
Still the same warning persists.
Please help me in resolving ... | You have some arithmetic operator in your expression that isn't really simply B, or that isn't really simply C, etc. The compiler is suggesting that you parenthesize whichever expression so that readers will see that you wrote what you meant. If you don't parenthesize, everyone has to remember exactly what the priori... |
2,972,146 | 2,972,393 | What sorting method to use: quicksort, bucket sort, radix, ... for tiny data pairs? (c++) | I need to optimize some code that sorts a vector<pair<int, float >>a where the pairs needs to be sorted on the float value. The vector will have an length between 0 and 5. I've been googling and reading up on sorting methods in C++ but cannot find any benchmarks on sorting tiny data sets. For the system it's important ... | First, premature optimization is the root of all evil. That is, first benchmark your code and make sure the sorting is the one that's actually taking the most time. If another part of your performance-critical code is taking 80% of the execution time, you will get drastic performance improvements optimizing that first.... |
2,972,160 | 2,972,409 | how to auto enable a signal on my programme window open | i am using QT4 for my c++ programme i want to enable a SIGNAL automatically when my window is open so please tell me how do i enable a SIGNAL when my programme window open.
i am new to QT so please give a detail description.
Thanks
| Overwrite QWidget::showEvent() (see QT documentation)
|
2,972,166 | 2,977,389 | Qt QPainter error when rotating an ellipse using horizontalSlider | I have to create a simple box which rotates an ellipse and some text depending upon value from horizontalSlider/spinBox. The widget has to be resizable, And size of the ellipse has to change depending upon that.
For now only the ellipse is being painted. The text painting will be added if this works. The problem is tha... | My guess is the call to constructor creates a temporary widget object and messes up the drawing.
|
2,972,800 | 2,972,917 | Windows context menu for multiple files [C++] | I want to create a context menu that support multiple files.
I read through SO and understand that either you must use DDE or shell extension (something to do with creating and registering COM object). However all the sourcecodes I found are in C#.
I then decided to go with COM object. I found 1 in C++ that uses COM bu... | It should work fine, the underlying mechanic hasn't changed in the last 4 years.
Take a look at the comments at the bottom of the article, people are using it without problems. (There is also a link to a VS 2008 template for multiple-files)
|
2,973,085 | 2,973,139 | MFC: Deleting dynamically created CWnd objects | Lets say in a dialog, we dynamically create a variable number of CWnds... like creating a and registering a CButton every time the user does something/
Some pseudo-code...
class CMyDlg : public CDialog
{
vector<CWnd *> windows;
void onClick()
{
CButton *pButton = new CButton(...);
//do other stuff like position... | CButton *pButton = new CButton(...);
These are C++ objects, which needs to be deleted explicitly. (Where as Main frame windows and Views are self destructed).
You can refer the detailed answer ( by me) Destroying Window Objects
|
2,973,087 | 2,973,205 | Convert C++/MFC from visual studio.net 2002 to visual studio 2010 | We will convert a number of programs written in C++ and MFC in Visual Studio.NET 2002 to Visual Studio 2010. What problems can we expect to encounter? What changes are there in the libraries that are worth knowing?
| MFC has had a number of breaking changes over those releases. All the changes are documented on MSDN, and usually they're pretty straightforward - function signature changes and the like (which can often be fixed simply by inspecting the compiler error message and working out what it wants instead).
|
2,973,301 | 2,973,322 | What is a possible workaround for object slicing in c++? | This is the code:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class A {
public:
virtual const string f() const { return "A"; }
};
class B : public A {
public:
const string f() const { return "B"; }
};
int main(int ac, char** av) {
vector<A> v;
v.push_back(B());
cout << v.at(0)... | You need to store pointers. If these refer to dynamically allocated objects, use smart pointers.
|
2,973,304 | 2,973,803 | How to load COM DLL at runtime | I have a VB6 COM DLL. I want to use it from C++. I know how to register it, generate a tlb file from the DLL, and #import it in C++.
I'd like however, to load and use DLLs like this dynamically, at runtime, without knowing them in advance. Is this possible?
Thanks,
| Yes, but you need to get the question clearer.
Sometimes, you do know the COM interface upfront, just not the implementation. In that case, you can create a dummy implementation of the interface and #import that. At runtime, you'd still register the real component, get an object from it (via CoCreateInstance probably) ... |
2,973,467 | 2,973,710 | How to tell if a MFC Dialog has been created/initialized? | I have an OnMove handler in my dialog class, which does some stuff with control objects (i.e a CButton). I'm finding this handler gets called before the dialog OnInitDialog method is called, and hence when I try to call methods on the child controls, I get ASSERTS in debug as the controls don't yet exist... they are cr... |
Set a flag in OnInitDialog
Use your dialog's m_hWnd:
if ( ::IsWindow(m_Ctrl.m_hWnd) ) {
...
}
|
2,973,914 | 2,973,932 | Will destructor be called? | If I create a vector of vector of vector, if I clear the first vector, or the first vector gets deleted, will all the child vectors call the destructor and free the memory or will it cause a memory leak? Thanks
| If you have:
vector <vector <vector <int> > > > v;
v.clear();
then destructors will be called suitably for all the subvectors.
|
2,973,917 | 2,974,001 | c++ global functions and OOP? | In C++ one can have a 'GLOBAL FUNCTION', which means it does not belong to any class. I wondered if that isn't just a violation of the basic principles of OOP?
What would be the difference with using a global function or function that is static in a class? I'm thinking the latter is more OOP oriented. But I may be w... | A static function inside a class is as OO as a global function inside a module. The thing is in JAVA, you don't have the choice.
In C++, you can encapsulate your global functions inside namespaces, you don't need a dummy class to do this. This way you have modularity.
So of course you can put functions outside namespac... |
2,973,964 | 2,974,112 | Conversion between different template instantiation of the same template | I am trying to write an operator which converts between the differnt types of the same implementation. This is the sample code:
template <class T = int>
class A
{
public:
A() : m_a(0){}
template <class U>
operator A<U>()
{
A<U> u;
u.m_a = m_a;
return u;
}
private:
int m... | VC10 accepts this:
template <class T = int>
class A
{
public:
template< typename U>
friend class A;
A() : m_a(0){}
template <class U>
operator A<U>()
{
A<U> u;
u.m_a = m_a;
return u;
}
private:
int m_a;
};
|
2,973,976 | 2,974,015 | Inheritance and method overloading | Why C++ compiler gives this error? Why i can access lol() from B, but can not access rofl() [without parameters]. Where is the catch?
class A
{
public:
void lol(void) {}
void rofl(void) { return rofl(0);}
virtual void rofl(int x) {}
};
class B : public A
{
public:
virtual void rofl(int x) {}
};
int _tmain... | The B::rofl(int) 'hides' the A::rofl(). In order to have A's rofl overloads, you should declare B to be using A::rofl;.
class B : public A {
public:
using A::rofl;
...
};
This is a wise move of C++: it warns you that you probably also need to override the A::rofl() method in B. Either you do that, or you ex... |
2,973,987 | 2,974,039 | Type or Vector for representing points\positions | I have a series of points\positions that won't change. Should I represent as Vector of ints or as a new type?
My preference at the moment is to go with vector:
doSomething(myVec[0], myVec[1] );
doSomethingElse(myVec[2], myVec[3] );
as opposed to:
doSomething( myType.getPos1(), myType.getPos2() );
doSomethingElse( m... | Since you're using stl, I'd use vector< pair<int,int> > (or vector< pair<double,double> > if the points aren't integer). It works great for points.
So then you could do something like this:
vector< pair<int,int> > points;
points.push_back(make_pair(1,2));
points.push_back(make_pair(2,2));
|
2,974,250 | 2,974,865 | WMI with Qt examples and info | Where can I find more information on and examples of using WMI with Qt? I have no prior experience with WMI.
| Microsoft have an overview of how to work with WMI from C++. I would start with that and then implement a user interface on top with QT. WMI exposes a COM interface so you should get familiar with that if you have not used it before. Don Box's Essential COM is one of the better books on the subject.
The Code Project si... |
2,974,470 | 2,974,501 | Efficiency of the STL priority_queue | I have an application (C++) that I think would be well served by an STL priority_queue. The documentation says:
Priority_queue is a container adaptor, meaning that it is implemented on top of some underlying container type. By default that underlying type is vector, but a different type may be selected explicitly.
a... | The priority queue adaptor uses the standard library heap algorithms to build and access the queue - it's the complexity of those algorithms you should be looking up in the documentation.
The top() operation is obviously O(1) but presumably you want to pop() the heap after calling it which (according to Josuttis) is O(... |
2,974,643 | 2,974,659 | Reading in 4 bytes at a time | I have a big file full of integers that I'm loading in. I've just started using C++, and I'm trying out the filestream stuff. From everything I've read, it appears I can only read in bytes, So I've had to set up a char array, and then cast it as a int pointer.
Is there a way I can read in 4 bytes at a time, and elimi... | To read a single integer, pass in the address of the integer to the read function and ensure you only read sizeof int bytes.
int myint;
//...
fstr.read(reinterpret_cast<char*>(&myint), sizeof(int));
You may also need to open the file in binary mode
fstr.open("table.dat", std::ios::binary);
|
2,974,676 | 2,974,690 | Should a programmer have mastery over C++ | I was wondering if it is necessary for programmers to have expertise on at least 1 programming language?
Programming languages like C#, java, VB.Net etc change every year or two. Should a programmer have mastery over C++, which is a stable language and rarely undergoes changes?
I am a C# developer and using it for a... |
Programming languages like C#, java, VB.Net etc change every year or two.
They don't "change" but evolve. Your knowledge and experience are not lost.
Should a programmer have mastery over C++, which is a stable language and rarely undergoes changes?
Programming is all about new and change. If you don't like it, con... |
2,974,771 | 2,976,043 | Force OpenGL to keep contents in memory? | I'm using OpenGL to render polygons. I notice that if I minimize the program then start using it again, it will be very slow for a few seconds. (I'm guessing its reuploading my display lists to the card). How can I prevent this because it's a bit annoying. I want it to always have the contents.
Thanks
| When you minimize a program under Windows, it does the equivalent of SetProcessWorkingSetSize(current_process, -1,-1);. This tells the virtual memory manager that all the memory occupied by that program is eligible for being paged out. The only way I know of to prevent this is to prevent the user from minimizing the pr... |
2,974,780 | 2,975,997 | Visual C++ Compiler allows dependent-name as a type without "typename"? | Today one of my friends told me that the following code compiles well on his Visual Studio 2008:
#include <vector>
struct A
{
static int const const_iterator = 100;
};
int i;
template <typename T>
void PrintAll(const T & obj)
{
T::const_iterator *i;
}
int main()
{
std::vector<int> v;
A a;
PrintAll(a);
Print... | This is not an extension at all.
VC++ never implemented the two phases interpretation properly:
At the point of definition, parse the template and determine all non-dependent names
At the point of instantiation, check that the template produces valid code
VC++ never implemented the first phase... it's inconvenient si... |
2,974,803 | 2,977,230 | Does Qt have resource system limits? | My Qt application depends on Oracle DLLs to start. As it's linked statically for the most part (except for these DLLs), I'd like to embed the DLLs and the EXE into a launcher that would behave like a fully static application (one exe, no DLLs to take along).
The launcher would extract the included files in a temp dire... | Limit comes from compiler, as error says it is INTERNAL compiler error. So compiller couldn't handle it. You could try to walkaround it, by splitting bigger files in to small parts and manualy put them together in your code. I'm not sure if it will work, but it is worth trying.
|
2,974,855 | 2,974,907 | How to create a function with return type map<>? | Fairly straightforward question. I have a map that I wish to initialize by calling a function like so:
map<string, int> myMap;
myMap = initMap( &myMap );
map<string, int> initMap( map<string, int> *theMap )
{
/* do stuff... */
However, the compiler is moaning. What's the solution to this?
EDIT 1:
I'm sorry, but ... | Either do:
map<string, int> myMap;
initMap( myMap );
void initMap( map<string, int>& theMap )
{
/* do stuff in theMap */
}
or do:
map<string, int> myMap;
myMap = initMap( );
map<string, int> initMap()
{
map<string, int> theMap;
/* do stuff in theMap */
return theMap;
}
i.e. let the function initial... |
2,974,908 | 2,974,993 | Error can not open source file "..." | I'm using VS2010 (downloaded via dreamspark) and although I can open the #include file by right clicking on it and pressing on Open Document, it complains "Error can not open source file "..."" which seems rather absurd. I'm using Qwt with Qt this time around and I'm specifically having the problem for:
#include <qwt_c... | As Neil indicated, try using quotes instead of the <> characters around the filename. When using the quotes, MSVC will look in the same directory as the file the #include is in for the specified file, then if it's not found there will look in the directories specified by the include path. When the filename is surroun... |
2,975,040 | 2,975,128 | C++ Refactoring Precompiled Header | Unfortunately on a project here at work, someone had the great idea to put every header every single file from pretty big project into the precompiled header. This means any change to any header in the project has to recompile the entire project, and all cpp files taking way too long.
Is there any decent C++ refactori... | There are very few decent C++ refactoring tools because parsing C++ code is hard (and therefore also slow). You'll probably have to write such a tool yourself, possibly with some assistance from GCC-XML.
|
2,975,052 | 3,041,224 | c++ project using c# assemblies: how to speedup compile time? | I've got a mixed c++/c# project. The original project is c++ and has been extended using c# assemblies. In the beginning this was ok, but since the c# part is growing I experience a big problem growing:
Compile time of the c++ part becomes a problem.
Why? Simple: every time I change something in a c# project, the c++ c... | You could extract interfaces from your C# classes and put those interfaces into a separate C# project. Since these interfaces will not change each and every time an implementation (in your original C# project) changes the C++ projects do not need a rebuild.
|
2,975,100 | 2,975,158 | C++ Constructor Parameters Question | I'm learning C++. I have a simple class named GameContext:
class GameContext {
public:
GameContext(World world);
virtual ~GameContext();
};
To initialize a GameContext object, I need a World object.
Should the GameContext constructur take a pointer to a World object (World*), the address to a Wor... | First, teminology: You're right that a World * would be a pointer to a World object. A World &, however, would be a reference to a World object. A World would be a copy of the World object, not a reference to it.
The const (used primarily with a pointer or reference, as in World const &world or World const *world) mean... |
2,975,275 | 2,975,421 | How large does a collection have to be for std::map<k,v> to outpace a sorted std::vector<std::pair<k,v> >? | How large does a collection have to be for std::map to outpace a sorted std::vector >?
I've got a system where I need several thousand associative containers, and std::map seems to carry a lot of overhead in terms of CPU cache. I've heard somewhere that for small collections std::vector can be faster -- but I'm wonderi... | It's not really a question of size, but of usage.
A sorted vector works well when the usage pattern is that you read the data, then you do lookups in the data.
A map works well when the usage pattern involves a more or less arbitrary mixture of modifying the data (adding or deleting items) and doing queries on the data... |
2,975,304 | 2,975,438 | Undefined reference to XOpenDisplay in a Qt project | Now I am feeling quite stupid. I am trying to do some stuff with xlib in Qt Creator.
My code:
#include <QtCore/QCoreApplication>
#include <X11/Xlib.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Display *display = XOpenDisplay(NULL);
return 0;
}
Just one line of code and gives me:... | I've figured it out.
Adding -lX11 to the the Makefile solved this issue.
|
2,975,330 | 2,975,401 | How do you indent preprocessor statements? | When there are many preprocessor statements and many #ifdef cascades, it's hard to get an overview since normally they are not indented. e.g.
#ifdef __WIN32__
#include <pansen_win32>
#else
#include <..>
#ifdef SOMEOTHER
stmts
#endif
maybe stmts
#endif
When I consider also indenting those preprocessor statements, I fea... | Just because preprocessing directives are "normally" not indented is not a good reason not to indent them:
#ifdef __WIN32__
#include <pansen_win32>
#else
#include <..>
#ifdef SOMEOTHER
stmts
#endif
maybe stmts
#endif
If you frequently have multiple levels of nesting of preprocessing directi... |
2,975,385 | 2,975,787 | Why does my data not seem to be aligned? | I'm trying to figure out how to best pre-calculate some sin and cosine values, store them in aligned blocks, and then use them later for SSE calculations:
At the beginning of my program, I create an object with member:
static __m128 *m_sincos;
then I initialize that member in the constructor:
m_sincos = (__m128*) _ali... | m_sincos[t] is a C expression. In an assembly instruction, however, (__asm?), it's interpreted as an x86 addressing mode, with a completely different result. For example, VS2008 SP1 compiles:
movaps xmm0, m_sincos[t]
into: (see the disassembly window when the app crashes in debug mode)
movaps xmm0, xmmword ptr [t]
... |
2,975,542 | 2,975,583 | Integer Types in file formats | I am currently trying to learn some more in depth stuff of file formats.
I have a spec for a 3D file format (U3D in this case) and I want to try to implement that. Nothing serious, just for the learning effect.
My problem starts very early with the types, that need to be defined. I have to define different integers (8... | Hex is just a representation of a number. Whether you interpret the number as binary, decimal, hex, octal etc is up to you. In C++ you have support for decimal, hex, and octal representations, but they are all stored in the same way.
Example:
int x = 0x1;
int y = 1;
assert(x == y);
Likely the file format wants you t... |
2,975,831 | 2,975,844 | Is leaked memory freed up when the program exits? | If I programmed — without knowing it — a memory leak, and the application terminates, is the leaked memory freed?
| Yes, a "memory leak" is simply memory that a process no longer has a reference to, and thus can no longer free. The OS still keeps track of all the memory allocated to a process, and will free it when that process terminates.
In the vast majority of cases the OS will free the memory - as is the case with normal "flavor... |
2,976,058 | 2,976,097 | C++: Can I get out of the bounds of my app's memory with a pointer? | If I have some stupid code like this:
int nBlah = 123;
int* pnBlah = &nBlah;
pnBlah += 80000;
*pnBlah = 65;
Can I change another app's memory?
You have explained me this is evil, I know. But I was just interested.
And this isn't something to simply try. I don't know what would happen.
Thanks
| In C++ terms, this is undefined behavior. What will actually happen depends on many factors, but most importantly it depends on the operating system (OS) you are using. On modern memory-managed OS's, your application will be terminated with a "segmentation fault" (the actual term is OS-dependent) for attempting to acce... |
2,976,076 | 2,976,127 | C++: synchronize 5 consumers to 1 producer (multithreaded) | I have five consumers and one producer. The five consumers each output different data, from the one producer, for ~10ms. During those 10ms the producer prepares the parameters for the next output. When the output parameters are set, I want to set a flag instructing the consumers to begin the next output. I only want th... | You will need 2 events and an integer reference count.
When producer has produced some thing it:
initiates read_count = 0;
sets event readme.
starts to wait on event completed;
Consumers wait on event readme. After doing their work they ATOMICALLY increment read_count. If the read_count reaches the number of consumer... |
2,976,246 | 2,976,265 | C++: How do applications like Cheat Engine and ArtMoney work? | After asking this question (C++: Can I get out of the bounds of my app’s memory with a pointer?),
I decided to accept it isn't possible to modify other app's memory with pointers (with a modern OS).
But if this isn't possible, how do programs like ArtMoney and CheatEngine work?
Thanks
| Check these functions:
ReadProcessmemory
WriteProcessmemory
|
2,976,274 | 2,976,423 | adjust bitmap image brightness/contrast using c++ | adjust image brightness/contrast using c++ without using any other 3rd party library or dependancy
| Image brightness is here - use the mean of the RGB values and shift them.
Contrast is here with other languages solutions available as well.
Edit in case the above links die:
The answer given by Jerry Coffin below covers the same topic and has links that still live.
But, to adjust brightness, you add a constant value ... |
2,976,296 | 2,976,304 | C++ dynamic array of matrices (from scythe statistical library) | I am trying to use the scythe statistical library (found here: http://scythe.wustl.edu/). I can initialize a matrix just fine with:
Matrix<double> A(2, 2, false);
But I would like to have a dynamic array of such matrices. Does anyone have any hints? Do I use vector? If so how?
Many thanks!
| A std::vector would be an excellent choice, especially if you don't know until runtime how many matrices you need. For example,
std::vector<Matrix<double> > vectorOfMatrices;
vectorOfMatrices.push_back(Matrix<double>(2, 2, false));
// etc.
|
2,976,396 | 2,976,443 | Compile and link errors | Are there strategies or methods to identify whether a particular piece of code or program will generate a link error or a compile error.
| You mention in your comments "if you don't have access to a compiler". Well if you have access to the web you have access to a compiler:
Ideon
Codepad's online compiler/parser
Comeau's "try it out" web-based compiler
(thanks commenters for the updates)
This will just help you with compiling what's in the web form tho... |
2,976,477 | 2,976,483 | Difference between iostream and iostream.h | What is the difference between iostream and iostream.h?
| iostream.h is deprecated by those compilers that provide it, iostream is part of the C++ standard.
To clarify explicitly there is no mention of iostream.h at all in the current C++ standard (INCITS ISO IEC 14882 2003).
Edit: As @Jerry mentioned, not only does the current standard not mention it, but no standard for C++... |
2,976,489 | 6,210,386 | IShellLink::SetIconLocation translates my icon path into %Program Files% which is WRONG | Does anyone know how to correct for this behavior?
Currently, when our installer installs our application, it obtains an IShellLink, then loads it up with the data necessary for our shortcut icon (in the start menu & desktop), and then uses IPersistFile::Save to write out the shortcut.
The problem is that the path spec... | Convert the name into a short filename, and it will only convert the drive letter, yet keep the correct path.
PWCHAR pIcon = L"C:\\Program Files (x86)\\Myfoo\\Bar.exe";
DWORD dwLen = GetShortPathName(pIcon, NULL, 0);
PWCHAR pShort = NULL;
if (dwLen) {
pShort = new WCHAR[dwLe... |
2,976,654 | 2,976,839 | gethostbyname creates a thread? | I am working in C++ with VS2008 and Win7.
While examining a program I was following the threads created, and it seems that gethostbyname() creates a thread for itself. Could you explain why?
On msdn is says:
"The memory for the hostent structure returned by the gethostbyname function is allocated internally by the Wi... | AFAIK, gethostbyname blocks.
WinSock often creates some helper threads though.
|
2,976,671 | 2,976,678 | Exposing a std::list as read only | I have a class that contains, among other things, an std::list. I want to expose this list but only in such a way that the structure and the data it contains are read only, but still can be used with iterators.
The way I've got it 'working' atm is to return a copy of the list. This leave my class 'safe' but of course d... | Why not return a const std::list& instead?
|
2,976,790 | 2,976,878 | Redirect a TCP connection | I have something like a proxy server (written in java) running between my clients and the actual video server (made in c++). Everything the clients send goes through this proxy and is then redirected to the server.
It is working fine, but I have some issues and think it would be better if I could make this proxy server... | You don't have control of TCP handshake in userland like that. This is what firewalls/routers do but it all happens in the kernel. Take a look at the firewalling software for your platform - you might not even have to code anything.
|
2,977,007 | 2,977,045 | Public Data members vs Getters, Setters | I am currently working in Qt and so C++. I am having classes that has private data members and public member functions. I have public getters and setters for the data members available in the class.
Now my question is, if we have getters and setters for data members in our classes then what's the point in making those... | Neither. You should have methods that do things. If one of those things happens to correspond with a specific internal variable that's great but there should be nothing that telegraphs this to the users of your class.
Private data is private so you can replace the implementation whenever you wish (and can do full rebui... |
2,977,077 | 2,977,201 | C++ boost mpl vector | I understand that the following code won't work, as i is a runtime parameter and not a compile time parameter. But i want to know, whether there is a way to achieve the same. i have a list of classes and i need to call a template function, with each of these classes.
void
GucTable::refreshSessionParams()
{
typedef... | I only used MPL for a collection of types for BOOST_AUTO_TEST_CASE_TEMPLATE, so my knowledge is quite limited. However, I'd guess you could use for_each to iterate through an MPL sequence.
|
2,977,174 | 8,539,875 | Is there a C++11 syntax file for vim? | In particular, the display of initialization lists is really bad:
vector<int> v({1,2,3});
will highlight the curly braces in red (denoting an error).
| There is now a C++11 script from http://www.vim.org/scripts/script.php?script_id=3797, which no longer mark the braces inside parenthesis as error.
|
2,977,982 | 2,977,992 | C++ struct definition |
Possible Duplicate:
What does ‘unsigned temp:3’ means
I just found this code in a book (was used in an example)
typedef struct {
unsigned int A:1;
unsigned int B:1;
unsigned int C:1;
} Stage;
What is the meaning of this structure definition? (the A:1;)
| Those are C bitfields. In compliant compilers, the combination of A B and C do not occupy more than one int. A, B, and C occupy one bit each in the integer.
|
2,977,983 | 2,978,011 | does VS express conflict with professional? | I just recently installed VS 2008 Professional on my computer and I already have C++ and C# express on my computer. But for some strange reason I can not find the executable for VS professional 2008. when I go into program files and look under visual studios 2008. All i see is a bunch of tools but no vs 2008 exe
| Strange...
have you check the directory C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe?
|
2,978,096 | 2,978,327 | Using * Width & Precision Specifiers With boost::format | I am trying to use width and precision specifiers with boost::format, like this:
#include <boost\format.hpp>
#include <string>
int main()
{
int n = 5;
std::string s = (boost::format("%*.*s") % (n*2) % (n*2) % "Hello").str();
return 0;
}
But this doesn't work because boost::format doesn't support the * spe... | Try this:
#include <boost/format.hpp>
#include <iomanip>
using namespace std;
using namespace boost;
int main()
{
int n = 5;
string s = (format("%s") % io::group(setw(n*2), setprecision(n*2), "Hello")).str();
return 0;
}
group() lets you encapsulate one or more io manipulators with a parameter.
|
2,978,118 | 2,978,377 | Data parallel libraries in C/C++ | I have a C# prototype that is heavily data parallel, and I've had extremely successful order of magnitude speed ups using the Parallel.For construct in .NETv4. Now I need to write the program in native code, and I'm wondering what my options are. I would prefer something somewhat portable across various operating syste... | If you're using Parallel.For in .Net 4.0, you should also look at the Parallel Pattern Library in VS2010 for C++; many things are similar and it is library based.
If you need to run on another platform besides Windows the PPL is also implemented in Intel's Thread Building Blocks which has an open source version.
Regard... |
2,978,259 | 2,981,617 | Programmatically create static arrays at compile time in C++ | One can define a static array at compile time as follows:
const std::size_t size = 5;
unsigned int list[size] = { 1, 2, 3, 4, 5 };
Question 1 - Is it possible by using various kinds of metaprogramming techniques to assign these values "programmatically" at compile time?
Question 2 - Assuming all the values in the ... | The closest you can get is using C++0x features to initialize local or member arrays of templates from a variadic template argument list.
This is of course limited by the maximum template instantiation depth and wether that actually makes a notable difference in your case would have to be measured.
Example:
template<un... |
2,978,315 | 2,978,575 | C++ - Where to store a global counter? | The diagram http://www.freeimagehosting.net/uploads/2fd3f4161c.png
Here's the Minimalist-UML diagram of an app I've been working on. It's supposed to simulate the management of a bunch of sensors relating to different measurements.
Please ignore the House class, the diagram is outdated...
However, I have trouble. Each ... | One option would be to create a static function in your Sensor class that increments and returns a static counter variable. The constructor for Sensor could call this function to get an ID.
// header file
class Sensor
{
...
protected:
static int getId() { return id++; }
private:
static int id;
int myId;
};
/... |
2,978,488 | 2,978,603 | select() hanging indefinitely | I have an application that runs on embedded linux (older kernel, 2.6.18). I'm using Live555. Occasionally when the camera is heavily loaded, my RTSP server (built using Live555) will hang indefinitely--no amount of connecting or cajoling seems to get it to snap out of it, short of resetting the application.
I narrowe... | That code looks pretty solid. I'm a little curious as to why you're casting to unsigned int, but it shouldn't hurt anything.
Some thoughts:
It's not hanging where you think it is. Hopefully you've double/triple checked this. (Check it again?)
Your netstat interpretation is wrong. That part, as the man page notes, is fo... |
2,978,689 | 2,978,713 | Playing sounds over the microphone in c++ | I am making a program in C++ for Windows XP that requires sound to be played so that any program that is currently recording the microphone can hear it, but it will not come out of the speakers. There seems to be no "real" way of doing it, but it is possible to go into "sndvol32 -R" and set the Wave out mix or similar ... | Doing this would require a complicated kernel-level driver.
Fortunately for you, someone has already done this (it's not free, but it's a fantastic program).
|
2,978,844 | 2,978,882 | Struct containing a Map in a Map? (C++/STL) | I was wondering if it was possible to create a struct containing a number of variables and a map in a map.
What I have at the moment:
typedef std::map<std::string,double> lawVariables;
struct ObjectCustomData {
std::string objectType;
bool global_lock;
std::map<std::string, lawVariables> lawData;
... |
I was wondering if it was possible to
create a struct containing a number of
variables and a map in a map
Yes. It is possible to have Map as value inside another map.
If you are particular about the order of insertion and the entries are less for inner map then your data structure can looks like:
typedef std::vec... |
2,979,165 | 3,063,297 | Fober et al Lock-Free FIFO Queue: multiple consumers and producers? | I was wondering if the fifo queue presented in Fober et al's paper http://nedko.arnaudov.name/soft/L17_Fober.pdf was a multiple consumer and produce fifo queue. If not, which is the best documented multiple consumer and producer FIFO queue?
Thanks
| yes. read section '3.1 Linearizability'
the pop operation assumes that concurrent dequeue might happen. This means that multiple threads will be able to consume the queue.
|
2,979,195 | 2,979,234 | How can I search PDF? | Im doing a small project in C++ in LINUX PLATFORM.i need to search 10 or more PDF files and find required data.how can i do so?.
i will make my question more clear with following eg
Suppose i have ten text books all about c++ and i need info about the topic array. How i can search the pdf and find data?
| Read this pdftotext
If you actually want to write code to do then you'll probably have to learn of to navigate the internals of a PDF file. There have been some answers on how to do that for example one pointing to this article which on the 2nd page has the code in C for a basic PDF parser
xtractpro
|
2,979,222 | 2,979,228 | How to use a object whose copy constructor and copy assignment is private? | In reading TCPL, I got a problem, as the title refered, and then 'private' class is:
class Unique_handle {
private:
Unique_handle& operator=(const Unique_handle &rhs);
Unique_handle(const Unique_handle &rhs);
public:
//...
};
the using code is:
struct Y {
//...
Unique_handle obj;
};
and I want to ... | As its name suggests, the Unique_handle isn't meant to be copied. Its implementation ensures it by disabling the copy constructor and copy assignment operator.
One solution for multiple instances having access to a Unique_handle is holding a pointer to it, and copying the pointer. Then multiple instances of Y point to... |
2,979,384 | 2,979,401 | Purpose of Header guards | In C++ what is the purpose of header guard in C++ program.
From net i found that is for preventing including files again and again but how do header guard guarantee this.
| The guard header (or more conventionally "include guard") is to prevent problems if header file is included more than once; e.g.
#ifndef MARKER
#define MARKER
// declarations
#endif
The first time this file is #include-ed, the MARKER preprocessor symbol will be undefined, so the preprocessor will define the symbol, a... |
2,979,386 | 2,979,503 | MultiOS "Jet Database" for C++/Qt? | Hopefully I can articulate this well: I'm porting an application I made years ago from VB6 (I know, I know!) to C++/Qt. In my original application, one thing I liked was that I didn't need an actual SQL server running, I could just use MS Access .mdb files. I was wondering if something similar exists for Qt that will w... | I second the comment by "Mosg". Have a look at SQLite.
|
2,979,392 | 2,979,430 | Why C/C++ have memory issue? | I have read lots of programmers saying and writing when programming in C/C++ there are lots of issue related to memory. I am planning to learn to program in C/C++. I have beginner knowledge of C/C++ and I want to see some short sample why C/C++ can have issues with memory management. Please Provide some samples.
| There are many ways you can corrupt or leak memory in C or C++. These errors are some of the most difficult to diagnose, because they are often not easily reproducible.
For example, it is simple to fail to free memory you have allocated. For example, this will do a "double free", trying to free a twice and failing to... |
2,979,523 | 2,979,573 | How to test if a string has a certain unicode char? | Supose you have a command line executable that receives arguments. This executalbe is widechar ready and you want to test if one of this arguments starts with an HYPHEN case in which its an option:
command -o foo
how you could test it inside your code if you don't know the charset been used by the host?
Should be not p... | In your case, Windows will deliver the command line as a UTF-16 string so you shouldn't need to worry about character sets. Just check (inputFile->c_str()[0] == L'-') and you should be good to go. Of course UTF-16 is a variable-length encoding but the hyphen character is represented by a single wide-char value.
|
2,979,525 | 2,979,557 | Boost threading/mutexs, why does this work? | Code:
#include <iostream>
#include "stdafx.h"
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
boost::mutex mut;
double results[10];
void doubler(int x) {
//boost::mutex::scoped_lock lck(mut);
results[x] = x*2;
}
int _tmain(int argc, _TCHAR* argv[])
{
boost::thread_group thds;
fo... | The assignment has an lvalue of type double on the left and that lvalue is the only object being accessed by a thread. Since each thread accesses a different object, there is no data race.
Note that subscripting an array does not constitute an access.
|
2,979,584 | 2,979,638 | How can I use STL sort in c++ to sort some values in the class? | I have a class named Graph, in this class I have a member named V, it is a vector. I have a struct named Edge, and a list of Edges. like below:
struct Edge{
int u;
int v;
Edge(int u,int v){
this->u=u;
this->v=v;
}
};
struct Vertex{
int d;
int f;
.
.
.
}
class Graph{
vector < Vertex > V;
.
.
.
... | You can't use a member function as the comparator. A member function needs the this pointer which cannot be passed from sort.
Instead, you have to create a function object to include the extra info, like:
class Graph{
vector < Vertex > V;
struct EdgeComparer {
const vector<Vertex>& V;
EdgeComparer(const ... |
2,979,673 | 2,979,689 | How do you use C++0x raw strings with GCC 4.5? | This page says that GCC 4.5 has C++ raw string literals: http://gcc.gnu.org/projects/cxx0x.html
But when I try to use the syntax from this page: http://www2.research.att.com/~bs/C++0xFAQ.html#raw-strings
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = R"[\w\\\w]";
}
I get this... | Try
R"(\w\\\w)";
The delimiters […] were changed to (…) in n3077.
|
2,979,954 | 2,979,973 | Parametrised and Conversion Constructors | Is there any difference between parametrised constructor and conversion constructor. If so what is it?
| A parameterised constructor is (presumably) any constructor that takes one or more parameters. A conversion constructor is a constructor that can be called with a single parameter and is not declared explicit.
struct A {
A(); // not parameterised or conversion
A( int x, int y ); // paramterised, not conver... |
2,980,219 | 2,980,228 | Achieving C# "readonly" behavior in C++ | this is my first question on stack overflow, so be gentle.
Let me first explain the exact behavior I would like to see. If you are familiar with C# then you know that declaring a variable as "readonly" allows a programmer to assign some value to that variable exactly once. Further attempts to modify the variable will r... | Why not just use Singleton::GetInstance directly? Why do you need to store it in a (readonly) global? This solves dependency issues as well.
|
2,980,240 | 2,983,544 | How to get the Drive letter and Mount Path - MSDN | I get the devices list from the system using SetupDiGetClassDevs Function - MSDN.
Also i can able to get the vendor id and product id from the devices.
But i cant able to get the drive letter and the mount path
For Example if i plug the usb drive means , i have to get the drive letter like "G:/"
Please help me to get t... | You can use QueryDosDevice function (see http://msdn.microsoft.com/en-us/library/aa365461(VS.85).aspx). See http://msdn.microsoft.com/en-us/library/cc542456(VS.85).aspx for an code example.
|
2,980,253 | 2,980,276 | how to convert utf-8 to ASCII in c++? | i am getting response from server in utf-8 but not able to read that.
how to convert utf-8 to ASCII in c++?
| First note that ASCII is a 7-bit format. There are 8-bit encodings, if you are after one of these (such as ISO 8859-1) you'll need to be more specific.
To convert an ASCII string to UTF-8, do nothing: they are the same. So if your UTF-8 string is composed only of ASCII characters, then it is already an ASCII string, an... |
2,980,385 | 3,006,182 | How to get only USB devices not all the devices in the system | Grretings to all,
I get devices list from the system.
but i am not sure that if i want to get only the usb devices currently in the system means ,
What class i must specify in the below code ( DWORD Flags )
hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE,
0, // Enumerator
... | Consider using EnumerateHostController().
Examples
www.intel.com/intelpress/usb/examples/DUSBVC.PDF
github.com/Microsoft/Windows-driver-samples/blob/master/usb/usbview/enum.c
Additional info and a detailed discussion here.
|
2,980,386 | 2,980,471 | base destructor called twice after derived object? | hey there, why is the base destructor called twice at the end of this program?
#include <iostream>
using namespace std;
class B{
public:
B(){
cout << "BC" << endl; x = 0;
}
virtual ~B(){
cout << "BD" << endl;
}
void f(){
cout << "BF" << endl;
}
virtual void g(){
cout << "BG" << endl;
}
... | Destructors are called in order, as if they were unwinding the effects of the corresponding constructors. So, first the destructors of the derived objects, then the destructors of the base objects. And making the destructors virtual doesn't have any impact on calling / not calling the base class destructor.
Also to men... |
2,980,581 | 2,987,560 | Help with WinAPI scroll bars | Right now I have a window with horizontal ad vertical scrollbars. I use these parameters to initialize it.
//Set OGL Frame scroll bar
SCROLLINFO inf;
inf.cbSize = sizeof(SCROLLINFO);
inf.fMask = SIF_PAGE | SIF_POS;
inf.nPage = 20;
inf.nPos = 30;
It creates them in the center and I like their size, ... | Right, here's my solution even though one is already accepted.
Everytime I have issues with the windows controls I use Controlspy to experiment with them. Controlspy also lists all the different messages that can be sent to the different controls. Find one that is similar to what you are trying to do and check that spe... |
2,980,778 | 2,980,872 | Boost singleton trouble | I have some class which uses boost singleton. It calls some function from own c++ library. This library is written in make file as dependence.
Now I have another singleton class and it should call first singleton class. After this code I got linkers error about undefined references for functions which are used in first... | These errors indicate you're not linking correctly with Ogre.
If they disappear when Second isn't referencing First, that's because First is not being referenced/used anywhere else.
Did you try using First in your code to check whether the errors remain?
|
2,980,790 | 2,981,896 | Make function declarations based on function definitions | I've written a .cpp file with a number of functions in it, and now need to declare them in the header file. It occurred to me that I could grep the file for the class name, and get the declarations that way, and it would've worked well enough, too, had the complete function declaration before the definition -- return ... | I compiled exuberant ctags version 5.8. This command gets me what I want:
/usr/local/bin/ctags -x --c-kinds=f $SOURCE |
awk -v OFS=" " '$1=$1' |
cut -d " " -f 5- |
sed -e 's/[A-Za-z]*:://g' |
sed -e 's/)$/);/'
where you substitute the filename you are interested in in place of $SOURCE.
Note that the ctags command b... |
2,980,822 | 2,980,921 | why it is up to the compiler to decide what value to assign when assigning an out-of-range value to a variable | in C++ Primer 4th edition 2.1.1, it says "when assigning an out-of-range value to a signed type, it is up to the compiler to decide what value to assign".
I can't understand it. I mean, if you have code like "char 5 = 299", the compiler will generate asm code like "mov BYTE PTR _sc$[ebp], 43"(VC) or "movb $43, -2(%eb... | It is up to the compiler whether or not to let it be decided by the CPU. :)
The C++ standard specifies how your program should behave. The compiler ensures that this behavior is achieved. if you do something that is not specified by the standard, then the compiler can do anything it likes. It can produce an error messa... |
2,980,823 | 2,981,056 | Frame skipping with OpenGL and WinAPI? | Here is my situation. I'm creating a drawing application using OpenGL and WinAPI. My OpenGL frame has scrollbars which renders the screen and modifies GlTranslatef when it gets a scroll message. The problem is wen I get too many shapes the scrollbar is less responsive since it cannot rerender it each and every time it ... | You can measure the runtime of your draw routine. When it is greater than a threshold you decide, you should either throttle the updates or draw less (if you can).
|
2,980,909 | 3,027,026 | Is it possible to catch media stream URL of flash player using NPAPI functions? | I'm trying to make a video download panel for Chrome likes Real Player's one ( a DLL plugin )..
My question is :
"Is it possible to use NPAPI functions such as
NPP_NewStream, NPP_StreamAsFile, NPP_DestroyStream... to catch the media stream URL of flash-player ? "
If not, then what part of NPAPI do I have to use ?
| Using the NPAPI you can't magically spy on other components in the browser, the stream functions are for dealing with streams for your own plugin instance.
If the Flash player gives you access to the URL using scripting functions however, you can use the scripting extensions to get it similar to how you'd retrieve it u... |
2,980,917 | 2,981,185 | C++ - Is it possible to implement memory leak testing in a unit test? | I'm trying to implement unit testing for my code and I'm having a hard time doing it.
Ideally I would like to test some classes not only for good functionality but also for proper memory allocation/deallocation. I wonder if this check can be done using a unit testing framework. I am using Visual Assert btw. I would lov... | You can use the debug functionality right into dev studio to perform leak checking - as long as your unit tests' run using the debug c-runtime.
A simple example would look something like this:
#include <crtdbg.h>
struct CrtCheckMemory
{
_CrtMemState state1;
_CrtMemState state2;
_CrtMemState state3;
CrtCheckMemo... |
2,980,920 | 2,982,227 | Strict pointer aliasing: any solution for a specific problem? | I have a problem caused by breaking strict pointer aliasing rule. I have a type T that comes from a template and some integral type Int of the same size (as with sizeof). My code essentially does the following:
T x = some_other_t;
if (*reinterpret_cast <Int*> (&x) == 0)
...
Because T is some arbitary (other than t... | static inline int is_T_0(const T *ob)
{
int p;
memcpy(&p, ob, sizeof(int));
return p == 0;
}
void myfunc(void)
{
T x = some_other_t;
if (is_T_0(&x))
...
On my system, GCC optimizes away both is_T_0() and memcpy(), resulting in just a few assembly instructions in myfunc().
|
2,981,247 | 2,981,261 | C++, Qt - How do I get rid of dll dependencies? | I have compiled my Qt application and now have the following question - now my built project requires QtCore4.dll and QtGui4.dll to be located at the same folder where the .exe file is. (I built my project using MSVS2008 with Qt addon)
Q:
Is there any way to combine my final application with these .dll files so that th... | You need to build and link to Qt statically.
Edit: Here's an updated link to at least similar information.
|
2,981,303 | 2,981,328 | Generate set/get methods for a c++ class | Is there any tool that generates set and get methods for a class automatically.
Just I create classes very frequently and would like to have a tool which for each class-member wil generate the following functions automatically:
Member_Type getMemberName() const; //in header file
Member_Type getMemberName() const //in s... | Not the tool actually, but you could use Encapsulate Method in Visual Assist X, for example, which makes getter / setter methods for some private class member.
Sure, many of tools that work similiar as VAX do have the same methods.
Also, if you have to do this action for a huge amount of classes, you could implement yo... |
2,981,349 | 2,981,363 | C++: Question about freeing memory | On Learn C++, they wrote this to free memory:
int *pnValue = new int; // dynamically allocate an integer
*pnValue = 7; // assign 7 to this integer
delete pnValue;
pnValue = 0;
My question is: "Is the last statement needed to free the memory correctly, completly?"
I thought that the pointer *pnValue was still on the st... | Setting a pointer to NULL (or zero) after deleting it is not necessary. However it is good practice. For one thing, you won't be able to access some random data if you later dereference the pointer. Additionally, you'll often find code with the following:
if(ptr)
{
delete ptr;
ptr = NULL;
}
So setting the point... |
2,981,386 | 2,981,400 | #define usage in C/C++ | I need to write such a define in C/C++
#define scanf( fscanf(inf,
in order to replace each scanf( with fscanf(inf, literary
But I do not know how...
Thanks
| You want to use a Variadic macro.
In your case, I believe you want:
#define scanf(...) fscanf(inf,__VA_ARGS__)
|
2,981,569 | 2,981,638 | boost::function & boost::lambda - call site invocation & accessing _1 and _2 as the type | Sorry for the confusing title. Let me explain via code:
#include <string>
#include <boost\function.hpp>
#include <boost\lambda\lambda.hpp>
#include <iostream>
int main()
{
using namespace boost::lambda;
boost::function<std::string(std::string, std::string)> f =
_1.append(_2);
std::string s = f("... | You need:
boost::function<std::string(std::string, std::string)> f =
boost::bind(&std::string::append, _1, _2);
|
2,981,593 | 2,981,600 | Does the following indicate a bad design? | I was wondering whether you think the following code usually indicates a bad design ...
class X
{
public:
...
private:
Y y;
};
Class Y
{
public:
Y( X& value ){ x = value; };
private:
X& x;
}
(i.e. there is some sort of cyclic dependency between the classes X and Y).
| No, I don't think it is bad design. It looks like a parent-child relationship (which is 1-to-1) where the child has a pointer back to the parent.
The main reason for such a design is if someone could get a reference to Y without coming through X. If all access to Y are done only through X, such a reference is more que... |
2,981,621 | 2,981,629 | How to draw to screen in c++? | How would I draw something on the screen ? not the console window but the entire screen, preferably with the console minimised.
Also, would it show up on a printscreen ?
What I want to do is create something like a layer on top of the screen that only me and my aplication are aware of yet still be able to use aplicatio... | in windows you can use the GetDC-function.
just a minimalistic example:
#include <Windows.h>
#include <iostream>
void drawRect(){
HDC screenDC = ::GetDC(0);
::Rectangle(screenDC, 200, 200, 300, 300);
::ReleaseDC(0, screenDC);
}
int main(void){
char c;
std::cin >> c;
if (c == 'd') drawRect();
st... |
2,981,724 | 2,982,247 | boost::function & boost::lambda again | Follow-up to post: Using * Width & Precision Specifiers With boost::format
I'm trying to use boost::function to create a function that uses lambdas to format a string with boost::format. Ultimately what I'm trying to achieve is using width & precision specifiers for strings with format. boost::format does not support ... | I think that, for this case, you would want to use boost.bind instead of boost.lambda. Part of the problem is that boost::io::group is a function template that takes and returns a variable number of objects, making it difficult to create the appropriate signature for the function<> declaration. I would create a string ... |
2,981,827 | 2,981,867 | Strict pointer aliasing: is access through a 'volatile' pointer/reference a solution? | On the heels of a specific problem, a self-answer and comments to it, I'd like to understand if it is a proper solution, workaround/hack or just plain wrong.
Specifically, I rewrote code:
T x = ...;
if (*reinterpret_cast <int*> (&x) == 0)
...
As:
T x = ...;
if (*reinterpret_cast <volatile int*> (&x) == 0)
...
wit... | Volatile can't help you avoid undefined behaviour here. So, if it works for you with GCC it's luck.
Let's assume T is a POD. Then, the proper way to do this is
T x = …;
int i;
memcpy(&i,&x,sizeof i);
if (i==0)
…
There! No strict aliasing problem and no memory alignment problem. GCC even handles memcpy as an intrinsi... |
2,981,911 | 2,982,051 | Drawing N-width lines? | Given a series of points, how could I calculate the vector for that line 5 pixels away? Ex:
Given:
\
\
\
How could I find the vector for
\ \
\ \
\ \
The ones on the right.
I'm trying to figure out how programs like Flash can make thick outlines.
Thanks
| A thick line is a polygon. (Let's forget about antialiasing for now)
picture http://img39.imageshack.us/img39/863/linezi.png
start = line start = vector(x1, y1)
end = line end = vector(x2, y2)
dir = line direction = end - start = vector(x2-x1, y2-y1)
ndir = normalized direction = dir*1.0/length(dir)
perp = perpendicula... |
2,981,928 | 2,981,961 | How do I get the size of the boost buffer | I am trying to make an asynchronised server in visual studio and I use
boost::asio::async_read(m_socket, boost::asio::buffer(m_buffer),
boost::bind(&tcp_connection::handle_read, shared_from_this(),
boost::asio::placeholders::error));
to get the buffer to be... | boost::array has a constant size. If you want to print it as a null-terminated string, use .data() to get a const char*.
If you just want to find the position of the \0, use std::find.
int size = find(array.begin(), array.end(), '\0') - array.begin();
|
2,982,158 | 2,982,165 | c++ function overloading, making fwrite/fread act like PHP versions | I'm used to the PHP fwrite/fread parameter orders, and i want to make them the same in C++
too.
I want it to work with char and string types, and also any data type i put in it (only if length is defined).
I am total noob on c++, this is what i made so far:
Edit: fixed the std::string &buf
size_t fwrite(FILE *fp, const... | If you want to write to a file in the best possible way, you should use std::iostreams. Dealing with the length of the buffer manually is a recipe for problems.
Also, the top overload should take a const std::string&, not const std::string.
However, I don't see any actual bugs.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.