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,446,236 | 2,446,430 | C++ threaded class design from non-threaded class | I'm working on a library doing audio encoding/decoding. The encoder shall be able to use multiple cores (i.e. multiple threads, using boost library), if available. What i have right now is a class that performs all encoding-relevant operations.
The next step i want to take is to make that class threaded. So i'm wonderi... | I think the problem is more at a design level, can you elaborate a bit on what classes do you have ? I work on CUDA too, and usually one creates an interface (aka Facade pattern) for using the architecture specific (CUDA) layer.
Edit: After reading the update interface I think you are doing the right thing.
Keep the En... |
2,446,273 | 2,446,278 | Safely remove window subclassing? | I am trying to subclass the currently focused window on a Windows system using a global CBT hook. This is related to what happens in this question, but the bug is different.
What happens when this subclassing is in effect, is that Opera's (version 10.50) main window is prevented from displaying. Opera has a "splash scr... | This can happen, as Raymond Chen writes:
Consider what would happen if somebody else had subclassed the window during the "... do stuff ..." section. When we unsubclassed the window, we would have removed two subclasses, the one we installed, and the one that was installed after us. If the other subclass allocated mem... |
2,446,839 | 2,469,835 | Why I am getting a Heap Corruption Error? | I am new to C++. I am getting HEAP CORRUPTION ERROR. Any help will be highly appreciated. Below is my code
class CEntity
{
//some member variables
CEntity(string section1,string section2);
CEntity();
virtual ~CEntity();
//pure virtual function ..
virtual CEntity* create()const = 0;
};
I derive CLin... | Finally, after two days of debugging, I was able to fix up the crash. It was due to me copying wrong number of characters from the string.
Lessons learnt :
1. When you encounter memory allocation errors, try to form a simple test case which has minimum entities to reproduce the problem.
2. A sure shot way is a line by ... |
2,447,172 | 2,447,245 | getting window screenshot windows API | I am trying to make a program to work on top of an existing GUI to annotate it and provide extra calculations and statistical information. I want to do this using image recognition, as I have learned a fair amount about this in University using Matlab and similar things. I can get a handle to the window I want to perfo... | One simple way is using the PrintWindow API (which is an automated Alt + Print basically). The following example takes a screenshot of the calculator, but you would just have to replace the handles.
void CScreenShotDlg::OnPaint()
{
// device context for painting
CPaintDC dc(this);
// Get the window handle ... |
2,447,271 | 2,447,300 | convert perl map with multiple key to c++ | I want to convert a code from perl to c++, and my problem is multi key map in perl!
example:
perl:
$address{name}{familyName} = $someAddress;
and keys are not unique.
I want similar data structure in c++ using map or ...!?
also I want to search and obtain values with first key for example I want such %keys{name} in c+... | You want something like:
#include <map>
#include <string>
struct Person {
Person( const std::string & n, const std::string & f )
: name( n ), family( f ) {}
bool operator<( const Person & p ) const {
if ( family < p.family ) return true;
else if ( family == p.family ) return name < p.name;... |
2,447,310 | 2,447,381 | Compiling C++ when two classes refer to one another | I am trying to write a simple wrapper around a connection pointer that will return it to the pool when the wrapper is destroyed, but it wont compile because the ConnectionPool and AutoConn need each other to be declared.
I tried to use forward deceleration but it didn't work. How do I solve this? (using g++)
class Conn... | A combination of forward declaration and separation of declaration from definition of members with circular dependencies works. For example:
class Connection {};
class ConnectionPool ;
class AutoConn
{
ConnectionPool* m_pool;
Connection *m_connection;
public:
AutoConn(ConnectionPool* pool, Connection *c)... |
2,447,392 | 2,448,318 | Does std::vector change its address? How to avoid | Since vector elements are stored contiguously, I guess it may not have the same address after some push_back's , because the initial allocated space could not suffice.
I'm working on a code where I need a reference to an element in a vector, like:
int main(){
vector<int> v;
v.push_back(1);
int *ptr = &v[0];... | Don't use reserve to postpone this dangling pointer bug - as someone who got this same problem, shrugged, reserved 1000, then a few months later spent ages trying to figure out some weird memory bug (the vector capacity exceeded 1000), I can tell you this is not a robust solution.
You want to avoid taking the address o... |
2,447,458 | 2,447,556 | Default template arguments for function templates | Why are default template arguments only allowed on class templates? Why can't we define a default type in a member function template? For example:
struct mycclass {
template<class T=int>
void mymember(T* vec) {
// ...
}
};
Instead, C++ forces that default template arguments are only allowed on a class temp... | It makes sense to give default template arguments. For example you could create a sort function:
template<typename Iterator,
typename Comp = std::less<
typename std::iterator_traits<Iterator>::value_type> >
void sort(Iterator beg, Iterator end, Comp c = Comp()) {
...
}
C++0x introduces them to ... |
2,447,696 | 2,447,716 | Overloading assignment operator in C++ | As I've understand, when overloading operator=, the return value should should be a non-const reference.
A& A::operator=( const A& )
{
// check for self-assignment, do assignment
return *this;
}
It is non-const to allow non-const member functions to be called in cases like:
( a = b ).f();
But why should it... | Not returning a reference is a waste of resources and a yields a weird design. Why do you want to do a copy for all users of your operator even if almost all of them will discard that value?
a = b; // huh, why does this create an unnecessary copy?
In addition, it would be surprising to users of your class, since the b... |
2,448,058 | 2,452,672 | Boost.MultiIndex: How to make an effective set intersection? | assume that we have a data1 and data2. How can I intersect them with std::set_intersect()?
struct pID
{
int ID;
unsigned int IDf;// postition in the file
pID(int id,const unsigned int idf):ID(id),IDf(idf){}
bool operator<(const pID& p)const { return ID<p.ID;}
};
struct ID{};
struct IDf{};
... | std::set_intersection(
L1_ID_index.begin(),L1_ID_index.end(),
L2_ID_index.begin(),L2_ID_index.end(),
output_iterator,
L1_ID_index.value_comp());
|
2,448,155 | 2,448,269 | SetThreadName not working with Visual Studio 2005 | SetThreadName does not set thread name with Visual Studio 2005, when used as below:
DWORD threadId;
HANDLE handle = CreateThread(NULL, stackSize, ThreadFunction,
ThreadParam, CREATE_SUSPENDED, &threadId);
if (handle)
{
SetThreadName(threadId, "NiceName");
ResumeThread(handle);
}
Aft... | After a few experiments I have found it is because the Visual Studio is trying to be smart and when the thread begins to execute it gives a name to itself. The workaround is not to try to give the name to thread before the thread has actually started, the easiest way how to achieve this is to call the SetThreadName fr... |
2,448,160 | 2,448,478 | Looking for design advise - Statistics reporter | I need to implement a statistics reporter - an object that prints to screen bunch of statistic.
This info is updated by 20 threads.
The reporter must be a thread itself that wakes up every 1 sec, read the info and prints it to screen.
My design so far: InfoReporterElement - one element of info. has two function, PrintI... | I would say that first of all, the Reporter itself should be a thread. It's basic in term of decoupling to isolate the drawing part from the active code (MVC).
The structure itself is of little use here. When you reason in term of Multithread it's not so much the structure as the flow of information that you should che... |
2,448,242 | 2,448,307 | Struct with template variables in C++ | I'm playing around with templates. I'm not trying to reinvent the std::vector, I'm trying to get a grasp of templateting in C++.
Can I do the following?
template <typename T>
typedef struct{
size_t x;
T *ary;
}array;
What I'm trying to do is a basic templated version of:
typedef struct{
size_t x;
int *ary;
}iA... | The problem is you can't template a typedef, also there is no need to typedef structs in C++.
The following will do what you need
template <typename T>
struct array {
size_t x;
T *ary;
};
|
2,448,302 | 2,448,457 | container won't sort, test case included, (easy question?) | I can't see what I'm doing wrong. I think it might be one of the Rule of Three methods. Codepad link
#include <deque>
//#include <string>
//#include <utility>
//#include <cstdlib>
#include <cstring>
#include <iostream>
//#include <algorithm> // I use sort(), so why does this still compile when commented ou... | I just kept messing around, and realized that my assignment operator needs to copy all the other parameters over as well, not just the heap allocated ones.
Man do I feel dumb. >_<
Btw followup question: Is there a way to do the sorting without needing to strncpy() all the buffers and just swap the pointer addresses aro... |
2,448,380 | 2,448,431 | C++ expected constant expression | #include <iostream>
#include <fstream>
#include <cmath>
#include <math.h>
#include <iomanip>
using std::ifstream;
using namespace std;
int main (void)
{
int count=0;
float sum=0;
float maximum=-1000000;
float sumOfX;
float sumOfY;
int size;
int negativeY=0;
int positiveX=0;
int negativeX=0;
ifstream points; //the poi... | float x[size][2];
That doesn't work because declared arrays can't have runtime sizes. Try a vector:
std::vector< std::array<float, 2> > x(size);
Or use new
// identity<float[2]>::type *px = new float[size][2];
float (*px)[2] = new float[size][2];
// ... use and then delete
delete[] px;
If you don't have C++11 ava... |
2,448,463 | 2,448,500 | Vector of vectors of T in template<T> class | Why this code does not compile (Cygwin)?
#include <vector>
template <class Ttile>
class Tilemap
{
typedef std::vector< Ttile > TtileRow;
typedef std::vector< TtileRow > TtileMap;
typedef TtileMap::iterator TtileMapIterator; // error here
};
error: type std::vector<std::vector<Ttile, std::allocator<_CharT... | Because the TtileMap::iterator is not known to be a type yet. Add the typename keyword to fix it
typedef typename TtileMap::iterator TtileMapIterator;
|
2,448,501 | 2,448,567 | Does the compiler optimize the function parameters passed by value? | Lets say I have a function where the parameter is passed by value instead of const-reference. Further, lets assume that only the value is used inside the function i.e. the function doesn't try to modify it. In that case will the compiler will be able to figure out that it can pass the value by const-reference (for perf... | If you pass a variable instead of a temporary, the compiler is not allowed to optimize away the copy if the copy constructor of it does anything you would notice when running the program ("observable behavior": inputs/outputs, or changing volatile variables).
Apart from that, the compiler is free to do everything it w... |
2,448,715 | 2,466,675 | Verbosity in boost asio using ssl | Is there a way to make ssl handshake more visible to me using boost asio?
I am getting an error: "asio.ssl error".
I just want more verbosity, because this message means almost nothing to me.
| I found that boost.asio with ssl use openssl.
I just need to recompile the libssl with debug flags to make ssl handshake process more verbose. I can do this just reconfiguring with './config -DKSSL_DEBUG'.
In the boost documentation I found no way to control the verbosity level.
|
2,448,738 | 2,448,846 | How to force a window to maintain a certain width/height ratio when resized | I want my window to always maintain a certain ratio of let's say 1.33333333. So, if the window is width = 800, height = 600 and the user changes the width to 600, I want to change the height to 450 automatically.
I'm already intercepting WM_SIZE but I don't know if it's enough; also I don't know how to change the width... | WM_SIZING is sent to the window while the user is resizing the window.
Rather handle WM_WINDOWPOSCHANGING - this is sent by the internal SetWindowPos function when code (or the user) changes the window size and will ensure that even tile & cascade operations obey your sizing policy.
|
2,448,802 | 2,449,201 | Chaining multiple ShellExecute calls | Consider the following code and its executable - runner.exe:
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
SHELLEXECUTEINFO shExecInfo;
shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shExecInfo.fMask = NULL;
shExecInfo.hwnd = NULL;
... | You have a bug in this line:
Params += argv[i] + ' ';
This will add 32 to the pointer argv[i], which isn't what you want. You can separate it to two lines:
Params += argv[i];
Params += ' ';
Or use:
Params += string(argv[i]) + ' ';
You may also want to add quotes around each parameter in case it contains spaces.
I'd... |
2,448,823 | 2,448,860 | Program compiled with MSVC 9 won't start on a vanilla SP3 XP | I installed XP on a virtual machine, updated it to SP3 and then tested a small program compiled with Visual C++ 2008 on my real computer - however it didn't start but outputted only an error saying that a problem had been detected and that a reinstall of the application (mine is 10KB in size and doesn't even have an in... | Either link statially against the runtime library (select multithreaded instead of multithreaded-dll) or follow tommieb75's advice and install the MSVC9 runtime redistributable (copying to system32 or to the application's folder works as well, but is not the way to go, afaik). For small applications with no need for an... |
2,448,879 | 2,448,962 | When will DllMain be called with the DLL_PROCESS_VERIFIER flag? | On Windows, the standard DLL entry point is called DllMain. The second parameter is a DWORD, ul_reason_for_call.
I have looked up the possible values for this second parameter on MSDN. The following are obvious:
DLL_PROCESS_ATTACH:
DLL_THREAD_ATTACH:
DLL_THREAD_DETACH:
DLL_PROCESS_DETACH:
But what about:
DLL_PROCESS_V... | I guess in theory Microsoft could invent new usages and flags any time they feel they need a new one. So the simple rule is to ensure that your code tolerates unexpected values: i.e. write it to handle the cases that you need to handle and ignore the rest, by returning zero.
|
2,449,159 | 2,449,654 | Linux time sample based profiler | short version:
Is there a good time based sampling profiler for Linux?
long version:
I generally use OProfile to optimize my applications. I recently found a shortcoming that has me wondering.
The problem was a tight loop, spawning c++filt to demangle a c++ name. I only stumbled upon the code by accident while chasin... | Glad you asked. I believe OProfile can be made to do what I consider the right thing, which is to take stack samples on wall-clock time when the program is being slow and, if it won't let you examine individual stack samples, at least summarize for each line of code that appears on samples, the percent of samples the l... |
2,449,271 | 2,449,330 | How to iterate on boost::mutable_queue | I need a priority queue where I can increase or decrease the priority key. So boost::mutable_queue seemed perfect despite the lack of documentation.
The problem is that I need to iterate at some point over all the elements in the queue. How can I do that?
Or is there an othe data structure that would work (preferably i... | Queues are not for iteration. The whole point of a queue is that you can only ever look at the element at the front of the queue.
If you want to iterate then I suggest just using an std::set, which is ordered. When you want to modify an element, you'll have to remove it and reinsert it with the new key. You can get the... |
2,449,386 | 2,449,404 | What does deleting a pointer mean? | Is deleting a pointer same as freeing a pointer (that allocates the memory)?
| Deleting a pointer (or deleting what it points to, alternatively) means
delete p;
delete[] p; // for arrays
p was allocated prior to that statement like
p = new type;
It may also refer to using other ways of dynamic memory management, like free
free(p);
which was previously allocated using malloc or calloc
p = mallo... |
2,449,405 | 2,449,773 | How can I declare constant strings for use in both an unmanaged C++ dll and in a C# application? | Curently I'm passing my const string values up from my C++ into my C# at startup via a callback, but I'm wondering if there's a way of defining them in a C++ header file that I can then also refer to in C#.
I already do this with enums as they are easy.
I include a file in both my C++ library project (via a .h file wit... | Call me funny, but I think the best way to do this is using C++/CLI and C++.
This lets you #include the same strings into two different contexts and let the compiler do the magic.
This will give you arrays of strings
// some header file
L"string1",
L"string2",
L"string3",
// some C++ file
static wchar_t*[] string = {
... |
2,449,578 | 2,449,617 | Implicit casting Integer calculation to float in C++ | Is there any compiler that has a directive or a parameter to cast integer calculation to float implicitly. For example:
float f = (1/3)*5;
cout << f;
the "f" is "0", because calculation's constants(1, 3, 10) are integer. I want to convert integer calculation with a compiler directive or parameter. I mean, I won't use ... | If you don't like either of the two methods you mentioned, you're probably out of luck.
What are you hoping to accomplish with this? Any specialized operator that did "float-division" would have to convert ints to floats at some point after tokenization, which means you're not going to get any performance benefit on t... |
2,450,155 | 2,450,211 | C++ Perfect Number. Need some help revising | I need some help revising this. It keeps only displaying 0s as the temp. Thank you.
// A program to determine whether the input number is a perfect number
// A perfect number is defined by the sum of all its positive divisors excluding itself
// 28: 1+2+3+7+14 = 28.
int perfect, limit, divisor;
cout << "Please enter... | I'm not sure, but I'd guess that in the code:
if ((perfect % divisor) == 0)
divisor = prevtemp;
you intended this to be prevtemp=divisor instead. That fixes an obvious problem, but still leaves quite a bit that doesn't look like it's doing that you probably intended. For example, I can't quite figure out what limi... |
2,450,270 | 2,480,875 | Getting a shared pointer to a derived class when base class inherits from enable_shared_from_this | I have a class B which inherits from A which in turn derives from enabled_shared_from_this. Now, I want to get a shared pointer to B from an instance of B. shared_from_this will return shared_ptr<A>, not shared_ptr<B>. Should I use boost::static_pointer_cast here? Or is there a better way?
| This seems to be a valid approach as the type is known at compile time.
|
2,450,279 | 2,450,357 | How to set bit values which are not divided on byte boundary | I have a header field of 2 bytes where first four bits are packet type and other 12 bits are for length. but i don't know how to store this values and retrieve them.
I am using ms c++ for client and java for server. It is the client which has to set this values and server has to retrieve it.
Thanks
| Storing
unsigned short get_header(unsigned char type, unsigned short length)
{
return (static_cast<unsigned short>(type) << 12) | length;
}
Retrieving (from unsigned short)
unsigned short header = /* get 2 header bytes */
unsigned char type = header >> 12;
unsigned short length = header & 0xFFF;
Retrieving (fro... |
2,450,340 | 2,450,451 | Ignore carriage returns in scanf before data.... to keep layout of console based graphics with conio.h | I have the misfortune of having use conio.h in vc++ 6 for a college assignment,
My problem is that my graphic setup is in the center of the screen...
e.g.
gotoxy( getcols()/2, getrows()/2);
printf("Enter something");
scanf( "%d", &something );
now if someone accidentally hits enter before they enter the "something... | The road to success will involve doing what the assignment asks you to do :) In particular, you should use one or more functions from conio.h to read your input. scanf() is not a conio.h function.
Because I'm lazy this is a homework question, I won't write the code for you.
One possibility would be to use cscanf() rat... |
2,450,408 | 2,450,437 | How to implement a network protocol? | Here is a generic question. I'm not in search of the best answer, I'd just like you to express your favourite practices.
I want to implement a network protocol in Java (but this is a rather general question, I faced the same issues in C++), this is not the first time, as I have done this before. But I think I am missi... | Read up on the State design pattern to learn how to avoid lots of switch statements.
"sometimes what comes out has some "blind spot", I mean statuses of the protocol that have not been covered..."
State can help avoid gaps. It can't guarantee a good design, you still have to do that.
"...as I have to write lines and ... |
2,450,982 | 2,451,012 | C++ stl collections or linked lists | I'm developing a OpenGL based simulation in C++. I'm optmizing my code now and i see throughout the code the frequently use of std:list and std:vector. What is the more performatic: to continue using C++ stl data structs or a pointer based linked list? The main operation that involve std::list and std::vector is open a... | How about stl containers of pointers?
It is highly unlikely that you will be able to develop better performing structures than the builtin. The only down part is the containers actually do contain copies of objects stored in them. If you're worried about this memory overhead (multiple structs hodling multiple copies of... |
2,451,103 | 2,451,190 | Use WM_COPYDATA to send data between processes | I wish to send text between processes. I have found lots of examples of this but none that I can get working. Here is what I have so far:
for the sending part:
COPYDATASTRUCT CDS;
CDS.dwData = 1;
CDS.cbData = 8;
CDS.lpData = NULL;
SendMessage(hwnd, WM_COPYDATA , (WPARAM)hwnd, (LPARAM) (LPVOID) &CDS);
the receiving par... | For an example of how to use the message, see http://msdn.microsoft.com/en-us/library/ms649009(VS.85).aspx. You may also want to look at http://www.flounder.com/wm_copydata.htm.
The dwData member is defined by you. Think of it like a data type enum that you get to define. It is whatever you want to use to identify t... |
2,451,175 | 2,451,212 | C++: Vector3 type "wall"? | Say I have:
class Vector3 {
float x, y, z;
... bunch of cuntions ..
static operator+(const Vector3&, const Vector3);
};
Now, suppose I want to have classes:
Position, Velocity,
that are exactly like Vector3 (basically, I want
typedef Vector3 Position;
typedef Vector3 Velocity;
Except, given:
Position positio... | I would recommend something like this:
template<typename tag>
class Vector3 {
float x, y, z;
... bunch of functions ..
static operator+(const Vector3&, const Vector3);
};
struct position_tag {};
struct velocity_tag {};
typedef Vector3<position_tag> Position;
typedef Vector3<velocity_tag> Velocity;
See here for ... |
2,451,209 | 2,456,604 | How could I redirect stdin (istream) in wxWidgets? | I'm trying to figure out how to redirect istream to wxwidgets.
I was able to accomplish redirecting ostream, here's how (so you know what I mean):
wxTextCtrl* stdoutctrl = new wxTextCtrl(...);
wxStreamToTextRedirector redirect(stdoutctrl); //Redirect ostream
std::cout<<"stdout -- does this work?"<<std::endl; //It... | No, there is no built in way to do this as it's much less common to want to redirect cin like this compared to cout. And it's also not really clear how do you expect it to work, i.e. you probably can't just map it to a wxTextCtrl as you do with cout. And more generally, reading is a blocking operation, unlike writing, ... |
2,451,214 | 2,451,224 | C++ Why is the converter constructor implicitly called? | Why is the Child class's converter constructor called in the code below?
I mean, it automatically converts Base to Child via the Child converter constructor. The code below compiles, but shouldn't it not compile since I haven't provided bool Child::operator!=(Base const&)?
class Base
{
};
class Child : public Base
{
p... | Because you provided a conversion constructor. If you don't want the compiler to automatically convert Base objects to Child using the
Child(Base const& base_)
constructor, make it explicit:
explicit Child(Base const& base_)
This way, the constructor will only be called when you explicitly specify it, in contexts lik... |
2,451,370 | 2,451,378 | Write a function in c that includes the following sequence of statements [Wont Compile] | There is a question in my programming languages textbook that is as follows:
Write a C function that includes the
following sequence of statements:
x = 21;
int x;
x = 42;
Run the program and explain the
results. Rewrite the same code in C++
and Java and compare the results.
I have written code, and played w... | Note the following requires C99:
int x;
void foo()
{
x = 21;
int x;
x = 42;
}
Since this is homework, you'll need to provide your own explanation.
|
2,451,415 | 2,451,701 | Why can't I input the integers from a file? | I'm trying to get this C++ code to input a series of numbers from a text file:
int x = 0;
cin >> x;
ifstream iffer;
int numbers[12];
iffer.open("input.txt");
for (int i = 0; i < 12; i++){
iffer >> numbers[i];
}
This doesn't seem to work on the Mac.
Every cell will equal to 0 regard... | I tried your code, slightly modified, on both Linux (g++ 3.4.4) and Mac (g++ 4.0.1) and it works just fine!
With respect to Chuck, if input.txt does not exist, iffer.fail() is true. Since you say that's not the case...
Another possibility is a different input.txt file than what you expected. If it had too few numbers... |
2,451,548 | 2,451,784 | iPhone - OpenGL using C++ tutorial/snippet | Is there any good tutorial or code snippet out there on how to use OpenGL via C/C++ on the iPhone?
| http://developer.apple.com/iphone/library/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html
I'm pretty sure you need a bit of Objective-C to create the context and do other initialization stuff. The rest is also usable in C++.
|
2,451,624 | 2,451,674 | How to get unsigned equivalent of an integral type in C++? | Is there a way to get an unsigned equivalent (same size) of a signed integral type in C++? I'm thinking along the lines of:
template<typename T>
struct get_unsigned { };
template<>
struct get_unsigned<int> {
typedef unsigned int type;
};
...
template<typename T>
void myfunc(T val) {
get_unsigned<T>::type u =... | Boost.TypeTraits has make_unsigned:
type: If T is a unsigned integer type then the same type as T, if T is an signed integer type then the corresponding unsigned type. Otherwise if T is an enumerated or character type (char or wchar_t) then an unsigned integer type with the same width as T.
If T has any cv-qualifiers ... |
2,451,681 | 2,451,700 | Why do I need to include both the iostream and fstream headers to open a file | #include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("test.txt");
return 0;
}
fstream is derived from iostream, why should we include both in the code above?
I removed fstream, however, there is an error with ofstream. My question is ofstream is derived from os... | You need to include fstream because that's where the definition of the ofstream class is.
You've kind of got this backwards: since ofstream derives from ostream, the fstream header includes the iostream header, so you could leave out iostream and it would still compile. But you can't leave out fstream because then you ... |
2,451,714 | 2,451,890 | Access Violation When Accessing an STL Object Through A Pointer or Reference In A Different DLL or EXE | I experience the following problem while using legacy VC6. I just cann't switch to modern compiler, as I am working on a legacy code base.
http://support.microsoft.com/kb/172396
Since there are no way to export map, my planned workaround is using static linking instead of dynamic linking.
I was wondering whether you al... | The KB article you linked is old, it was written before VS2008 came out. It doesn't solve the problem, it is a fundamental limitation of C++. There is no mechanism to verify that classes in separately built binaries have compatible memory layouts and were allocated with the same memory allocator.
Things you can do to... |
2,452,132 | 2,453,300 | Does it ever make sense to make a fundamental (non-pointer) parameter const? | I recently had an exchange with another C++ developer about the following use of const:
void Foo(const int bar);
He felt that using const in this way was good practice.
I argued that it does nothing for the caller of the function (since a copy of the argument was going to be passed, there is no additional guarantee of... | Remember the if(NULL == p) pattern ?
There are a lot of people who will tell a "you must write code like this":
if(NULL == myPointer) { /* etc. */ }
instead of
if(myPointer == NULL) { /* etc. */ }
The rationale is that the first version will protect the coder from code typos like replacing "==" with "=" (because it i... |
2,452,278 | 2,452,303 | Problem with memset after an instance of a user defined class is created and a file is opened | I'm having a weird problem with memset, that was something to do with a class I'm creating before it and a file I'm opening in the constructor. The class I'm working with normally reads in an array and transforms it into another array, but that's not important. The class I'm working with is:
#include <vector>
#include ... | You use memset() like this:
memset(matrix,0,sizeof(matrix));
Here matrix is a pointer, so sizeof(matrix) gives the size of a pointer, not the size of the array. To fill the whole array, use columns * rows * sizeof(int) instead.
|
2,452,283 | 2,452,392 | Turn off the warnings due to boost library | I am building an application in C++, Mac OS X, Qt and using boost libraries. Every time I build a project I get a huge list of warnings only from boost libraries itself.
How to turn them off, so that I can see only my project specific warnings and errors?
| Use -isystem instead of -I to add Boost headers to include path. This option means to treat headers found there as system headers, and suppress warnings originating there.
|
2,452,393 | 2,452,501 | std::iostream link error vs2010 rc1 | I'm converting a project from vs2008 to vs2010 and getting linker errors for std:ifstream/ofstream
error LNK2001: unresolved external symbol "__declspec(dllimport) public: bool __thiscall std::basic_ofstream<char,struct std::char_traits<char> >::is_open(void)const " (__imp_?is_open@?$basic_ofstream@DU?$char_traits@D@st... | If you don't get an answer for this particular problem, there is a brute force approach that I've used with great success:
Using Visual Studio 2010, create a new project of the same type in a temporary folder somewhere (use the same project and solution name), and make sure you use the same options as your VS2008 proje... |
2,452,398 | 2,452,466 | Splash screen in Windows | How can I display a splash screen using C or C++ in Windows? What libraries or Windows components would be applicable?
| Try to create a window with the createwindowex function and use the style (dwStyle) WS_POPUP.
You can read about CreateWindowEx here.
|
2,452,457 | 2,452,511 | Network file transfer in Windows | I want to transfer files across the network using C or C++. What topics should I look up? How can I do this?
| While you could use ReadFile to read the file's contents and then send it over a socket, Windows also provides the TransmitFile API to enable you to read a file's data and send it over a socket with one system call.
|
2,452,476 | 2,452,494 | Auto-Update for a Windows application | Is there an open source project that allows for an auto-update of windows binaries? The Luau update library is very similar to what I'm looking for but it was abandoned in 2005.
| Google Omaha . But I have not tried it and don't know how easy it is to use.
|
2,452,510 | 2,452,556 | Doesn't the Visual Studio 2008 compiler autocast to double with sqrt in C++? | Shouldn't the compiler automatically cast to a double in the following? At least according to Walter Savitch.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int k;
for(k = 1; k <= 10; k++)
cout << "The square root of k is: " << sqrt(k) << endl;
return 0;
}//error C2668: 'sqrt... | The problem is that there are three versions of sqrt to choose from:
double sqrt ( double x );
float sqrt ( float x );
long double sqrt ( long double x );
Since you're passing in an int, the compiler is going to promote your argument but it's equally valid to promote your integer to any of the ab... |
2,452,561 | 2,494,462 | OutputDebugString + DebugView = not tabs! | I am dumping \t delimited data using using OutputDebugString and then use ex-Sysinternals DebugView to capture it.
The problem is that all the data in DebugView appear to be space delimited, hence I need to perfrorm CTRL+H "\x20" "t" to replace spaces with the tabs before I can use it (I really need tab delimited data... | It seems this is a "feature" in DebugView. I have tried with Hoo Wintail and this dude collects tabs without any problem. So I see 3 solutions:
You get Hoo Wintail (highly recommended)
You write your on tool (look here for some idea how to do it or even get a complete one)
You redirect to file.
I strongly vote for op... |
2,452,576 | 2,452,596 | Run process in .NET and C++ | I search for the function that run programm by path, and working of main programm is stopped until run second programm. Can i do that by using System.Diagnostics.Process class?
| look at this question
Use this if you want to just use the win32 api
#include <stdio.h>
#include <Windows.h>
int main(int argc, char ** argv)
{
STARTUPINFO SI;
PROCESS_INFORMATION PI;
memset(&SI,0,sizeof(SI));
memset(&PI,0,sizeof(PI));
SI.cb = sizeof(SI);
//ProcessorCap
if(!CreateProcess(NULL,"Notepad.exe "... |
2,452,728 | 2,452,787 | Is it a good design to return value by parameter? | bool is_something_ok(int param,SomeStruct* p)
{
bool is_ok = false;
// check if is_ok
if(is_ok)
// set p to some valid value
else
// set p to NULL
return is_ok;
}
this function return true and set p to a valid value if "something is ok"
otherwise return false and set p to NULL
Is th... | Since you have tagged the question as C++ and not C, I would suggest you to:
return the value directly
if you have more than one value, use output parameters
use non-const references as output parameter where possible (instead of pointers), and use const-references for the input parameters.
if something went wrong, ra... |
2,452,872 | 2,453,481 | Visual C++ 9 compiler options to make the program run faster | I have built an open-source application from the source code. Unfortunately, the original executable runs significantly faster. I tried to enable few compiler optimizations, but the result wasn't satisfactory enough. What else do I need to make in Visual Studio 2008 to increase the executable performance?
Thanks!
| Basically try enabling everything under Optimisation in project settings, then ensure Link Time Code Generation is on, enable Function-level linking and full COMDAT folding (that only reduces the size of the EXE but could help with caching), and turn off security features such as by defining _SECURE_SCL=0. Remember so... |
2,452,880 | 2,452,928 | What is the best and useful debug tool in Linux environment for Perl and C++ scripts? | What is the best and useful debug tool in Linux environment for Perl and C++ scripts?
In related to that, does anyone know the differences between Eclipse to DDD tools?
Thank you,
YoDar.
| Sorry, I don't do Perl.
But I do Eclipse & DDD.
Eclipse is an IDE (which also supports Perl). IF you use C/C++, for instance, it supports the GDB. If you can compile Perl, it will probably support that too, which means that you can step through your code, line by line, examining the call stack, looking at variables, ch... |
2,453,048 | 2,455,729 | How can i hold reference in boost::shared_ptr using boost::bind without definition of explicit function? | I want to hold reference to object so it doesn't get deleted in bind function, but without using helper function.
struct Int
{
int *_int;
~Int(){ delete _int; }
};
void holdReference(boost::shared_ptr<Int>, int*) {} // helper
boost::shared_ptr<int> fun()
{
boost::shared_ptr<Int> a ( new Int );
// I get '... | You may be looking for the "shared ownership" constructor, this allows ref counting an interior pointer.
struct Int
{
int *_int;
~Int(){ delete _int; }
};
boost::shared_ptr<int> fun()
{
boost::shared_ptr<Int> a (new Int);
a->_int = new int;
// refcount on the 'a' instance but expose the interior _int p... |
2,453,189 | 2,453,212 | How to produce 64 bit masks? | Based on the following simple program the bitwise left shift operator works only for 32 bits. Is it true?
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void)
{
long long currentTrafficTypeValueDec;
int input;
cout << "Enter input:" << endl;
cin >> input... | Make input an long long too, and use 1LL << (input - 1LL). Here your shift is computed on 32 bits, and converted to 64 bits when stored in currentTrafficTypeValueDec.
|
2,453,191 | 2,453,260 | How get Win32_OperatingSystem.LastBootUpTime in datetime format | I have been trying to get LastBootUpTime using Win32_OperatingSystem class (WMI).
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn)
{
break;
}
VARIANT vtProp;
// Get the value of the Name property
hr = pclsObj->Get(L"LastBootUpTime", 0, &v... | You'll have to do some parsing to convert it. The format is yyyyMMddhhmmss.ffffff+zzz (zzz is UTC offset in minutes). The SWbemDateTime.GetVarDate() method can do it for you.
|
2,453,225 | 2,453,388 | Is there any need for me to use wstring in the following case | Currently, I am developing an app for a China customer. China customer are mostly switch to GB2312 language in their OS encoding. I need to write a text file, which will be encoded using GB2312.
I use std::ofstream file
I compile my application under MBCS mode, not unicode.
I use the following code, to convert CString... | About 1. Endianness is a problem you meet when you serialize a unit in term of smaller units (i.e. serialize seizets in term of octets). I'm far from being a specialist of CJK encodings, but it seems to me that GB2112 is a coded character set which can be used with several encoding schemes. The encoding schemes cite... |
2,453,318 | 2,459,031 | Get application icon from ProcessSerialNumber | I would like to get the application icon for all foreground applications running on my Mac. I'm already iterating over all applications using the Process Manager API. I have determined that any process that does not have the modeBackgroundOnly flag set in the processMode (as retrieved from GetProcessInformation()) is a... | On Mac OS X 10.6 or later, you can ask a running application for its icon.
On earlier versions of Mac OS X, you'll have to get it by looking at the application's bundle. Pass the PSN to the GetProcessBundleLocation function to get the bundle's location as an FSRef, then pass that to the GetIconRefFromFileInfo function.... |
2,453,367 | 2,453,489 | Abstract base class puzzle | In my class design I ran into the following problem:
class MyData
{
int foo;
};
class AbstraktA
{
public:
virtual void A() = 0;
};
class AbstraktB : public AbstraktA
{
public:
virtual void B() = 0;
};
template<class T>
class ImplA : public AbstraktA
{
public:
void A(){ cout << "ImplA A()"; } ... | You have two paths of inheritance from AbstracktA, you implement AbstraktA::A() only in one of them, so the compiler complains.
You probably want to inherit virtually from AbstraktA in both case so that there is only one AbstraktA base object (add virtual before AbstraktA).
|
2,453,399 | 2,577,475 | How to make Visual C++ 9 not emit code that is actually never called? | My native C++ COM component uses ATL. In DllRegisterServer() I call CComModule::RegisterServer():
STDAPI DllRegisterServer()
{
return _Module.RegisterServer(FALSE); // <<< notice FALSE here
}
FALSE is passed to indicate to not register the type library.
ATL is available as sources, so I in fact compile the impleme... | Turns out the key is to enable link-time code generator all the way through the compiler settings.
It must be enabled on the General tab - Whole program optimization must be set to "Use link-time code generation". It must also be enabled on the C++ -> Optimization tab - "Whole program optimization* must be set to "Enab... |
2,453,417 | 2,469,118 | LsaCallAuthenticationPackage returns ERROR_INVALID_PARAMETER 87 (0x57) when trying to purge a specific ticket | I'm trying to purge a specific ticket from the cache,using LsaCallAuthenticationPackage.
I always get ERROR_INVALID_PARAMETER 87 in the package status.
What could be the reason?
Here is my code (All other steps succeeded):
KERB_QUERY_TKT_CACHE_REQUEST tktCacheRequest = {
KerbQueryTicketCacheMessage};
void* ... | I kust use the memory allocation model as in the original Microsoft's klist (found in Microsoft Windows Platform SDK's samples), and got it works.
Thanks.
|
2,453,425 | 2,453,456 | How can i sort a map by its .second parameter | If i have a stl map from string to int and i want to print all the int values sorted - how can i do that?
| You cannot sort a map by its values due to the implementation of the map.
If you want to emit the elements in the map in such a sorted order then you have to first dump the map contents into a vector (say) and sort that vector:
template <typename T1, typename T2>
struct less_second {
typedef pair<T1, T2> type;
... |
2,453,476 | 2,453,519 | To catch or not to catch | Should application catch "bad" signals such as SIGSEV, SIGBUS?
| Those signals are produced in "should never happen" circumstances, when your program is in an undefined state. If you did catch them, continuing execution would be extremely problemeatic, as it would almost certainly cause more, possibly even more severe, errors. Also, if you don't catch them, the OS may be able to do ... |
2,453,865 | 2,453,913 | why Floating point exception? | I have a floating point exception, and I don't know why.
the code is this:
void calcola_fitness(){
vector<double> fitness;
int n=nodes.size();
int e=edges.size();
int dim=feasibility.size();
int feas=(feasibility[dim-1])*100;
int narchi=numarchicoll[dim-1]/e;
int numero_nodi=freePathNode.siz... | "Floating point exception" (SIGFPE) is actually a misnomer. Any kinds of arithmetics exception will trigger SIGFPE. This includes divide-by-zero.
You should check if nodes and edges are empty.
|
2,453,867 | 2,453,884 | GCC problem: in template | i have redhat with gcc 4.1.1 i have compile as "gcc test.c" and give the following error
Error : expected '=' ,',' , ';' , ásm' or '__ attribute__' before '<' token
the code in "test.c" is as follow
template <typename T> class A {
public:
T foo;
};
| This is C++ code, not C. You need to use g++, i.e. g++ test.c. Also, to avoid confusion, you should rename your file to end with .cpp or .cxx.
|
2,454,019 | 2,454,082 | Why aren't static const floats allowed? | I have a class which is essentially just holds a bunch of constant definitions used through my application. For some reason though, longs compile but floats do not:
class MY_CONSTS
{
public :
static const long LONG_CONST = 1; // Compiles
static const float FLOAT_CONST = 0.001f; // C2864
};
Gives the fo... | To answer the actual question you asked: "because the standard says so".
Only variables of static, constant, integral types (including enumerations) may be initialized inside of a class declaration. If a compiler supports in-line initialization of floats, it is an extension. As others pointed out, the way to deal with ... |
2,454,483 | 2,454,754 | inserting std::strings in to a std::map | I have a program that reads data from a file line-by-line. I would like to copy some substring of that line in to a map as below:
std::map< DWORD, std::string > my_map;
DWORD index; // populated with some data
char buffer[ 1024 ]; // populated with some data
char* element_begin; // points to some location in bu... | To answer your supplementary question slightly. Try changing the map temporarily to a vector of strings, and then time it inserting a fixed string value into the vector For example:
vector <string> v;
string s( "foobar" );
your insert loop:
v.push_back( s );
That should give you a lower bound of what is possible r... |
2,454,817 | 2,455,080 | error C2784: Could not deduce template argument | Still fighting with templates. In this example, despite the fact that is copied straight from a book I'm getting the following error message: Error 2 error C2784: 'IsClassT<T>::One IsClassT<T>::test(int C::* )' : could not deduce template argument for 'int C::* ' from 'int'.
This is an example from a book Templates - T... | My compiler (MSVC2008TS) likes it if you don't fully qualify the test expression:
enum { Yes = sizeof(test<T>(0)) == 1 };
But is this even legal code?
|
2,454,871 | 2,455,014 | Is there a library for editing program flow? | I was wondering if there is a library for editing program flow. I refer to conditions if, loops (do, while, for) and other elements that can exist inside a program.
What I would like to have is some sort of a CAD application (similar to an UML editor) from where I can take some elements and edit their properties, make ... | A short advice.
Programming languages were actually invented to describe program flows...
It is possible to draw flows, but as the notation is much less powerful, you will find that it will become easy to design trivial or simple flows, and impossible to design even moderatly complex flows.
Phrased in another way; ... |
2,454,905 | 2,458,547 | Force type of C++ template | I've a basic template class, but I'd like to restrain the type of the specialisation to a set of classes or types. e.g.:
template <typename T>
class MyClass
{
.../...
private:
T* _p;
};
MyClass<std::string> a; // OK
MYCLass<short> b; // OK
MyClass<double> c; // not OK
Those are just examples, the allow... | Another version is to leave it undefined for the forbidden types
template<typename T>
struct Allowed; // undefined for bad types!
template<> struct Allowed<std::string> { };
template<> struct Allowed<short> { };
template<typename T>
struct MyClass : private Allowed<T> {
// ...
};
MyClass<double> m; // nono
|
2,455,071 | 2,455,638 | Validating document in Xerces C++ | I want to load an XML document in Xerces-C++ (version 2.8, under Linux), and validate it using a DTD schema not referenced from the document. I tried the following:
XercesDOMParser parser;
parser.loadGrammar("grammar.dtd", Grammar::DTDGrammarType);
parser.setValidationScheme(XercesDOMParser::Val_Always);
parser.parse("... | You'll need to set an error handler before calling parse if you want to see anything:
Handler handler;
parser.setErrorHandler( &handler );
where Handler is a class derived from ErrorHandler
|
2,455,146 | 2,455,364 | MapViewOfFile shared between 32bit and 64bit processes | I'm trying to use MapViewOfFile in a 64 bit process on a file that is already mapped to memory of another 32 bit process. It fails and gives me an "access denied" error. Is this a known Windows limitation or am I doing something wrong? Same code works fine with 2 32bit processes.
The code sort of looks like this:
hM... | When you call CreateFile in the 32-bit application, you're passing 0 for the sharing parameter, which means no sharing is allowed. Changing that to FILE_SHARE_READ | FiLE_SHARE_WRITE would probably be a step in the right direction.
Edit: I just whipped together a demo that works (at least for me):
#include <windows.h>
... |
2,455,216 | 2,455,323 | Are pointers primitive types in C++? | I was wondering about the last constructor for std::string mentioned here. It says:
template<class InputIterator> string (InputIterator begin, InputIterator end);
If InputIterator is an integral type, behaves as the sixth constructor version (the one right above this) by typecasting begin and end to call it:
string(st... | C++ doesn't have a concept of "primitive" types; integers are fundamental types and pointers are compound types.
In this case, char* can't be converted into either size_t or char, so it will be taken as the InputIterator template parameter.
|
2,455,371 | 2,455,525 | How to implement a private virtual function within derived classes? | I know why I want to use private virtual functions, but how exactly can I implement them?
For example:
class Base{
[...]
private:
virtual void func() = 0;
[...]
};
class Derived1: public Base{
void func()
{ //short implementation is ok here
}
};
class Derived2: public Base{
void func(); //long implementatio... |
How do you define the Base::func() of Derived2, if you cannot do it within the class declaration of Dereived2?
You don't define "Base::func() of Derived2" (whatever this might be), you define Derived2::func(). This compiles just fine for me:
#include <iostream>
class Base{
private:
virtual void foo() = 0;
public:
... |
2,455,403 | 2,456,482 | How visual studio intellisense recognize functions and properties in classes even though there is no reflection in C++? | I want to list properties and functions present in c++ classes. Is that functionality already implemented in any library ? Does visual studio intellisense use any library ? Is that library available publicly from Microsoft?
| The Visual C++ team maintains a blog that has had several very nice articles about how IntelliSense has worked in the past and how it will work in the future:
IntelliSense History, Part 1
IntelliSense, Part 2 (The Future)
Visual C++ Code Model
Rebuilding Intellisense
Visual C++ Code Model in Visual Studio 2010
Essent... |
2,455,806 | 2,456,756 | Unsigned long with negative value | Please see the simple code below:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void)
{
unsigned long currentTrafficTypeValueDec;
long input;
input=63;
currentTrafficTypeValueDec = (unsigned long) 1LL << input;
cout << currentTrafficTypeValueDec << endl;
printf("%u \n... | Fun with bits...
cout is printing the number as an Unsigned Long, all 64 bits are significant and print as unsigned binary integer (I think the format here would be %lu).
printf(%u ... treats the input as an normal unsigned integer (32 bits?). This causes bits 33 through 64 to drop off - leaving zero.
printf(%ld ... tr... |
2,456,308 | 2,456,350 | Recursion with an Array; can't get the right value to return | Solution found - in under 5 minutes, thanks folks!
Clarification: The contents of my array are the values 0-29. So array[0][0] = 0, while array[29][0] = 29 --- they're just test values. Also, I have a potential solution that's been posted multiple times, going to try that.
Recursive Solution: Not working!
Explanatio... | Don't use the global total, make it an argument.
int totals = calcTotals(time-1, 0); // Call it starting at the end,
// so we don't have to pass along the `time`
int CompanySales::calcTotals( int counter, int total )
{
if ( counter == 0 ) {
return total;
}
else {
ret... |
2,456,430 | 2,456,571 | Intellisense in header files | I just right now "migrated" from C# to C++/CLR. First I was annoyed, that I had to write all class' declarations twice (into .h and .cpp). Then I figured out, that I could place the code also into the h-files - it compiles at least. Well, I deleted all cpp's of my classes and now I realized, VS won't give me any Intell... | You're blowing intellisense out of the water because code for every class is being inlined into every implementation file, and that's just more data than Intellisense can parse reliably. It starts failing due to timeouts.
I know you said it's annoying, but you have to put the class in twice -- that's how C++ works. If ... |
2,456,445 | 2,456,535 | C++ how can I refactor this? | I have the code below in my test code in many places:
//
// Make a function call while expecting an exception should be thrown
//
bool exceptionThrown = false;
try
{
expectNotEqual(someData, anotherData, methodName);
}
catch(std::logic_error&)
{
exceptionThrown = true;
}
if(!exceptionThrow... | I know you say no macro's, but why? They exist for generating code:
#define SHOULD_THROW(x, name) \
{ \
bool didThrow = false; \
try \
{ \
x; \
} \
catch(...) { didThrow = true; } \
\
if (!didThrow) \
throw std::logic_error(name " did n... |
2,456,584 | 2,456,622 | Getting Segmentation Fault in C++, but why? | I am getting segmentation fault in this code but i cant figure out why. I know a segmentation fault happens when a pointer is NULL, or when it points to a random memory address.
q = p;
while(q -> link != NULL){
q = q -> link;
}
t = new data;
t -> city = cityName;
t ... | In the else clause in Database::add, you do not set t->link = NULL, so it is uninitialized.
You should add a constructor for data that initializes its members, or use the value-initializing new to ensure that everything is initialized correctly:
t = new data(); // note the parentheses
|
2,456,664 | 2,456,729 | Google protobuf in Linux | I'm working with protobuf and Linux. Where is its compiler protoc? I've downloaded the package from the main site, compiled and installed it successfully but I can't find protoc to build my own format file. Where is it?
UPDATE
Here is folder where I built protobuf:
aclocal.m4 depcomp Makefi... | It's probably installed into /usr/local/bin
On Ubuntu at least, you can apt-get install protobuf-compiler instead.
From the INSTALL.txt:
Installation Names
By default, 'make install' will install the package's files in
'/usr/local/bin', '/usr/local/man', etc. You can specify an
installation prefix other than '/us... |
2,456,862 | 2,456,880 | Why can't one ctor call another ctor to initialize the object | class Foo {
public:
Foo() { Foo(1)}
Foo(int x, int y = 0):i(x) {}
private:
int i;
}
Can anybody give me some reasonas about can I do this? If not why?
| Because the language specification doesn't allow it. Just the way the language is. Very annoying if you're used to Java or other languages that allow it. However, you get used to it after a while. All languages have their quirks, this is just one of C++'s. I'm sure the writers of the specs have their reasons.
Best ... |
2,456,955 | 2,456,980 | What to do if a failed destructor can't throw an exception | I noticed that you can't throw an exception in a destructor. So my question is what should I do if destructor fails.
Another question is, under what situation a destructor might fail?
Thanks so much
| Ignore the error.
A destructor might "fail" if for example the class wraps some kind of output, and the destructor flushes and closes that output. Writing data might fail. Your options then are to terminate the program, or to catch the exception, ignore the error, and return. Usually the right design is to ignore it.
I... |
2,457,072 | 2,457,086 | C++ std::equal -- rationale behind not testing for the 2 ranges having equal size? | I just wrote some code to test the behavior of std::equal, and came away surprised:
int main()
{
try
{
std::list<int> lst1;
std::list<int> lst2;
if(!std::equal(lst1.begin(), lst1.end(), lst2.begin()))
throw std::logic_error("Error: 2 empty lists should always be equal");
lst2.push_back(5);
... |
Observation: why is it the std::equal does not first check if the 2 containers have the same size() ? Was there a legitimate reason?
How? You do do not pass containers to the function, you pass in iterators. The function has no way of knowing the size of the second container. All it can do is assume bona fide that th... |
2,457,182 | 2,457,274 | C++ -malign-double compiler flag | I need some help on compiler flags in c++. I'm using a library that is a port to linux from windows, that has to be compiled with the -malign-double flag, "for Win32 compatibility". It's my understanding that this mean I absolutely have to compile my own code with this flag as well? How about other .so shared libraries... | You usually dont need to change alignment settings for modern compilers.
Even if compiler will store someting unaligned, program will be not broken.
The only place where it can be needed is stuctures passed between linux and windows version of programm in binary (via files or via network). But in these cases the usage ... |
2,457,331 | 3,214,923 | Replacement for vsscanf on msvc | I've run into an issue porting a codebase from linux (gcc) to windows (msvc). It seems like the C99 function vsscanf isn't available and has no obvious replacement.
I've read about a solution using the internal function _input_l and linking statically to the crt runtime, but unfortunately I cannot link statically since... | A hack that should work:
int vsscanf(const char *s, const char *fmt, va_list ap)
{
void *a[20];
int i;
for (i=0; i<sizeof(a)/sizeof(a[0]); i++) a[i] = va_arg(ap, void *);
return sscanf(s, fmt, a[0], a[1], a[2], a[3], a[4], a[5], a[6], /* etc... */);
}
Replace 20 with the max number of args you think you might ... |
2,457,340 | 2,457,555 | How to work with a DATE type in a COM/ATL project | I've got an ATL method that takes a DATE type, which is really a double. I can't find the class/functions for this type. Does anyone know how to operate on this type? I just need to make it into something I can get into boost::gregorian::date (yyyy/mm/dd). Also, I would really like to know what this double represents. ... | With ATL use COleDateTime for VT_DATE variants.
|
2,457,389 | 2,457,484 | Looping on a closed range | How would you fix this code?
template <typename T> void closed_range(T begin, T end)
{
for (T i = begin; i <= end; ++i) {
// do something
}
}
T is constrained to be an integer type, can be the wider of such types and can be signed or unsigned
begin can be numeric_limits<T>::min()
end can be numeric_li... | Maybe,
template <typename T> void closed_range(T begin, const T end)
if (begin <= end) {
do {
// do something
} while (begin != end && (++begin, true));
}
}
Curses, my first attempt was wrong, and the fix above isn't as pretty as I'd hoped. How about:
template <typename T> bool adva... |
2,457,409 | 2,458,396 | Programmatically Installing Fonts | How could I programmatically install a font on the Mac platform (Snow Leopard)? What steps would I need to follow? I would like for the user to input a font file, then my software installs it.
| Fonts belong in ~user/Library/Fonts/ for a single user or /Library/Fonts/ to be accessible to all users. You need to get permission in order to write to /Library/Fonts/, although there is an API for that which makes it relatively easy. (I have the code somewhere and can look it up if no one else knows offhand.)
As req... |
2,457,465 | 2,457,592 | Do Java or C++ lack any OO features? | I am interested in understanding object-oriented programming in a more academic and abstract way than I currently do, and want to know if there are any object-oriented concepts Java and C++ fail to implement.
I realise neither of the languages are "pure" OO, but I am interested in what (if anything) they lack, not what... | Off the top of my head, I'd say:
multiple dispatch
generic functions
a metaobject protocol
being able to subclass native types (I don't know that this has a name, because there are relatively few OO languages I know which don't allow this)
|
2,457,658 | 2,457,690 | How to switch iostream from binary to text mode and vice versa? | I want to read both formatted text and binary data from the same iostream. How can I do that?
Why? Imagine this situation: You have different resources, and resource loaders for them, that take a std::istream as a parameter. And there are a "resource source" that provides these streams. Resources can be both text and b... | All that binary mode does is prevent special handling of newline characters. C++ has no concept of "resources" or "resource types". Simply read everything in binary mode.
|
2,457,672 | 2,457,731 | CODE1 at SPOJ - cannot solve it | I am trying to solve the problem Secret Code on SPOJ, and it's obviously a math problem.
The full problem
For those who are lazy to go and read, it's like this:
a0, a1, a2, ..., an - sequence of N numbers
B - a Complex Number (has both real and imaginary components)
X = a0 + a1*B + a2*(B^2) + a3*(B^3) + ... + an*(B^n)... | The key is that a0 .. an are not arbitrary numbers, they're integers (otherwise, this wouldn't be possible in general). You're given the number X , and are asked to express it in base B. Why don't you start by working a few examples for a specific value of B?
If I asked you to write 17 in base 2, would you be able to... |
2,458,001 | 2,458,307 | C++ Question on the pow function | I'm trying to get this expression to work, I'm pretty sure its not the parenthesis because I counted all of them. Perhaps there something I'm doing wrong involving the parameter pow (x,y).
double calculatePeriodicPayment()
{
periodicPaymentcalc = (loan * ((interestRate / yearlyPayment))) / (1-((pow ((1+(interestRate... | Notice how much easier it is to figure out what the function is doing if you break each step up into pieces:
(I find it even easier if your variables match the source material, so I'll name my variables after the ones Wikipedia uses.)
// amortization calculator
// uses annuity formula (http://en.wikipedia.org/wiki/Amor... |
2,458,025 | 5,615,856 | How to properly downcast in C# with a SWIG generated interface? | I've got a very large and mature C++ code base that I'm trying to use SWIG on to generate a C# interface for. I cannot change the actual C++ code itself but we can use whatever SWIG offers in the way of extending/updating it. I'm facing an issue where a C++ function that is written as below is causing issues in C#.
A... | By default SWIG generates C# and Java code that does not support downcast for polymorphic return types. I found a straightforward way to solve this, provided your C++ code has a way to identify the concrete class of the C++ instances that are returned. That is, my technique will work only if the C++ API you are wrapp... |
2,458,028 | 2,486,043 | Is There a Good Pattern for Creating a Unique Id based on a Type? | I have a template that creates a unique identifier for each type it is instanced. Here's a streamlined version of the template:
template <typename T>
class arType {
static const arType Id; // this will be unique for every instantiation of arType<>.
}
// Address of Id is used for identification.
#define PA_TYPE_TAG(T... | Return a std::type_info object from a function on each object and use operator == on the result. You can sort them by using the before() function which returns the collation order.
It's specifically designed to do what you want. You could wrap it in an opaque "id" type with an operator< if you wanted to hide how it wor... |
2,458,087 | 2,458,740 | How do you do masked password entry on windows using character overwriting? | Currently I am using this implementation to hide user input during password entry:
void setEcho(bool enable) {
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hStdin, &mode);
if(enable) {
mode |= ENABLE_ECHO_INPUT;
} else {
mode &= ~ENABLE_ECHO_INPUT;
}
SetConsoleMode(... | The solution is to not use stdio.h but to use conio.h. The following routine solves the above problem. Note that disabling echo is no longer needed:
void scanPass(char* passwordEntry, int length) {
int index, ch;
for(index = 0; index < (length - 1) && ((ch = _getch()) != EOF)
... |
2,458,090 | 2,458,179 | Can we overload a function based on only whether a parameter is a value or a reference? | I got the answer NO! Because passing by value and passing by reference looks identical to the caller.
However, the code below compiles right
class A {
public:
void f(int i) {}
void f(int& i) {}
};
But when I try to use it, there is compile error.
int main () {
A a;
int i = 9;
int& j = i;
a.f(1);
... | Yes, they can be overloaded based on reference or not. That is why it's perfectly fine to have them coexist like that; they are different.
The problem has to do with ambiguity. While f(1) can only be called on one variation, f(i) can be called on both. Neither is preferable, therefore you get an error for ambiguity. If... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.