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 |
|---|---|---|---|---|
6,147,839 | 6,149,450 | Inverse Interpolation with angles greater than Pi? | I'm making an API for skeletal animation. Right now it works fine, except Lets say you want to go from 2.0f to 1.0f. It will end up doing almost a full circle when it should only do about 1/6th of one.
I think I've got a way to find it it should go counter clockwise but I'm not sure how to use it with this:
bool CC... | I think this may help. Especially sections 8,9 and 30.
|
6,148,309 | 6,148,368 | File saved to Program files folder is not there | I linked my application with the following options and saved a file from the application to the location 'C:\Program Files\ICEHost\Projects'. The file saved without any issues. But when I open the folder the file is not there.
I don't want to execute the application as run as administrator. How can I solve the issue?
| Probably your files had been virtualized:
http://www.windowsecurity.com/articles/Protecting-System-Files-UAC-Virtualization-Part1.html
Check if you have "Compatibility Files" option in Windows Explorer (in C:\Program Files\ and then with that option on navigate to your folder)
BTW, you souldn't save files to that locat... |
6,148,637 | 6,149,546 | How can I know what libs are being linked dynamically into a static lib? | Say I have a libmy.a static library, and I want to know what libraries it links dynamically. Actually I need that for the following: I am gonna create a new dynamic lib say libmy2.so which will link say an .o file (object file) and the libmy.a. So I wonder what libs will load libmy2.so eventually.
| Static libraries do not link other libraries, either static or dynamic.
OK, assuming two C++ files, a.cpp and b.cpp.
g++ -c a.cpp -o a.o // compile a.cpp to a.o
rm -f lib1.a // no existing lib1.a (this is not essential)
ar rvs lib1.a a.o // create library lib1.a and add a.o to it
g++ -c... |
6,148,940 | 6,149,048 | Can a private operator be accessible from outside? | i.e. if I define operators == and + in my class in a private section, can they be accessible from main?
It works in MSVS 2008 and 2010 but for me it seems to be a bug in a compiler. Is it so?
| You will have to show the code to get a sensible explanation of why the compiler is accepting it. My guess is that you are implementing them as friend free functions. At any rate, for the sake of argument, assume you have:
class bar {
friend bool operator==( bar const &, bar const & ) {
return true;
}
ba... |
6,149,175 | 6,149,318 | Logical question: Given corners, find Center of Quadrilateral? | Given the cordinates of all corners of a quadrilateral, how can the cordinates of its center be found?
Thanks.
| Origin = x=0,y=0
a(0,0) b(10,0)
c(0,5) d(10,5)
a+(b-a/2)=5
a+(c-a/2)=2.5
centre co-ordinate = 5,2.5
or dx-ax/2=5
dy-ay/2=2.5
with those formulas it wouldn't matter if the sides were uneven the centre can always be calculated.
Regards
Ray
|
6,149,314 | 6,149,362 | Why is an empty wchar_t literal allowed? | Look at the following code:
int main(int argc, char* argv[])
{
// This works: (Disable Lang Ext = *Yes* (/Za))
wchar_t wc0 = L'\0';
wchar_t wc_ = L'';
assert(wc0 == wc_);
// This doesn't compile (VC++ 2010):
char c0 = '\0';
char c_ = ''; // error C2137: empty character constant
assert(c... | This is a bug in VC++.
|
6,149,331 | 6,149,415 | Native C++ performance using C# or within C# | I was wondering if the two following scenarios have the same performance impact on native C++ code (if there is any performance impact at all).
Let's assume I have the function cpp_calc() that is doing some calculation stuff and is written in native C++. Also, there is cs_show_gui_stuff(), which is written in C#.
Now, ... | It really depends on what the other parts of the system are mainly written in. From a performance-only perspective, one PInvoke (via DllImport attribute) call will probably be faster than one COM call if the method arguments do not need any special marshaling.
A third, and probably the best alternative, is to create a... |
6,149,406 | 6,149,619 | Why are TClientSocket and TServerSocket deprecated and what should I use instead? | I'm just starting to get familiar with Embarcadero RAD Studio 2010 after living a life of Eclipse, Emacs, Visual Studio and notepad :)
I'm jumping into quite a large C++ application (500.000 - 1.000.000 lines) that I found made extensive use of TClientSocket and TServerSocket. The IDE first complanied about that TClien... | Deprecated because not supported any more. They are a wrap up of Winsock sockets, so the overall internal mechanism is the same - 'Create listener, listen, accept, create a client handler thread, passing it the ServerClientSocket, client thread reads and writes streams'.
You could maybe try just importing the componen... |
6,149,633 | 6,149,742 | Linking to V8 does not work in release mode | I built the v8 libraries on visual studio 2005 in release mode, put the resulting .lib files (in release mode) and compiled my project against them.
While everything is working fine in debug mode (compiling and running correctly), in release mode I get the following link errors (as if the lib files are not there).
erro... | In Visual Studio the build options are separate for debug and release builds. You probably set everything up properly for debug mode, but not for release mode, hence the errors.
I forget exactly how things are layed out in VS2005, but in VS2008, there is a combobox at the top of the solution properties dialog that let... |
6,149,740 | 6,149,927 | Size of byte (clarification) | I'm writing a game server, and this might be an easy question, but I just want some clarification.
Why is it that a byte (char or unsigned char) can hold up to a value of 255 (0xFF, which I believe is 2 bytes)? When I use sizeof(unsigned char) the compiler tells me it is 1 byte.
Is it because (in ACSII) it is getting ... | This touches on a bunch of subjects, including the historical meaning of a byte, the C definition of a char, and mathematics.
For starters, a byte has historically been a lot of things, but nowadays we nearly always mean an octet, which is 8 bits. As a play on words, there's also the nybble (or often nibble) which is ... |
6,149,798 | 6,149,859 | Is it possible for "using" keyword to inherit fewer functions? | In Derived there is a template foo(T). There are 2 overloads of foo() in Base.
struct Base
{
void foo (int x) {}
void foo (double x) {}
};
struct Derived : Base
{
template<typename T> void foo (T x) {}
using Base::foo;
};
Now, when foo() is called with Derived object; I want to use only Base::foo(int) if appl... | using bringes all overloads into the scope. Just hide it in the derived class, it's a bit more to write but does the job:
struct Derived : Base
{
template<typename T> void foo (T x) {}
void foo(int x){
Base::foo(x);
}
};
|
6,149,930 | 6,150,267 | Create JVM after destroying it | I am trying to call JNI_CreateVM after calling destroyVM but it always return -1. Is that a bug in JDK?
I found the following link that describes the same problem:
JNI Bug
The link has a sample code that reproduces the issue that I hace. Does anybody have an idea how to resolve this issue?
Thanks,
Sami
| I've found a couple of forum postings that report that CreateJavaVM / DestroyJavaVM / CreateJavaVM doesn't work; e.g.
http://lists.apple.com/archives/java-dev/2004/Mar/msg00966.html
http://comments.gmane.org/gmane.comp.jakarta.poi.user/11742
The consensus is that DestroyJavaVM doesn't completely work due to limitatio... |
6,149,995 | 6,199,868 | Compilation error - Static member | I have a class definition with a virtual method.
On compiling I get the error that 'MethodType Class::Method' is not a static member of class Class
The most popular solution I have found is to add the keyword static to the Method definition in the header file.
However, the method is defined as virtual. So to add the s... | Figured it out.
Finally. In the implementation of MethodName1
structType * X::MethodName(ParamType1 P1, ParamType2 P2)
ParamType1 was a non-standard type. It is actually a class in the underlying application
to which I have only the API.
Turns out that the implemtation for class ParamType1 was missing / not comp... |
6,150,030 | 6,150,308 | VC++ error when using a pointer to a template function | I'm trying to write a template callback function for libcurl. However, when using a pointer to an instance of the template function, VC++ 2008 and 2010 keep giving me this error:
template-callback.cpp(27) : error
C2664: 'curl_easy_setopt' : cannot
convert parameter 3 from 'size_t
(__cdecl *)(void *,size_t,size_t... | I have reproduced the issue on ideone (C++03 with gcc-4.3.4):
#include <iostream>
typedef void (*FuncType)(int);
void foo(FuncType);
void bar(...);
template <typename T>
void callback(T t) { std::cout << t << "\n"; }
int main() {
foo(&callback<int>); // OK
bar(static_cast<FuncType>(&callback<int>)); // OK
bar... |
6,150,083 | 6,150,103 | returning a NULL string from a function c++ | string receiveFromServer();
this function returns a string that was received from some server. If there was an error along the way (including protocol), i want to return a NULL string. However, this doesn't work in c++ (unlike java).
i tried:
string response = receiveFromServer();
if (response==NULL) {
cerr << "... | You can throw an exception to indicate an error.
try {
std::string response = receiveFromServer();
} catch(std::runtime_error & e) {
std::cerr << e.what();
}
Then you would need a throw std::runtime_error("Error receive response") somewhere in receiveFromServer().
It is often considered good practice (though s... |
6,150,256 | 6,159,963 | How to deal with autotools for building a google test exec file? | I'm failing in generating a test executable file containing all my google tests with autotools.
Our dev project is quite large and contains several modules. So, what I want is to have each module to create a test lib/object file and then to put these altogether to create a single test exec file (actually through make ... | Google Test's Primer wiki page contains a special section on tests in libraries. It is worded for Visual C++ users but actually applies to static libraries under GCC, as well. In short, you have to reference your libraries with tests in order to prevent the linker from throwing them out.
|
6,150,265 | 6,150,606 | use c++ class in objective-c | Basically I have 2 source files like following in my workspace:
vectormath_aos.h
#ifndef _VECTORMATH_AOS_CPP_SCALAR_H
#define _VECTORMATH_AOS_CPP_SCALAR_H
#include <math.h>
#ifdef _VECTORMATH_DEBUG
#include <stdio.h>
#endif
namespace Vectormath {
namespace Aos {
//--------------------------------------------------... | Since you’re using namespaces,
Matrix4 mvpmatrix;
should be:
Vectormath::Aos::Matrix4 mvpmatrix;
instead.
|
6,150,361 | 6,160,110 | STL link error with CodeComposerStudio | I'm compiling an mixed C/C++ program using STL with CodeComposerStudio.
I have many compiler remarks and link errors
compiler remarks
!defined(__MINGW32__)
!defined(__MINGW32__) "C:/CCStudio_v3.3/C2000_v5.2.5/include/yvals.h",
line 470: remark #195-D: zero
used for undefined preprocessing identifier #if... | The remarks for #if 199901L <= STDC_VERSION and #if GNUC < 3 are with respect to the fact that in a test for the value of an undefined macro, the macro is substituted with zero. So in this case GNUC < 3 will be true even when the compiler is not GNUC. It should be qualified with #if defined GNUC && GNUC < 3 or enclos... |
6,150,368 | 6,294,725 | CUDA and Eclipse: How can I tell eclipse that <<< (or >>>) is part of the syntax? | So far I figured out that one can prevent Eclipse from complaining about proprietary CUDA keywords by defining them if __CDT_PARSER__ is defined. The following code prevents Eclipse from complaining about most of the CUDA keywords.
// Prevent eclipse from bitching about unknown keywords
#ifdef __CDT_PARSER__
#define __... | Here's a solution that will work with Eclipse CDT, Visual Studio or Qt Creator This is my solution:
#if (defined __CDT_PARSER__) || (defined __INTELLISENSE__) || (defined Q_CREATOR_RUN)
#define __global__
#define __device__
#define __host__
#define __shared__
#define CUDA_KERNEL_DIM(...)
#else
#define CUDA_KERNEL_DIM(... |
6,150,382 | 6,204,006 | C++: Process 2d array elements in a diagonal fashion | Let's say we have a two dimensional arrays, arr[N][N], where N is a constant integer.
Assume that every element of arr is initialized.
How do I print the elements of arr antidiagonal-wise using nested for loops?
What I mean is:
After first iteration of the outer-most loop, arr[0][0] will be printed
After second iterat... | Sorry to everybody who wrote "The second half should be similar"... it's not.
Anyway, here you go:
// traverse array diagonally
int c, tmp, x;
for (c = N - 1; c > -N; c--) {
tmp = N - abs(c) - 1;
x = tmp;
while (x >= 0) {
if (c >= 0) {
std::cout << arr[x][tmp - x] << ", ";
}
... |
6,150,570 | 6,150,600 | Pointer to a vector item -- On Windows | I have the following classes:
class A {};
class B { vector<A> vect; };
I can access an arbitrary A like this:
A a = b.vect[0];
// A *a_ptr = &a;
But how can I get directly to *a_ptr?
A *a_ptr = &b.vet[0];
compiles and doesn't give runtime errors, but it points to a wrong memory location.
EDIT:
my real world example... | It's not "wrong", you just missed the difference. Namely:
A a = b.vect[0]; // Makes `a` a *copy* of the vector element
A *a_ptr = &a; // Address of the copy
A *a_ptr2 = &b.vect[0]; // Address of the element, not a copy
To get the equivalence, you should change your first one to:
A& a = b.vect[0]; // Makes `a` a refer... |
6,150,761 | 6,151,320 | Elegant way to force vector elements having same properties | The title is a bit vague but I can't come up with a better wording, here's the deal:
class A
{
public:
A();
A( const PropertyB& b );
PropertyA GetPropertyA();
PropertyB GetPropertyB();
SetPropertyA( const PropertyA& b );
SetPropertyB( const PropertyB& b );
//assignment not allowed
};
Suppose I want to us... | This doesn't make sense, from an OO design viewpoint. Remember the Liskov Susbsitution Principle: A is-a B whenever an A object can be used in the place of a B object? Per that rule, the elements of your proposed std::vector<A> fail the is-an-A test, since you can't set their B property. Yet std::vector<A> is supposed ... |
6,151,558 | 6,151,580 | Displaying fully qualified name of the function | #include <iostream>
class A{
public:
void myfunction(){
std::cout << __func__;
}
};
int main(){
A obj;
obj.myfunction();
}
Output is myfunction. Unfortunately __funct__ does not work. How to output the fully qualified name of the member function i.e A::myfunction ?
| There is no standard defined way for the same. However if you are using gcc you can use __PRETTY_FUNCTION__ instead of __func__.
Standard C++ (i.e C++03) does not have either __func__ or __PRETTY_FUNCTION__.
C++0x derives __func__ from C99 and it is defined in 8.4.2/8 (n3290)
The function-local predefined variable __f... |
6,151,563 | 6,152,687 | CDocument::SetPathName behaves differently in WinXp and Windows 7 | When I called CDocument::SetPathName with 'eererr.hpr' in Windows XP it updates the member variable m_strPathName with value 'C:\Program Files\ICEHost\Projects\eererr.hpr'
When I executed the same method in Windows 7 it updated m_strPathName with 'C:\Program Files\ICEHost\eererr.hpr' Projects directory is missing in th... | SetPathName() calls GetFullPathName() which "merges the name of the current drive and directory with a specified file name". So the difference is probably on how the current directory is obtained.
It is documented how CFileDialog selects a different initial directory on different OS (check lpstrInitialDir in the foll... |
6,152,126 | 6,152,230 | How to build a filter handler for a custom file format so that its contents could be searched through the windows search? | I have started building a filter handler for a custom file format. I came to know that I need to implement the IFilter interface for that. Moreover, I got a sample from the internet which was doing just the needful. It registered the persistent handler for the custom file format in the regedit/classes_root. But still m... | I haven't done this, but Developing Filter Handlers for Windows Search on MSDN seems like a good starting point.
|
6,152,175 | 6,153,018 | Luabind: "No matching overload found, candidates:" | Note, I have read and applied the answer to: Calling C++ member function from Luabind causes "No matching overload found", but this did not solve my issue.
I have a simple class that I expose to LUA via luabind
Here is the binding code:
void LogManager::luaBindImpl() const
{
using namespace luabind;
lua_State* ... | In the Lua part, you need to use colon (:) instead of a dot:
LogManager:registerSource("lol");
And you do realize the global variable LogManager has the same name with the class LogManager; that way you won't be able to use the enum constants, e.g. LogManager.Info will return nil.
|
6,152,312 | 6,152,835 | binary read/write arbitrary std::vector<std::vector<int> > in c++ | Hi,
I would like to store binary a std::vector<std::vector<int> > object MATRIX in a file.
out.write((char*)&MATRIX, sizeof(MATRIX));
The problem is, that only the column dimension is fixed. The row dimension changes.
If I read the object out of the binary file, it's not enough to know only the size, isn't it? So, in... | I will give you a short example on how to do this with boost.
#include <iostream>
#include <fstream>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
std::vector<std::vector<int > > g_matri... |
6,152,487 | 6,152,503 | Request administrator rights on Win Vista/7 from a c++ app | I found info on how to do it in c#, but how to make a C++ app pop-up that UAC "Run as administrator" when it is run?
| You can set the manifest in Visual Studio in:
Project >> Properties >> Configuration Properties >> Linker >> Manifest File >> UAC Execution Level.
|
6,152,749 | 6,152,807 | Is there a difference between these codes | I was coding away today when I came across something I do all the time without thinking as wondered if it had any after affects.
Here are two ways of doing the same thing
if(foo != true)
{
bar ++;
}
if(foo == true)
{
}
else
{
bar ++;
}
Now I know the compiler would probably optimise this to the same thing but I wan... | Neither is good. Apart from the fact that the second contains a typo (= instead of ==), comparing booleans to constants is just redundant. Just test their values directly:
if (! foo) …
// Instead of
if (foo != true) …
// or
if (foo) …
// Instead of
if (foo == true) …
First of all, it removes the possibility of creat... |
6,152,956 | 6,153,010 | Are there any guarantees with unget? | Considering the following:
char c;
cin >> c;
cin.unget();
Assuming the char input was successful, is unget guaranteed to be able to back up at least that one character? If I ask for, and successfully get a string, can I be guaranteed to be allowed to call unget all the way to the beginning of that string?
| You are guaranteed to be able to unget at least 1 character. Any more than one is up to the implementation and circumstances, so you shouldn't assume that you can unget more than one.
EDIT: Sorry I was thinking of libc's int unget(int ch, FILE *stream). Which the standard says:
One character of pushback is
guarantee... |
6,153,615 | 6,154,099 | Mysql database writes and file writes | I have a program which writes data to mysql database and also huge amounts of logs to a file.. i have noticed that if i give huge amounts of data as input to the program, i.e data that creates logs as big as 70GB and mysql database table count(*), of the table that i use, to >1,000,000 entries, the whole programme slow... | There's an easy way to test for this.
If you create a blackhole table, MySQL will pretend to do everything but never really write any data to file.
create table(s) just like your
normal table(s),
Make a copy of the logs.
Now write to the blackhole database just like you would in the real database.
If it's much ... |
6,153,704 | 6,153,971 | Opengles mixing VBO and non VBO renders gives EXC_BAD_ACCESS | Hey guys. Im trying to render two methods shown below. RenderA() is using VBOs and RenderB() isnt. Im getting an EXC_BAD_ACCESS error when it reaches glDrawArrays() in RenderB().
RenderB() works fine though if i dont create and use any VBOs, ie when i comment out CreateVBOs() and RenderA().
So does this mean once you... | Try binding GL_ELEMENT_ARRAY_BUFFER and GL_ARRAY_BUFFER to zero before doing your non-VBO draw calls.
Add the following lines of code to the end of your VBO draw calls (RenderA):
glBindBuffer(GL_ElEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
6,153,735 | 6,153,977 | unalignment warning when initializing SQL DBPROP structure | I have a Visual Studio 2008 C++ project for Windows Mobile 6 ARMV4I using Microsoft SQLCE 3.5. When I initialize the VARIANT component of a DBPROP structure (as below), I get a compiler warning message: C4366: The result of the unary '&' operator may be unaligned.
#include <sqlce_oledb.h>
DBPROP prop = { 0 };
::Varian... | If you plan to pass the DBPROP structure to other APIs, do NOT change its alignment, since that can change the packing and it will stop working. I notice the following comment in the header:
#if 0
//DBPROPINFO is an unaligned structure. MIDL workaround. 42212352
typedef DBPROPINFO *PDBPROPINFO;
#else
typedef DBPROPIN... |
6,153,738 | 6,153,800 | What to learn to be able to send files online using c++ on windows? | What to learn to be able to send files online using c++ on windows ?
i know c++, and i got a program that does some benchmark and saves into a text file, i want that text file to be sent to me after the benchmarking is done, so what should i search for ? tried searching found something called sockets and something abou... | I think you better off just emailing the file after a benchmark is done, and doing it using some bash or Python scripting rather than C++ or any other low level language. Here is an example of sending email using Python. Another option would be to upload to the FTP or use rsync to transfer file over SSH. And in any cas... |
6,153,795 | 6,154,356 | Virtual Destructor causes Access Violation | I am trying to make a DLL file compatible with different compiler configurations (Debug, Release,..). In order to make sure that an object is removed the right way I managed to write a pointer wrapper class that uses a compiled delete operator whenever I take an object of the DLL and run out of scope.
I am perfectly fi... | You can't export a template definition as the compiler generates the types based on usage of the template. You simply inline them in the header file or you can do something like this but that requires declaring your template instantiation upfront.
Also note in C++ prefer new and delete over malloc and free functions f... |
6,153,904 | 6,153,919 | Issue with static functions, g++ says the class hasn't been declared | I am trying to compile this code, and g++ keeps telling me that 'TimeFinder' has not been declared
Header File
#ifndef _TIMEFINDER_H
#define _TIMEFINDER_H
#include <vector>
#include "timefinder.cpp"
using namespace std;
class TimeFinder
{
public:
static vector<int> time_from_name(string filename);
static int c... | Do not do this:
#include "timefinder.cpp"
You are pulling your definitions into your header so they appear before their declarations.
There is a lot of other stuff wrong with your code - the use of static members in the first place, passing vectors and strings by value when they should be references, and placing using... |
6,154,101 | 6,154,142 | Making an application run on WinXP/Vista that uses Win7 features | I've developing an app that uses some of the advanced Windows 7 features that werent available on WinXP.
Lets say I want to use ChangeWindowMessageFilterEx (or any other calls that were added since Win7), the app compiles and works fine on Win7. But on XP I get "The procedure entry point ChangeWindowMessageFilterEx cou... | You do that by dynamically resolving ChangeWindowMessageFilterEx using LoadLibrary and GetProcAddress. If GetProcAddress returns NULL, you just don't call this function.
See also:
Checking for existence of Windows API Functions
Using Run-Time Dynamic Linking
|
6,154,258 | 6,154,506 | Performance of embedding resource files into executable | Recently I found here how to embed my resource files inside the executable. There is also the xxd method. Given this new found toy, that I used at first to embed the text of GLSL shaders into my game, now I want to embed every resource file needed to the game.
For now I only have a few kb of 3-D mesh data, but before t... | The disadvantage to this resource allocation method is that all resources will be present in virtual memory for the entire duration of your application.
For example, if you have 10 levels in your game, using a more common file-based storage solution you would only load the data for whichever level you are going to play... |
6,154,442 | 6,155,928 | How to configure swig to map size_t as ulong instead of uint (c#) in 64 bit platforms | The problem is that swig is mapping size_t variables as uint in c# this is correct in 32 bit, but I need to create the wrapper for the 64 bit version too. I need help with the configuration of the interface to use ulong instead of uint for size_t on 64 bit platforms.
The interface is really simple I just added the head... | %apply is sort of like a #define. I've been using it to convert int64_t to long long.
%apply ulong {size_t}
|
6,154,618 | 6,154,944 | Delete a line in an ofstream in C++ | I want to erase lines within a file. I know you can store the content of the file (in a vector for example), erase the line and write again. However, it feels very cumbersome, and not very efficient if the file gets bigger.
Anyone knows of a better, more efficient, more elegant way of doing it?
| There's nothing particularly magical about disk files. They still like to store their data in contiguous areas (typically called something like "blocks"). They don't have ways of leaving data-free holes in the middle of these areas. So if you want to "remove" three bytes from the middle of one of these areas, something... |
6,154,628 | 6,154,948 | Building a new library on top of another library (SDL and Eclipse) | I am working on a project with SDL. I feel like a lot of my code could/should be reusable for any other projects I might want to take on.
I was going to start a library project, but I don't know how to go about linking to the SDL libraries.
Usually, I go to Project Settings and edited Mingw32 Linker to include the lib... | As an introduction, you have to distinguish very well static library from dynamic ones, they are completely different beasts... said that, to your questions:
Is there no linker settings because building a library is only a compiling operation?
I guess you are creating a static library in this case. A static library i... |
6,154,796 | 6,155,279 | What is the fastest way to access files in a zip file? | What is the fastest way to read individual files (in a random fashion) from a zip file?
As I understand it, zip files have a directory that stores the individual file entries, and I could scan this directory to build an external index. Are there any standardized ways (i.e. existing libraries) that already do that? Or ... | Scanning the directory and building the index is the fastest and best way to provide random access to the compressed entries archived in a zip file. The directory is usually small and lies at the end of the archive. If you have seekable media, then this is what you want.
The zip format is documented pretty well; it's ... |
6,154,844 | 6,155,918 | Partial specialization for a parent of multiple classes | I want to use partial specialization for a template class so that all children of that template class will use that specialization. Let me explain it with an example :)
template < typename T, unsigned int rows, unsigned int cols>
class BaseMatrix {...};
This class will have children that specify the structure of the m... | Inheritance does not apply to template specializations. When you invoke matrix<int,StackDenseMatrix,3,2> matrix;, it will select the general template for matrix, because the second argument is StackDenseMatrix, not BaseMatrix. Even though those classes are related through inheritance, it doesn't make any difference, th... |
6,155,060 | 6,155,109 | Problem with class definitions in C++ | I have a class defined in the file board.H:
class Board
{
private:
...
public:
...
};
and in another class, I want to have a member that is a pointer to a Board object:
#include "board.H"
class Bear
{
private:
Board* board;
...
public:
...
};
When I try to compile it (using g++ in linux) I get t... | Common problem. You probably have a #include "bear.H" line in your "board.H" file or in a file included by "board.H".
So when you include "bear.H" into "board.H", the "bear.H" file is processed and tries to include "board.H", but that file is already being processed so the header guard of "bear.H" won't include the co... |
6,155,094 | 6,155,142 | Is it possible to get the Linux source code for mmap and the Windows source code for MapViewOfFile? | Goog afternoon, I recently downloaded the www.kernel.org mainline 2.6.39 Linux kernel source distribution. We are looking for the Linux source code for void mmap(void start , size_t length, int prot, int flags, int fd, off_t offset). After we decompressed the tar.bz2 distribution, we found a file mmap.c which contains ... | For MapViewOfFile, I'd check Winbase.h, but it might just be the declarations, else you'd have to turn to reverse engineering, which is considered illegal in most countries.
I have found an extensive article here on MMAP and how it works. Maybe that helps.
|
6,155,148 | 6,155,231 | Is there any obvious drawback to use a no assignment swap? | I was implementing (for training purpose) a Bubble Sort template function:
template<typename iterInput,
typename predicate>
void BubbleSort(iterInput first1,iterInput last1,predicate func)
{
bool swapped(false);
do
{
swapped = false;
iterInput begin = first1;
iterInput begin... | The difference is that when the assignment operator fails, you still have the same number of objects.
If you destroy one object and fail to create a new one, one object is lost! If it was part of a container, the container's state is probably also invalid.
|
6,155,285 | 6,155,418 | Code crashes when derived class' destructor is virtual and base class' dtor is not | I tried the following code on gcc 4.4.5.
If the member 'data' is not present, the code executes fine, but in its presence, it crashes. It also doesn't crash when the derived class' dtor is not virtual.
I'm aware that the behavior would be Undefined as listed in C++03 (5.3.5 / 3) in both the cases, but still could someo... | Assuming what happens on my system (gcc 4.6.0, linux x86_64) is the same as what happens on yours (it also crashes with data and runs without), the implementation detail is that p does not point at the beginning of the memory block allocated for the object of type derived.
As valgrind told me,
Address 0x595c048 is 8 b... |
6,155,414 | 6,156,305 | c++ terminal application concurrent input and output | I'm trying to implement an application similar to a chat client where messages can arrive while the user is typing his own message.
I'll explain how I want my program to behave with an example:
Before an incoming message:
>user partial input
After an incoming message:
>the new message
>user partial input(cursor is her... | While ncurses may be the most flexible and simple way to achieve this, you can do it yourself with some work.
You have to arbitrate the IO yourself. You can use "\r" to return to the beginning of a line without ncurses or any platform-specific terminal interaction.
The overall flow would be:
You have an input loop th... |
6,155,844 | 6,155,926 | Queue Problem while modeling a shortest path algorithm | I have a queue problem. Modeling a graph, I'm doing a shortest path algorithm in C++.
In my while (!q.empty()) the front vertex* gets changed when I return to this statement.
Can you figure out why?
int MyMatrix::searchBreadth(MyVertex* from,MyVertex* to)
{
queue<MyVertex*> q;
path=INFINITY;
from->visit();
from-... | Your problem is subtle, but related to q.push(&nb[i]). What you're doing is adding a pointer to a location in a vector, which is not conceptually the same as adding a pointer to a MyVertex object. The vector of neighbors contains the MyVertex objects "by value" (if that helps in your understanding of the problem).
A lo... |
6,155,925 | 6,156,097 | How to right button drag with Win32 API? | I implemented the IDropTarget interface and the drag & drop (file from explorer) works well.
When I drag & drop a file with right mouse button, the context menu does not popup.
So I think it's my responsibility to show the context menu,
But in IDropTarget::Drop method, (grfKeyState & MK_RBUTTON) is always 0.
How can I ... | I guess (grfKeyState & MK_RBUTTON) is always 0 because when the Drop() method is called, the mouse button is already released (you've just made the drop) - so naturally the keyboard/mouse state flags would indicate that it is indeed released.
What you can (and should, according to the documentation) do, is to decide ah... |
6,155,973 | 6,156,215 | COM Interface Methods limit | I am going to develop a COM component for a WIN CE device. Is there any limits on the number of methods that can be added to a COM Interface(Component)?
| No.
But if you have to add a lot of methods to a single class, there's a very good chance your design is broken.
Also, keep in mind that once you publish a COM interface, your never "supposed" to change it.
|
6,156,370 | 6,156,472 | Force Visual C++ to generate XML comments solely for my files? | having an issue that I can't seem to find a direct answer to. I'm in the late stages of building a game engine with a few friends and at this point, we're looking to streamline the comments to make them more readable and useful for any developers that may wish to join the team. Since we use Visual Studio 2010, the embe... | Forget Visual Studio and use a real documentation generation tool like doxygen. It handles the MS XML based documentation and you can configure it to only search certain files or directories.
EDIT Doxygen has it's own documentation tag format described here but it also handles JavaDoc style comments. XML style comment... |
6,156,862 | 6,156,940 | operator>> and << output being nulled when outputted | i dont understand why the output of both functions are getting nulled when i output them:
class uint128_t{
private:
uint64_t UPPER, LOWER;
public:
// constructors
uint128_t(){
UPPER = 0;
LOWER = 0;
}
template <typename T>
uint128_t(T rhs){
UPPER = 0;
LOWER = (u... | Your int is 128 bits, you are shifting it down (right) 127 bits which means the upper most bit will be moved to the lower most position, and all other bits will be 0.
But the int in your example is 0x1...., 0x1 (the highest nibble) is 0001 in binary, which does not have the upper bit set. So 0 is the correct output.
I... |
6,157,402 | 6,157,430 | Automatically determine if type is Abstract Base Class via templates at compile-time | Is it possible to automatically determine if a class is an abstract base class at compile time?
I have an object factory that, via other generic code, sometimes gets instantiated with an Abstract Base Class type. The code doesn't compile because it calls new T() on the ABC. I end up having to specialize the object fa... | The Boost Type Traits library has an is_abstract functor. You could either use that directly, or take a look at the implementation and see how they handled it.
|
6,157,409 | 6,174,586 | std::vector to boost::python::list | I have a method in c++ that gets called from python and needs to return a python list object.
I have already created the method, and its attached to an exposed class and callable from python right now... (it returns void).
So the question is, how do I create a python list from this:
std::vector<std::string> results;
I ... | I have this function using iterators to convert std::vector to py::list:
namespace py = boost::python;
template<class T>
py::list std_vector_to_py_list(const std::vector<T>& v)
{
py::object get_iter = py::iterator<std::vector<T> >();
py::object iter = get_iter(v);
py::list l(iter);
return l;
}
|
6,157,513 | 6,158,035 | Ignore missing .obj files or "/P switch + external tool + linker = hell" | I am trying to make a setup as described in my previous question: Any way to parse preprocessed source through external tool before it compiles?
All of my .cpp files are set to compile with /p, which generates .i (preprocessed) files for all of them, but no object files. Those generated .i files are also added to my pr... | maybe this can help you : instead of the extension .obfuscated.cpp give it an simpler extension like .icpp and add those .icpp files (after first compile) to your project (in a separate folder in your project) ,then for each of those .icpp files goto their property-page and set the correct build-tool (C\C++ compiler) a... |
6,157,561 | 6,157,818 | What I/O function should I use to write to a .bmp file? | The example code I've seen for this seems to use standard C file output functions, but I'd like to make it in C++.
I tried using fsteam functions to do it, but no data is written to the .bmp file at all.
So far, I have tried the standard <<, put, and write, and none of these work. If I open it up with a hex editor, t... | You have a buffer overflow bug in this code:
char data[30000]; // Prepare file for usage -- just copy one thing from the file to the other
sourcefile.read(data, image.height * image.width );
You are reading in image.height*image.width bytes, and trying to fit them into 30000 bytes. You should structure your code so... |
6,157,589 | 6,159,493 | Need help creating log4cxx appender using Eclipse in Ubuntu | When attempting to inherit from AppenderSkeleton I get "error: expected class-name before ‘{’ token " when I attempt to compile. I seems to not be recognizing the class but I am referencing the log4cxx library and have included the appenderskeleton.h file.
The .h file is below:
#include <log4cxx/appenderskeleton.h>
/... | Is AppenderSkeleton in a namespace by any chance? In that case you'd have to qualify the class name for the compiler to be able to properly resolve the symbol.
|
6,157,908 | 6,157,951 | C++ if...then statement | So I'm trying to make a simple application that quizzes the user. It asks a question and the user answers 1, 2, 3, or 4. The app then takes that answer and if it is correct adds +1 to the total_score which will be displayed at the end. Everything looks sound to me, but when I run it and I get to the if (q1_valid == fal... | I have a few tips here:
If... then is a conditional, not a loop. Sorry, that's just me being slightly picky. ;)
Never, ever, ever, ever use goto. ADVANCED USAGE: only use goto when there's a damned good reason to.
When testing boolean values, you don't need "== true" or "== false".
It looks like you haven't learned ... |
6,158,124 | 6,158,567 | SDL TextInput (using the new 1.3 structure) | Okay, I have been studying text input in SDL (how to turn the keystrokes data into letters and append them to a std::string called Text) and most of the tutorials have covered it this way:
//If a key was pressed
if(event->type == SDL_KEYDOWN )
{
//If the key is a lowercase letter
else if( (event->key.k... | You might give this tutorial a try.
|
6,158,188 | 6,158,407 | How to set up opengl/glut for programming in XCode on snow leopard? | How can I configure my snow leopard environment to begin programming with OpenGL and GLUT? Are there nice macports available that will set it all up for me? And how does it link with XCode?
Thanks for the help. Just getting started with using XCode for this..
| All you need to do is include the OpenGL and GLUT frameworks in your project and then use #include <OpenGL/OpenGL.h> and #include <GLUT/glut.h> to access them.
Of course you have forgotten to state which version of Xcode you are using so it is hard to give specific help as Xcode 3.x and Xcode 4.x are significantly diff... |
6,158,224 | 6,160,154 | Can i execute using V8 engine from Javascript to execute a C or C++ or JNI functions with Flash user interface? | Can i have my javascript which is getting executed via Flash gui button to trigger backend application layer written with either C, C++ or Java?
Example: My operating system is Flash full screen. Button on press it use javascript and execute local system built in functions and give interactive response.
Thank you
| One option is to have your back-end Java code exposed through a Java Web application. The JavaScript can invoke the Web application (ex. through Ajax) which in-turn will delegate the call to your Java code.
|
6,158,326 | 6,161,440 | visual c++ 2005 x64? | Could somebody please point me at the download link for Visual C++ 2005 Express x64 (AKA Visual Studio 8) before I am sectioned under the mental health act?
If I want any GCC point release from the last 10 years I can get it in under 30 seconds from a single page. Microsoft's website is a nightmare beyond imagining. E... | Try the last one here Microsoft Windows SDK Update for Windows Vista and .NET Framework 3.0.
That will give you Visual C++ 2005 SP1.
|
6,158,484 | 6,158,488 | Multiple #define within #ifdef or #ifndef | This is a simple question, but I have not ran across similar code before to know the answer. Basically, am I allowed to have more than two #define in an #ifdef or #ifndef statement? For a basic example:
#ifdef __GNUC__
#define HELLO(x) x
#define WORLD(y) y
#else
#define __attribute__(x)
... | Of course you are. This is perfectly valid.
You can have as many C statements or preprocessor directives within a preprocessor block as you want.
|
6,158,608 | 6,158,661 | Partitioning a vector of objects into 2 or more subgroups | I would like to partition a vector of references to MyObject (i.e. vector<MyObject*>) into 2 or more sub-vectors based on some common traits.
I have an equivalence function bool belongToSameGroup(MyObject *x, MyObject *y); which is true if certain data fields of MyObject are equal, and false otherwise. Because this eq... | I think std::partition is what you want. (Hey, it's even in the title of your question!)
|
6,158,754 | 6,158,856 | Overwriting existing used Clusters | If I used WriteFile to rewrite certain bytes in a file, would that overwrite the originaly used clusters. Or would those clusters be written to new clusters?
| On FAT and NTFS filesystems, windows rewrites the same clusters. On media like CD-RW and DVD-RW, it may write the same clusters, but it may not. It would be easy to tell by checking the free disk space.
There might be an exception for compressed NTFS files. Rewriting some bytes could cause the number of clusters of ... |
6,159,069 | 6,159,124 | How to properly remove Mutex? | Using C++, in one of my destructors, i say
mutex = NULL;
This however results in an error "No viable overloaded '='" in my Xcode.
Same mutex was previously initialized in a constructor as
mutex = PTHREAD_MUTEX_INITIALIZER;
Please advise, how can i properly handle this as part of C++ destructor
| You may use pthread_mutex_destroy() to destroy the mutex object.
According to the POSIX specification:
The pthread_mutex_destroy() function
shall destroy the mutex object
referenced by mutex; the mutex object
becomes, in effect, uninitialized. An
implementation may cause
pthread_mutex_destroy() to set the
... |
6,159,217 | 6,159,269 | Timing a Process (Windows 7 DOS Prompt) | I am running a C++ program and want to know how much time it takes. I can do it with in-built functions in the header files time.h and Windows.h but I want to use something like "time" command in UNIX. The reason is because my program is redirecting the output to a text file which is 750 MB and I am in no mood of tryin... | You can capturing the time before and after using echo %TIME%, or there are some free utilities for this purpose. For example, check out the stopwatch program from this link. It only has accuracy down to the second, unfortunately,
http://www.jfitz.com/dos/index.html
Also refer to this similar question. There are som... |
6,159,431 | 6,206,282 | RASDIAL API not connecting on windows vista and windows 7 in release builds | I am trying to connect using RASDIAL API on windows vista and windows 7. I am able to easily do this on windows XP systems.
I am not able to connect on windows vista and windows 7 only in release build. I am able to do this via the debug builds. Any idea why this is happening? I have written down the code i am using f... | It was because I wasn't initializing all the parameters in rasdialparams. Also we need to set the mask param in the ngauthdata to its respective values before we use it.
|
6,159,533 | 6,159,563 | Serialization with Streams in Java | In C++, I've created a class called Serializer. And I want to duplicate the functionality in Java. Here's how Serializer works.
Serializer s;
s.writeString(myString); // automatically converted to Big-Endian unicode string with length prepended.
s.writeInt(myInt); // automatically converted to Big-Endian integer (swizz... | Java has an object serialisation system, which sounds like a good fit for what you want to do. Quick summary:
Have your class implement java.io.Serializable, and add a private static final long serialVersionUID field (use any value you like---usually I just start with 1).
Mark all fields you don't want to serialise as... |
6,159,665 | 6,159,728 | A standard way in C++ to define an exception class and to throw exceptions | I want to build a class with functions that may throw exceptions that I want to catch when I use it.
I inherit my_exception from the standard exception class.
I implement the what() function so that it returns a string that is stored in a private string variable
I think it would be better to define the exception as a ... | Short answer: You are going to want to throw the exceptions as objects, rather than as pointers. You will catch them as references.
Longer answer: all of the options you list are valid. In general, the reason you are going to want to throw an object, rather than a pointer, is becuase of the choices you give yourself an... |
6,159,869 | 6,165,355 | How do I configure freeglut to work with Code::Blocks | I would like to know how to configure freeglut to work with the Code::Blocks IDE and minGW compiler. I don't have much experience with Code::Blocks and I have tried both glut and freeglut for ages.
Any help would be appreciated, including tutorials, etc.
| I found a tutorial which shows how to install glut. I was able to use it to configure freeglut as well. It worked perfectly.
|
6,159,955 | 6,160,066 | C++ Templates: Byval/Reference interfering with eachother | Here's a simplified version of my problem. I have a property class. It has data like has_initalized and such which i removed for this example.
When i call a function which uses T its fine. However T& isnt so i decided to write a T& version of it. But this causes all functions which uses plain T to get a compile error. ... | There is nothing in the overloading rules of C++ which allows the compiler to choose between operatorT() and operatorT&() in the call to Q. So removing the
operator T() const { return v; }
will also remove the ambiguity. But then you'll have a problem because returning a non const reference to a member in a const fun... |
6,159,968 | 6,159,973 | Declaring array of int | Is there any difference between these two declarations?
int x[10];
vs.
int* x = new int[10];
I suppose the former declaration (like the latter one) is a pointer declaration and both variables could be treated the same. Does it mean they are intrinsically the same?
| #include<iostream>
int y[10];
void doSomething()
{
int x[10];
int *z = new int[10];
//Do something interesting
delete []z;
}
int main()
{
doSomething();
}
int x[10];
- Creates an array of size 10 integers on stack.
- You do not have to explicitly delete this memory because it ... |
6,160,365 | 6,163,529 | getting connection timeout of socket function | I am very new to networking,i am trying to open a socket and get a file from a server.
I am getting connection timeout error 100060.
my code is:-
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsoc... | Have you tried using AF_INET instead of AF_UNSPEC?
Maybe you should printf() the values in results, especially ptr->ai_addr, to make sure the resolution went fine.
And obviously check that a server is listen()ing and accept()ing on the other side; did you prove it, with, for instance:
telnet 74.125.236.83:27015
|
6,160,471 | 6,160,541 | QML/D text editor and basic considerations | I am going to code a text/code editor (GUI with QML and the rest in D*). But I have several problems:
I code the GUI with QML and C++ and then I connect it with a D-Backend for formatting etc. purposes. What is the best way to connect different Languages? Pipes, Sockets or in D the ability to use C++ Libraries?
IMHO r... | As you might know, there is QtD, Qt binding for D. It's not production ready right now, but it might be some day.
Another option would be connecting C++ and D, through C wrapper. This is the most commonly used way of interacting between C++ and D.
extern(C++) interfaces are specific to DigitalMars C++ compiler on Windo... |
6,160,818 | 6,161,455 | Binding member functions | In the example in member function section: Member functions
We got a struct X:
struct X {
int foo(int);
};
Preferred syntax
boost::function<int (X*, int)> f;
f = &X::foo;
X x;
f(&x, 5);
Portable syntax
boost::function2<int, X*, int> f;
f = &X::foo;
X x;
f(&x, 5);
My questions are:
Why do I have to put an addi... |
Any member function has a pointer to the object to operate on implicitly set as its first parameter. When you have code like this: X x; x.foo(10); the compiler might really be calling foo(&x, 10) for you (see here for two ways this may be handled) - obviously, the name foo would have been mangled in some way.
See the... |
6,160,838 | 6,160,871 | How to use c++ functions in c? | C++ can use c functions by extern "C",
can c use c++ functions somehow?
| Just the same way, if you declare a C++ function as extern "C", C will be able to link with it.
|
6,160,975 | 6,161,067 | What's the meaning of MOV EAX, DWORD PTR SS:[EBP+8h] and how can I translate it into AT&T format? | I'm using Code::Blocks to code, but one of the code I referenced is from Visual C++,so I have difficulties on the difference...:(
the full code are here
NAKED void ijlWrite()
{
__asm {
PUSH EBP
MOV EBP, ESP
MOV EAX, DWORD PTR SS:[EBP+8h]
MOV ECX, ssQuality
MOV DWORD PTR DS:[EAX+50... | MOV EAX, DWORD PTR SS:[EBP+8h]
is equivalent to
movl %ss:8(%ebp), %eax
You just swap the order of the source and destination, the DWORD translates to an l suffix. The %ss: prefix is strictly unnecessary, it's the default when using EBP based memory access.
|
6,161,008 | 6,161,108 | union initialisation | I'm attempting to globally initialise a union as in the following example:
#include <cstdio>
typedef union {
char t[4];
int i;
} a;
enum {
w = 5000,
x,
y,
z
};
a temp = {w};
int main() {
printf("%d %d %d %d %d\n", temp.t[0],temp.t[1],temp.t[2],temp.t[3],temp.i);
return 0;
}
However, ... | You would want to do this:
a temp = {i: w};
That should work for both gcc and g++.
|
6,161,032 | 6,161,104 | Push elements of pointer to array to a std::list in C++ | I suppose I could just use a list however, at this point I am just curious why the following code does not work:
struct treeNode{
char symbol;
double freq;
int left;
int right;
};
treeNode *tree;
int nOS = 16;
tree = (treeNode *)malloc(sizeof(treeNode) * nOS);
list<treeNode> treeList;
After ... | I have done this in ideone, and it seems to work: (no segfaults)
#include<list>
#include<vector>
#include <stdlib.h>
#include<iostream>
struct treeNode{
char symbol;
double freq;
int left;
int right;
};
int main(int argc, char** argv)
{
treeNode *tree;
int nOS = 16;
tree = (treeNode *)malloc... |
6,161,034 | 6,483,160 | Mocking pure virtual methods if class also has non-virtual methods? | I am currently using HippoMocks as mocking framework, and can't figure out how to mock the pure virtual method MockMe() in the code below. I do not want to mock any of the non-virtual methods (which is likely not even possible), instead I want them to do what they are meant for and call the mocked virtual one.
struct A... | update/answer: I found a way around it by deriving a new class from B and adding a helper to forward the calls to the appropriate method. Apart from that it's also important to use ClassMock instead of InterfaceMock.
So, using the example above, this works:
struct MockHelper : public B
{
void InvokeRunImpl()
{
... |
6,161,075 | 6,161,105 | How to make STL throw exceptions instead of assertions? | I have to write tests for some poorly written C++ code. The problem is that the code causes STL assertions/debug breaks in many situations (usually caused by dumb mistakes like access beyond bounds of a string/vector), which result in termination of the tests.
Is it possible to make the STL throw exceptions (which can ... | It definitely depends on the STL you are using. That said, it might simply not be possible.
The Standard defines a number of guarantees (especially the C++0x one) and whether a function throws or not is part of those guarantees. For example std::vector<T>::operator[] will not throw.
That being said, there could be a nu... |
6,161,235 | 6,161,261 | What is the difference between the heap and the free store? | Originally a pedantics war on @Als answer here, it also sparked a discussion in the C++ chatroom.
This article by Herb Sutter distinguishes between the two, but is also over a decade old, as it clearly was written before 2000 and also talks about the standard draft, which can only mean C++98 draft. Though, I still expe... | Well, the current C++ standard only uses the term "free store" - the only use of "heap" in the Standard is to describe the heap data structure in the Standard Library. So "heap" is not a very useful term to use when trying to discuss C++ problems accurately, though of course everyone does it.
|
6,161,322 | 6,161,352 | Using stdlib's rand() from multiple threads | I have several threads which all run the same function. In each of these they generate a different random number several times. We tried to do this by putting srand(time(0)) at the start of the function, but it seems that they all get the same number.
Do we need to call srand(time(0)) only once per program, i.e at the ... | srand() seeds the random number generator. You should only have to call srand(time(NULL)) once during startup.
That said, the documentation states:
The function rand() is not reentrant
or thread-safe, since it uses hidden
state that is modified on each call.
This might just be the seed value to
be used by the ... |
6,161,471 | 6,162,614 | Deleting an entire node from a singly linked list | I've tried, but I can't get it to work. I need to delete an element number from a linked list. Here's what I've done so far:
class MatrixLL
{
private:
struct MatrixLLElem
{
Matrix elem;
MatrixLLElem* next;
MatrixLLElem(const Matrix& m1): elem(m1), next(NULL)
{ }
};
Matrix... | The problem is when you want to delete the first element (index=1).
instead of
start = NULL; // wrong
the correct one is:
start = (*currP).next; // the second element now becomes the first element
|
6,161,725 | 6,162,575 | boost::asio threadpool vs. io_service_per_cpu design | Currently I´m not sure, I try to make a high-performance server, I got a 6Core CPU, so if I would use the "io_service_per_cpu" design, I have 6 io_service´s.
I already heard that the threadpool design isn´t the best one, but I´m not sure about that.
What knowledge do you have? Someone already made a Stress test with ea... | In my experience it is vastly easier to approach asynchronous application design with the following order:
single thread and a single io_service
multiple threads, each invoking io_service::run() from a single io_service. Use strands for handlers that require access to shared data structures.
io_service per cpu
The mo... |
6,161,736 | 6,161,778 | What happens to a queue? (c++) | queue1.h mainwindow.h
/ /
A.h---Mainwindow.cpp
A #includes queue1
Mainwidow #includes A
A and MainWindow both need to use one instanse of queue1, so i define it in A like "static queue1 q1;"
Then in A.h i push "A" in a q1, but when i try to output it in mainwindow i get tra... | static does not mean what you mean it does in this context — it takes away external linkage from a symbol, meaning it will only be visible within a given translation unit. And because you have it in the header, included by two units, there will be two distinct instances of your class — so when you push in A, you push t... |
6,161,747 | 6,162,813 | QListView , how to resize to the best fit size? | i implemented a new class which inherits QListView , and now i want to modify sizeHint() to calculate the best width for my new listviewer.
First thought is to hook up the insert of model , retrieve max length , but how to ? Or is there any better suggestions ?
Many thanks.
| Views should resize based on space allocated by parent layouts and available screen space. After they are sized they should trim/clip text from the model , this way you can easily switch models and use the same view on any screen. If you size the view based on data from the model , there is no guarantee that the view ... |
6,161,765 | 6,171,044 | How to access the picture file on iPod/iPhone? | When I connect the iPod (or iPhone) to the Windows PC,
it look like an USB drive, but I can't open a file on it because I can't know the correct file path.
I was also unable to drop the file to my application because the drag source does not have CF_HDROP.
Some applications can open a file on iPod, but it was a copy on... |
Applications that do that use Picture Transfer Protocol (PTP). On Windows Microsoft implements many interfaces as part of Windows Image Acquisition (WIA). Read more here: http://msdn.microsoft.com/en-us/library/ms630344(v=VS.85).aspx
http://support.microsoft.com/kb/307859 or manually edit registry at HKEY_CLASSES_ROOT... |
6,161,776 | 6,161,842 | Convert Windows Filetime to second in Unix/Linux | I have a trace file that each transaction time represented in Windows filetime format. These time numbers are something like this:
128166372003061629
128166372016382155
128166372026382245
Would you please let me know if there are any C/C++ library in Unix/Linux to extract actual time (specially second) from these n... | it's quite simple: the windows epoch starts 1601-01-01T00:00:00Z. It's 11644473600 seconds before the UNIX/Linux epoch (1970-01-01T00:00:00Z). The Windows ticks are in 100 nanoseconds. Thus, a function to get seconds from the UNIX epoch will be as follows:
#define WINDOWS_TICK 10000000
#define SEC_TO_UNIX_EPOCH 1164447... |
6,161,843 | 6,161,923 | Notation of UML class diagram | I have the following classes:
class cManipulator : public cEditor
{
public:
cManipulator( ICanvas *canvas, cCompositeRoot* obj );
~cManipulator();
private:
....
class VisitorSetProp* m_SetVisitor;
class VisitorGetProp* m_GetVisitor;
}
cManipulator::cManipulator( ICanvas* canvas, cCompositeRoot* o... | The first one is right (named composition), since the cManipulator has the lifetime responsibility for m_SetVisitor and m_GetVisitor.
The second one is named aggregation. It's used when more then one object point to the visitors, and they are not resposible for the lifetime.
Regards
|
6,161,844 | 6,165,197 | Dllmain not being called? | I was writing a dllmain like this:
#include "main.h"
#include "init.h"
#include <iostream>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
//std::cout<<"hi\n"; //only for debug. did not shown.
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// attach to process
// return... | After some tries(alot :( ) I found that I missed
#define DLL_EXPORT extern "C" __declspec(dllexport)
This makes the function name correctly and finally the DLLMain is successfully called. Anyway thanks you all!
|
6,161,882 | 6,161,909 | Standard says, we can define static data member template like class template and function template, but how exactly? | The chapter of Templates in the C++03 Standard starts with the following:
A template defines a family of classes or functions.
template-declaration:
exportopt template < template-parameter-list > declaration
template-parameter-list:
template-parameter
template-parameter-list , template-parameter
Th... | No, it refers to:
template<typename T> int A<T>::staticDataMember;
// ^~~~~~~~~~~~~~~~~~~~~~~~~~~ declaration
If A is a class template like the following
template<typename T>
struct A { static int staticDataMember; };
|
6,161,963 | 6,166,936 | close for text file causing segmentation fault and `glibc detected` under linux in C++ | I have a log class, that class contains a stream defined as:ofstream logfile and a mutex to make sure that each time only one thread writes to the file (the program is multi-threaded).
The class is defined as:
#define LOG_NAME "log.txt"
using namespace std;
class Log
{
private:
pthread_mutex_t mutex_write;
of... | The problem was that we have a problem with checking that all threads have finished. We have repaired this, and now it works fine.
The problem probably happened because other threads tried to access a closed file, and sometimes tried to access a killed entity.
|
6,162,021 | 6,162,061 | How to fetch image from URL (HTTP) in c++? | How can I fetch an image from a URL in c++ and store it on harddisk?
Thanks.
I am working in the openGL environment in c++ so that code is not related to my question.
All i want to do is fetch some image from a URL and store it on my hard disk.
Which is the Google Map static map API which i want to use to fetch the ima... | C++ isn't PHP and has no means to do that itself. You'll have to use the platform API at least (to open a socket, which isn't a part of the C++ standard), and better yet, use a third-party library — for example, with Qt you could do that in a few lines.
|
6,162,027 | 6,162,043 | Notation of UML class diagram | I have the following class cDrawObjectCreator:
class cDrawObjectCreator
{
public:
cDrawObjectCreator( cCompositeRoot *compositeObject ) { m_compositeRoot = compositeObject; }
~cDrawObjectCreator() {};
...
private:
cCompositeRoot *m_compositeRoot;
};
It is correct diagram?
or the following diagram is cor... | First one again. For the same reasons as in the previous Question.
Please read this, to see the difference between Compostion and Aggregation.
|
6,162,226 | 6,164,397 | What rvalues have names? | @FredOverflow mentioned in the C++ chatroom that this is a rare case of rvalues that have names. The C++0x FDIS mentions under 5.1.1 [expr.prim.general] p4:
Otherwise, if a member-declarator declares a non-static data member (9.2) of a class X, the expression this is a prvalue of type “pointer to X” within the optiona... | One prominent case are enumerators
enum arity { one, two };
The expressions one and two are rvalues (more specifically, prvalues in C++0x). Another are template non-type parameters
template<int *P> struct A { };
The expression P is an rvalue too (more specifically again, a prvalue in C++0x).
|
6,162,265 | 6,162,296 | Floating point constants in templated code | I have a template function operating on a floating point argument. The function is templated so that a caller can use either float, double or any other floating point data type.
At one point in my code, I compare a value with zero (or any other floating-point constant). Should I use 0.0 or 0.0f for the comparison?
temp... | I'd suggest
if (a == T(0)) ...
|
6,162,338 | 6,162,348 | segmentation fault cause by delete[] while writing to a file | I'm trying to write to a file and i get a segmentation fault when i delete the allocated memory. I don't understant what is the problem, please help:
void writeToLog(string msg) {
int len = msg.size()+1;
char *text = new char(len);
strcpy(text,msg.c_str());
char* p = text;
for(int i=0; i<len; i... | Well, delete[] doesn't balance new char(N), it balances new char[N]. The former creates a pointer to a single char and gives it the value N; the latter creates a pointer to an array of char with length N, and leaves the values indefined.
Of course, to write a std::string to a FILE *, why not just do:
fwrite(msg.c_str()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.