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,541,186 | 7,542,366 | Transformations seem to work improperly | Ok, so I have a weird problem with OpenGL in landscape mode on iOS.
From what I've read on the internet I have to rotate the scene myself, so I did that like this:
void GameViewController::onSurfaceChanged(int width, int height)
{
float aspect = (float)width / (float)height;
float fovy = 90.0f;
glMatrixMode(GL_PROJECT... | Seems like there was an error in the template I was using. Using the default Open GL ES template way of creating a context gives me the proper 1024*768 screen size. Problem fixed.
|
7,541,378 | 7,541,462 | How to get more encapsulation in C#? | I have recently learned C# fully, approximately. However, in C++ I could implement a better encapsulation when passing objects to methods, with const modifier. But in C#, objects can be modified through the reference parameter, such as Dispose on Graphics object.
I need sometimes more encapsulation. Properties can give... | You cannot the X property of Form.Location, because Form.Location is a property that returns a value type (Point). As soon as you access Form.Location, you get a copy of the location; thus, changing something in this copy is meaningless. Since this.Location.X = ... is an obvious mistake, the C# compiler prevents you fr... |
7,541,415 | 7,541,442 | Segmentation Fault on creating an array in C | I have recently migrated to a new laptop - HP dv6119tx (Intel Core i5, 4 GB RAM). It has Windows 7 Home Premium 64 bit installed.
I am trying to create an array of type int of length 10^6 in C++ (Dev C++), which I used to create comfortably on my last laptop (32 bit Windows 7 Ultimate/Ubuntu Linux, 2GB RAM) and every ... | A four megabyte stack is pretty big. The default size on Windows is 1MB. You need to use the /STACK option to the linker to ask for a larger size.
|
7,541,548 | 7,541,576 | C++ class has no member named 'blah' | I have a .h file with this in it:
#ifndef CS240_LINKED_LIST_H
#define CS240_LINKED_LIST_H
#include <string>
//! LLNode implements a doubly-linked list node
class LLNode {
friend class LinkedList;
public:
LLNode(const std::string & v, LLNode * p, LLNode * n) :
value(v), prev(p), next... |
You have misspelt LLNode as LLnode.
You need to add a default constructor to the LLNode class
you need to take the address of the this->beginning and this->end members in the LinkedList constructor:
.
LinkedList::LinkedList(){
this->beginning.prev = NULL;
this->beginning.next = &this->end;
this->end.prev ... |
7,541,629 | 7,541,909 | Skipping text while reading files in C++ | I'm learning C++, and I'm doing work with data loaded from external text files using cin.
I'm trying to recognize certain strings in large amounts of data that I need to skip through.
How would I write a function that skips through a certain number of characters in a file / on a line, either as I'm importing them from ... | On general skipping: seekg
On the real issue:
It seems like you would want to be matching patterns against a large body of (semi?) text. Since the pattern is long enough that you can gain from skipping input stretches, it really seems you are trying to invent optimized string search all over.
It has been done:
http:... |
7,541,682 | 7,541,799 | Handle time of received interrupt in windows | I have an external controller with only one button connected to PC with RS232.
Operating in Windows, I want to know the time of hardware interrupt being received.
Time of control being received by user application process is incorrect here.
I want to know the way of redefining the primary ISR (like asm "int 14h") in Wi... | int 14H is right for actually handling the UART on COM1 or COM2: see here. But setting up an ISR is a different matter and for that I would look around for a BIOS listing. It might be hard to find, but I don't believe there's any way around it. Try googling "pc BIOS listing"; you might get lucky.
There is a way to chai... |
7,541,750 | 7,541,870 | c++ win32 dynamic menu - which menu item was selected | i have a win32 application (c++) that has a context menu bind to the right click on the notify icon. The menu/submenu items are dynamicly created and changed during runtime.
InsertMenu(hSettings, 0, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR) hDevices, L"Setting 1");
InsertMenu(hSettings, 1, MF_BYPOSITION | MF_... | Try the following:
MENUINFO mi;
memset(&mi, 0, sizeof(mi));
mi.cbSize = sizeof(mi);
mi.fMask = MIM_STYLE;
mi.dwStyle = MNS_NOTIFYBYPOS;
SetMenuInfo(hDevices, &mi);
Now you'll get the WM_MENUCOMMAND instead of WM_COMMAND. The menu index will be in wParam and the menu handle in lParam. Take care to eat up messages only ... |
7,541,810 | 7,541,852 | How do I make any C++ library I make thread safe? | First of all, I'm fairly experienced with C++ and understand the basics of threading and thread synchronization. I also want to write a custom memory allocator as a pet project of mine and have read that they should be thread-safe.
I understand what the term "thread-safe" means, but I have no idea on how to make C++ co... | Same as all threading issues: make sure that when one thread is changing something, no other thread is accessing it. For a memory allocation system, I would imagine you would need a way of making sure you don't allocate the same block of memory to 2 threads at the same time. Whether that is by wrapping the entire searc... |
7,541,916 | 7,542,081 | Invoke Java from C++ | I am trying to invoke the Java Virtual machine from C++ following the example found here:
Basically I have a small Java program:
public class TestJNIInvoke
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}
Then I have a C++ program that I want to create a JVM and call the Tes... | Even though you include the same header file, the Java Native Interface uses two different interfaces for C and C++.
In C++, it's:
jclass cls = env->FindClass("java/lang/String");
instead of (for C):
jclass cls = (*env)->FindClass(env, "java/lang/String");
So the C function call that requires env in two places become... |
7,541,955 | 7,546,297 | recording dll APIs and then mimicking it | Is there some tool that can record APIs in some c++ dll , and then playback them .
At our costumer site we have a machine with some vendor software that exposes it's functionality .
We wanted to record that dll and then mimic it back at the office .
Any idea how We can do that ?
Thanks for help.
| You can start with Detours or its open-source equivalent EasyHook. Your hook function can log the activity, and then back at the office you can write a replacement DLL that replays the activity.
|
7,542,027 | 7,542,105 | How do I override some functions in the Queue STL object? | I am trying to override the push and pop functions from the STL queue. I think I need to use templates. I get a 'MyQueue' does not name a type (this error is in my main.cpp file) and an error saying expected initializer before '<' token. Here is the snippet of code:
#include "MyQueue.h"
sem_t EmptySem;
sem_t Presen... | You cannot override functions that are not defined as virtual. So you gain nothing by publicly inheriting from std::queue.
It would be best if MyQueue stored a member that was a std::queue. That way, you can do whatever you want and just forward the functions to the std::queue member.
Also, C++ has no keyword super; th... |
7,542,043 | 7,542,325 | C/C++ FLAC tagging library | Is there any C/C++ FLAC tagging library that work on streams? Wherever I look I only find ones that work on files. It's kinda weird to me - why use something limited like file instead of more abstract stream. Well, maybe I'm just spoiled by managed languages neatness (I'm more of a Java guy, but this time I need unmana... | I'm not familiar with any FLAC libraries, but the reference FLAC library supports an interface for custom I/O. This allows you to write a small stub that will convert I/O calls to a custom data source, which needn't be a file.
It seems to require capacity to seek, though. If that is the case, then you might not be ab... |
7,542,054 | 7,542,150 | Global vector emptying itself between calls? | I have a vector in a header, like so:
extern std::vector<Foo> g_vector;
In the associated cpp file I have this:
std::vector<Foo> g_vector;
I also have a class Bar, and in it's constructor it will add some stuff to g_vector, like so:
Bar::Bar(/* stuff */)
{
// do things
std::cout << g_vector.size() << std::end... | Not sure what the issue really is, but I guess the following pattern will help solve it: define an accessor to the global variable and allocate it as a static function variable as shown below.
In the header file:
std::vector<Foo> &getGlobalVector();
In the cpp file:
std::vector<Foo> &getGlobalVector()
{
static std::... |
7,542,209 | 7,548,064 | Texture transform matrix in a constantbuffer not working properly | I'm trying to clip a texture by hardcoding the texture coordinates through 0 and 1, and then sending a constantbuffer containing a 3x3 texture transform matrix to the vertexshader.
However, the texture is not rendering as I expected it to. I'm not sure where I went wrong. Could someone help? See code below.
For testing... | The problem is the 16 byte alignment. An XMFLOAT3X3 is just 9 floats in a row. When this gets stored in registers, its just going to take the first four floats and put them in c0, the next four in c1, and the remaining float in c2.x. You can see this yourself with the following:
cbuffer cbChangesEveryFrame : register( ... |
7,542,391 | 7,542,460 | Convert array of unsigned char (byte) into unsigned short in C++ | I have array^ byteArray and I need to extract bytes in Little Endian sequence to make unsigned shorts and ints. I've tried every combination of the following I can think of so am asking for help.
int x = UInt32(byteArray[i]) + (UInt32)(0x00ff) * UInt32(byteArray[i + 1]);
int x = UInt32(byteArray[i]) + UInt32(0x00ff) * ... | You are using managed code. Endian-ness is an implementation detail that the framework is aware of:
array<Byte>^ arr = gcnew array<Byte> { 1, 2, 3, 4 };
int value = BitConverter::ToInt16(arr, 1);
System::Diagnostics::Debug::Assert(value == 0x302);
Whether the framework's assumptions are correct depends on where the d... |
7,542,522 | 7,543,498 | read irregular file into a 2-dimension array using C++ | I am very new to C++. I believe there are solutions already in stackoverflow but I cannot find any.
I need to read data from a txt file into a 2 dimension array. File is like
54 3 5 678
10 1 2 3 46 8 1 1 2 3 4
9 8 10
Each line contains up to 120 integers and there are no more than 60 lines.
Your reply is high appreci... | My solution, just substitute cin with your file stream
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char* argv[]) {
string line;
int ints[60][120] = {0}, i = 0;
stringstream ss;
while (getline(cin, line)) {
ss.str(line);
for(int j =... |
7,542,566 | 7,542,574 | UInt64 on a 32 bit system, need to generate from UInt32's or array of bytes, how? | To generate UInt64 the following results in "warning C4293: '<<' : shift count negative or too big, undefined behavior"
UInt64 byteArrayToUInt64(int %stI, array<Byte>^ byteArray) {
UInt64 retV = byteArrayToUInt32(stI, byteArray);
retV |= byteArrayToUInt32(stI, byteArray) << 32;
return retV;
}
or
UInt64 byt... | Before shifting the value, you need to static_cast it to an UInt64. Otherwise you are shifting a 32 bit value by 32 positions, and that's undefined behavior. Shifting a 64bit value by 32 positions is ok.
|
7,542,572 | 7,548,019 | How to send a 2-D array as a reference in C++, and back? | yet another beginner-to-intermediate question. I'm trying to pass a 2-D array to a function in C++. I'm aware that the array can't be sent directly to the function, so I first created a pointer (names edited but you'll get the idea):
double input[a][b] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
Class.calculate (*(input), a, b... | It's hard to say for sure without seeing the declaration of calculate(), but I'd guess it's an argument type mismatch. You can send your array as a double*, but not as a double** - it is an array of doubles (they're laid out linearly in memory, even if the compiler lets you treat them as a multidimensional array). Bu... |
7,542,630 | 7,542,716 | How do I return the address of a node? | I want to return the address of a node after I find it.
The node object class is inside a tree class set as private (private is the node inside)
I'll show you a function that's very similar to what I want but with a bool return type.
It returns true if the node exists within the tree or false if it's not there, I only ... | Node is a nested type within Arbol, so you should actually declare your function like this:
template< class T > Arbol<T>::Node<T>* Arbol<T>::Buscar(const T t);
|
7,542,802 | 7,550,971 | ifstream can't locate file? | I'm trying to read a file called "sample.txt" but whenever i try to do an ifstream, it can never locate the file. So my question is where do you put the file so that it can be located?
ifstream iFile("sample.txt");
| Here is the solution.
1) Open your project in Xcode;
2) Locate the Products folder in the Groups & Files tree on the left side of your Project window;
3) When you expand that folder, you should see the icon for the Unix Executable File (usually a black rectangle);
4) Ctrl-click on that icon and select Show in Finder_ ... |
7,542,836 | 7,542,870 | C++ linked list append method | I am writing a linked list template class in C++ as an exercise for myself to help me get back into C++ programming. I've got the following class definition:
template <typename T>
class List
{
public:
List();
~List();
void append(T data);
void display();
int count();
private:
struct Node
... | The second method only handles the case where the list is non-empty.
When the list is empty, the line q->next = p; is never reached, so the new element is leaked with no pointer existing to it after p goes out of scope.
What you want, if you would like to eliminate the special case for empty list, is a Node **, like th... |
7,543,165 | 7,543,180 | How do I insert a variable result into a string in C++ | I just started learning C++ in Qt and I was wondering how can I put a variables result in a string? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence. I know in objective-c it would be like,
NSString *name = [NSSt... | You don´t mention what type your string is. If you are using the standard library then it would be something along the lines of
std::string name = "Hello, " + nameField;
That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this:
std::ostringstream stream;
stre... |
7,543,313 | 7,543,439 | How to handle keypress events in a Qt console application? | For example, that when you press "Esc", the application ends.
| Qt doesn't handle console events, it can just read \n-terminated lines from the console.
You need to use native APIs or other libraries (curses).
|
7,543,424 | 7,543,588 | Leaking Memory In C++ With boost::ptr_vector | I been working in a project, but recently I check if my program has some leaking and the results is that it's leaking and a lot.
I use _CrtDumpMemoryLeaks(); to receive all the messages of leaking and I check that most of them are related with boost, I know that it must be my problem, but I can't understand why it's le... | Depending on where you placed it but in almost all cases, _CrtDumpMemoryLeaks will not show you the truth when using STL/BOOST smart pointers. It will see the usage of new within the STL as a memory leak.
|
7,543,471 | 7,543,660 | Is there a high level shape drawing API for C or C++? | I am starting a new project (Windows application), which needs a simple graphical interface. The graphics are not the main point of the application, the algorithms behind them are, so I'd like to spend as little time as possible thinking about graphics.
I need to draw simple shapes, connect them with lines, and label ... | Due to the general ease of writing that kind of high-level system, given a low-level drawing API, you generally don't see this kind of 2D scene graph library. The kind where there are explicit objects in the scene, and you move the objects around on the level of objects.
The closest I can think of is the way WPF handle... |
7,543,491 | 7,543,573 | libboost_date_time linker error | I just built and installed boost on cygwin and was trying to compile a program but it gave me a linker error because it was looking for libboost_date_time, and I have libboost_date_time-mt instead in usr/local/lib
I tried to reinstall boost using the following (the same command I had used initially)
./bootstrap.sh --wi... | ./bootstrap.sh means run the shell script bootstrap.sh in the cirrent directory.
So you need to be in the sirectory the script is in So
cd C:\cygwin\home\ba\boost_1_47_0
and then run the bootstrap script
An alternative is to install boost via cygwin itself if you can use 1.43
|
7,543,548 | 7,543,886 | Piping a program that uses WriteConsole | I wanted to call _popen to get the results from an executable but it was blanking out.
I looked in debugger and found out the program uses Kernel32.WriteConsoleW to write a unicode string to the console, instead of using stdout.
How do I capture it?
| You should be able to redirect the Output of a child process.
Have a look at Creating a Child Process with Redirected Input and Output
Furthermore the application might use STD_ERROR_HANDLE instead of STD_OUTPUT_HANDLE.
|
7,543,623 | 7,543,676 | Does a template type waste space in C++? | I was going through EASTL's list class to look at how the author has implemented the nodes. My expectation was a simplistic class/structure. Instead, I see a base and a node that is inheriting from this base (still simplistic, but why two classes?). His comments explain why:
We define a ListNodeBase separately from Li... | Without the helper class, the list root node would contain an instance of T that is never used. The second sentence is saying that you might not expect an empty list to create a T. For example, creating a T might have side effects.
|
7,543,637 | 7,543,655 | Reading text fields from file with custom separator | I am working on a problem for a class I'm taking in which we need to read in text from a file to a 2d table of strings (called 'string table[][]'). The text file I'm reading in is formatted as follows:
Ain el Beida # - # - # OEB # Algeria # Africa # F # 42578 # 61997 # 90560 # #
Segbana # - # - # ALI # Benin # Africa ... | Consider using std::getline, since it allows you to specify a delimiter (in your case, the delimiter is #).
std::ifstream file("somefile.txt");
std::string field1;
std::getline(file, field1, '#'); // Ain el Beida
Note though that each field is actually separated by a space and a #, so you will have leading / trailing ... |
7,543,687 | 7,543,692 | Crash when calling clear on an Empty Map | I'm getting a strange crash when I try to interact with a map in this particular class. When I try to call clear() or even begin() on the map it crashes. I haven't added anything to map, at this point nothing has touched it at all.
Code in question:
spriteMap_.clear();
if (!spriteMap_.empty())
{
SpriteMap::const_it... | You are probably corrupting the map´s memory somewhere within that class. Get the map memory address, and see what happens when you attach breakpoints to such locations.
Edit:
Sprite* newSprite = &Sprite(nextSpriteId_, this, image);
Here you are taking a pointer to a temporary object; note that is not even legal C++ ... |
7,543,697 | 7,543,702 | Does "vector<x>::iterator" mean there is a "vector<x>" namespace? | I have seen the code
vector<char> v(10);
vector<char>::iterator p;
here what is the need of vector<char>::.Does it mean iterator is a class inside vector namespace?
|
Does it mean iterator is a class inside vector namespace?
Not quite, is a type inside vector class template. The iterator not only depends on the type of container (here a vector), but on the type of element iterated over as well (here a char).
|
7,543,765 | 7,543,927 | Pop function and linked list implementation | Alright guys, so I know how the pop function works obviously. I also know that I need to set a LinkNode * top = head and that if top == NULL that you need to return NULL. I'm just not sure what I'm honestly supposed to do after that. The return is supposed to remove and return a value and the data type of the functi... |
“I … know that I need to set a LinkNode * top = head and that if top == NULL that you need to
return NULL. I'm just not sure what I'm honestly supposed to do after that.”
Well, the things you mention have nothing to do with pop.
For a linked list, pop is about unlinking the first node. Depending on the level of abs... |
7,543,870 | 7,543,884 | which operator overloading has been used for ifstream object to evalute to boolean | I am new to C++. recently I come across the following code
ifstream in("somefile");
if(in){
//read the file....
}
I am wondering which operator overloading the ifstream might have used for the in object to automatically evaluate to boolean in if condition. I tried but couldnt find a clue. please help me. thank in... | It's actually operator void *.
It's overridden to return a non-zero pointer if the stream is valid, and a NULL pointer otherwise. The pointer it returns is meaningless and should not be dereferenced, it's only there to be evaluated in a boolean context.
|
7,543,891 | 7,543,998 | Doubly-linked list infinite loop? | If I were to create a node class, as shown below, and if it were used in a doubly-linked list, would it create an infinite loop upon deconstruction of the doubly linked list? Or would it terminate nicely?
class Node
{
Node( );
~Node( )
{
delete mNext; //deallocs next node
}
Contact mConta... | If considering the mNext pointer the nodes are forming a loop then then destruction of any of the nodes will indeed probably form an infinite recursive loop and it will terminate the program by blowing up the stack.
What it will probably happen is
The first "external" delete node; is issued.
When entering the node des... |
7,544,032 | 7,567,323 | Can't get the handle of a Cwnd Class in MFC Windowless Activex? | I have asked two questions earlier about this and for each post there was some solutions i tried them, but the problem still exist.
My first question was : why a windowless Activex does not return the Handle. the suggestion was "change the creation setting an make windowless activate off, i have tried it but still m_... | As you mentioned you need a window handle to be able to receive user messages through it, you always have an option of creating a helper window, such as message only window, see Using CreateWindowEx to Make a Message-Only Window.
For your windowless control it is okay to not have any window handle at all, so you canno... |
7,544,049 | 7,544,085 | win32 api function to get processor's current speed | I am unaware of a win32 api function/functions used to query the local PC processor's current speed. I wish not to use WMI because it seems unlikely to be feasible on all PCs.
| You can (usually) get the processor speed using the QueryPerformanceFrequency function. I'm saying "usually" since this function returns the frequency of the performance timer component of the system, but virtually all current CPU's available operate at the same frequency as the performance timer component.
This functi... |
7,544,099 | 7,544,955 | A weak/shared pointer, detect when one user remains, boost | I want a pointer where I can tell when the reference count is one. Essentially the pointer works like a weak_ptr, but the cleanup needs to be manual. That is, every so often the program goes through a loop of its pointers and checks which ones have only one reference remaining. Some it will clean, others it will retain... | You cannot in general accurately determine the number of references. But you can tell when it is exactly one - use unique().
|
7,544,153 | 7,544,242 | What is the difference between _chdir and SetCurrentDirectory in windows? | Are there any difference that I should choose one over the other?
| They achieve the same result but belong to different APIs, so they return their results and report errors in different ways.
If you're already using other routines from either API, pick that one. If not, SetCurrentDirectory() is more "Windowsy", while _chdir() is more similar to the POSIX API. If you have a mind to por... |
7,544,233 | 7,544,265 | Difference between implicit conversion and explicit conversion |
Possible Duplicate:
Implicit VS Explicit Conversion
What is the difference between "implicit conversion" and "explicit conversion"? Is the difference different in Java and C++?
| An explicit conversion is where you use some syntax to tell the program to do a conversion. For example (in Java):
int i = 999999999;
byte b = (byte) i; // The type cast causes an explicit conversion
b = i; // Compilation error!! No implicit conversion here.
An implicit conversion is where the conversi... |
7,544,411 | 7,544,444 | C++: Are left/right bitshifts for negative and large values defined? | My question is, within C++, is the following code defined? Some of it? And if it is, what's it supposed to do in these four scenarios?
word << 100;
word >> 100;
word << -100;
word >> -100;
word is a uint32_t
(This is for a bottleneck in a 3d lighting renderer. One of the more minor improvements in the inner most ... | In the C++0X draft N3290, §5.8:
The behavior is undefined if the right operand is negative,
or greater than or equal to the length in bits of the promoted left
operand.
Note: the above paragraph is identical in the C++03 standard.
So the last two are undefined. The others, I believe depend on whether word is sign... |
7,544,426 | 7,544,435 | Initialize a static const array member of class in main(...) and not globally? | Suppose class Myclass { private: static const int myarray[2]; }
If I wanted to initialize myarray I should put the following statement in global scope:
const int Myclass::myarray[2] = {1,1};
What should I do If I want to initialize my array in main() (at some runtime calculated values eg at {n1, n2} where n1 and n2 ar... | There's nothing much you can do.
You could create a member function that would initialize the values, and call it. But, if it's static, private and const - then you can't even do that and out of options.
You cannot initialize a static member at run-time, you cannot access a private member from outside of class (unless ... |
7,544,847 | 7,544,879 | How to run different threads on different cores? |
Possible Duplicate:
how to set CPU affinity of a particular pthread?
I am writing a c++ program, using g++ compiler in Ubuntu. I have 4 threads in my program and 4 cores on my CPU. I want to be sure that each thread will be run on a different core. I am rarely familiar with pthread.
| See sched_setaffinity function: http://manpages.courier-mta.org/htmlman2/sched_setaffinity.2.html
|
7,545,206 | 7,545,214 | How to check if a Windows version is Genuine or not? | Is it possible to check whether a Windows installation is Genuine or not programmatically?
Lets just say I want to check Windows 7 from C, C++, Java or Python.
| this from CodeProject, in C++ ( Check for Windows Genuine in VC++ )
#include <slpublic.h>
#pragma comment(lib,"Slwga.lib")
bool IsWindowsGenuine()
{
GUID uid;
RPC_WSTR rpc=(RPC_WSTR)_T("55c92734-d682-4d71-983e-d6ec3f16059f");
UuidFromString(rpc,&uid);
SL_GENUINE_STATE state;
SLIsGenuineLocal(&uid,&... |
7,545,309 | 7,574,498 | Gluing a variadic template to a variadic function | In an attempt to bypass GCC's unimplemented always-inlining variadic functions in libc++, I thought I could maybe wrap the variadic functions (like snprintf, more precisely, the *_l variant) in a variadic template to achieve a similar effect. An instantiation would fill in the variadic function's varargs, allowing the ... | I think the question you're asking is confusing so let me restate it.
You want to use variadic templates to write a function that simulates inlining a variadic function.
It cannot be done. va_args is often implemented as a void* to the first parameter on the stack (note variadic functions are required to have at least... |
7,545,377 | 7,545,408 | Getting a string representation of a template parameter | I want to be able to create a method in a templated class that returns the name of the type subsituted in the template parameter.
eg:
template <typename T>
class CPropertyValueT
{
std::string GetTypeName()
{
return #T;
}
}
This is possible with a preprocessor macro using #, I figured there must be a way wit... | You can use typeid(T).name(), though it will return decorated name of the type.
If you're using GCC, then you can use GCC API, declared incxxabi.h header, to demangle the names.
Here is an example (source):
#include <exception>
#include <iostream>
#include <cxxabi.h>
struct empty { };
template <typename T, int N>
s... |
7,545,430 | 7,545,656 | Strange error message when a class method is missing |
Possible Duplicate:
GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'
I have been banging my head against a wall for a long time because of a strange ld error.
So I reproduced it in a small test case to understand the issue.
I declared a class and I deriv... | vtable is created for the class that contains virtual function and for the classes derived from it.It means in your program vtable will be created for BaseClass and DerivedClass.Each of these vtables would contain the address of virtual function void func().Now note that DerivedClass doesn't contain the definition of ... |
7,545,501 | 7,545,545 | mutex problem in windows | I have problem with mutexes
I have this code and I dont any idea why it doesn't work correctly...
#include <windows.h>
#include <process.h>
#include <stdio.h>
HANDLE mutex;
unsigned _stdcall t(void*){
printf(":D:D:D\n");
return NULL;
}
int main(){
mutex=CreateMutex(NULL,FALSE,NULL);
WaitForSingleObject(mutex,INFINITE);... | As per MSDN:
The thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its execution.
Thus in your first sample, the second call to WaitForSingleObject() doesn't block the main thread as it is the thread that owns the mutex.
|
7,545,524 | 7,545,538 | Which of these two dimensional array are advantageous to use and why? | In a facebook group, I saw a question like :
If a row dominated two dimensional array in the following which one is advantage and why?
a) for(i=0;i<1000;i++)
for(j=0;j<1000;j++)
temp=temp+a[i][j];
b) for(j=0;j<1000;j++)
for(i=0;i<1000;i++)
temp=temp+a[i][j]
From my point I can see the... | There is no difference in theory.
The practical advantage is in cache locality. If you access locations which are far apart, you increase the number of cache misses, which in turn makes the code run slower.
Depending on your processor cache size, you would perhaps need to replace 1000 with some reasonably bigger number... |
7,545,563 | 7,546,335 | How to get the argument for promise::set_exception(x)? | I found in several places on how a promise should be used references to copy_exception, but I can not find it in the current FDIS. Is there an alternative way on how to use set_exception() since those blogs?
For example here
void asyncFun(promise<int> intPromise)
{
int result;
try {
// calculate the res... | There is a different name for copy_exception. copy_exception was renamed late in the standardization process over confusion of what it actually did:
template<class E>
exception_ptr make_exception_ptr(E e) noexcept;
Effects: Creates an exception_ptr object that refers to a copy of
e, ...
Use of either make_exce... |
7,545,804 | 7,547,888 | Modeless, parentless wxDialog still always above wxFrame window in z-order? | My program opens a wxFrame-based window and multiple modeless and parentless wxDialog-based windows. It all works beautifully, except that the wxDialog-based windows insist on always being on top of the wxFrame-based one.
I know about wxDIALOG_NO_PARENT, and I'm using it. The dialogs stay open when I close the wxFrame,... | It seems that this behavior comes from a difference in how Gnome handles windows with different "type hints"...it puts them into their own z-index groupings:
https://developer.gnome.org/gdk3/stable/gdk3-Windows.html#GdkWindowTypeHint
The dialog is created with GDK_WINDOW_TYPE_HINT_DIALOG while your other window is most... |
7,545,817 | 7,545,826 | Copying a file multiple times using loop; C/C++ | I wanted to copy a file multiple times using different names.
The program is this:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <sstream>
#include<cstring>
using namespace std;
main()
{
string text;
int i;
char ch;
ostringstream oss;
FILE *fp1,*fp2;
if((fp1=fopen("One Dollar.... | You should open and close the first file in each iteration of the loop.
....
for(i=1; i<=5; i++)
{
if((fp1=fopen("One Dollar.jpg", "rb"))==NULL)
{
cout<<"Error";
exit(-1);
}
....
The reason is because at the end of the first iteration, the first file pointer is at the end of the file, s... |
7,545,917 | 7,545,946 | Default parameters for methods of template class | Is there a way to provide default parameter values for methods of a template class? For example I have the following:
template<class T>
class A
{
public:
A foo(T t);
};
How should I modify this to give foo a default parameter of type T? For example: T is int then a default value of -23, or T is char* then default ... | If you want the default parameter to be just the default value (zero, usually), then you can write A foo(T t = T()). Otherwise, I suggest a trait class:
template <typename T> struct MyDefaults
{
static const T value = T();
};
template <> struct MyDefaults<int>
{
static const int value = -23;
};
template<class T>... |
7,545,969 | 7,546,009 | Converting byte number to grayscale and vica versa | I got a number between 0-255 and need to convert it to a RGB grayscale color. And how do I convert a RGB-color to a grayscale value between 0-255?
| The common formula is luminosity = 0.30 * red + 0.59 * green + 0.11 * blue. Matches the human eye's color perception, doesn't otherwise correct for display device gamma.
|
7,546,023 | 7,546,039 | A simple C++ While loop not working | I have a simple while loop i'm trying to implement but for the life of me can't figure out what I'm missing. I have currentuser initialized at the top to -1
while(currentuser = -1){
cout << "Enter user ID: ";
cin >> id;
currentuser = search(a, length, id);
}
My search function is this:
int search (User a[ ... | The = (assignment) operator is not the same as the == (equality) operator.
The line :
while(currentuser = -1){
first assigns -1 to currentuser, and then checks if currentuser has a non-zero value. This will always be the case (-1 != 0), so the loop will never end.
You likely meant this instead :
while(currentuser == -... |
7,546,083 | 7,546,787 | GrabCut - bgdModel & fgdModel empty - Assertion error | I am attempting image segmentation using GrabCut algorithm in OpenCV2.1 (C++)
Here my code:
Mat rgbWorkImage = imread(argv[1]);
Mat mask;
mask = Scalar(0);
Mat bgdModel, fgdModel;
Rect rect = Rect(Point(0,0), imageSize);
grabCut(rgbWorkImage, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT);
grabCut(rgbWorkImage, ... | One case where that error could happen is when your image has zero for either its width or height (but not for both) because of this bug: https://code.ros.org/trac/opencv/ticket/691 (which seems to be fixed after OpenCV 2.1).
If the image dimensions are non zero, you should also check that the ROI rect:
is not empty (... |
7,546,107 | 7,546,172 | Question about static variable | I have read many documentation about static variables. Here is one example which I didn't understand. Suppose that static variable in a class is declared like this:
class Something
{
public:
static int s_nValue;
};
int Something::s_nValue = 1;
int main()
{
Something::s_nValue = 2;
std::co... | In a usual C++ program, your classes are defined in headers that get included by all the source files that use them. So if it worked the way you expect, each source file would have its own copy of that static variable, when in reality they are supposed to all share one copy. This would be a violation of the one-defin... |
7,546,119 | 7,546,427 | C++ Winsock unicode problem | I have just converted a program that uses winsock to unicode, and im running into a problem.
Here's my code, well part of it
TCHAR http_request[MAX_REQUEST_LEN];
TCHAR data[65536];
int nDataLen = 0;
/* Create http_request */
send(mySocket, (char*)http_request, lstrlen(http_request), 0)
nDataLen = recv(mySocket, (char... | The main problem is that you are mixing up different concepts.
To get the correct program you have to know what you are doing instead of mechanically replace "char" with "TCHAR" in your entire code.
Your internal string representation and the data you are sending over the network is totally different things.
How you r... |
7,546,310 | 7,546,319 | Is there a pattern or trick to force evaluation on both expressions in an OR conditional statement? | What is the best way (pattern) around return method1() || method2() not invoking method2() if method1() returns true?
Example
I'm using this class to bound a table:
class Bounds {
// return true iff bounds changed
boolean set(int start, int end);
}
and I want this function to resize both the rows and columns a... | Use a non-short circuiting (sometimes called "Eager") operator, |.
public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
return rows.set(0, 1) | columns.set(0, 1);
}
You can read more about that in the operator documentation for || (C# specific link, but still holds true for Java and C++).
|
7,546,397 | 7,546,426 | C++ For loop problem | I have a loop that takes two inputs, a last name and an ID, then converts it to a user id. The code looks like this:
void User::setUserid(string ln, string id){
string temp = "0";
string temp2 = "0";
for (int k = 0; k < 6; k++){
temp += ln[k];
}
for (int i = id.l... | Is ln guaranteed to have at least six characters? You may be shooting past the end of the string.
In any event, you've chosen a slow and complicated way to copy parts of strings around. This should suffice:
void User::setUserid(string ln, string id){
userid = "0" + ln.substr(0, 6) + "0" + id.substr(id.size() - 2);
... |
7,546,620 | 7,546,745 | Operator new initializes memory to zero | There is such code:
#include <iostream>
int main(){
unsigned int* wsk2 = new unsigned int(5);
std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
delete wsk2;
wsk2 = new unsigned int;
std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
return 0;
}
Result:
wsk2: 0x928e008 5
wsk2: 0x928e008 ... | There are two versions:
wsk = new unsigned int; // default initialized (ie nothing happens)
wsk = new unsigned int(); // zero initialized (ie set to 0)
Also works for arrays:
wsa = new unsigned int[5]; // default initialized (ie nothing happens)
wsa = new unsigned int[5](); // zero initialized (ie all ... |
7,546,629 | 7,546,754 | explicit specialization of template class member function | I have this :
template<class T, class U>
class A
{
template<size_t N>
void BindValues();
}
template<class T, class U>
template<size_t N>
inline void A<T, U>::BindValues()
{
conn->setValue<N-1>( std::get<N-1>(m_Tuple) );
BindValues<N-1>(conn);
}
template<class T, class U>
template<>
inline void A<T, U>... | Unfortunately a template method inside a template class cannot be specialized just based on template argument of method.
You need to specialize the template class also. In other words, the member method specialization should be a complete specialization with respect to class template (i.e. <T,U>) params as well as the ... |
7,546,672 | 7,546,890 | Memory leak using QVector | QVector<cLibraryRecord> Library;
...
Library.push_back(cLibraryRecord(ReaderFullName, BookGenre, BookTitle, AuthorsFullName, IssueDate, ReturnDate));
...
Library.remove(i);
QVector::remove() does not clear the memory. How can I clean the memory?
Thanks in advance.
| QVector.remove() always calls the destructor for the contained object, but the reserved size (returned by QVector::capacity()) doesn't shrink automatically when you remove elements.
You can use QVector::squeeze() to release the unused reserved memory.
But you can also have a memory leak in your class cLibraryRecord.
S... |
7,546,912 | 7,546,985 | Can I load a dll in such a way that it can be deleted while it's loaded? | The title pretty much says it all..
What I'm trying to do is write a tool that will monitor a dll file containing a plugin and when I overwrite it, by recompiling, it should automatically reload it.
I know I can make a copy, load the copy and monitor the original, but I thought there might be a better way..
If I under... | No, that's not how Windows works. Loading a DLL merely creates a memory mapped file, nothing is actually read from the file beyond the relocations (if necessary). Not until your code calls an exported function. Which causes a page fault because the code wasn't loaded yet. Now the code gets read from the file into R... |
7,547,067 | 7,547,261 | Best way to store large amounts of different types of data? | I want to store a buffer data. I will have to append data to data in the form of BYTEs, WORDs, and DWORDs. What is the best way to implement data? Is there something in the STL for this?
| From the little you've said, it sounds like you want to have different types in an STL container. There are two ways to do this:
Have a hierarchy of objects and store a reference/pointer to them (i.e. std::vector< boost::shared_ptr<MyBaseObject> >
Use boost::variant (i.e. std::vector< boost::variant<BYTE, WORD, DWORD... |
7,547,068 | 7,547,076 | Can not use template argument in function declaration | I'm struggling to find a good reason why the following code does not compile.
It gives me the following error.
Error 2 error C2923: 'std::pair' : 'std::set::iterator' is not a valid template type argument for parameter '_Ty1'
I need a little insight, as to why C++ does not allow me to use the template parameter ... | All you need is the "typename" keyword. Since your print function is templatized with T, you have to tell the compiler the set::iterator is not a value but a type. This is how.
#include<iostream>
#include<set>
#include <utility>
using namespace std;
template <typename T>
void print(const pair< typename set<T>::iterato... |
7,547,082 | 7,547,124 | How do I declare a C++ prototype with a void * pointer so that it can take any pointer type? | I want to create a function prototype in C++ so that there is a void * argument that can take pointers of any type. I know that this is possible in C. Is it possible in C++?
[EDIT] Here is a simplified version of the code that I am trying to get to work:
#include <stdio.h>
void func(void (f)(const void *))
{
int ... | Yes.
int i = 345;
void * ptr = &i;
int k = *static_cast< int* >(ptr);
UPDATE ::
What you have shown in the code certainly cannot be done in C++.
Casting between void and any other must always be explicitly done.
Check these SO link for more details on what the C -standard has to say:
1) http://stackoverflo... |
7,547,161 | 7,547,380 | C++ header-implementation-header-implementation dependency chain | I'm trying to create simple C++ incremental-build tool with dependency resolver.
I've been confused about one problem with cpp build process.
Imagine we have a library consists several files:
// h1.h
void H1();
// s1.cpp
#include "h1.h"
#include "h2.h"
void H1(){ H2(); }
// h2.h
void H2();
// s2.cpp
#include "h2.h"
... | In the case you stated to see the implicit dependence on s2.cpp you need to parse the implementation module s1.cpp because only there you will find that the s1 module is using s2. So to the question "can I solve this problem without parsing .cpp files" the answer is clearly a no.
By the way as far as the language is co... |
7,547,206 | 7,547,820 | Undefined Reference Trying to invoke Java from C++ | I am trying to create a Java virtual machine from C++ and invoke the main method passing a String argument to the main method of the Java program. I am following this example found on Sun's website: http://java.sun.com/docs/books/jni/html/invoke.html#11202
Here is the simple Java Program:
public class TestJNIInvoke
{
... | First, don't use gcc. By default, it assumes the code it's handling is written in C. When you want it to compile or link C++ code, you should run g++. This will bring in the C++ standard headers and libraries.
Second, you need to include the java libraries. Section 7.2.1 in the page you linked discusses this.
Your comm... |
7,547,228 | 7,547,292 | Problems after server uses accept() to accept connections | This is my first time ever using sockets, and I am having trouble accepting connections on the server side. My server is only designed to accept one connection at a time. Once a connection is received, the current date and time are written to the socket, and then the client prints out the date and time it received from... | This shouldn't happen.
It's even hard to imagine a broken scenario, like you have two instances of the server running, and the other one is accepting the connections, but then the new instance shouldn't be able to use the same port number again, so you probably doesn't verify return values of system calls, but then acc... |
7,547,421 | 7,547,560 | C++ Custom "List" implementation doesn't work | I tried to create a list container with similar access of elements in c++ as in C#
I'm totally lost now because my main method first printed weird numbers.
The RList class should be like:
RList<ClassName or Primitive> VariableName;
VariableName.AddData(Class or Primitive);
VariableName[IndexOfElement] get the element... | Lots of problems:
Constructors should initialize all members
Rule of three not implemented (on owned pointers).
Horrible spacing (you need to format that code better).
All your array memory allocation is wrong.
Allocate:
template <class T>
void RList<T>::AllocateNew(T obj)
{
if (this->m_Length == 0)
{
... |
7,547,506 | 7,547,558 | getch equivalent in assembly language | I am prigramming in assembly Language, x86 in C++ and I need to know the getch equivalent in assembly language instead of C++ language as I dont want to use any function from the C++ programming language.
I found the code on the web but it saves the given value to a variable and created in C++. I want to use the funct... | This is an OS-specific question. For example if you're using Linux, you can issue a read system call like this:
; Allocate some stack buffer...
sub esp, 256
mov eax, 3 ; 3 = __NR_read from <linux/asm/unistd.h>
mov ebx, 0 ; File descriptor (0 for stdin)
mov ecx, esp ; Buffer
mov edx, 256 ; Length
int ... |
7,547,538 | 7,547,608 | Virtual dtor segmentation fault | I've got the following code in C++:
#include <iostream>
class Number
{
public:
virtual void foo(){std::cout << "Number foo\n";};
Number (){ std::cout << "Number ctor" << std::endl;}
virtual ~Number(){ std::cout << "Number dtor" << std::endl;}
};
class Complex : public Number
{
public:
virtua... | I'm not entirely sure, but this is what I suspect...
I wonder if this is related to the fact that an array of derived classes should not be casted to an array of base classes (they're not the same, see: http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3): how would delete know the size of the object... |
7,547,561 | 7,547,667 | Loading .obj file in OpenGL in Visual Studio 2010 | In which directory should I store the .obj models in Visual Studio 2010?
I am using the OpenGL Mathematics (GLM) library to use them in OpenGL, and when I try to load the object it shows
Error11error LNK2019: unresolved external symbol _glmReadOBJ referenced in function _SDL_main
| Your question seems to have no relation to your actual problem. You're not getting this error when you "try to load the object"; this is a linker error. You get this when you try to compile and link your code. It has nothing to do with where the ".obj" files are stored, because you haven't created a functioning executa... |
7,547,655 | 7,547,767 | Why can't I define a nested class externally? | I'm having trouble putting together an object model that involves nested classes, using MinGW C++. Here is an example that exposes my issue:
foo.h:
/*
* foo.h
*
* Created on: Sep 25, 2011
* Author: AutoBot
*/
#ifndef FOO_H_
#define FOO_H_
class Foo
{
public:
class Bar;
Bar bar;
} extern foo;
#end... | The problem is here:
class Foo
{
public:
class Bar;
Bar bar;
};
At this point Foo::Bar is an incomplete type. And you cannot declare a variable of an incomplete type. It would be no different from trying to do this:
class Foo;
Foo foo;
They're both not allowed and for the same reason.
You could turn bar into ... |
7,547,786 | 7,547,802 | Is this the proper way to open a file for input? | Is this the proper way to open a file for input?
void BinaryTree::read(char * path, int line_number)
{
ifstream * file(path); //error: cannot convert ‘char*’ to ‘std::ifstream*’ in initialization
file->seekg(0, std::ios::beg);
int length = file.tellg();
char * buffer = new char[length];
file->getlin... | Dont use pointer. It is not needed here.
Try this:
ifstream file(path);
and then use it as:
//...
file.getline(buffer, line_number);//file->getline(buffer, line_number);
//...
|
7,547,928 | 7,562,388 | Get and set wchar_t chars from c++ to MySQL to c++ | I have a database (Mysql) with some fields in UTF-8 (I can change that if needed).
I use an old MySQL 'Communicator' or its predecessor, I wrote the code ~3 years ago and all I know today is that I link with libmysql.lib and #include "mysql.h" (do tell if you want me to dig up more).
The thing is I don't have a clue ab... | I recommend that you store your data in MySQL in UTF-8 form, rather than try to convince it to take Windows-native UTF-16. If your text is mostly Western, UTF-8 encoding will be more compact, and it will be more likely to work with the C-and-Unix nature of MySQL.
There are Visual C++ specific examples in MySQL++ that s... |
7,548,313 | 7,548,378 | Pointer questions regarding linked lists | Alright guys, so I've been working on a linked list program and I've run into a problem. I'm trying to place a piece of data into an already sorted linked list in a sorted fashion. Right now, I'm comparing the pointer data the user gives (Data * newData) to the head (LinkNode * current = head) and I know that's where... | Simply
if(*newData < (*current->data))
assuming that operator< is overloaded for the Data type
The minimal idiomatic way to provide std::less<> compliant weak total ordering (I.o.w. implement operator<):
struct Data
{
int id;
std::string other;
// details omitted
bool operator<(const Data& b... |
7,548,375 | 7,548,414 | Performing data error correction on Byte level, to video stream | Does anyone has an idea for efficient error correction algorithm?
Suppose all the operations and manipulation on the stream is on
the Byte level.
| Maybe Reed-Solomon error correction?
|
7,548,405 | 7,565,161 | Getting omnicppcomplete and ctags to work in VIM | Here's my .vimrc
syntax on
set number
set nowrap
set autoindent
" configure tags - add additional tags here or comment out not-used ones
set tags+=~/.vim/tags/cpp_files
set tags+=~/.vim/tags/cpp_src/
set tags+=~/.vim/tags/qt
" build tags of your own project with Ctrl-F12
map C-F12 :!ctags -R --sort=yes --c++-kinds=+p -... | This line should be the one that causes the problem:
autocmd FileType cpp set omnifunc=cppcomplete#CompleteCPP
You see, you have the following commands:
au BufNewFile,BufRead,BufEnter *.cpp,*.hpp set omnifunc=omni#cpp#complete#Main
autocmd FileType cpp set omnifunc=cppcomplete#CompleteCPP
The thing is, the first auto... |
7,548,427 | 7,548,763 | Multiple threads with locks vs single threads? | I am designing a client and server socket program.
I have a file to be transferred to the server from the client using UDP, I repeat I am using UDP.....
I am sending through UDP so, the sending rate is too fast then the receiver, so I have created 3 threads listening on the same socket, so that when one thread is doin... | Similar to Ed's answer, I'd suggest using asynchronous I/O and a single thread for your server. Though I find using Boost.Asio easier than posix AIO.
|
7,548,480 | 7,548,904 | How do I create a packaged_task with parameters? | Following this excellent tutorial for futures, promises and packaged tasks I got to the the point where I wanted to prepare my own task
#include <iostream>
#include <future>
using namespace std;
int ackermann(int m, int n) { // might take a while
if(m==0) return n+1;
if(n==0) return ackermann(m-1,1);
ret... | Firstly, if you declare std::packaged_task to take arguments, then you must pass them to operator(), not the constructor. In a single thread you can thus do:
std::packaged_task<int(int,int)> task(&ackermann);
auto f=task.get_future();
task(3,11);
std::cout<<f.get()<<std::endl;
To do the same with a thread, you must mo... |
7,548,564 | 7,548,605 | float <-> std::string conversion alternative? | is there any alternative to atof, strtod, lexical_cast, stringstream or sprintf?
that is:
fast
C++ way (std::string instead of char*)
safe (no buffer overrun risk)
valid (return NaN if conversion couldn't be made)
no external library (independent)
I prefer more like this , a simple function, optimized, and to the poi... | I'd look at Boost Spirit
http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/qi/reference/numeric/real.html
At least the benchmarks of the formatters (that is float -> string) consistently turn out as top-of-the-bill*1*
Also the exact input format specification and semantics when parsing can be configure... |
7,548,691 | 7,548,714 | C++ operator() optimization on vectors | I'm writing numerical code, in which it is useful to define vector operations. E.g if x and y are n-long vectors full of floats, it is nice to have x^y result in a in the ith element of y equaling some arbitary function of the ith element of x. One simple way of doing this is:
#include <vector>
#include <stdio.h>
#incl... | You're passing the arguments by value. That makes copies of the vectors.
template <typename T>
void operator^(vector<T> A, vector<T> B)
If you pass them by reference, you may get a speedup.
template <typename T>
void operator^(vector<T> const& A, vector<T>& B)
(A quick test on ideone.com shows even better performance... |
7,548,722 | 7,548,748 | Alternate of BufferedImage in C++ | I am using BufferedImage in my Java program for storing some information in an image. The problem is that I want to create a similar program in C++ but I can't find an alternate of BufferedImage..
Looking forward to some useful ideas.
Thanks
| You can have a look at the cairo library: http://cairographics.org/
In the examples:
cairo_surface_t *surface;
cairo_t *cr;
surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 120, 120);
cr = cairo_create (surface);
|
7,548,770 | 7,548,855 | Any good simple DirectX samples for Windows 8 (Developer preview)? | Are there any good tutorials on how to draw a simple triangle in DirecX for Windows 8 Developer preview? The game sample is too complex to understand the "basic" workings of the new DirectX version (which seems to be completely different from DirectX 9).
| The point of the sample is the Windows 8, not the DirectX. You need to learn DirectX11 before doing it with Windows 8. You're trying to read a sample on interoperation between two technologies, neither of which you understand. The point of Windows 8 Dev Preview is not to teach DirectX.
|
7,548,896 | 7,548,919 | How can I check in C++ whether std::cout is redirected to a file? | I need my program to behave differently, depending on whether the output is to a terminal or to a file. How can I find this out from within C++?
I assume there is no solution that works for all operating systems. For my purposes, it would be good to have one strategy which works under Windows and one which works under ... | This will help under linux: How to tell if running in a linux console versus an ssh session?
Yes it is a C call, but it can definitely be called from C++.
GetStdHandle gives a similar starting point under windows:
|
7,548,916 | 7,549,108 | c++ win32 how to store persistent data | I'm developing a c++ win32 application and i would like to implement persistent storage into it. I know I can use filesystem or a database or the registry, but what would be the best way for storing a:
boolean
unsigned int
wchar_t [256]
boolean [15]
I need to read/write from the storage only when the application ... | I think the easiest way to write settings on Windows is to put them in the registry. For user specific settings you will write in the HKEY_CURRENT_USER section. Here is the full list of registry access functions in the Win32 API.
If you consider you will ever need to port your application to other platforms, then you m... |
7,548,961 | 7,548,994 | c++ to java conversion, a few questions | I am converting a some C++ to java and have a small bit that I am unsure about
first question is what is tested for in the line
if (ampconst[i][0] || ampconst[i][1])
this in an example to the data in the array.
static short ampconst[NUT_SERIES][2] = {
{0,0},
{0,0},
{46,-24}
};
and my second question is that the amp... | if (ampconst[i][0] || ampconst[i][1])
tests whether the first/second column in ampconst[i] contain non-zero (it is an early-out optimization: if both the constants are 0 then the calculation can be skipped)
Edit I just found (google!) that this is a nutation calculation that has been adopted in quite a few places, ... |
7,549,180 | 7,550,409 | Search for file by creation Time | I'm trying to write C++ code in windows to find a file by creation time, not by name of file. Can't seem to find anything. Any help or suggestions are welcome.
| If you are looking for files that are under 20 seconds old, searching the whole tree could take longer than that.
If you are looking for files that were created while your program is running, you could use ReadDirectoryChangesW to wait for notifications of file changes with a filter of either FILE_NOTIFY_CHANGE_FILE_NA... |
7,549,187 | 7,549,216 | What is the correct term for ->,->* and .* operators? | Wikipedia refers to them as:
-> Member b of object pointed to by a
->* Member pointed to by b of object pointed to by a
.* Member pointed to by b of object a
But I need to refer to them without using "a" and "b". Do they have any names?
| The standard has calls ->* and .* "pointer-to-member operators" (5.5). The former expects the first operand to be of pointer type, the second of class type.
Similarly, -> and . are called "class member access" (5.2.5), or "dot" and "arrow".
|
7,549,195 | 7,549,268 | boost single thread libraries in cygwin | I just built and installed boost_1_47_0 using the following on cygwin
./bootstrap.sh --with-libraries=chrono,date_time,exception,filesystem,graph,graph_parallel,iostreams,math,program_options,random,serialization,signals,system,test,thread,wave link=static link=shared threading=single threading=multi
then I ran the b... | You need to use "--layout=system"
|
7,549,211 | 7,549,254 | Sorted linked list and the addSorted function problem. | So I've been working on this for awhile and I can't seem to figure out what's wrong. This addSorted function adds in all the correct values in their respectable places of the sorted array but when it goes into add a 0 to the front of the list, the program will not terminate and there is no result displayed. Anyone ha... | Is the result of compareTo being -1 mean that it is less than the current node?
And if previous==NULL you set current->next to point to the newNode, which means they are pointing to each other, as newNode->next is also pointing to the current node.
I think the root of your problem may be this, actually.
newNode... |
7,549,255 | 7,549,289 | C++ program to calculate greatest common divisor | I have started this program to calculate the greatest common divisor. This is what I have so far:
#include <iostream>
#include <math.h>
using namespace std;
int getGCD(int a, int b)
{
a = a % b;
if (a == 0)
{
return b;
b = b % a;
}
if (b == 0)
{
return a;
}
}
int main... | You should be looping through to find this, and it may help if you put, with some equations, your algorithm for how this should work.
But you have two problems I see, unless you are calling this inside of another loop.
You are returning in both cases, either the if or else, so you only go through here once.
Also, this ... |
7,549,280 | 7,549,313 | c++ char arrays, use in cin.getline() | I have the following code:
char myText[256];
cin.getline(myText,256);
Why exactly do I have to pass a character array to cin.getline() and not a string?
I have read that in general it is better to use strings than character arrays. Should I then convert a character array to a string after retrieving input with cin.ge... | You are using the member method of istream. In this case cin. This function's details can be found here :
http://en.cppreference.com/w/cpp/io/basic_istream/getline
However you could use std::getline
Which uses a string instead of a char array. It's easier to use string since they know their sizes, they auto grow etc. ... |
7,549,402 | 7,555,590 | How to program in Windows 7.0 to make it more deterministic? | My understanding is that Windows is non-deterministic and can be trouble when using it for data acquisition. Using a 32bit bus, and dual core, is it possible to use inline asm to work with interrupts in Visual Studio 2005 or at least set some kind of flags to be consistent in time with little jitter?
Going the dire... | Real time solutions for Windows such as LabVIEW Real-time or RTX are expensive; a stand-alone RTOS would often be less expensive (or even free), but if you need Windows functionality as well, you are perhaps no further forward.
If cost is critical, you might run a free or low-cost RTOS in a virtual machine. This can wo... |
7,549,507 | 7,549,513 | Whats wrong with my C++ syntax here | while input != 0
{
if input == "r";
cout << "Please input a floating point value for the height, and then a floating point value for the width, seperated by a comma." << endl;
cin >> height >> width;
}
I am trying to write a basic program that takes the dimensions of basic shapes and ... | The condition must be in parentheses. Here's your formatted code:
while (input != 0)
{
if (input == "r")
{
cout << "Please input a floating point value for the height, and then a floating point value for the width, seperated by a comma." << endl;
cin >> height >> width;
... |
7,549,518 | 7,549,535 | Have I Implemented Mutal Exchange Correctly? | I'm trying to implement mutual exchange on a multi-threaded program. I'm not sure if I'm doing it right, and it's difficult to test.
In main.cpp, I have something like this:
//mutex handle
HANDLE hIOMutex = CreateMutex (NULL,FALSE,NULL);
//main
while (1) {
Sleep(STEP);
WaitForSingleObject(hIOMutex,INFINITE);
... |
Are the sections of code even using the same HANDLE or am I declaring them locally and therefore screwing up the functionality?
No, they are not using the same handle or the same mutex, for that matter (there may be multiple handles to the same mutex). In the posted code, the two threads each have their own mutex, w... |
7,549,633 | 7,549,692 | Compilation error when calling function with default arguments | I'm getting errors when I call a function which uses a default argument.
The two files are cache.cpp and cache.h
Command I use to compile is
g++ -c cache.cpp
and the error is:
cache.cpp: In member function ‘bool mem::read(long unsigned int)’:
cache.cpp:205:88: error: no matching function for call to ‘vcache::swap(lon... | That's not how default arguments work. The default argument has to go in the declaration, not the definition:
// foo.h
void foo(int, int, int = 5); // default values here
// foo.cpp
void foo(int a, int b, int c)
{
// ...
}
Think about it: Every TU that wants to use the function has to know the default value. This... |
7,549,690 | 7,549,725 | Adding an Item to QGraphicsItemGroup Makes It Invisible | The code below
QGraphicsEllipseItem *ellipse = addEllipse(x, y, 6, 6, series_pen);
ellipse->translate(-ellipse->boundingRect().width() / 2,
-ellipse->boundingRect().height() / 2);
ellipse->setToolTip(label);
draws the QGraphicsEllipseItem on a QGraphicsScene. However, the following code doesn't:
QGr... | From the Qt manual page for QGraphicsItemGroup:
There are two ways to construct an item group. The easiest and most
common approach is to pass a list of items (e.g., all selected items)
to QGraphicsScene::createItemGroup(), which returns a new
QGraphicsItemGroup item. The other approach is to manually construct ... |
7,549,703 | 7,568,365 | Boost spirit grammar based string splitting | I am using Boost 1.44, The Spirit parser works well for numeric parsing but really is tricky for string parsing. I am trying to parse a string to be split using multiple delimiters: ',' ,';' or ' '. It works well for numbers when I do this (where vect = vector < double >):
qi::parse(first,last,double_ >> *(',' >> doubl... | String handling (the way you do it) got a lot easier with more recent versions of Spirit. I'd suggest to use Spirit from Boost V1.47, which got a major rewrite of the attribute handling code.
But even if it compiled the way you want, it wouldn't parse the way you expect. Spirit is inherently greedy, that means that +ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.