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 |
|---|---|---|---|---|
7,688,374 | 24,148,191 | How to I catch and handle a fatal error when Py_initialize fails? | I am embedding python in a C++ dll (so ultimately I can put it in an xll). When the setup is wrong Py_Initialize is documented as terminally failing - see http://docs.python.org/c-api/init.html, "...it is a fatal error if the initialization fails.".
Is it possible to catch this error and how?
Thinking maybe a global wi... | I solved this by creating a separate executable that attempts to initialize python. My primary process will launch it and check the exit code and only call PyInitialize if the child process was successful. So, python is initialized twice, but it is better than an apparent crash to the user.
|
7,688,419 | 7,711,733 | How to define an AnimationSet in 3DS Max for the Direct3D Animation Controller | I'm building a Direct3D App using C++.
I managed to load a mesh hierarchy from an X file found in a tutorial which had different animations or tracks build into it. And just as the tutorial explained it worked fine.
I was able to switch between the animations in my App.
I had no luck with a custom made X file however. ... | You do not state what exporter you use, so I dug up this one for you,
http://www.andytather.co.uk/Panda/directxmax.aspx
this plugin for 3dsmax supports animation naming named animation sets, amongst many other features.
|
7,688,429 | 7,688,787 | Templatize stream operator for printing enumerations | I have a namespace that creates a series of enums used through my application with associated print statements, like so:
namespace NS {
enum EnumA { A1, A2, A3 };
enum EnumB { B1, B2, B3 };
inline std::string toString(const EnumA key) {
switch(key) {
case A1: return "A1";
case A2: r... | If the only things in namespace NS are toString-capable types, you can put your operator<< in the namespace, thusly:
namespace NS {
enum EnumA { A1, A2, A3 };
enum EnumB { B1, B2, B3 };
inline std::string toString(const EnumA key) {
...
}
inline std::string toString(const EnumB key) {
...
}
temp... |
7,688,462 | 7,688,636 | C++ ReadProcessMemory into byte array | I'm attempting to use ReadProcessMemory to read a dynamic amount of bytes into an array and then return it. I simply can't get it to work properly. My current code is...
byte *Application::readMemory(DWORD address, int length) {
byte *buffer = new byte[length];
SIZE_T bytesRead;
ReadProcessMemory(piProcessI... | Shouldn't it be
ReadProcessMemory(piProcessInfo.hProcess, (void *)address, buffer, length, &bytesRead);
? If you give buffer-pointer address as input parameter, then ReadProcessMemory copies it where buffer pointer lies (not to the buffer but into buffer pointer vatiable and beyond) - and sice it is on the stack, ... |
7,688,739 | 7,689,597 | Intermittent memory exception error with COM communication | This code is for Windows 7. I am trying to grab the response to an AT command and print just the part of the string I need. Visual Studio Express is randomly telling me I have memory exceptions with this code. It doesn't happen every time.
#include <Windows.h>
#include <iostream>
#include <string>
int main()
{
HA... | The built-in iterator debugging is going to complain about your substr() call. You are making some wrong assumptions:
ReadFile() will only return what's available in the serial port receive buffer. Serial ports are slow, you typically only get one or two characters. You cannot ignore dwBytesRead.
A serial port does... |
7,688,740 | 7,689,013 | How to instantiate objects whose constructor requires parameters from a string holding the class name? | Is there a way to instantiate objects from a string holding their class name?
I got a problem basically the same with the above question. But I need to instantiate a class with some parameters. different class constructor name may require different number of variables and the type of each variable may differ either. A... | I'm going to preface this by saying, maybe C++ isn't the right language for whatever you're trying to accomplish. The more you try to control your program via external data, the closer you get to full on scripting. And there are lots of more powerful options when that is your goal.
That said, sure, it is possible, al... |
7,688,767 | 7,688,955 | Replacing some chars in a string | If I have a variable like:
char *sql;
sql = "insert into Norm1Tab values (?,?,?,?,?,?)";
I would like to replace each ? by values that are stored in other char or char* variables. How I can do that in C++ ?
| If you are using sqlite (sure looks like it), you do not have to do the string replaces yourself. Use sqlite3_bind_* instead.
bind documentation
There are a lot of benefits from using the APIs from your database provider, so you really shouldn't avoid them if you can help it. You'll have better type safety, better pr... |
7,688,845 | 7,688,873 | performance test between two directions of a 2D array | This code (A) executes much faster (10 times) then the second one:
for(int w=0; w<width; w++) {
for(int h=1; h<height; h++) {
image[h][w] = (1-a)*image[h][w] + a*image[h-1][w];
}
}
Second one:
for(int h=0; h<height; h++) {
for(int w=1; w<width; w++) {
image[h][w] = (... | This has to do with locality of reference. If you access the elements in the same order as they are stored in memory, this will be much faster than accessing them in a strided pattern, as the memory caches and memory bandwidth will be utilized far more effectively.
The above would explain the second version being faste... |
7,689,011 | 7,689,153 | Getting the decimal point value | I have a function which should covert a double value into string one:
inline static string StringFromNumber(double val) // suppose val = 34.5678
{
long integer = (long)val; // integer = 34
long pointPart; // should be = 5678 how do I get it?
}
How do I get a long value for both integer and pointPart?
Add: I want a ... | You can use modf to separate the integer and fractional parts. You can then multiply the fractional part by 1.0e17, and call floor to properly round the results to it's integer component, and then cast to a unsigned long (the fractional part will never be negative, and this allows you to maximize the number of bits i... |
7,689,059 | 7,690,540 | Qt: some slots don't get executed in release mode | I am doing some simple program in Qt (MSVC++2008) with few checkboxes and buttons. In debug mode, everything works fine, but I can't distribute such executable, because most people don't have Visual Studio installed. When I do compile it in release mode, only 2 pushbuttons work.
I have designed my window using Qt Creat... | Your code looks good.
Try running "make clean" or "qmake". Your "ui_" or "moc_" files might need updating.
|
7,689,068 | 7,689,117 | C++ Critical Section not working | My critical section code does not work!!!
Backgrounder.run IS able to modify MESSAGE_QUEUE g_msgQueue and LockSections destructor hadn't been called yet !!!
Extra code :
typedef std::vector<int> MESSAGE_LIST; // SHARED OBJECT .. MUST LOCK!
class MESSAGE_QUEUE : MESSAGE_LIST{
public:
MESSAGE_LIST * m_pList;
MES... | Two questions in one. I don't know about the first, but the critical section part is easy to explain. The background thread isn't trying to claim the lock and so, of course, is not blocked. You need to make the critical section object crt visible to the thread so that it can lock it.
The way to use this lock class is t... |
7,689,266 | 7,689,745 | C++ Source code organization - COM port initialization | I have a program that will be communicating with multiple COM ports. As of now I have all the code in one file and it is semi messy. How could I organize it in a way where all the serial connections and connection parameters are set up somewhere else allowing me to just read or write to the port in the main file.
Here... | HANDLE hSerial = CreateFile("COM3",GENERIC_READ|GENERIC_WRITE,.......
The only thing that is unique to each com port is the name "com3" so this is all you need to supply to the function. The handle returned by Createfile completely identifies the open port, it's the only thing you need to read/write the port and close... |
7,689,288 | 7,939,108 | less verbose way to declare multidimensional std::array | Short question:
Is there a shorter way to do this
array<array<atomic<int>,n>,m> matrix;
I was hoping for something like
array< atomic< int>,n,m> matrix;
but it doesnt work...
| When nested, std::array can become very hard to read and unnecessarily verbose. The opposite ordering of the dimensions can be especially confusing.
For example:
std::array < std::array <int, 3 > , 5 > arr1;
compared to
char c_arr [5][3];
Also, note that begin(), end() and size() all return meaningless values whe... |
7,689,334 | 7,689,402 | Getting boolean from true_type/false_type typedef from dependent class in enable_if | I have a class
template <typename T>
struct Trait { typedef std::false_type IsGood; };
template <>
struct Trait<int> { typedef std::true_type IsGood; };
A call like this fails to compile on MSVC 2010
template <typename T, typename Enable = void> class Foo;
template <typename T>
class Foo <T, std::enable_if<typename ... | You're using typename at wrong place. This is correct:
template <typename T>
class Foo <T, typename std::enable_if<Trait<T>::IsGood::value>::type>
{}; // ^^^^^^^ here should be typename
Now it compiles fine: http://ideone.com/0SwO9
But you're using typename as:
template <typename T>
class Foo <T, std::enable_if... |
7,689,534 | 7,689,628 | How to Make Visual Studio C++ 2010 Compilation Behave Like gcc/g++? (or vice-versa) | Say you've got the following simple main.cpp file:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
const string FILENAME = "foo.txt";
ifstream somefile(FILENAME);
populations.close();
return 0;
}
This compiles fine via Visual Studio C++ 2010.
However, on a ... | It is available as part of the newer c++ standard.
To disable, add
#define _HAS_CPP0X 0
at the top before your includes.
|
7,689,803 | 7,689,852 | BCD Calculator issue | I am converting a hex 0xE0 to BCD. When I do this I am getting back a 64. I know this is completely wrong and maybe it's something in my C++ code, but 64 just doesn't sound correct. Any ideas? Is 0xE0 a special case? (0xE0 is 224 in decimal.)
Here is part of my code:
unsigned char Hex2BCD(unsigned char param)
{ unsig... | my idea is that your code for converting to BCD is buggy. it does not do what it is supposed to, thus the wrong result you are observing.
aside from this joke: 0xe0 if stored in signed char is a negative number. that could play nasty tricks on you if you don't pay special attention on the sign of temporary variables yo... |
7,690,027 | 7,690,050 | Strange GetLastError return in Managed C++ | I have a really strange problem with GetLastError and managed C++. GetLastError is returning something very strange after transitioning from unmanaged code to managed code.
The error code: 122 - The data area passed to a system call is too small.
Additionally, the passed in strMessage is making it to the server.
Unman... | Many functions will call SetLastError as a side-effect while doing their work. Typically this means that a function calls some other function, which might have some internal failure for which it might call SetLastError, and so the previous error value is overwritten.
As an example, it's quite likely that something cal... |
7,690,474 | 7,690,717 | Any pitfalls with allocating exceptions on the heap? | Question says it all: Are there any pitfalls with allocating exceptions on the heap?
I am asking because allocating exceptions on the heap, in combination with the polymorphic exception idiom, solve the problem of transporting exceptions between threads (for the sake of discussion, assume that I can't use exception_ptr... |
Are there any pitfalls with allocating exceptions on the heap?
One obvious pitfall is that a heap allocation might fail.
Interestingly, when an exception is thrown it actually throws a copy of the exception object that is the argument of throw. When using gcc, it creates that copy in the heap but with a twist. If hea... |
7,690,500 | 7,690,872 | What is a good api to sql from visual c++ | I want to do simple stuff like adding entries and reading entries by index. What libraries are there and which ones are the best?
| SQLite would be a good simple SQL database engine, with a simple embedded C++ interface.
SQLAPI++ would be a good choice for many commercial SQL databases (Oracle, SQL Server, DB2, Sybase, Informix, InterBase, SQLBase, MySQL, PostgreSQL, SQLite and ODBC)
|
7,690,564 | 7,690,597 | linking error in vc ++ | i have Point3D class in my project.
to create an object of Point3D i have added a cpp file & a header file as follows:
CreatePoint.h
#include "stdafx.h"
#pragma once
#include "Point3D.h"
//*******************************************************************
int counter = 0;
int size = 50;
Point3D **point;
//**********... | In header file use extern when declaring the variables, as:
//CreatePoint.h
extern int counter; //it is only a declaration
extern int size; //it is only a declaration
extern Point3D **point; //it is only a declaration
And in the source file, define and initialize them as:
//CreatePoint.cpp
#include "... |
7,690,580 | 7,690,649 | how to write C++ inheritance constructors | I've been away from C++ for a while, and I'm having a little trouble with this one. I'll spare you my bad code - can someone please post a 'model answer' for how to write a simple header file and source file for a small class with a constructor that accepts a few values, and passes a few on to it's base classes constru... | // ExampleClass.h
#ifndef ExampleClass_H_
#define ExampleClass_H_
#include "ExampleBase.h"
class ExampleClass : public ExampleBase {
public:
ExampleClass(int a);
};
#endif
// ExampleClass.cpp
#include "ExampleClass.h"
ExampleClass::ExampleClass(int a) : ExampleBase(a)
{
// other constructor stuff here
}
|
7,690,807 | 7,690,835 | overloading << operators and inherited classes | I've got a base class and then several derived classes. I would like to overload the "<<" operator for these derived classes. For normal operators, i.e. '+', virtual functions do the trick. What I understand to be the standard convention is to declare
friend ostream& operator<<(ostream& out, MyClass& A);
within my cla... | You can use a virtual helper function. Here's a completely untested example, so excuse any syntax mistakes:
virtual ostream& Foo::print(ostream& out) const {
return out << "Foo";
}
virtual ostream& Bar::print(ostream& out) const {
return out << "Bar";
}
// If print is public, this doesn't need to be a friend.... |
7,690,873 | 7,691,036 | Cross Platform Tray App | I'm looking to develop a type of system tray/dock application that will run in the background and perform some tasks. I want to target Windows and OSX. After doing some research and based on my own skillset, I'm going to go with C++. It will monitor a specified directory and perform actions based on the files in the di... | The best practice is to make a cross platform library. I would stick with static libraries if you can help it. Then create varied applications for your platform specific needs.
It is better to "pull in" functionality from the library, as opposed to writing extensions on top of the library. That way you get to pick... |
7,690,965 | 7,690,991 | How to get partition where value belongs in partitioned interval? | I have interval that is partitioned int large amount of smaller partitions.
There aren't any spaces also there aren't any overlapping intervals.
E.g: (0;600) is separated into:
(0;10>
(10;25>
(25;100>
(100;125>
(125;550>
(550;600)
Now i have large amount of values and i need to get partition id for each of them.
I c... | Since there are no "empty spaces" in your partitioning, the end of each partition is redundant (it's the same as the start of the next partition).
And since you have the partition list sorted, you can simply use binary search, with std::upper_bound.
See it in action.
Edit: Correction (upper_bound, not lower_bound).
|
7,691,025 | 7,691,122 | How to generate a set of values that follow certain distribution in c++/java? | For example, I have a p.d.f f(x) = 1/25 - x/1250 (from x = 0 to 50);
My question is that how to generate a set of values that satisfy the given p.d.f.
Please give an idea about how to implement in c++ or java.
Thanks so much.
| I don't know about directly from a pdf, but you can convert a pdf to a cdf (by integrating) and then use inverse transform sampling. This assumes that you have a technique to generate a random number u in [0, 1] (e.g. Math.random() in Java).
Once you have generated such a u, find an x such that cdf(x) = u. That x is ... |
7,691,038 | 7,698,309 | Boost Graph Library dynamic edges weights | I'm wondering if it's possible to make dynamic edges weights in BGL? I'm writing public transport navigator so except time as weight it would be nice if I can promote actualy using line instead of change at every stop event if it would be 3 minutes faster - this is just inconvenient.
Thanks for your help
edit:
Or maybe... | I'm not entirely clear on what you mean by dynamic... the weights are presumably stored in edge properties; there's nothing to stop you updating the properties with new values as required.
If you mean that you want the edge weights to be a function-object (or "functor", if you must) rather than "just a value", then see... |
7,691,141 | 7,750,948 | What is the fastest and easiest way to call a C function from Erlang via ports? | Francesco Cesarini's "Erlang Programming" book provides a nice and simple-to-start-with example of connecting Erlang to Ruby (implemented through ports):
module(test.erl).
compile(export_all).
test() ->
Cmd = "ruby echoFac.rb",
Port = open_port({spawn, Cmd}, [{packet, 4}, use_stdio, exit_status, binary]),
... | Start by reading the Interoperability Tutorial in the Erlang/OTP online documentation: http://erlang.org/doc/tutorial/users_guide.html. When communicating with a C program, you just write the C code to read from stdin and write to stdout, and this will be hooked up to the Erlang port. You could also read chapter 12 in ... |
7,691,215 | 7,691,587 | How do optimizing compilers decide when and how much to unroll a loop? | When a compiler performs a loop-unroll optimization, how does it determined by which factor to unroll the loop or whether to unroll the whole loop? Since this is a space-performance trade-off, on average how effictive is this optimization technique in making the program perform better? Also, under what conditions is it... |
When a compiler performs a loop unroll optimization, how does it determined by which factor to unroll the loop or weather to unroll the whole loop or not.
stack consumption and locality. instruction counts. ability to make/propagate optimizations based on the unrolled and inlined program. whether the loop size is fix... |
7,691,292 | 7,694,237 | Labview type conversion to C# | I am just hoping for somebody out there who might have an answer.
I am posting here eventually after fruitless dealing with Labview and the Device company.
I am currently making an application to control a device, which is provided with Labview compiled DLL. The dll is compiled with missing some necessary Labview funct... | You need to look in extcode.h to see the definitions of the various types. I found an instance online here:
typedef int32 MgErr;
#define LV_PRIVATE(T) typedef struct T##_t { void *p; } *T
/** @struct File
Opaque type used by the file manager. See filemgr.cpp */
LV_PRIVATE(File);
/** @struct Path
Opaque typ... |
7,691,303 | 7,691,687 | Getting the rightmost element in an unordered_set (or print the contents in reverse) | I have an unordered_set as follow:
unordered_set <long> valueSet;
/*the following insertion is done in order (from 1 to 10000),
*unordered_set will keep the elements based on the insertion order, right,
*just like in a vector ?
**/
for(long i = 1; i <= 10000;++i)
{
valueSet->insert(i);
}
Then I performed... | From what I've gathered from your comments, using a std::bitset or its dynamic counterpart boost::dynamic_bitset should be appropiate here. You get O(1) insertion and deletion and O(N) for determining the maximum element (by linear search). One could even argue that finding the maximum is amortized O(1), as you have to... |
7,691,504 | 7,691,757 | example code of escaping lambdas | I watched the cool clip:
http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2011-C11-Panel-Scott-Meyers-Andrei-Alexandrescu-and-Herb-Sutter
and there Andrei(54:00) talks about escaping lambdas that take references to locals. In general I think I get the idea of the problem, but I'm not sure that I really get it, so... | Here's a simple example:
std::function<int()> f() {
int local;
return [&]() { return local; }
}
The local variable is captured by reference, and then the lambda is returned. Calling the returned function later on will use the reference, which is now invalid and thus invokes undefined behaviour. This seems like... |
7,691,527 | 7,695,277 | Crossplatform library to normalize audio? | Do you know any cross-platform audio library I can use to normalize sampled audio?
| Google is your friend:
http://normalize.nongnu.org/
https://neon1.net/prog/normalizer.html
If you can't use GPL code in your project, then just read the description of the algorithm on the second website and implement your own. It's pretty simple.
|
7,691,610 | 7,715,928 | Can I cross compile my AS3 code or Flex project to native C++? | I would like to tak emy existing AS3 or Flex project and compile it to run on native C++ code. Is there a way to do this? What sort of solutions exist? I do not want to change my AS3 code.
| No, because of
absense of dynamic features in C++ (you don't have Object and describeType equivalent there)
absense of Flash native types in C++ (String (std::string is not equivalent), display objects and many others)
absense of language features (event listeners, garbage collection)
absense of Flex framework equival... |
7,691,697 | 7,691,969 | C++ unique static id and class name with base class | Having class TaskBase, each derived class of it must have name and unique id.
The TaskBase is something like below:
class TaskBase
{
public:
static const int id()
{
// return an unique id, for each object or derived class, HOW ??
}
static const string name()
{
// return class name f... | class TaskBase
{
private:
const void* m_id;
string m_name;
public:
TaskBase(const void* m_id, string m_name): m_id(m_id), m_name(m_name)
{
}
const void* id() const
{
return m_id;
}
string name() const
{
return m_name;
};
};
template< typename DERIVED >
c... |
7,691,792 | 7,691,903 | Coping with different types with the same underlying data structure | I am in need of mixing C code with C++ code in a computer simulation.
A C library has functions which take references to a regular array of doubles:
void position(double[3])
Another C library defines its own vector type:
void do_something(*custom_vector)
And my front-end (in C++) uses boost::numeric::ublas::vector.
I... | As long as both source and destination types support the standard iterator interface (which is true for std::vector, arrays, and every Boost sequence type I can think of; so you just need to fix your custom_vector), and as long as there are implicit conversions possible between the numeric types, you should be able to ... |
7,692,295 | 7,692,425 | Compilation Error with C++ core libraries | During compilation of a software I am consistently receiving the following error messages.
PasteBin Link: http://pastebin.com/TmHKqey2
I have tried the solutions on forums that discussed similar issues: changing all makefiles from makefile.* to Makefile.*; updating the headers etc - but no success.
Any suggestions/insi... | I usually get this if I have an error before the included file. So I would look in Util.c before the include of stdio.h to see if there is some syntax error. The error could be in some include that you've included before stdio.h.
Most common cause, missing ';' or '}'.
|
7,692,319 | 7,692,649 | Overload a pointer to an overloaded function | If I try to define a pointer to an overloaded function
void myprint(int );
void myprint(const char* );
void (*funpointer)(int) = myprint;
the compiler understands that funpointer should point to the version of myprint that matches its arguments. Instead, I want funpointer to be overloaded as well.
I tried simply addin... | Why are you doing this? Function pointers are for runtime polymorphism based on application state. Plain old overloads work fine if, the only variance is the argument type.
If you want to be able to, say write a library that will call overloads defined later, in client code, do something like the following:
void foo(... |
7,692,380 | 7,700,904 | Possible states for native threads on Android? | What are all the possible thread states during execution for native (C/C++) threads on an Android device? Are they the same as the Java Thread States? Are they Linux threads? POSIX threads?
Not required, but bonus points for providing examples of what can cause a thread to enter each state.
Edit: As requested, here's t... | I've been told that native threads on Android are just lightweight processes. This agrees with what I've found for Linux in general. Quoting this wiki page:
A process (which includes a thread) on a Linux machine can be in any of the following states:
TASK_RUNNING - The process is either executing on a CPU or waiting ... |
7,692,411 | 7,692,563 | Incorrect values are being printed to file. Serial Port communication program | This code is supposed to send a command to COM3 send the response to a file - then read a certain number of characters from COM5 and write that to a file. Weird values are printing.
I think I have been looking at the code too long. Any assistance would be awesome.
#include <Windows.h>
#include <iostream>
#include <st... | When I've had COM ports spitting out weird characters, it's usually because of a baud rate mismatch.
You should call SetCommState on hSerial2 to ensure it has the same baud rate as hSerial.
|
7,692,554 | 7,692,595 | C++ custom calling convention | While reverse engineering I came around a very odd program that uses a calling convention that passes one argument in eax ( very odd compiler ?? ). I want to call that function now and I don't know how to declare it, IDA defines it as
bool __usercall foo<ax>(int param1<eax>, int param2);
where param1 is passed in the ... | There are "normal" calling conventions which pass arguments via registers. If you are using MSVC for example, __fastcall.
http://en.wikipedia.org/wiki/X86_calling_conventions#fastcall
You cannot define your own calling conventions, but I would suggest that you do create a wrapper function which does its own calling / c... |
7,692,639 | 7,692,687 | Is it possible for std::sort to lead to a bug? | My Question is related to this as I solved the problem, I wrote my own sorting algorithm (a simple insertion sort), and it works. I am quite surprised by this as I thought that the standard library is well-tested. Are there any known special cases in which std::sort might mess up?
| No, it's highly unlikely that there are any known bugs in any of the common C++ standard library implementations of std::sort. It's rigorously tested.
If you see a crash or incorrect results, it's almost certainly because you didn't adhere to the contract: either you passed in invalid arguments, or your comparator doe... |
7,692,946 | 7,692,978 | Overuse of redefining primitive data types? | My current project code base has every unit and its friend refined.
Extract :-
...
typedef int m; // meter
typedef int htz;
typedef int s; // second
...
Good or Bad?
I hate it! Its a pain, there is no benefit, and "m" globally defined, omg!
But I want to state the reason why I hate it, in a bit more of technical/artic... | Better to make them custom types, as then you can control conversions and overload operators. Right now, I can do meaningless things like multiply a metre by a hertz. Ideally, m / s would yield a velocity- but it won't. It's meaningless to just typedef them like that.
|
7,693,131 | 7,693,161 | Cin and point to function chosen | I am not understanding how to make it so when i input my selection in testSelection for it to point to the function test. How do i go about doing this? Shouldn't it just go there?
#include <iostream>
using namespace std;
int test (int testSelection);
int main()
{
int testSelection;
cout << "Welcome to the pizza... | You need to call the function...
cin >> testSelection;
test(testSelection);
Basically, you've written a function definition int test(int testSelection) {...code...} but, it's just dormant code until you invoke it by calling it.
|
7,693,315 | 7,693,397 | How can I take a single element out of a boost library (e.g. shared_pointer)? | I've been playing around with some Boost components, and the only one I see a direct need for in the project I'm working on is boost::shared_ptr.
Would it be difficult to just include the required files for shared_ptr, or at least just include files for the Boost smart_ptr directory in my project? They seem to have so... | You can use the bcp tool to extract only the header you want.
bcp shared_ptr /foo
This copies shared_ptr and all dependencies to the directory foo
|
7,693,394 | 7,696,997 | Fast C/C++/MATLAB SURF Feature Library | What is the fastest C/C++ implementation of SURF out there? Is OpenCV superior or are there any standalone implementations that are faster? Matlab Mex wrappers is a plus.
| I expect that one of the GPU-based solutions listed in http://en.wikipedia.org/wiki/SURF#Implementations will be faster than the OpenCV version on the CPU. Of course, your mileage may vary depending on the specific application.
|
7,693,495 | 7,693,523 | For loop writing special signs | void printchars()
{
for (x=128;x<224;x++)
write(x);
I want the x to be a char in the write function. How can i change the x to be treated by the write functions as a char, but an int in the loop?
| What is the point of making x an int if you're just going to strip away its range? That's what makes this a very strange request. You should just make x a unsigned char -- for(unsigned char x = 128; x <224; ++ x) { ....
If you just want to ensure you're calling the unsigned char template specialization of write<>, then... |
7,693,533 | 7,693,548 | Namespace + overloaded std::ostream << operator | I'm trying to make a Vector3D class in my c++ application. For my entire program, I'm using a namespace. In this namespace I've declared my Vector3D class and an overloaded operator<< for it as such:
namespace space
{
class Vector3D
{
public:
float x, y, z;
Vector3D(float _x = 0, float ... |
My problem is to cout a Vector3D, I have to manually call space::operator<<(cout, vector);
You don't, that's what ADL (Argument-dependent name lookup, also known as Koenig's lookup) is about. It should be enough to do
cout << vector;
If it doesn't work, either you are working with an ancient compiler or you are doin... |
7,693,596 | 7,721,593 | C++ LoadLibrary ERROR_NOACCESS "Invalid access to memory location." | OK, so I have a situation in which I call LoadLibrary on a DLL that I wrote. This call to LoadLibrary returns error #998, or ERROR_NOACCESS "Invalid access to memory location."
The DLL in question uses MFC in one configuration, and not in another; only the MFC configuration has this problem. It used to work, but I have... | OK, this question was answered by a friend of mine (no idea if he has a StackOverflow account; not going to pester him with answering it twice).
The deal is that I had a global object, the class of which had a constructor that called a function that depended upon another global object (ironically enough, the function i... |
7,693,692 | 7,695,500 | How can you avoid repeating type information using c++11's type inference feature to create a shared_ptr instance? | You can make a pair instance using the new c++11 auto keyword to completely minimalize the typing information that you're supplying to the compiler:
auto my_pair(make_pair(10,"yay"));
Is there a similar mechanism for creating shared_ptr's? The only syntax I can find repeats the type information to the compiler 2 time... | I don't think you should be scared of exception safety in this case. What you're considering could look like:
template<
typename T
// for convenience:
typename Decayed = typename std::decay<T>::type
>
std::shared_ptr<Decayed>
deduce_shared(T&& t)
{
static_assert(
!std::is_array<
type... |
7,693,716 | 7,693,813 | Should I check for NULL in my assignment operator? | I have a class
class Node {
public:
int value;
Node * next;
Node();
Node(const Node& other);
Node& operator= (const Node& other);
};
It's not very useful, but it has an overridden assignment operator. Everything in there is public because I am such an open and cooperative guy.
Now elsewhere I h... | The problem is that you're dereferencing other.next, which might be NULL. So you should check if other.next is null before dereferencing it:
this->next = other.next ? new Node(*other.next) : 0;
Dereferencing a NULL pointer is undefined, so if you do it, anything might happen -- it might NOT crash immediately and inst... |
7,693,724 | 7,693,760 | Confusing template code | What does the below mean
template < template < template < class > class, class > class Param >
I never used template <template <X>> kind of syntax
Got it off of another website
template < template < template < class > class, class > class Param >
struct Bogus {
int foo() {
printf("ok\n");;
}
};
Appreciate any light... | It's called a template template parameter. It's been discussed a number of times before:
Syntax of C++ Template Template Parameters
What are some uses of template template parameters in C++?
Use template template class argument as parameter
etc.
|
7,693,751 | 7,693,885 | How can I improve formatting number with commas performance? | I'm using the following method to format a number with commas:
template<class T>
static std::string FormatNumberWithCommas(T value, int numberOfDecimalPlaces = 0)
{
std::stringstream ss;
ss.imbue(std::locale(""));
ss.precision(numberOfDecimalPlaces);
ss << std::fixed << value;
return ss.str();
}
Pr... | You could start by making the string stream a static variable:
{
static std::stringstream ss;
static bool ss_init = false;
static std::string emtpy_string;
if (!ss_init) { ss.imbue(std::locale("")); ss_init = true; }
ss.str(empty_string);
// ...
}
If that's still a bottleneck, you could look at an alterna... |
7,693,781 | 7,693,840 | C++ OpenGL SDL Screen Trouble | I'm back again with probably what is a small problem that I can't seem to work out whilst undertaking my OpenGL/SDL adventure.
This program brings up a 640x480px SDL screen, but there is nothing inside it, not even a background, it is just transparent through to whatever is on the screen behind it and I have to admit, ... | You don't clear the screen despite setting the clear colour. You need a call like glClear( GL_COLOR_BUFFER_BIT ); to actually do the clearing.
Also, it is best to continuously render inside of the loop if you want to do anything other than static drawing... it is likely you see nothing at all because its expecting you ... |
7,693,995 | 7,694,021 | Using protected static variable in another file | How can I access a variable that has been declared as static and protected in a class definition for use in another file b.cpp
| The only code allowed to use protected class members (static or not) are explicit friends of the class in question and classes derived from the class in question (and of course, members of the class itself). Therefore, if "you" want to access that value, then "you" must either be a friend of that class or a member of a... |
7,694,120 | 7,694,229 | How to compile a c++ dll using visual studio? | I have some c++ classes that I'd like to compile into a dll file. When I am trying to compile the project, I receive an unresolved external symbol error:
error LNK2019: unresolved symbol _WinMain@16 referenced in function tmainCRTStartup
fatal error LNK1120: 1 unresolved external
This is what I've done so far:
I... | When you create a new Win32 Application project, select "Application Settings" in the wizard, and select "DLL" for the application type. It will start with an empty DllMain.
You say that you did this, but it should not be looking for WinMain then. To double check you're really building a DLL, look in project settings -... |
7,694,130 | 7,694,142 | How to check OS version in a cross platform fashion with C++? | Well, I think the question is fairly objective. So, is there anyway to do it?
Actually, I need to check what version of the OS because I want to get a directory from a string:
"directory/file.ext"
or
"directory\file.ext"
So I split one of those strings according to "\" or to "/", depending on which OS I'm dealing wit... | Actually, you don't need to do that. The POSIX style "/" will work as a directory separator just fine, even on a Win32 system (try it out.)
That said, other filesystem operations are platform-specific (drive letters, for instance.)
The Boost Filesystem library is a good option - code to this, and it will handle the pl... |
7,694,158 | 7,696,652 | boost compressed_pair and addresses of empty objects | AFAIK, boost::compressed_pair is supposed to ensure that the address of the first and second memebrs are different while it does its magic of compressing the pair. It says so here. Seems like it is not the case and its behavior is different on different compilers. I'm using boost v 1.47. What am I missing?
struct E1 {}... | When the types are different and one or both of the types is an empty class, the subobjects are supposed to be at the same address (if the compiler can pull the empty base class optimization off), that's the point of the compressed pair.
When the types are the same, I think a note from chapter 10 in the standard applie... |
7,694,375 | 7,694,750 | Copy user input to char vector | Quick disclaimer, this is a contrived example meant to simulate an issue I am seeing in my homework problem. To that end, using strings is out of the question; I can only use char arrays as per the instructor :(
What I am trying to do is continuously read input from the keyboard and store it in a vector . The problem i... | Use a std::vector<std::string>, that should "just work" with your existing code.
Since you cant do this with std::string (which would have been the proper way to use the language), the you a nested vector, like this:
std::vector<std::vector<char> > vex; // notice the space between the '>' chars, older compilers may ne... |
7,694,410 | 7,695,013 | How to develop nice-looking, visually modern applications in QT? | I'm wondering how to develop visually modern, with attractive GUI applications in QT. When I run QT Creator and start new project, the GUI looks very basic and "pure", just like simple win32 apps. But look for example at Allegorithmic Substance Designer 2, where GUI looks somehow similar to WPF. There are many other ap... | As well as Nano's answer, I think it would be worth your while to search around for any Qt stylesheets others have made.
For example, this one that mimics Microsoft Office.
Unfortunately, there doesn't seem to be very many of them available.
I found these useful links, some of whose links may give some ideas:
Qt Style... |
7,694,515 | 7,694,526 | C Wrapper for C++: How to deal with C++ templates? | Earlier was asking about writing a c wrapper for c++ classes ( C Wrapper for C++ ), which is basically clear.
There's one more question though: how do I deal with c++ templates?
Let's say this is my class:
template<typename T> class Temp
{
T get();
void set(T t);
}
Is there an elegant way to write ... | You have to write a separate wrapper for each specialization.
|
7,694,563 | 7,694,657 | Port ruby solution to C++ | Is there any way to do this in C++ especially the range section.
answer = (0..999).select { |a| a%3 ==0 || a%5==0 }
puts answer.inject { |sum, n| sum+n }
I have created my own c++ solution but using a more standard for loop and wondered if there was a cooler way to do it?
| Template metaprogramming solution:
The following assumes the lower bound of the range is 0.
template <int N>
struct sum
{
static const int value = sum<N-1>::value + (N % 3 == 0 || N % 5 == 0 ? N : 0);
};
template <>
struct sum<0>
{
static const int value = 0;
};
int main(int argc, char** argv)
{
int n = sum<999... |
7,694,715 | 7,694,770 | When should I make a repository for my project? | I've been looking into using Mercurial for version management and wanted to try it out. I'm planning on doing a project on my own to help me learn C++ coming from Java and thought it would be a good idea to try version management with it. It would probably be a game or some sort of simple application, not sure with a G... | On repos:
You should use a VCS repository as soon as possible. Not only does it allow for off-site backups, but it allows you to track changes. To find out when a bug was introduced.
Having a VCS, particularly a distributed VCS like Mercurial, will change the way you code. You won't have to be careful not to break thin... |
7,694,830 | 7,694,851 | C++ Linked List: Overload bracket operators [] | So, I decided to look back at some data structures to keep myself sharp ;)
I started to implement a hash table, when I remembered that I needed linked lists for the buckets so that I can avoid hash collisions. So I started my linked list...
I implemented all of the functional methods of my linked list class (add, get,... | it looks like you want to return nodes by reference:
template <typename T>
class LinkedList {
...
T& operator[](const size_t& i) { return this->get(i); }
const T& operator[](const size_t& i) const { return this->get(i); }
...
};
(also assumes LinkedList::get() returns references)
|
7,695,001 | 7,707,009 | Access SPSS data from a Python, Java (groovy/grails)' or C++ app without license for SPSS? | I am finding mixed results googling. I have a need to parse a SPSS .sav file to discover the data layout and extract the survey results. Step one is to read the "schema" of the data. For example I need to know the question and its type of allowed responses. I plan to model this data in my own SQL table so I can slice a... | You can get the SPSS i/o modules with detailed documentation for free in order to build your own app to read (or write) sav files. The modules are available for all platforms supported by SPSS Statistics.
Go to the SPSS Community site at http://www.ibm.com/developerworks/spssdevcentral and follow the links for SPSS Do... |
7,695,061 | 7,695,282 | Why is this 'if' statement looping? | Hey guys I'm writing part of a code for a project and I'm stuck on one thing. If this is something good coders figure out on their own at some point (as I'd like to become a good one, week five with c++; so far so good...) and its a trial, say the word and I'll screw, but I've been at debugging for about a half hour an... | Your first problem is that 'colon' gets all of ":34", then start_minutes gets the 12 that was supposed to be the next hour. But the real problem is that cin leaves cruft on the stream that is picked up by subsequent calls, so those calls skip asking you for more input and just take the left over characters. Use cin.ign... |
7,695,084 | 7,695,113 | Template methods and template classes C++ | Can class member functions be template functions, or must they be static class functions. Basically can the class and the function be technically instantiated separately on demand?
What are the limitations of using a template function as a member of a template class? Can both be done at the same time at all, or is it ... | You can have template member functions of template classes, like this:
template <typename T>
class Foo {
public:
template <typename U>
void bar(const T& t, const U& u);
};
template <typename T>
template <typename U>
void Foo<T>::bar(const T& t, const U& u) {
// ...
}
|
7,695,230 | 7,695,268 | While loop doesn't loop | Here I set up a while loop where I input a selection number 1 or 2. If I choose 1 or 2 it couts the 1 or 2 whatever I choose; if I choose a number below 1 or above 2 it goes to the else statement which asks the user to input again. But if the user inputs the problem is that it won't loop back to the beginning if they ... | If you enter 1 or 2, it won't even enter the loop as neither 1 or 2 are either bigger than 2 or smaller than 1, they are equal.
This should fix it:
while ( selection >= 2 || selection <= 1) //equals while(true)
Note that you should also use an else if statement at the second if, it doesnt work correctly the other way... |
7,695,555 | 7,695,625 | Removing namespace of type name in C++ | In C++, when we use typeid to get type name of an object or class, it will show a decorated(mangled) string. I use cxxabi to demangle it:
#include <cxxabi.h>
#include <typeinfo>
namespace MyNamespace {
class MyBaseClass
{
public:
const std::string name()
{
int status;
char *realname = abi::__c... | There is no standard way to do this, period, because there is no standard way to do name mangling. How to represent names was intentionally unspecified. There is no ABI in the C++ standard. The function you are using, abi::__cxa_demangle, is a part of the Itanium C++ ABI. That function may or may not exist elsewhere.
... |
7,695,638 | 7,696,158 | Conditional CMAKE link to rt-library | How to write CMakeLists.txt to conditionally link to the system-wide librt library only when on Linux environment?
| cmake has several predefined variables useful for environment detection (WIN32, UNIX, APPLE, CYGWIN). Here is the full list: http://www.cmake.org/cmake/help/cmake-2-8-docs.html#section_VariablesThatDescribetheSystem
So you can write something like
if(UNIX AND NOT APPLE)
target_link_libraries(target_name rt)
endif()... |
7,695,645 | 7,695,675 | Is there a way get an integer out of boost::any if you don't know if original type was signed or unsigned | I'm using boost::any in combination with boost::any_cast<> to write some framework code which should take a set of arguments, almost like a function call, and convert them into an array of boost::any types.
So far everything has been working great, except in places where it is hard to predict if the number the caller g... | There isn't a way; boost::any does the simplest form of type-erasure, where the type must match exactly. You can write your own boost::any-like class that supports the additional features you want. I've previously demonstrated how this can be done.
Failing that, you can:
Have two code paths, one for each sign. (Switch... |
7,695,852 | 7,695,866 | Is There A C++ Wrapper / Binding For SDL? | I really have no problem with SDL in C , but it's kind of tiring. Using structs doing stuff without classes, or worse, having to wrap the functions up in a class yourself etc. I was wondering whether there was a good , mature , well-designed (i.e NO Macros , using templates and the STL) wrapper (binding?) for SDL?
| SDLmm is a C++ wrapper for SDL. I'm not sure when it was last updated though and I can't vouch for the style of C++ used either.
|
7,695,891 | 7,695,944 | Is there a match_partial in C++11 Regular Expressions? | I read through n1429 with the section
The algorithms regex_match and regex_search both support a feature not commonly seen in regular expression libraries: a partial match. When the flag std::regex_constants::match_partial is set in the flags passed to the algorithm, then a result of true may be returned if one or mor... | It seems the match_partial flag is removed in N1723 "Proposed Resolutions to Library TR Issues" (2004 Oct) as a resolution to N1507 "Errata to the Regular Expression Proposal":
7.34 Meaning of the match_partial flag
Remove match_partial.
The rationale according to N1837 "Library Extension Technical Report Issues ... |
7,695,926 | 7,696,696 | Sudoku backtracking algorithm | First of all, I'll state that this is a university assignment so I'm not asking for someone to write the code for me I just need to be pointed in the right direction. :)
Ok, so I need to write an algorithm to solve any (solvable) sudoku board of arbitrary size. I've written a recursive function that can solve any 9x9 b... | Between filling the squares with only one choice and going full recursive on the board there are more advanced actions you can do. Lets take that "region" is one row, or one column, or one square region (3x3 or 4x4).
Tactic 1
If there are K squares in a region that can take only identical K numbers (for instance two sq... |
7,696,022 | 7,696,046 | C++ Includes in a cycle | Please consider the following three simplified files:
student.h:
#ifndef STUDENT_H
#define STUDENT_H
#include "course.h"
class Student
{
private:
Course someCourse;
};
#endif
course.h:
#ifndef COURSE_H
#define COURSE_H
#include "student.h"
class Course
{
private:
Student someStudent;
};
#endif
and main.... | This is going circular, as long as you declare someCourse and someStudent as non-pointer members of class Student and Course respectively (as you've done), because the compiler sees the definition of Student, it needs to know its size which in turn means, it needs to know the size of its all members, including Course ... |
7,696,063 | 7,701,540 | Regular Expressions misunderstanding or just broken implementation? | I tried a very simple use of regex_search and can not understand why I do not get a match:
Alas, the gcc-C++0x-implementations 4.5 does not seem to be working, I get a link error here.
But here is my gcc-4.7.0 try, quite straightforward:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int ma... | As you can see from the C++-0x status of libstdc++ the regex support is incomplete.
In particular match_results are not finished. Iterators are not even started.
Volunteers are welcome ;-)
[EDIT] [As of gcc-4.9]2 will be fully supported.
|
7,696,133 | 7,696,171 | C++ return reference variable in prefix overloading | I am confused when all the code I find shows returning a reference variable when overloading the prefix operator. I went through the parashift.com FAQ (http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.14) and it isn't clear, even though it says it WILL be clear when you read it. I adapted their ex... | First, there's an efficiency issue. You are creating a new instance of the class in order to return it for no reason.
Second, there's the semantic issue. Your code invokes the empty constructor or the copy constructor to make the temporary and then destructs the temporary. If that has semantic meaning that's inappropri... |
7,696,260 | 7,701,456 | Functions as template parameters issue | I have this problem bothering me. I have the FSM class which associate keys to callbacks
class FSM
{
public:
typedef bool (FSM::*InCallback_t)( int );
typedef std::map< std::string, InCallback_t > Table;
// Since I would like to allow the user to register both functors and class member functions
template< typename... | You haven't defined Callback::operator(). There is no secound function for Callback just the function from CallbackBase which takes a CallbackBase and a int as parameters! This is why the compiler moans about "unresolved overloaded function type".
The type of the inherited function is bool (CallbackBase::*operator())(... |
7,696,280 | 7,696,368 | Print() method is not known for class | I am trying to implement a binary search tree. Here is the code I have so far:
#include <iostream>
using namespace std;
class BST{
public:
int n,*v,vn;
struct node{
int val;
node *left,*right;
node (int v){ val=v; left=right=0;}
};
node *root;
... | C++ is case-sensitive. You typed Print but the method is called print. And, of course, you need to pass that method a node pointer.
|
7,696,285 | 7,696,351 | program to implement password security in c languge? | Any idea how to get like this feature in c or c++
password= ********
but at the end system gets right password(means real input) but other people see this.
| To confirm the password of a user, use pam (the official page is hosted on kernel.org and therefore down as of writing), in particular pam_authenticate.
If your application has its own authentication architecture (and most of the time, it shouldn't), execute stty -echo, ask for the password, and then execute stty echo ... |
7,696,422 | 7,696,452 | Why socket(PF_INET,SOCK_STREAM,0) returns -1? | I trying to create a socket application on visual studio c++, but I can't.
The problem is int listen_sock = socket(PF_INET,SOCK_STREAM,0) returns -1 and I don't know why...
What am I doing wrong?
| You should print the error (using GetLastError). I suspect you are not initializing things:
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
|
7,696,569 | 7,696,594 | Split expressions but leave separators | There are such expressions like:
name=="sometext"
value!=4
I would like to split such expressions with string separators like "==" and "!=" and keep these separators, so result would be:
name=="sometext" -> [name] [==] ["sometext"]
value!=4 -> [value] [!=] [4]
How can it be done with Boost or some other l... | With boost I would use this simple regex :
(.*?)(==|!=)(.*)
Edit : provided that the expression is a string.
Edit 2 : explanation of the regex
// (.*?)(==|!=)(.*)
//
// Match the regular expression below and capture its match into backreference number 1 «(.*?)»
// Match any single character that is not a line br... |
7,696,591 | 7,696,608 | can we give size of static array a variable | hello every one i want to ask that i have read that we can declare dynamic array only by using pointer and using malloc or newlike
int * array = new int[strlen(argv[2])];
but i have wrote
int array[strlen(argv[2])];
it gave me no error
i have read that static array can only be declared by giving constant array size ... | What you have is called a variable-length array (VLA), and it is not part of C++, although it is part of C99. Many compilers offer this feature as an extension.
Even the very new C++11 doesn't include VLAs, as the entire concept doesn't fit well into the advanced type system of C++11 (e.g. what is decltype(array)?), an... |
7,696,629 | 7,696,671 | getting crash om memory set After updating to lion and xCode | I have just updated to Lion and now my app is crashing which was working fine in older version. It crash on memset function with no logs.
unsigned char *theValue;
add(theValue, someotherValues);
I have passed theValue reference to function
add(unsigned char *inValue, some other perameter) {
memset(inValue,0,sizeOf(i... | Is there really no code between the declaration of theValue and the call to add()? If so, then that's your problem. You are passing a random value as the first parameter to memset().
For this code to make sense, you have to allocate a block of memory for theValue and pass its size to add(), like so:
unsigned char *theV... |
7,696,838 | 7,697,544 | How do I get Keyboard and Mouse Input in GTK? | I want to recieve keyboard and mouse input in GTK+. For keyboard input, I tried using the accelgroup but it wasn't somehow as smooth as say SDL or SFML. When I pressed a key. It responded, paused for some time, responded again, pause for sometime and so on. By Mouse input I mean getting the position of the Mouse at a g... | What you want to do is moderately complex. Take a look at
http://developer.gnome.org/gtk-tutorial/2.90/
and especially at
http://developer.gnome.org/gtk-tutorial/2.90/x344.html
and
http://developer.gnome.org/gtk-tutorial/2.90/c2422.html
The second link has source code for a keyboard callback that seems to do what you w... |
7,697,148 | 7,697,166 | Is there a functional difference between "2.00" and "2.00f"? | I ask because I am using the Box2D library, which calls for mostly float arguments. Although I see a lot of example code that uses the 0.00f format, I am not quite sure if there is an actual difference between that and plain old 0.00.
Will I be hurting myself later on by not appending the additional f? Is it a speed th... | The f suffix makes it a single precision(float) literal instead of a double precision literal. This usually means 32 bit instead of 64 bit floats.
Floating-point constants default to type double. By using the suffixes f or l (or F or L — the suffix is not case sensitive), the constant can be specified as float or long... |
7,697,176 | 7,697,221 | Parsing commands with regular expression | There is such pattern:
(parse file_name (txt or ini)) or/and (if (string)(== or !=)(string)/* must be at least one */ (and)/*cannot be at the end without expression on right*/)
Explanation: there are two commands - 'parse' and 'if'. There are three cases of mixing these commands:
'parse' + 'if'
'parse'
'if'
If 'pars... | You should consider using an actual parser instead of regular expressions. Regular expressions are a powerful tool, but what you're trying to do is not really what they're meant for. Either write one yourself (shouldn't be that hard for the problem at hand), or go looking for a parsing library or parser generator.
|
7,697,183 | 7,697,381 | Why won't my lines move? | Okay, so I'm calling a function that draws three lines to display an 'I' on-screen.
Then, I call another function which calls this function, but adds 1 to the x variable to
make a the letter bold. Then I want to put x++ add in the 'tick' function, which executes
every frame. It isn't working, but why? If you don't unde... | When you call DrawI it has x and y passed to it as parameters:
void Game::DrawI(int x, int y)
These mask the global x and y, such that within DrawI everywhere you say x and y it refers to the function parameters. (You can access the global ones using ::x and ::y though).
Since you always call DrawI with literals, not ... |
7,697,257 | 7,697,269 | Suitability of Visual Studio 11 Developer Preview for development | I recently downloaded the Visual Studio 11 Developer Preview, and it looks awesome. I read the fine print on the download page, and it says:
Visual Studio 11 Developer Preview is prerelease software and should not be used in production scenarios.
I would be using only the C++ compiler/IDE of VS11, so does anyone know... | The licence prohibits it. The WinDP and the associated vNext tools are free- Microsoft would obviously want you to pay. When you download the tools, you agree to the licence terms, which includes not using it in production.
Another obvious thing is that the C++ Intellisense is more than a tad buggy.
|
7,697,373 | 7,697,417 | Access Violation when calling LockFileEx() | I have a FileMapping class that allows me to also lock a file for exclusive use by my process by using the Win32 API function LockFileEx().
bool FileMapping::lockFile(bool wait) {
if (isFileLocked())
return true;
// We want an exclusive lock.
DWORD flags = LOCKFILE_EXCLUSIVE_LOCK;
// If we don... | Your last argument is NULL, while it should be a pointer to a OVERLAPPED structure. The error about reading location 0x00000008 probably corresponds to the documented requirement that:
You must initialize the hEvent member to a valid handle or zero.
Given the hEvent member comes after two pointers, in 32 bit compilat... |
7,697,569 | 7,697,626 | GUI easy and fast without .NET framework? | Is there any way to build graphical interfaces in the same rapid and easy way we could do in Visual Studio, but without .NET Framework? I'm looking to native Windows GUIs, so using Qt with Qt Creator is not an option (and it doesn't need to be cross-platform). Something with the Windows API using C++ would be great (no... | Given:
You don't want to use Qt
You want to use Win API
The natural option is MFC. It's basically quite a thin wrapper around the Win32 UI API, but VS has an MFC UI designer that will save you a lot of work (no need to manually set the co-ordinates of controls etc.).
|
7,697,581 | 7,697,680 | Return Obj-C blocks in C++ code | I'm currently porting some classes from the Apple iOS Foundation Framework to C++ and i'm expecting some issues. I'm trying to port this Obj-C method from the NSExpression @class :
- (id, NSArray *, NSMutableDictionary *)expressionBlock
So in my sfExpression class, I have the following code (when deleting others metho... | Edit: Moral of the story, don't use GCC when dealing with blocks.
Here is a full example as far as I can see, this works in my tests.
class Foo
{
public:
Foo(NSExpression *_exp) : expression([_exp retain])
{
}
~Foo()
{
[expression release];
}
id (^ExpressionBlock())(id, NSArray*, ... |
7,697,588 | 7,697,613 | #include <cstdatomic> "no such file" in ubuntu | when compile with g++ -std=c++0x -Wall test.cc -o hello,
output fatal error: cstdatomic No such file or directly
Where is missing?
| The include should be #include <atomic>
|
7,697,617 | 7,698,068 | Pipe between sockets | I've got a C++ server that acts as a mirror. What gets in gets out to a different socket. Right now, it reads the socket into a buffer and writes it into the other socket. I want to improve the throughput.
I've read stuff about sendfile() and splice(), but it seems limited to "file-to-socket" transfers. Maybe a simple ... | You can setup a named pipe in linux. Multiple processes could read/write from this. Check out this link: http://www.cs.fredonia.edu/zubairi/s2k2/csit431/more_pipes.html.
Also as mentioned above using netcat should do the trick (http://netcat.sourceforge.net/).
|
7,697,621 | 7,697,628 | how to unload managed c++ dll? | A.dll is a native c++ dll, B.dll is a managed c++ dll. A.dll depends on B.dll, so when load A.dll, B.dll is loaded automatically, but after A.dll is unloaded, B.dll is still loaded. Only A.dll depends on B.dll, why B.dll can't be unloaded? How to unload the managed c++ dll? I'm using vs2010.
Thanks
| You cannot unload a managed assembly once it is loaded by the CLR. The only way is to kill the AppDomain.
|
7,697,819 | 7,697,848 | Why cvWaitKey(0) doesn't work? | I'm not sure why, but for a mysterious reason my c++ application doesn't wait anymore when it reaches cvWaitKey(0) it just passes this line, like this function doesn't do anything!
I also tried cvWaitKey(100000) it doesn't work either...
void main() {
cvWaitKey(0);
return;
}
My project is a little complex, I'm u... | Have you called cvNamedWindow yet? It will not work without cvNamedWindow.
|
7,697,842 | 7,697,878 | Printing output on the Output Window in Visual C++ IDE | How do I print on the output window in Visual C++? The project that I am working on isn't of a console window project type. That's when I build and run it, it doesn't open a console window. Instead, it opens a win32 application, which isn't built by me. I am just adding things to it.
I am pretty new to C++ and because ... | You can use OutputDebugString("..."); to print to the Output window of Visual Studio. You have to #include <windows.h> though.
|
7,697,859 | 7,697,916 | Visual Studio: Macro for checking configuration type (exe/dll) | Is there a macro I can use for checking the current configuration type in visual studio?
Depending on the current setting I'd like to either include a main or dllmain function:
#IFDEF CONFIGURATION_TYPE_EXE
int main(int argc, char **argv)
{
...
}
#ELSEIF CONFIGURATION_TYPE_DLL
BOOL APIENTRY... | If it's a DLL project, the _USRDLL will be defined. (see Configuration Properties\Preprocessor\Preprocessor definitions).
Be careful though, because the list is filled by wizard and will not update automatically if the project was created as something else and then configured as DLL. Also, you have to be careful if yo... |
7,697,922 | 7,698,023 | Invalid conversion error when overloading ostream& operator<< | Here is the prototype of my class Rational
#ifndef RATIONAL_H
#define RATIONAL_H
//forward declaration
class ostream;
class Rational
{
int numerator,denominator;
public:
// the various constructors
Rational();
Rational(int);
Rational(int,int);
//member functions
int get_numerator()const{return numera... | Your first issue is that you try to forward declare ostream as a class. Assuming that you mean to use std::ostream, you can't do that, its not legal.
For one, it's a typedef for a template specialization, not a class itself.
Second, because you don't #include <ostream> you don't have a definition for any of the standar... |
7,697,943 | 7,697,993 | More SDL C++ Opengl display trouble | I seem to be having the same trouble over and over again and cannot get my thick head around it. This program will not display a paddle as I want (and expected it) to do on screen :( -
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
SDL_Event event;
const int paddle_width = 20;
const int paddle_height = 80;
class P... | At a minimum you screwed up your constructor. Again.
It should probably be this:
PlayerPaddle()
{
xloc = 20;
yloc = 200;
yvel = 0;
}
You may also want to toss in a SDL_Delay(100) at the end of your main loop to slow things down until you get some more sophisticated physics handling going.
|
7,698,044 | 7,698,142 | C++ write and read from mysql database | I'm working on a project where we want to write to a mysql database, I've googled around and tried a few implementations but they all fail.
For example I tried this: http://markalexanderbain.suite101.com/using-a-mysql-databases-with-c-a70097
#include "StdAfx.h"
#include <iostream>
#include <my_global.h>
#include <mysql... | Error code 0xc0000135 means "The Application Failed To Initialize Properly". This is almost certainly due to a missing DLL (or two); probably the ones relating to MySQL mentioned in your #pragma lib statements.
Either add them to your path or copy them to the same directory as the .exe.
EDIT: Follow the instructions ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.