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 |
|---|---|---|---|---|
5,714,491 | 5,714,913 | Downloading custom file formats | I've been tasked with allowing users to upload files to a webpage, and then other users can download that file.
The file format is a custom one, for this example I'll just call it .ccx. This is opened by our own custom software. The idea is, users can upload tutorial files to share with each other.
However, I'm conce... | On the server, you can run any command line virus scanner over them and have them look for known virus signatures. However, it is questionable whether this will improve security: since the virus writers would need to taylor your format, it doesn't seem very likely that their malicious files would match any known signat... |
5,714,616 | 5,714,720 | Usage of local class in C++ function | I see some usage of internal struct in c++ function.
There is a common interface IBase. Here is the draft code.
class IBase
{
virtual Method()=0;
}
vector<IBase*> baseList;
Then a function defined an internal class based on that IBase, and then push the internal class object into the baseList.
void func()
{
s... |
What's the scope of internal struct of "struct Object"?
The scope of the local classes is the function in which they're defined.But that isn't interesting in itself.
What makes local classes interesting is that if they implement some interface (like your code does), then you can create instances of it (using new) and... |
5,714,665 | 5,726,218 | Explicit specialization in non-namespace scope error... Desperately need help | Can somebody please help me to port the following code to GCC? I have found a lot or related questions on this site, but I just can't seem to apply suggested workarounds in my case...
typedef float MyData __attribute__ ((__vector_size__ (16)));
template <typename T> class Data_T
{
public:
template < typename U... | In this case overloading should suffice instead of specializing:
template <typename T> class Data_T
{
public:
template<typename U> static bool IsEqual(const U& a, const U& b)
{
return a == b;
}
static bool IsEqual(const MyData& a, const MyData& b)
{
return MyDataTypeIsEqual (a, b);
... |
5,714,689 | 5,714,726 | size_t to unsigned int (from API function) | I am using the Oracle API to access a database and this API has a function readBuffer(char * buffer, unsigned int size); to which I cannot make any changes.
I have a class that uses this API and the signature of my function currently takes a std::string and an unsigned int for the size, the problem is that when I pass ... | Yes, write a helper function that will check whether such conversion is valid and throw an exception otherwise. Something like:
unsigned int convert( size_t what )
{
if( what > UINT_MAX ) {
throw SomeReasonableException();
}
return static_cast<unsigned int>( what );
}
|
5,714,766 | 5,714,782 | C++ internals: Messing with the this-pointer | I have some questions about the internal workings of C++. I know for example that every member function of a class has an implied hidden parameter, which is the this-pointer (much in the same way Python does):
class Foo
{
Foo(const Foo& other);
};
// ... is actually...
class Foo
{
Foo(Foo* this, const Foo& o... | You cannot assign to this - it is of type Foo * const. You can delete this; in certain circumstances, but it's rarely a good idea.
|
5,714,854 | 6,170,644 | Invalid call stack in crash dump due to mismatched/missing *system* binary file? | Got this callstack when I open a Windows crash dump in Visual Studio 2005:
> myprog.exe!app_crash::CommonUnhandledExceptionFilter(_EXCEPTION_POINTERS * pExceptionInfo=0x0ef4f318) Line 41 C++
pdm.dll!513fb8e2()
[Frames below may be incorrect and/or missing, no symbols loaded for pdm.dll]
kernel32.dl... | If you absolutely want to debug this dump in Visual Studio, then you can get away with copying the system DLLs from the machine that produced the dump to the same folder where your .dmp file is. That way, it will load those binaries instead of trying to find them in the same path on the debugging system as they were on... |
5,714,870 | 5,714,907 | Should I use the initializer list or perform assignments in my C++ constructors? | class Node
{
public:
Node *parent; // used during the search to record the parent of successor nodes
Node *child; // used after the search for the application to view the search in reverse
float g; // cost of this node + it's predecessors
float h; // heuristic estimate of distance to goal
float f;... | For plain old data (POD), this has little benefit, but once you start either using references or composing classes it makes a difference:
class Foo {
Bar bar;
public:
// construct bar from x
Foo(int x) : bar(x) { }
};
versus
Foo::Foo(int x)
{
// bar is default-constructed; how do we "re-construct" i... |
5,715,045 | 5,717,221 | Setting registry value for all users | What is the best way to set registry value for all users on a machine.
Enumerating HKEY_USERS and changing ntuser.dat is one solution.
Any other solution that can be used in XP,VISTA as well as Windows 7?
Actually installer needs to write one key into registry. And that key need to be used by all users. Once its used ... | The pattern used by all software that needs this facility is, HKLM is a read-only store of defaults, set at installation time.
At runtime, the software must always try to read from HKCU first, and fallback to HKLM if the HKCU data is not present, or stale. Regular users always write to HKCU, ensuring that their own set... |
5,715,063 | 5,715,201 | Regarding encrypting a song | I want to encrypt an eminem song into a file in such a way that it cannot be decrypted. And i want to use it as a hash to encrypt my password.
How should i go about it in C or C++? What APIs can i use in Windows/Linux.
| Google around for password managers.
Some (keepass eg) will even allow you to use a key file.
If you wanted to use a keyfile to generate a password, may I suggest doing it yourself like so:
cat eminem.mp3
| openssl dgst -sha1 -binary -hmac password \
| openssl enc -base64 \
| cut -c 1-8
Replace 'password' by some... |
5,715,504 | 5,715,514 | How to create a reference to arrays and boost::array (or ideas to not have to)? | I have
int valA[3] = {290, 340, 390};
int valB[3] = {160, 200, 240};
boost::array<myStruct, 4> myStructA = {{{250,8}, {170,8}, {70,8}, {30,3}}};
boost::array<myStruct, 4> myStructB = {{{50,4}, {110,6}, {220,6}, {270,8}}};
and I want to avoid copy and paste when doing the following:
if(useA) {
// do a lot with valA... | int (&val)[3] = valA;
(You need the & to refer to val rather than int).
boost::array<myStruct, 4> &myStruct = myStructA;
(Template parameters are part of the type, not the variable name).
Also it needs to be int (&val)[3] = useA ? valA : valB; or equivalent, since in your example code you're planning to use val outside... |
5,715,851 | 5,718,736 | Exe produced with VS 2010 and VS 2005 loaded with a different offset | Loading process image file different between VS 2005 and VS 2010
We have a post build step which modifies (patches) some locations in the executable. The patching process loads the process in the memory using CreateProcess and reads its code segment memory using ReadProcessMemory. Then a sequence 0x8D, 0x05, XX, XX, XX... | It seems exe produced with /OPT:WIN98 has a slightly larger header (aligned to 4 KB). When this flag is not specified, the code is still loaded from 0x401000, but the header is only 0x400 instead of 0x1000, resulting in the image offset of 0xc00.
|
5,715,865 | 5,716,028 | How to perform casting with multiple inheritance | My classes structure is like:
class MethodHelper : public QObject, public IMethodHelper {
public:
// Stuff
};
Now, I get a pointer to the object:
QObject* someObject = getMethodHelper();
Here, I am extremely sure that someObject is a type of MethodHelper. I somehow want to cast it to IMethodHelper. How should I g... | You could do it the way you present, but it isn't necessary. The Below should work fine.
IMethodHelper* myIHelper = dynamic_cast<IMethodHelper*>(someObject);
|
5,715,923 | 5,715,960 | What is default destructor if a class inherits from a pure base class? | Considering next two classes :
struct Base
{
virtual ~Base()
{
}
virtual void foo() = 0;
};
struct Derived : public Base
{
virtual void foo()
{
}
};
Is the following causing an undefined behaviour :
Base *obj = new Derived;
delete obj;
?
Additional question : how come that one a method is declared vir... |
Is the following causing an undefined behaviour :
No, that is not invoking undefined behaviour precisely because the destructor of Base is virtual.
EDIT: Its just to clarify a doubt (raised in the following comment), and to emphasize what I said above.
@Oli Charlesworth commented:
Technically, even if it were not d... |
5,716,003 | 5,718,579 | Post data on Web using C++ Script | I am using TestComplete 7. In this for configuration I have to post XML on web at specified IP and port address. I am using C++ Scripting language. How can I do this? or if there is other way to do same using interface and without scripting??
| Looks like you need something like this:
XmlHttpRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
XmlHttpRequest.open("POST", "http://camera.ip/configuration_page", false);
XmlHttpRequest.send("<?xml version="1.0" ?> <Config> <Video_Input_Source>IP CAM 3</Video_Input_Source> </Config>");
This is JScript. This c... |
5,716,064 | 5,716,168 | Warning: should not initialize a non-const reference with a temporary | I get the warning from the title on Sun Studio 12.1 with the following snippet:
#include <vector>
std::vector<int> g()
{
std::vector<int> result;
result.push_back(5);
return result;
}
int main()
{
int b = g()[0]; // <- Warning in this line
return b;
}
Warning text is:
Warning: should not initialize a non... | This Sun compiler looks very weird, it doesn't seem legitimate at all to me. Ideone has no problem compiling it.
Regarding the silencing part:
std::vector<double> const tmp = g();
int b = tmp[0];
That is, introducing a named variable instead of leaving the temporary floating.
EDIT:
As suggested in comments, const-qual... |
5,716,153 | 5,716,179 | Light-Weight Database System for C++ | I need to use light-weight database because i have limited resource for application.
So i'm searching a light-weight database which i can use with C++, which is easy to manage, fast to retrieve data and uses up limited amount of resource.
I have found SqlLite in the internet. But before i start to implement my projec... | You've already find your best option in my opinion: SQLite.
You could technically use something even lighter like plain old file system with random file access. But you will miss two key points:
Easy creation of indexes on your data
An awesome language to get and manipulate data: SQL
SQLite will only add a couple of ... |
5,716,291 | 5,716,317 | Can POD-structs be initialized using named attributes in a portable way in C++? | I am trying to initialize a struct using named attributes in a way that is compatible both with GCC 4.3.4 and Clang 2.9.
struct A {
unsigned int x;
};
// GCC: error: expected primary-expression before '.' token
A a = {
.x = 0xdeadbeef;
};
// Clang: error: use of GNU old-style field designator extension [-Werror,-... | No, you cannot name the values, just give them in order.
A a = { 42 };
If new fields are added at the end of the struct, they will be zeroed.
|
5,716,352 | 5,716,761 | Data and Time format in c++ | I need to convert Date time in 17 byte format.
The format is
MMDDYYYY HH:MM:SS
in ASCII.
Example date and time: 01212009 09:38:57
Hexadecimal format
0x30 0x31 0x32 0x31 0x32 0x30 0x30 0x39
0x20 0x30 0x39 0x3A 0x33 0x38 0x3A 0x35 0x37
the problem is how to convert this 01... | The hexadecimal values that you posted are exactly the ascii values for the string that you posted, 01212009 09:38:57.
There's really no conversion done from that string to the hex values in your example.
so if you have this:
const char* dateStr = "01212009 09:38:57";
and you print it like this:
for (int i=0; i < strl... |
5,716,463 | 5,716,569 | Printing details about file stream objects in gdb - c++ | I have function whose signature is something like so:
void someFunc(ifstream ifile) {
This function is embedded deep within the code. When I am debugging this code with ddd, how can I get the name of the file from the ifstream object. Trying the following:
p ifile or
ptype ifile
leads to a mountain of informati... |
Is there a way to get the filename that ifile is a stream to?
No way. That's not possible.
std::ifstream doesn't store the filename, neither does it provide any get function to get the filename. Thus, you cannot get it, given an object of type std::ifstream.
If you really need to know the filename inside the functio... |
5,716,550 | 5,716,582 | waiting for time to pass without busy waiting in C windows | I have a thread whose job is to send messages to UDP peers. the threads sends the messages iff one of the following apply:
1) a certain time has passed since the last time it sent a message (like a timeout).
2) an update boolean flag in a shared struct has been raised by other thread.
i want to be able to wait for the... | For windows, use an event (CreateEvent) rather than a bool, then WaitForSingleObject on it.
|
5,716,651 | 5,716,748 | C++, How floating-point arithmetic operations get optimized? | I observed a surprising behavior when testing simple arithmetic operations at limit cases, on an x86 architecture:
const double max = 9.9e307; // Near std::numeric_limits<double>::max()
const double init[] = { max, max, max };
const valarray<double> myvalarray(init, 3);
const double mysum = myvalarray.sum();
cout << "... | Just a guess, but: It may be that Average (2) is computed directly in the floating point registers, which have a width of 80 bits and overflow later than the 64 bit storage for doubles in memory. You should check the disassembly for your code to see if that is indeed the case.
|
5,716,693 | 5,716,788 | how to get string from a line of strings? | I have following string:
"hw_core_detectionhook::Iocard const*"
I have to get only first part, i.e all text present before space, i.e I need the "hw_core_detectionhook::Iocard" part only.
| s.substr(0,s.find_first_of(" "));
|
5,716,710 | 5,716,778 | create control dynamically vs drag and drop | Are there any differences as far as performance, memory usage, etc. between creating controls (picturebox, button, textbox, etc.) by drag and drop into the form vs created it dynamically in code for ASP.NET in C# or C++? Which method is preferred by the pro?
| Generally professionals design the Forms by writing Code.
But the the control needed at runtime or compile time is really depends upon situation or need.So It is not having any performance aspects between these two approaches.
Generally beginners should design the form by daragging and dropping controls on the form , a... |
5,716,917 | 10,054,386 | Is there a good DirectX (3D) DirectWrite tutorial somewhere? | I'm refactoring some of my directx10 code to directx11 and trying to figure out DIrectWrite for my text functions. From MSDN, I hear that they're switching everything to this and that directwrite is now included with direct3d. But, eh - I can't find a tutorial that actually shows 3d Rendered text with directwrite. Anyo... | Microsoft "Direct3D and Direct2D text overlay sample" should do the trick ! http://code.msdn.microsoft.com/windowsapps/Direct2D-Direct3D-Interop-ee641e46
|
5,717,163 | 5,717,389 | C++ STD::find_if using structure predicate | key_struct kStruct;
kStruct.x = 2;
std::find_if(m_cueCommands.begin(), m_cueCommands.end(), find_MyInt(kStruct));
struct key_struct
{
int x;
string y;
string z;
}
struct find_myInt : std::unary_function<key_struct, bool>
{
int x;
find_myInt(key_struct kStruct):myInt(kStruct.x){} ... | Do you always want to compare with x? Or only if x != 0?
Btw, there seems to be an error in your struct constructor: there is no member named myInt, thus it should be: find_myInt(key_struct kStruct) : x(kStruct.x){}. But that doesn't matter, it needs to be changed anyway.
Here's what I would try. This is untested, migh... |
5,717,474 | 6,714,578 | rapidxml parse error with url attribute | I'm getting a strange error with rapidxml when parsing a xml file like
<?xml version="1.0" encoding="UTF-8"?>
<IMG align="left"
src="http://www.w3.org/Icons/WWW/w3c_home" />
It throws "expected >".
Im using a code like the following to parse the data
std::fstream file("./test.xml");
std::istream_iterator<char> eos;
s... | The way you load the XML data into vector is wrong. In C++ text mode streams have "skipws" flag set by default, which causes them to skip all whitespace in the input. You can verify this by examining the contents of your vector - it will have all spaces/endlines missing. This obviously causes the parser to complain.
Un... |
5,717,627 | 5,717,671 | empty while synchronization in c++? | static char szInfo[256];
static volatile bool bIsLocked = false;
static void ApiFunc() {
while (bIsLocked) { }
bIsLocked = true;
//do something to szInfo
bIsLocked = false;
}
It has been awhile since I have done any threading in C++, Is this safe enough? This is a much simpler solution to me than usin... | You would use a mutex (or more likely a critical section) because that would work. This code does not synchronise. Multiple threads can enter the critical region.
And of course, real locks don't spin. Well, spin-locks do, but you need a deep understanding of the performance implications of a spin-lock before electing t... |
5,717,679 | 5,717,925 | Using std::transform and tr1::bind to transform a vector of std::complex | Given a std::vector of std::complex, I would like to transform it to a vector containing only the real part of the complex, divided by some constant coefficient.
Right now, I do that:
std::vector<std::complex<double> > vec;
std::vector<double> realVec;
double norm = 2.0;
...
for (std::vector<std::complex<double> >::ite... | Unfortunately, you can't do this, at least not directly. The types of Standard Library member functions (like complex<double>::real) are left unspecified, so an implementation may provide additional overloads and the functions that are there may have additional parameters with default arguments.
In effect, there is ... |
5,717,852 | 5,720,602 | How to mark a function as non-returning in Parasoft C++test? | We have a die function that outputs an error message and exits, e.g.:
void die(const char* msg) {
fprintf(stderr, "Error: %s\n", msg);
exit(1);
}
We use Parasoft C++test to statically analyze our code, but it doesn't realize that die is a non-returning function. So when it sees code like:
void foo(Bar* bar) {
... | I figured it out. It turns out Parasoft has a built-in list of NRFs you can customize; they're called "terminating functions". You can edit them through the VS GUI or through the configuration file if you run Parasoft outside of VS
Through Visual Studio
Open the Test Configurations dialog from the C++test menu
Select ... |
5,718,119 | 5,718,173 | C++: How to add raw binary data into source with Visual Studio? | I have a binary file which i want to embed directly into my source code, so it will be compiled into the .exe file directly, instead of reading it from a file, so the data would already be in the memory when i launch the program.
How do i do this?
Only idea i got was to encode my binary data into base64, put it in a st... | The easiest and most portable way would be to write a small
program which converts the data to a C++ source, then compile
that and link it into your program. This generated file might
look something like:
unsigned char rawData[] =
{
0x12, 0x34, // ...
};
|
5,718,393 | 5,718,690 | My getline and cout statement within my for loop are being truncated | For this code, it asks for the first song, and stores and prints it. But after the first entry, i'm asked if i would liek to continue like i wanted, but then after i type in Y, it skips over my song question and getline function and straight into asking about if i want to continue or not, what am i doing wrong here?
Th... | The problem is that your "cin>>answer" reads a single character but you type 'y' then press enter, so the the newline character is still sitting in cin. So when your loop goes back around getline just reads that newline character and you end up with an empty string.
If you do:
string dummy;
getline(cin, dummy);
after ... |
5,718,405 | 5,731,251 | debugging a fastcgi application | I have deployed a fastcgi application on my server. When I try to run it on the server, it crashes (more of this later).
First some facts on the local (dev) machine:
The application is C/C++ application
I developed the app on Ubuntu 10.0.4 LTS (same OS on server)
During development, I used gdb to step through code to ... | Posting as an answer at original poster's request:
1. You can copy your core dump to a machine with gdb and see a backtrace there. gdb -c core_name binary.name, then bt.
2. How do you know your app crashes before starting? Start logging things to a file instead of relying on live gdb sessions only.
|
5,718,556 | 10,141,963 | VS2010 with extern keyword | I have the following two files:
foo.h
bar.cpp
In foo.h I decleare a variable extern.
Now, I would like to use the same variable in bar.cpp (after including foo.h).
Under VS2008 and VS2010 I get unresolved external symbol errors, while under Ubuntu with gcc the compilation is successfull.
(Namely, I'm trying to compil... | The problem was, that the afformentioned symbol has to be exported (via dllspec) from the dll, to be visible from outside. Only the extern keyword did not allowed it to be seen from outside.
|
5,718,944 | 5,719,238 | gdb catchpoint for uncaught C++ exceptions only? | I can tell the gdb debugger to stop as soon as any C++ exception is thrown by setting a catchpoint with the gdb command
catch throw
However, is there any way to only stop at uncaught C++ exceptions (like in C# or Java)? This would make it much easier to find bugs in some situations.
Thanks!
| If an exception is uncaught, the special library function terminate() is automatically called. Terminate is actually a pointer to a function and default value is the Standard C library function abort(). You may be able to set a breakpoint on the call to the abort() function and identify the location of the uncaught e... |
5,719,093 | 5,719,203 | In place constrution of member variable via constructor | Take the following class:
template <typename TPayload>
class Message
{
public:
Message(const TPayload& payload)
: m_header(sizeof(TPayload)),
m_payload(payload) {}
private:
const Header m_header;
const TPayload m_payload;
};
Whenever I construct a Message ... | What you're looking for is forwarding of constructor arguments given to Message to the constructor of Message::m_payload.
This can be done neatly in C++11 (using variadic templates and std::forward, as used in std::vector<>::emplace_back() and many other functions) or with several overloads in C++03, as you started wri... |
5,719,438 | 5,719,555 | How to check if path leads to executable file? | I try to create some kind of file browser. I want to know if file under path is executable in a cross-platform way.
How to do such thing with boost::filesystem?
| Boost doesn't have stuff about permissions, because POSIX permissions are not "crossplatform".
Use the platform-specific APIs at your disposal as required. Sorry!
|
5,719,636 | 6,180,198 | Lifetime of temporary bound to aggregate initialized struct member | Given the following code:
class foo
{
};
class bar: public foo
{
public:
~bar() { printf("~bar()\n"); }
};
class zab: public foo
{
public:
~zab() { printf("~zab()\n"); }
};
struct foo_holder
{
const foo &f;
};
int main()
{
foo_holder holder[]= { {bar()}, {zab()} };
printf("done!\n");
retur... | I got an answer on comp.std.c++:
http://groups.google.com/group/comp.std.c++/msg/9e779c0154d2f21b
Basically, the standard does not explicitly address it; therefore, it should behave the same as a reference declared locally.
|
5,719,842 | 5,719,867 | What is wrong with my usage of C++ standard library's find? | I'm trying to use the C++ standard library's find algorithm like this:
template<class T>
const unsigned int AdjacencyList<T>::_index_for_node(
const std::vector<T>& list, const T& node
) throw(NoSuchNodeException)
{
std::vector<T>::iterator iter = std::find(list.begin(), list.end(), node);
}
When I... | std::vector<T>::iterator iter = /* .... */;
iterator is a dependent name (effectively, it depends on the type parameter T). Dependent names are assumed not to name types unless you use typename:
typename std::vector<T>::iterator iter = /* .... */;
For more, consider reading the Stack Overflow C++ FAQ entry "Where a... |
5,719,861 | 5,720,411 | Managing propagation of Event: pointer or instance? | I'm coding an event handling system ( following observer pattern... ) and I'd like to know which is the best way to propagate or spread an Event class, something like this:
class Event{
public:
Event(int code);
virtual ~Event();
int getCode() const;
private:
int code;
};
In detail if better to send it... | If you pass a stack-allocated object by reference, there is no performance difference between that and passing by pointer.
If you pass by pointer, then some piece of code has to be responsible for delete-ing the object. OTOH, if the lifetime of the object needs to persist beyond the scope in which it's created, then y... |
5,719,891 | 26,214,627 | Numeric unique identifier of a class via typeid | The typeid operator in C++ returns an object of class std::type_info which can yield its textual name. However, I'm just interested in getting an unique numeric identifier for any polymorphic class. (unique in the scope of a single program run - not necessarily between runs)
In practice, I could just dereference the po... | std::type_index (C++ 11) can be used in containers to store values based on type. It won't give you a number though.
std::type_index index = std::type_index (typeid (int));
More: http://en.cppreference.com/w/cpp/types/type_index
The type_index class is a wrapper class around a std::type_info object, that can be used ... |
5,720,039 | 5,720,116 | g++ on Mac OS X - CoreServices.h Error | When I compile the following code with g++
#include <CoreServices/CoreServices.h>
int main(int argc, char ** argv)
{
return 0;
}
I get this error.
bash-3.2$ g++ test.C
In file included from /System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:43:0,
from /System/Library/Framew... | It looks like you're trying to use Apple's frameworks without using Apple's toolchain - that's probably not going to work. Your example program compiles fine here for me, using the gcc that came with Xcode (and with clang):
$ cat example.cpp
#include <CoreServices/CoreServices.h>
int main(int argc, char ** argv)
{
... |
5,720,167 | 5,720,244 | Why is passing a char* to this method failing? | I have a C++ method such as:
bool MyClass::Foo(char* charPointer)
{
return CallExternalAPIFunction(charPointer);
}
Now I have some static method somewhere else such as:
bool MyOtherClass::DoFoo(char* charPointer)
{
return _myClassObject.Foo(charPointer);
}
My issue is that my code breaks at that point. It doe... | You need to build the project with Debug settings. Release settings mean that optimizations are enabled and optimizations make debugging a beating.
Without optimizations, there is a very close correspondence between statements in your C++ code and blocks of machine code in the program. The program is slower (often ... |
5,720,326 | 5,721,475 | Suspending and resuming threads in c++ |
My application has to suspend and resume a different process every few *microsec*s.
It works fine only sometimes it feels like it suspends the process for non-uniforms times.
I use the win API: ResumeThread and SuspendThread.
On the other hand, I tried something a little different.
I suspended the thread as usual wi... | SuspendThread() call does not suspend a thread instantly. It takes several time to save an execution context, so that ResumeThread() might be called when a thread has not suspended yet. That's why while (ResumeThread(threadHandle) > 0); works. To determine the current thread state you can call NtQueryInformationThread(... |
5,720,359 | 5,720,418 | No matching function call to <anonymous enum> | Given:
template<typename T>
void f( T ) {
}
enum { // if changed to "enum E" it compiles
e
};
int main() {
f( e ); // line 10
}
I get:
foo.cpp: In function ‘int main()’:
foo.cpp:10: error: no matching function for call to ‘f(<anonymous enum>)’
Yet if the enum declaration is given a name, it compiles. Why do... | Unnamed type simply cannot be used as a template argument
C++03 says in 14.3.1[temp.arg.type]/2
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
This limitation was lifted in C++0x, and your progr... |
5,720,360 | 5,720,375 | What is T (& var)[N]? | In boost/utility/swap.hpp I have found this piece of code:
template<class T, std::size_t N>
void swap_impl(T (& left)[N], T (& right)[N])
{
for (std::size_t i = 0; i < N; ++i)
{
::boost_swap_impl::swap_impl(left[i], right[i]);
}
}
What are left and right? Are they references to arrays? Is this code allowed... | A reference to an array of type T and length N.
This is a natural extension of C's pointer-to-array syntax, and is supported by C++03.
You could use cdecl.org to try to parse these complex type declarations.
|
5,720,539 | 5,720,572 | Change constructor precedence | Is it possible to define a constructor for all derived types and a template constructor?
I've written this testcase to illustrate my problem:
#include <iostream>
class Variant;
class CustomVariant;
class Variant
{
public:
Variant(void)
{}
Variant(const Variant&)
{
std::cout << ... | template <typename T> Variant(const T&) // (a)
Variant(const CustomVariant&) // (b)
No conversion is required to call (a); the argument type, DerivedVariantB, is an exact match where T = DerivedVariantB.
A derived-to-base conversion is required to call (b). Therefore, (a) is a better match than (b).
If yo... |
5,720,650 | 5,732,650 | How to use `randomize_property` with bundled property graph in boost graph library? | In the documentation: http://www.boost.org/doc/libs/1_46_1/libs/graph/doc/random.html#randomize_property
There is only a function prototype, I cannot find a working example.
I tried several things but it just cannot compile.
Here's a simple source code:
#include <ctime>
#include <iostream>
#include <boost/graph/random.... | This compiles for me:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/random.hpp>
#include <boost/random/linear_congruential.hpp>
struct myedge {
myedge(int x) : testme(x) {
}
int testme;
};
typedef boost::adjacency_list<boost::setS, // disallow parallel edge
boost::vecS,
boost::undirectedS,... |
5,720,834 | 5,720,850 | iostream header vs iostream class | If there is a file foo.cpp, then it usually has an associated header file foo.h with all the declarations for the functions defined in foo.cpp. That way all other files which make use of functions in the foo.cpp can just include the foo.h file and use them. Thats my simple understanding of header files.
However, I don... | The relation between headers and classes isn't necessarily one-to-one; that's just a rule of thumb often taught to novice programmers. In fact, the C++ language standard does not specify any direct relation between classes, implementation files (translation units), and headers at all and the standard library often devi... |
5,720,884 | 5,720,902 | Load 32-bit shared library from 64-bit application? | I have a shared library that is compiled as 32-bit. Can I use it from a 64-bit application or do I need to compile the shared library as 64-bit as well?
| No, you cannot load a 32-bit library in a 64-bit application through conventional means.
There are some clever hacks out there such as having a 32-bit application which loads the library and exports the functions through an IPC interface, but if you have the option to compile the library as 64-bit, then that is by far ... |
5,721,064 | 5,721,132 | Is this a deep copy and properly implemented = operator for a C++ Linked List? | I'm running into some bugs now that I'm trying to use the doubly linked list class that I made. My implementation of the = operator looks like the following:
template <typename T>
Dlist<T>& Dlist<T>::operator=(const Dlist &l)
{
copyAll(l);
return *this;
}
template <typename T>
void Dlist<T>::copyAll(const Dli... | You say "some bugs". It's helpful to mention what those are when asking a question.
That said, look at the first two lines of copyAll. The first line allocates a new node, the second overwrites that pointer, losing it forever. Maybe you meant copyList.first = l.first. You'll also need to construct new nodes inside the ... |
5,721,111 | 5,721,166 | Returning abstract datatypes in C++ without dangling pointers | Hallo,
I come from a C# background and don't have a lot of C++ experience. To produce clean code I try to separate implementation and interfaces and use inheritance when possible. And when I tried to apply typical C# concepts to C++ I ran into a problem that I've been unable to resolve so far. I assume that this is pro... | If you're afraid of memory leaks, switch to smart pointers. That has the additional benefit of being self-documenting wrt. ownership of the returned object.
class IProperty
{
public:
virtual ~IProperty() {};
virtual std::unique_ptr<PropertyBase> correct(const ICorrector &) = 0;
virtual std::unique_ptr<Prope... |
5,721,532 | 5,722,017 | Placement new strange behaviours | Do not ask me what I'm trying to do, this is just a quick test and its only purpose is to see if there is something wrong with placement new.
I've found an issue, or I just misunderstood something.
#include <vector>
using namespace std;
#define WORKS
int main(int argc, char** argv) {
vector<int>* pp = (vector<in... | §5.3.4/12:
-- new T[5] results in a call of operator new[](sizeof(T)*5+x)
[ ... ]
Here, x and y are non-negative unspecified values representing array allocation overhead; the result of the new-expression will be offset by this amount from the value returned by operator new[]. This overhead may be applied in all arra... |
5,721,692 | 5,722,697 | QListView height according to contents | I have a QListView with a list of strings.
Basically, I use it as pop window for a QLineEdit for an autocomplete process.
I dont want the QListView to display blank lines, only lines that have strings in it.
See this:
I want it to resize itself automatically so it wont have these blank rows after the last entry.
Thank... | You can try to do this: Reimplement QListView::rowsInserted() method class. Say you have MyListView inherited from QListView. So the code can look like this:
void MyListView::rowsInserted ( const QModelIndex & parent, int start, int end )
{
QListView::rowsInserted(parent, start, end);
int rc = model()->rowCount... |
5,721,714 | 5,721,744 | Defining constants in C | I was working with C++ for a long time and now I am on a C project.
I am in the process of converting a C++ program to C.
I am having difficulty with the constants used in the program.
In the C++ code we have constants defined like
static const int X = 5 + 3;
static const int Y = (X + 10) * 5
static const int Z = ((Y +... | You need to remove the semi-colon from the #define X line
#define X (5+3)
#define Y (((X) + 10) * 5)
#define Z ((((Y) + 8) + 0xfff) & ~0xfff)
|
5,721,728 | 5,721,773 | Dynamic allocation with DOUBLE POINTERS | I have a base class Toy and derived classes Toy_remote_car amd Toy_battery_car.
I am doing this:
Toy** ptr;
ptr=new Toy*;
ptr[0]=new Toy_remote_car[1];
ptr[1]=new Toy_battery_car[1];/*this is completely wrong according to my teacher because i never created ptr[1]. Instead this is a misuse of memory according to him.*/
... | Toy **ptr = new Toy *[n];
where n holds the number of Toy pointers you want. Growing the array is hard, but it can be done:
// Add x to toypp, an array of n pointers
// very stupid, linear-time algorithm
Toy **add_toy(Toy *x, Toy **toypp, size_t n)
{
Toy **new_toypp = new Toy*[n+1];
// copy the old array's co... |
5,721,765 | 5,722,160 | Unable to start the program, System cannot find the file specified VS2010 | The problem is that when I try to debug is gives me the error message in this topic title.
I have checked the debug command and it is pointing to the correct location of the General Output Directory and the Linker Output File.
I've had this problem before and the above solution would fix it, but this time I'm stumped.
... | It may be that the file it cannot find isn't the executable itself, but a dependency of it, such as a DLL.
Make sure that:
You have really rebuilt the project
You have specified the correct executable
The "Current working directory" is someplace from which you can see the Dependant DLLs
|
5,721,813 | 5,722,191 | Compile-time assert for string equality | Is this possible to do using templates?
There are two string constants. They come from defines in different modules. They must be equal, or I shall raise compile-time error if they are not equal. Can I do this using templates?
#define MY_STRING "foo"
CompileAssertIfStringsNotEqual(MY_STRING, HIS_STRING);
P.S. I was de... | This is only possible with C++0x. No chance with C++03.
EDIT: Constexpr function for C++0x. The following works with GCC4.6, however the Standard is not explicit in allowing it, and a small wording tweak was and is being considered to make the spec allow it.
constexpr bool isequal(char const *one, char const *two) {
... |
5,721,894 | 5,722,025 | Always create classes in C++? | Coming from a Java background it is new for me to deal with the choice of creating a class or just implementing the functions I might need. Normally this is no question when it comes to modeling something which could have a state.
Now I am implementing a shared library which has no main function and exclusively static ... | Not sure if I completely understand you but yes you can create a container class that provides static methods. It may be worthwhile to make the constructors private to prevent people from instantiation an instance of the class.
class HelperFunctions
{
public:
static void DoSomethingUseful() { /* useful bits */ }
... |
5,722,189 | 5,722,362 | MFC Unclickable Button (Running away from cursor on MouseMove) | How would i make a button that will change it's position on MouseMove Event if the cursor is close enough to the center of the button in MFC ?
| WM_MOUSEMOVE is not delivered to the button if the cursor is not over it (and is not captured, but you don't want that). So you have to process WM_MOUSEMOVE in the parent dialog. If you want your button to be a self-contained control, you have to subclass the parent window upon button creation.
Subclassing, in this con... |
5,722,307 | 5,722,454 | why does the standard disallow "virtual void funcFoo() = 0 { }"? | [I couldn't find a proper answer to this. Kindly point me to proper links if this is already answered.]
I know that it illegal to do something like this,
class Base
{
public:
virtual void funcFoo() = 0 {} //illegal. should be defined outside the class body
virtual ~Base() {}
};
But this works fine on VS2008.... | I don't think there is much of an answer to this. It came up once before (possibly on Usenet instead of SO -- I don't remember), so I did some looking. I didn't really come up with much of anything. As far as I can tell, that's how Bjarne originally devised it. Although it could be changed, I couldn't find any proposal... |
5,722,536 | 5,722,877 | C++ runtime datatype identification & avoiding switch-case | I have the following code that I hope to simplify and minimize duplication.
// Gather.cpp
void GetParam()
{
ProParameter * param; // 3rd party struct
ProParamvalue proValue; // 3rd party struct
ProParameterValueGet( param, & proValue ); // this is a call to a 3rd Party API
shared_ptr< CPartParam > pPara... | Have a look at Boost.Variant (which is available in Boost 1.36.0). This provides a variant type that encapsulates the discriminated union (taking the place of your CPartParam type), and a static_visitor idiom that takes the place of the switch.
|
5,723,013 | 5,723,156 | Templates and STL Containers | template<typename T>
class Foo {
template<???>
Foo(Container<T> c) {
}
};
...
//this can't be changed
std::vector<int> vec;
Foo<int> foo1(vec);
std::list<double> list;
Foo<double> foo2(list);
Hmmm?
| It isn't at all clear to me what you are asking for. I think you may need to edit your question to be more specific and more complete.
Until then, your program will compile just fine if you do this:
#include <vector>
#include <list>
template <typename T>
class Foo {
public:
template<typename T1>
... |
5,723,048 | 5,723,100 | Strange outputs of mixed up std::cout | C++'s std::cout seems to be an interesting thing. I tried the following program on my C++ compiler today:
cout<<"!"<<"@"<<endl;
cout<<"!"<<cout<<"@"<<endl;
cout<<"!"<<(cout<<"@")<<endl;
And the outputs are rather curious:
!@
!0x601068@
@!0x601068
The first line is pedestrian; the second is understandable; however, th... | This line:
cout<<"!"<<(cout<<"@")<<endl;
It is first executing:
(cout << "@")
Note: It could have executed something else first, but the compiler optimized this sub-expression and found it could move this to the start of the statement without breaking any constraints.
The result of this expression is a stream (cout).... |
5,723,077 | 5,723,119 | How to read part from file into stringstream? | I need to stream data to a stringstream from a binary file:
stringstream body;
body << std::ifstream( path.string().c_str(), ios::binary).rdbuf();
But it read the whole file from its begining to its end.
How do I read the file to the stringstream starting from 200th byte, and going to 3000th?
| There's no way that I know of to directly read from the file's read buffer into the stringstream. That doesn't mean one doesn't exist; it just means that I don't know it off the top of my head. :-)
One option you might want to explore would be to read the data into a temporary buffer, then put that string into the str... |
5,723,271 | 5,723,345 | Fast Algorithm for finding largest values in 2d array | I have a 2D array (an image actually) that is size N x N. I need to find the indices of the M largest values in the array ( M << N x N) . Linearized index or the 2D coords are both fine. The array must remain intact (since it's an image). I can make a copy for scratch, but sorting the array will bugger up the indi... | Selection is sorting's austere sister (repeat this ten times in a row). Selection algorithms are less known than sort algorithms, but nonetheless useful.
You can't do better than O(N^2) (in N) here, since nothing indicates that you must not visit each element of the array.
A good approach is to keep a priority queue ma... |
5,723,309 | 5,723,331 | memory leak! how to fix? | Ok, so i'm just learning about memory leaks. i ran valgrind to find memory leaks. i get the following:
==6134== 24 bytes in 3 blocks are definitely lost in loss record 4 of 4
==6134== at 0x4026351: operator new(unsigned int) (vg_replace_malloc.c:255)
==6134== by 0x8048B74: readInput(char&) (in calc)
so does that... | // ...
return new double(atof(in.c_str()));
// ...
new acquires resource from free store which is being returned. The returned value must be deallocated using delete to avoid memory leak.
If you are calling the function in a while loop, number should be definitely deallocated using delete before running the loop n... |
5,723,323 | 5,723,363 | Segmentation fault error - C programming | I am receiving a Segmentation Fault error when I run this program. To summarize, the program reads in multiple data files (129 of them). Each file contains information about a specific name. The information includes how many people were named a specific name in a specific year and the gender. For now, I am trying to st... | Surely
tempPtr->namePtr = (char *) malloc(sizeof(length + 1));
should be
tempPtr->namePtr = (char *) malloc(length + 1);
since you copy that many characters to the string. sizeof (length + 1) would evaluate to four on a 32-bit machine (eight on 64-bit). Not enough memory was being allocated, so the strncpy which fo... |
5,723,619 | 5,723,667 | Is it possible to create function-local closures pre-C++11? | With C++11, we get lambdas, and the possibility to create functions/functors/closures on-the-fly where we actually need them, not somewhere where they don't really belong.
In C++98/03, a nice way to make function-local functors/closures would've been the following:
struct{
void operator()(int& item){ ++item; }
}foo_f... | bind1st only works for binary functions, and in general it's very restricted. mem_fn works with non-static member functions only; for your application you would want ptr_fun.
Really the best tool for the job in C++03 is Boost Bind, or I'll demonstrate here with tr1::bind which is (in my opinion) more portable.
#include... |
5,723,639 | 5,723,732 | C++ DLL called from C++ Console App Works, called from C# Console App has stack overflow | I recieved some C/C++ code for use in another project. I put it into a DLL and then called the DLL from a C++ test harness. It worked fine and matched the results from when the code was just a function call.
However, I then tried to get the DLL to work from a C# application. I converted the test harness, and made the D... | The ref double array seems problematic,
Add [MarshalAs] to it and pass IntPtr, not a double array.
.net arrays are not pointers, as they are in C++.
Mark that c# method as private,
wrap with public method that uses Marshal.Copy to transfer returned pointer to .net array.
Example for transferring array when allocated in... |
5,723,739 | 5,723,824 | how to receive map<A, B>& from function/class? | How to receive map<string, factory<BaseClass, ConstructorType> > from such function?
So I have
template <class BaseClass, class ConstructorType>
map<string, factory<BaseClass, ConstructorType> > get_factories (shared_library & lib) {
type_map lib_types;
if (!lib.call(lib_types)) {
cerr << "Types map no... | If you need a reference to a map, you should declare the function as returning a reference, not a value:
template <class BaseClass, class ConstructorType>
map<string, factory<BaseClass, ConstructorType> >& get_factories (...
Of course, this assumes that the reference returned by lib_types.get() is safe to pass out as ... |
5,723,766 | 5,724,633 | Which compiler did macport use? | I'm working on a c++ project which just implemented some of the shared pointer features from boost and/or TR1. Since the upgrade, my code no longer compiles with gcc 4.2.1 (provided by Xcode), I'm installing gcc 4.5.x which is suppose to provide the aforementioned features. I need to recompile mpich2 (and then my code)... | MacPorts - Using the Right Compiler
|
5,723,893 | 5,723,966 | is there any way to configure waf to build c++ program in mac os? | I just suffer a problem that the all the things works well on my ubuntu.
However, I want to get things work on my mac, bad thing happens.
it shows the following errors
cc1plus: error: unrecognized command line option "-std=c++0x"
I am total new to mac stuff, I got the xcode 4 installed.
I guess there must be c++0x,... | I’m guessing you’re using GCC supplied with Xcode. That’d be GCC 4.2.1, a rather old version that won’t be updated by Apple in the foreseeable future.
You have essentially two options:
Xcode ships Clang/LLVM besides GCC, so you could use Clang/LLVM instead. That -std=c++0x option is recognised by Clang/LLVM but C++0x ... |
5,723,949 | 5,723,979 | Serial communication timeout in C++ with Arduino | The code below is what I am using to send and receive information from my Arduino. My problem is when the Arduino is first plugged in. Reading from it hangs because the command doesn't return anything because there is nothing there yet so my whole program crashes. How can I add a time-out to the read function, which i... | Set arduino->ReadTimeout = duration_in_ms and then catch TimeoutException.
|
5,724,119 | 5,724,134 | Why I cant return Boost::Scoped_ptr from function? | So I try to create some wrapper around boost.extension functions for class creation. So I have created a function:
template <class BaseClass, class ConstructorType>
boost::scoped_ptr<BaseClass> get_class (shared_library & lib, std::string class_name, ConstructorType value ) {
map<string, factory<BaseClass, Construct... | boost::scoped_ptr is noncopyable. Since you can't copy a scoped_ptr, you can't return one either (returning an object by value requires that you are able to make a copy of it, at least in C++03). If you need to return an object owned by a smart pointer, you need to pick a different type of smart pointer.
If your comp... |
5,724,578 | 5,724,685 | Why does this OpenGL Shader segmentation fault on calls to glCreateShader? | I'm trying to learn how to write OpenGL Shaders. Why does this code segmentation fault when run on my machine? (I'm using Ubuntu 10.04 and I called it shader.cpp.)
#include <GL/glut.h>
#include <iostream>
using namespace std;
int
main (int argc, char **argv)
{
GLuint myVertexShader = glCreateShader(GL_VERTEX_SHADER)... | You cannot create a shader in a vacuum. It must be created with a valid RenderContext current. As a matter of fact, there is very little that can be done in OpenGL without a current RenderContext. (Creating a RenderContext is left as an exercise for the reader)
The other thing to consider is that the GL driver on yo... |
5,724,718 | 5,724,931 | Implementing packet timeout c++ | For a computer networks project, we are writing an ftp server in c++ with different window protocols. We are having issues implementing a working timeout function. The gist of it is to set a timestamp to when a packet is transmitted, and if the "ack" isn't revived in a certain amount of time (say 2.5 milliseconds), ret... | you might want to change your code to say:
// time in microseconds
currtime = timeout2.tv_sec * 1000000 + timeout2.tv_nsec / 1000;
Just make sure you don't get any integer overflows! It's probably a good idea to explicitly cast to a 64 bit integer for instance.
Also, you most likely want a timeout at least one order o... |
5,724,768 | 5,724,779 | SQLite3 in cygwin causing linker errors | I'm trying to get a basic "hello world" sqlite3 program going in cygwin. I had originally installed it from the setup.exe, but when I ran the program I got linker errors such as "undefined reference to `_sqlite3_open'". I AM using the -lsqlite3 switch when compiling.
The location is here:
$ ls /usr/lib/ | grep sql
libs... | It's the placement of the -l option which is causing your problem. Try executing this instead:
gcc test.cc -lsqlite3
As per the following transcript:
pax$ cat qq.c
#include <sqlite3.h>
int main (void) {
sqlite3 *x;
sqlite3_open("db", &x);
return 0;
}
pax$ gcc -L/usr/lib -lsqlite3 -o qq qq.c
/c... |
5,724,985 | 5,725,153 | C++ or Python: Bruteforcing to find text in many webpages | Suppose I want to bruteforce webpages:
for example, http://www.example.com/index.php?id=<1 - 99999>
and search each page to find if there contain a certain text.
If the page contains the text, then store it into a string
I kind of get it working in python, but it is quite slow (around 1-2 second per page, which would t... | Most likely your problem has nothing to do with your ability to quickly parse HTML and everything to do with the latency of page retrieval and blocking on sequential tasks.
1-2 seconds is a reasonable amount of time to retrieve a page. You should be able to find text on the page orders of magnitude faster. However, i... |
5,725,015 | 5,725,077 | Pure virtual function vs. virtual function? | I'm developing a class with some functionality that I think might need to be extended later, but not now. If the class were to be extended, then I think this would make instantiating the base class meaningless.
For example, let's say my base class is a tree. One approach would be to just put everything that the tree n... | I wouldn't decide that now. Later you could make an abstract base class for Tree and move code there, if that made sense.
Another option to inheritance for this kind of thing is a pointer-to-function or functor type to call. It's a lot easier to reuse, because you don't have to keep making new classes for each new si... |
5,725,272 | 5,725,331 | Importing XML to DOM tree in Qt | I'm using Qt 4.7 on Mac OS X, and I have a QString containing a path to an XML file. I would like to import that file into a DOM tree and store the data as a member variable to a class. What is the best way to do this?
I've been looking at the QtXml documentation, but I can't find a clear way to convert from the QXml*... | I don't think you need to bother with the QXml* classes to traverse the DOM.
The QDomDocument class has a setContent() method that can take an open QFile.
There's a code sample in the "Details" section of the QDomDocument documentation.
QDomDocument doc("mydocument");
QFile file("mydocument.xml");
if (!file.open(QIODev... |
5,725,288 | 5,725,640 | Is it possible to bypassing std::cin after a specified amount of time? | I'm looking for a way to skip user input after X seconds.
Something like:
std::cout << "Enter a number \n";
timer(5000)
{
std::cin >> number;
}
//the rest of the program.
Anything like this exist?
| I'm pretty sure there's nothing that's even close to portable. For that matter, there's probably nothing that works directly with iostreams.
Given that you want it for Windows, you could use the console API directly. In particular, you can use WaitForSingleObject on the standard input handle, and give a timeout:
HANDLE... |
5,725,424 | 5,725,666 | ATL COM class registration .rgs file defaults | I'm creating a COM server executable, and have run into a problem with class registration. When I created my class object, the automatically generated .rgs file looked like this:
HKCR
{
NoRemove CLSID
{
ForceRemove {4C6DAD45-64B4-4C55-81C6-4CE125226421} = s 'Test Class'
{
ForceRemove... | That's the ProgID for the coclass. It is primarily used by scripting languages, the ones that use late binding. CreateObject() is the usual function name. That this has anything to do with a hang is unexplainable, you'd better debug it.
The .rgs entry is otherwise automatically generated by the ATL wizard. The Prog... |
5,725,487 | 5,725,505 | Why put a '*' on functions that return a struct pointer? | I ran into a problem where I declared a function this way:
struct my_struct get_info();
It's supposed to return a pointer to a struct, and then in main that pointer is captured, like so:
struct my_struct *p_struct;
p_struct = get_info();
Then I got a compiler error saying that it could not convert from 'my_struct *' ... | You can pass (struct)s around by value instead of as pointers. It's usually not a good idea (use references, or pointers if you must, instead). So you need to use & for reference or * for pointer, or it will expect you to return it by value.
|
5,725,506 | 5,725,662 | STL map for an struct defined in ANSI C | I am coding in a mixed C/C++ environment. I have an struct in C part and I would like to collect it in a map container in C++ part.
I think I should define a custom key_compare function object, and let STL map::insert() orders nodes. However I don't know how can I modify map container to customize map::find() function... | To use the type as the key in a map or set, you need to provide a "less-than" comparison, which takes two arguments and returns true if the first should come before the second. The easiest way to use it in a set is to define it as a function object:
struct key_compare {
bool operator()(const iotrace_arh_node & a, c... |
5,725,924 | 5,800,914 | "Standard library" for building C/C++ projects with Make | Sometimes I need my project to use plain makefile, although it's a dated building technology not recommended for any use, but since make is available almost everywhere it sometimes makes sense.
However I want my Makefile to look something like
Include "../buildexec.mk"
TARG = my_exec
CPPFILES = file1.cpp \
... | There's a googlecode project doing exactly what I wanted:
http://code.google.com/p/nonrec-make/
|
5,726,338 | 11,718,500 | Upgrade property sheets to Visual Studio 2010 | I updated my Visual Studio 2005 solution to Visual Studio 2010. I used property sheets (*.vsprops) to configure my projects. After upgrade, it updated all the *.vsprops to the new *.props. However, the new property sheets are just empty:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersi... | The .vsprops -> .props conversion is really shoddy, looks like it was hacked together by some intern. It will surely break when you're trying to convert a project that uses more than one property sheet.
The solution is to create a dummy project in VS2008 with a single property sheet, and open that in VS2010 to convert ... |
5,726,526 | 5,726,565 | Selection appropriate STL container for logging Data | I require logging and filtering mechanism in my client server application.where client may request log data based on certain parameter.
log will have MACID,date and time,command type and direction as field.
server can filter log data based on these parameter as well.
size of the the log is 10 mb afterwards the log will... | I'd go with a deque, double ended queue. It's like a vector but you can add/remove elements from both ends.
|
5,726,562 | 5,726,592 | DEFINE() macro usage in expressinions | So I defined..
#define RADIAN(x) x*3.14159265f/180.0f
and then used it like this:
RADIAN(theta-90)
My program constantly gave me incorrect results, it took me a couple hours to realize that there was a huge difference between the above statement and the statement below.
RADIAN((theta-90))
Now my program is running p... | #define makes just text substitution, so RADIAN(theta-90) was really theta-90*3.14159265f/180.0f, what obviously wasn't what you meant. Try
#define RADIAN(x) ((x)*3.14159265f/180.0f)
instead.
|
5,726,630 | 5,726,645 | How to find the fprintf() actual error? | In my program fprintf() returns -1, which indicates an error. How can I find out what actual error was?
| #include <errno.h>
#include <string.h>
...
rc = fprintf(...)
if (rc < 0)
printf("errno=%d, err_msg=\"%s\"\n", errno,strerror(errno))
|
5,726,775 | 5,726,865 | Finding typeid of a template parameter | The print statement in the constructor's definition doesn't get printed, isn't the constructor calling correct in main? I know I am missing some point here, please point out.
#include <iostream>
#include <typeinfo>
template <typename T> class List
{
public:
template <typename T2> List (List<T2> const&);
}... | There are a couple of things wrong in your code that you might not be aware of.
List<int> kk( List<int> );
That line is not a variable definition, but rather the declaration of a function that takes a List<int> as argument and returns a List<int>, so that effectively will not call any constructor. That is know as the... |
5,727,264 | 5,727,594 | How can I avoid using a const_cast with std::vector::erase() in C++? | I have a class like this:
template<class T>
class AdjacencyList {
public:
void delete_node(const T&);
protected:
const typename std::vector<T>::const_iterator _iterator_for_node(
const std::vector<T>&, const T&
);
};
template<class T>
void AdjacencyList<T>::delete_node(const T& node)... | Aside from my direct modification of the code, here's an idea:
Instead of a member function _iterator_for_node which
has const issues
is uselessly tightly bound to a particular container type (inducing a typename template resolution mess)
does nothing more than std::find and throw an exception if not found
I sugges... |
5,727,307 | 5,727,932 | c++ isalpha lookup table | Whats the easiest way to implement a lookup table that checks to see if a character is an alpha or not using a lookup table with an array 256 chars (256 bytes)? I know I can use isalpha function, but a lookup table can supposedly be more efficient, requiring one comparison instead of multiple ones. I was thinking of... | Remember the first rule of optimisation: don't do it.
Then remember the second rule of optimisation, to be applied very rarely: don't do it yet.
Then, if you really are encountering a bottleneck and you've identified isalpha as the cause, then something like this might be faster, depending on how your library implement... |
5,727,364 | 5,727,582 | C++ Overload or monitor the dereference operator (on a pointer) | I was wondering if it is possible to add code (checks of the validity of the object pointed to actually) when a pointer is dereferenced.
I saw many subjects on overloading operator ->, but it seems the operator was called on an object, not a pointer. Maybe (probably) there is something I'm misunderstanding.
here's an e... | operator-> can only be overloaded as a member function of a class, not for a normal pointer.
In general there is no way to check that a (non-null) pointer actually points to a valid object. In your example delete pObj; does nothing to change the pointer; it just leaves it pointing to invalid memory, and there is no way... |
5,727,648 | 5,727,697 | Choosing a STL Container for a very large list | I have a very large list of items (~2 millions) that I want to optimize for access speed. I iterate trough the items using an iterator (++it).
Right now the code is implemented using std:map<std::wstring, STRUCT>.
I wonder if it's worth to change std::map with a std::deque<std::pair<std::wstring, STRUCT>>. I think I wo... | With deque, you would lose ( or would have to re-implement ) the advantage of Key-Value pairs. If it's not essential for your data, I would consider using deque.
|
5,727,660 | 5,729,646 | Comparing 2 string format SIDs | Can I compare 2 string-format SIDs for equality?
As per my understanding, a Group SID is a unique identifier in an Active Directory forest, so the string that I get by using ConvertSidToStringSid will also be unique and can thus be compared to any other Group SID (string format) by using string comparison functions?
| AFAIK the answer is "yes as long as you're using case insensitive comparison".
However, if I were you I'd consider using the EqualSid API to compare them as binary, and only convert them to string to show to the end user of your software.
|
5,727,686 | 5,728,465 | Convolution with FFT, how does this work? | I know that in time domain convolution is a pretty expensive operation between two matrices and you can perform it in frequency domain by transforming them in the complex plane and use multiplication (and then back in the time domain)
Anyway I don't understand how this is performed in the CUDA SDK where the data and th... | As to why this can be done with the FFT, you need to read about the convolution theorem.
In general, your input data may be complex. So that is why C2C is used.
|
5,727,791 | 5,727,958 | Opening a text file with fstream but filename characters are not in ASCII |
Possible Duplicate:
How to open an std::fstream (ofstream or ifstream) with a unicode filename ?
I want to open a text file using c++ fstream but the character used for the filename didn't fall in ASCII character set.
for example :
fstream fileHandle;
fileHandle.open("δ»Wüste.txt");
Is there way exist in through ... | From the question How to open an std::fstream with a unicode filename @jalf notes that the C++ standard library is not unicode aware, but there is a windows extension that accepts wchar_t arrays.
You will be able to open a file on a windows platform by creating or calling open on an fstream object with a wchar_t array ... |
5,727,889 | 5,729,817 | How do I set the interface on CComPtr in a Superclass? | I want to try and modify my code to use a superclass to handle creating CComPtr, but I'm not sure how to pass the class to the CComPtr to create, ie the part in
void CSuperClass::CreateSmartPointer(CString class, Interface interface)
{
CLSID clsid;
hr = CLSIDFromProgID(class, &clsid);
CComPtr<interface> spInt... | Depending on what you want to achieve, templates can do the job:
template<class Interface> class CSuperClass {
// ...
void CreateSmartPointer(CString class) {
// ...
CComPtr<Interface> spInterface;
// ....
|
5,727,968 | 5,728,176 | Fast way to "backup" (copy) large STL vector of custom objects | I'm using a STL vector to store a large (~ 10^6) number of custom objects (sizeof() gives 368 bytes for one of these objects). The structure of my program requires me to make frequent backup copies of this vector as changes made in a certain step might need to be unrolled under certain conditions. Roughly this looks so... | Hm, this is not an trivial thing and I don't think that you can avoid this copying, if you really need to use only (and one) std::vector.
The best solution would be to use Persistant Data Structure.
But this would be very helpful, if you need to store more than one version of your container.
If you need just the p... |
5,727,994 | 5,728,054 | C++ ofstream not operating as expected | I have a feeling that I'm missing something obvious but can't seem to resolve the following:
Please see the code below. All it does is loop 20 times and write the index of a loop to a file. After every three writes to the file that file is closed and a new one started (using an IF loop that checks for the 3 writes.
It ... | You're declaring a second ofstream fsTestOutput in your if statement when you create the new file.
That second ofstream has scope local to your if statement, so it'll work fine within your if. However, when you leave the if statement and head back to the for loop, the new ofstream instance goes out of scope, and your c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.