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,457,006
7,457,045
Improve board game turn processing
I have a fairly simple board game i've been building in C++. Currently, players are assigned a player number (1, 2, 3...N) depending on the number of players in the game. Pretty standard. The players and their stats are kept in a file which include their name and their number. I then process turns via reading a dir...
You might think of defining an Action class for a player acting in his turn, which is defined by a player number and a turn number, and define a comparison on this class. Read all Actions from the files, insert them into an ordered list, and then process these actions.
7,457,100
7,457,116
How can I delete a directory and all files in it with C++?
How can I delete all the files in the directory? I've used rmdir and other methods suggested in the internet but no one helped me: this is one of them: (I want to remove directory tmp in the current work directory) removeDir() { char currentPath[_MAX_PATH]; GetCurrentPath(currentPath); std::string tmp(...
http://www.cplusplus.com/reference/clibrary/cstdio/remove/ int remove ( const char * filename ); #include <stdio.h> int main () { if( remove( "myfile.txt" ) != 0 ) perror( "Error deleting file" ); else puts( "File successfully deleted" ); return 0; }
7,457,296
7,457,537
Smart references in C++
Edit: Welp, I guess this was a terrible idea. Is it possible to make a smart reference in C++ (for a specific class, since you can't overload the . operator) with the same semantics as a normal C++ reference, but which is reseated when used in an STL container? For example, if I have some int_ref class with the normal ...
One problem with even trying to do this is operator&. For a reference, it gives you the address of the referand (since references have no address). For a element of a container, though, it's expected to give you the address of the element (since those do have addresses). So, an element of a container cannot mimic refer...
7,457,370
7,457,885
C++ constructor calling and object creation
class Test{ public : int x; Test() { x = 0; cout<<"constructor with no arguments called"<<endl; } Test(int xx) { x = xx; cout<<"constructor with single int argument called"<<endl; } }; int main() { ...
All of the answers you've gotten so far are overly complicated and/or slightly misleading. In the first construction/initialization: T a(10); The very obvious thing happens. The second construction/initialization is more interesting: T aa = 10; This is equivalent to: T aa(T(10)); Meaning that you create a temporary ...
7,457,642
7,457,717
C++ Sharing variable between objects.
I'm having a little problem where I want two different classes to be able to share and make changes to another class object. I've got a HumanPlayer class, a ComputerPlayer class, and a Board class. The two player classes need to be able to interact with the one Board class. I thought that I could pass a reference to t...
It sounds like you are copying the board object instead of passing it by reference. The constructor of your player classes should look like this: class Player { public: Player(Board& board) // REFERENCE TO Board : the_board_(board) // initialize the reference { } protected: Board& the_board_; /...
7,457,741
7,457,765
How to correctly shorten an if-statement in C++?
Okay, I have an if sentence in which I compare a specific value multiple times. I bet there is a shorter way to do this: if(letter == "%" || letter == "+" || letter == "-" || letter == "!") I tried writing it as: if(letter == "%" || "+" || "-" || "!") But it works incorrectly.
Something like this might work: string s("%+-!"); if (s.find(letter) != string::npos) { ... }
7,457,747
7,457,999
Before or after when adding to sets in C++
Given my_type m; std::vector<my_type> v; Which runs more quickly? m.generate_data_inside_self(); v.push_back(m); Or v.push_back(m); v[0].generate_data_inside_self(); If the vector held pointers to the my_types then both would seem about the same. However when copying in the whole my_type object as in this example I ...
Add it when the complexity of copy constructor/operator == is smaller. If you are generating data, most likely increasing that complexity, insert before generating. If you have many vector copies and you are concerned about performance, my suggestion is to have a vector of pointers and new (and of course one day delete...
7,457,817
7,458,082
How to launch Chrome maximized via shell execution?
I am launching Chrome with the app="http://..." parameter (a Chrome application shortcut) via C++. Now it seems to open with a size of roughly 400x800 which is crazy. I'd like to open it maximized or at least have it remember the size. Is there a way to achieve this?
If you don't mind using the default browser (which, in my opinion, is the best option) instead of forcing the use of Chrome, you can simply open your URL with ShellExecute specifying that you want the window to be maximized: #include <windows.h> #include <Shellapi.h> // requires linking towards Shell32.lib // ... if(...
7,457,826
7,458,819
using libevent to read a continuous http stream and sending data at random times
Firstly I think I need to say that I'm still learning C++ so apologies if this is blindingly obvious/simple. I'm trying to use the libevent library (by trying I've looked through code in the sample folder and tested some) in my C++ program to consume an http stream. I'm wondering if anyone can provide me with an exampl...
Yuck. Given that this isn't really HTTP, I don't think you're going to be happy using a HTTP library - even if you get it to work today after a lot of frustration, it could easily be broken tomorrow. This is too rare to be a supported feature. But...it sounds like it's also simple enough that you could just open a raw ...
7,457,877
7,458,136
2D-Array : prefered way access items
So here I am tonight with this question that came up into my mind : What is your favourite way to access the items of a m x n matrix there is the normal way where you use an index for the columns and another index for the rows matrix[i][j] and there's another way where your matrix is a vector of length m*n and you a...
There are only two reasons to go for the one-dimensional array to represent n-dimensions I can think of: Performance: The usual way to allocate n-dimensional arrays means that we get n dimensions that may not necessarily be allocated in one piece - which isn't that great for spatial locality (and may also result in at...
7,457,959
7,457,975
Formatting objects into strings
I'm coming back to c++ after using Java for a long time. In Java overriding the toString method on an object allows the object to be automatically translated into a string and concatenated to other strings. class Test { public static void main(String[] args) { System.out.println(new Test() + " There"); // ...
The equivalent is to overload operator<<: #include <ostream> class Test { int t; }; std::ostream& operator<<(std::ostream& os, const Test& t) { os << "Hello"; return os; } You would then use it like this: #include <iostream> int main() { std::cout << Test() << " There" << std::endl; } See the code in act...
7,457,992
7,458,021
boost::unordered_map -- Need to specify a custom hash function for hashing std::set<int>?
I'd like use boost::unordered_map<key,value>, where key is a std::set<int>. Since a set of integers is no built-in type, I assumed I had to supply my own hash function (or, rather, I was thinking of using boost's hash_range). However, now I tried initializing a hash map like this, neither supplying a hash function nor...
According to the Boost documentation: the default hash function is Boost.Hash And, according to the documentation for Boost.Hash, default hash functions are provided for the standard containers. Consequently, there is already a hash function written for std::set. The Boost hash containers aren't smart enough to kno...
7,458,110
7,458,222
C++ Unified Assignment Operator move-semantics
EDIT: solved see comments --don't know how to mark as solved with out an answer. After watching a Channel 9 video on Perfect Forwarding / Move semantics in c++0x i was some what led into believing this was a good way to write the new assignment operators. #include <string> #include <vector> #include <iostream> struct ...
Be very leery of the copy/swap assignment idiom. It can be sub-optimal, especially when applied without careful analysis. Even if you need strong exception safety for the assignment operator, that functionality can be otherwise obtained. For your example I recommend: struct my_type { my_type(std::string name_) ...
7,458,193
7,458,526
WriteFile() always succeeds when used for COM device, even if no device is attached, is this normal?
I open the COM port ("COM1") with CreateFile and then use WriteFile to send data to device. And as the title says, WriteFile always succeeds and even returns correct number of bytes in *lpNumberOfBytesWritten, as if it had really delivered the bytes, even though the device is not connected!! Is this normal behavior or ...
The serial port is a fairly simple device, and I don't think it has much notion of whether or not a device is attached. So, naturally, you can always write characters to the serial port and the bits will just harmlessly ooze out of the connector.
7,458,200
7,458,347
What is the reasoning behind the different return types in string::insert?
Click here to see the functions. As you can see, all but the last three return a reference to the string. The 3rd last overload returns an iterator, which I am guessing (I may be wrong...) is because the iterator in the argument may become invalid after the insert operation. What about the last two functions? Why are t...
This is all about history. std::string is a thing that should not even exist in C++. Not because C++ shouldn't have a string class (it must have had tens of thousands when std::string was being worked on), but because the C++ standardization was meant to codify existing practice, and there was no single string class th...
7,458,327
7,458,354
C++ class specialiation when dealing with STL containers
I'd like a function to return the size in bytes of an object for fundamental types. I'd also like it to return the total size in bytes of an STL container. (I know this is not necessarily the size of the object in memory, and that's okay). To this end, I've coded a memorysize namespace with a bytes function such that...
Modified your code accordingly: /// specialization for a vector of anything template < typename Anything > size_t bytes(const std::vector< Anything > & object) { return sizeof(std::vector< Anything >) + object.capacity() * bytes( object[0] ); } Note that now you have a problem if invoking bytes with an empty vector....
7,458,374
7,458,386
Which C++ object copies more quickly?
Two instances of this C++ object exist. my_type { public: std::vector<unsigned short> a; } One where the std::vector is empty and the other where it contains 50 elements. Which instance copies most quickly or do they copy in the same time?
When a std::vector is copied all of it's elements are also copied - so the time taken should be proportional to vector.size(). In c++0x so called move semantics are introduced, allowing a move constructor and move assignment operator to be defined for types. These are defined for standard library containers (such as st...
7,458,436
7,458,456
Why does prevInstance exist in WinMain and wWinMain if it is always NULL
Since I am a beginner, it may be a very basic question. I am starting DirectX 11, and while creating my first application, wWinMain was used, and while searching for difference between WinMain and wWinMain, i came across this parameter prevInstance. prevInstance is always null according to MSDN, and since it is always ...
Raymond Chen's blog is almost entirely dedicated to discussing aspects of the Windows API that are "oddities" to us today. And fortunately, he has a blog post that answers this exact question: In 16-bit Windows there was a function called GetInstanceData. This function took an HINSTANCE, a pointer, and a length, and...
7,458,571
7,458,612
I do not understand this C++ error - error C2101: '&' on constant
This code supposedly works with GCC - I am trying to get it to work with Visual Studio. I can't figure out if the code is actually faulty or I'm not doing something right with the port. 1>c:\somepath\aaa.h(52): error C2101: '&' on constant 1> c:\somepath\aaa.h(52): while compiling class template member functi...
Constructing T() where T is a reference type is not valid, and makes no sense. Some versions of gcc incorrectly accept it.
7,458,645
7,458,683
Why am I getting ambiguous call for the following functions?
Consider the following: template <typename T> class testString { public: typedef T* iterator; void insert(iterator aPos, size_t numChars, T aChar); testString<T>& insert(size_t aIndex, size_t numChars, T aChar); }; template <typename T> void testString<T>::insert( iterator aPos, size_t numChars, T aChar ) { }...
Ah, one of those times when you're like "wouldn't it be better if in c++, 0 was not the same as null?" Anyway, your iterator type is typedef'd to T*, which is char*, and 0 is a fine value for a char*, hence the ambiguity (er, as K-ballo wrote). In std::string, the iterator type won't be a char*, it'll be something fanc...
7,458,654
7,458,779
OpenGL Depth Spaz Attack
I've begun learning OpenGL today, and it's just plain fantastic. However I cannot for the life of me make objects draw according to depth, instead of drawing order, so I hope someone can tell me what I'm doing wrong. Here's the extremely simple code I'm using to create a cube: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_...
I found the answer! http://www.opengl.org/resources/faq/technical/depthbuffer.htm Here's where I found the answer, My near frame was at exactly 0, it needs to be slightly away from 0 in order for the depth buffer's precision to take effect. (If I read that correctly) All is well.
7,458,696
7,458,732
Should I centralize all calls to new/delete to a single class?
Currently, I have all my objects managing their own memory, allocating with new in their constructors typically, and using delete in their destructors. This works for now, but the number of classes I have that use arbitrary amounts of memory is growing. The fact that new is essentially a "request" also bothers me, si...
Can I still use STL containers and force them to use the heap I provide? STL containers accept custom allocators: http://en.wikipedia.org/wiki/Allocator_(C%2B%2B)#Custom_allocators Here is a thread with links to samples: Compelling examples of custom C++ allocators? Is it beneficial in terms of performance ... ? Yo...
7,458,735
7,458,794
Resizing a label inside a gridlayout?
I'm learning Qt, maybe this is easy but I can't seem to figure it out. First, I have a file path in a QString, myPath. I want to load it and show it in a window. Suppose I have a window with a label inside it: QPixmap image(myPath); ui->myLabel->setPixmap(image); ui->myLabel->resize(image.size()); It works, but the on...
I'm not sure if I understood correctly but I believe you want some padding inside the label. That can be accomplished for example with QSS, Qt's flavor of CSS. ui->myLabel->setStyleSheet("QLabel { padding: 10px; }"); should do the trick.
7,458,763
7,458,829
using qsort causing a segmentation fault
Well, as part of learning C++, my project has a restriction on it. I'm not allowed to use any libraries except the basic ones such as <cstring> and a few other necessities. The project should take in input from a file that is an "n" number of columns of strings and be able to sort the output according to lexicographic...
char* line1 = new char[1000]; char* line2 = new char[1000]; This is not good at all. You're never freeing this, so you leak 2000 bytes every time your comparison function is called. Eventually this will lead to low-memory conditions and new will throw. (Or on Linux your process might get killed by the OOM-killer). ...
7,458,807
7,460,728
Why must SetWindowsHookEx be used with a windows message queue
I've been trying some things with hooks, and I don't understand why hooks must be used with a message queue hook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, NULL, 0); MSG msg; while(GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } UnhookWindowsHookEx(hook); Why ...
The low-level hooks, WH_KEYBOARD_LL and WH_MOUSE_LL are different from all the other hooks. They don't require a DLL to be injected into the target process. Instead, Windows calls your hook callback directly, inside your own process. To make that work, a message loop is required. There is no other mechanism for Win...
7,458,835
7,458,859
Library for C++ File Upload/Download?
Is there a C++ library that provides functions for uploading/downloading files over http without having to deal with sockets etc?
Try cURLpp (formerly cURL++), the official C++ binding to libcurl. Here's an example of downloading from a URL and outputting to standard out.
7,458,857
7,458,908
Why doesn't C++ support dynamic arrays on the stack?
In C99 this was legal: void f(size_t sz) { char arr[sz]; // ... } However, this - dynamically sized stack arrays - has been dropped in C++, and not seeing a return in C++11. AFAIK C++ was made with C compatibility in mind, so I wondered There must be some very good argument of not including this useful feature...
I think, it's because C++ provides superior solutions: std::vector<T> and std::array<T,N> (C++11); though the latter is not dynamic as such but it's superior to raw arrays. You can always know the size, no matter which function you pass the vector or array. Since C cannot provide these solutions, C99 came up with Var...
7,459,080
7,459,092
How to force a Library to use custom std::allocator?
I am using SFML, which handles most of it's memory through std::vector<Uint32> and other types similar to that. All declarations use the default Allocator. The SFML library is compiled into .lib files that are statically linked against in Visual Studio. (I possess all the source code to it however if needed.) My que...
Well, the most 'bruteforce' or foolproof method would seem to create a preload library that implements malloc/free (and friends?) This is usually the way in which heap debuggers/bounds checkers operate. However, I know nothing about the SFML allocator requirements, so it might not work if the space is very limited. In ...
7,459,249
7,522,827
Can't compile mongodb 2.0 c++ driver
I tried to build mongodb c++ 2.0 driver,but got the following error message: security_commands.cpp:(.text+0x865): undefined reference to mongo::CmdAuthenticate::getUserObj(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::basic_string<char, std::char_traits<char>, std::allocator...
The tarball for the driver seems to be missing mongo/db/security.cpp file among others to make a shared lib. But, it has enough for building static lib with few missing symbol. open SConstruct and comment out the line saying libs += env.SharedLibrary( "mongoclient" , allClientFiles ) and you are set.
7,459,269
7,459,310
Function pointers as parameters in C++?
I am confused by the form of parameters for function pointers. The following two: int fun(int (*g)()) { cout << g() << endl; } int fun(int g()) { cout << g() << endl; } Both these two definitions work well. But as you have noticed, there are some differences in the prototypes of these two functions: the firs...
In the second case, the function type adjusts to become pointer-to-function-type, which makes the both function identical. int fun(int (*g)()); int fun(int g()); //same as above, after type adjustment The C++03 Standard says in §13.1/3, Parameter declarations that differ only in that one is a function type and the o...
7,459,321
7,459,511
Using a function to call a functor
I have an algorithm that calls several functions to process its data. Each of these functions share and manipulate many of the same variables. Therefore I'm trying to avoid having a set of functions that contain a long list of reference arguments as I find that to become very difficult to read, especially since many ...
With umpteen functions working on the same shared data, making them member functions of a class with the data as instance data is the rational choice. However, “functor” is perhaps not the correct term for your beastie. A functor behaves much like a simple function pointer: it can be freely copied around, and usually, ...
7,459,358
7,459,383
New vs. Malloc, when overloading New
I'm overloading new and delete to implement my own small-objects/thread-safe allocator. The problem is that when I am overloading new, I cannot use new without breaking universal causality or at least the compiler. Most examples I found where new is overloaded, use Malloc() to do the actual allocation. But from what ...
Short answer: if you don't want existing malloc, you need to implement your own heap manager. A heap manager, for example malloc in glibc of Linux, HeapAlloc in Windows, is a user-level algorithm. First, keep in mind that heap is optimized for allocating small sizes of objects like 4~512 bytes. How to implement your ow...
7,459,442
7,459,595
Creating a shared_ptr from an allocator using typedefs?
I have some code that I am retrofitting to use an allocator instead of operator new and operator delete directly. One part of this code's public interface is to return not a bald pointer but a shared_ptr (being constructed from the bald pointer wandering out of new.) I see in the public contract for an allocator sever...
shared_ptr (and the other TR1 smart pointers) are defined (ie, take template parameters) in terms of the element type, not the pointer type. As such, if you are using shared_ptr, you cannot substitute your own pointer representation; nor does it make sense to do so in most cases.
7,459,452
9,593,738
Reserving Shared Memory with No File Backing (Linux/Windows) (boost::interprocess)
How can I reserve and allocate shared memory without the backing of a file? I'm trying to reserve a large (many tens of GiBs) chunk of shared memory and use it in multiple processes as a form of IPC. However, most of this chunk won't be touched at all (the access will be really sparse; maybe a few hundred megabytes thr...
On Windows, all memory has to be backed by the disk one way or another. The closest I think you can accomplish on windows would be to memory map a sparse file. I think this will work in your case for two reasons: On Windows, only the shared memory that you actually touch will become resident. This meets the first requ...
7,459,528
7,459,656
Passing char ** as reference and returning const char * as reference
I have a class which parses the Command line arguments and then returns the parsed value to the client class. For parsing, I need to pass argv to parse function. I would like to pass by reference but from what I know , we never use the '&' symbol when passing arrays. Arrays are not objects that can be passed by referen...
Arrays are not objects that can be passed by reference. What makes you think that? 1) Is the way argv is treated, correct? CmdLineObj.parse(argc, const_cast< const char** >(argv)); Why are you const casting that? Instead of casting, you could change your definition of main to const char** argv. 2) Better way to ha...
7,459,611
7,459,683
Can Qt call two slots simultaneously, if they get called from the same signal?
If there are two slots in two different threads and these slots are connected to a signal in a third thread. Can it happen, that both slots get called at the same time by the signal or do they get called synchronized every time? I ask because i want to send some callback data structure (encapsulated with QSharedPointer...
Have a look here (official Qt documentation for Qt's signal/slot mechanism regarding threads). Each slot is called inside its thread, therefore I am pretty sure anything can happen. You should install a lock mechanism.
7,459,655
7,459,681
Throwing exceptions in c++ syntax
For throwing exceptions I know that you can declare/define the function with the implication that it throws an exception EX. void foo(void) throw(const char *) {}; What is the appropriate time to do this. If we are going to declare/define it this way, do we do it with both the prototype and the definition or just th...
Don't do that, it was deprecated in C++11 for a good reason: it does not do what people think it does. Update: More information on the subject here http://www.boost.org/development/requirements.html#Exception-specification Another update: As pointed out by @Steve Fallows, here is another good reference on the topic: ht...
7,459,711
7,459,732
How to write standard C++ iterator?
I have the following simple Graph class, where for each Node, I store a set of outgoing Arcs: #include <iostream> #include <vector> #include <map> #include <set> struct Arc { char label; int targetNode; }; struct Graph { std::vector<int> nodes; std::map< int, std::set<Arc*> > outgoingArcsPerNode; }; How can ...
If you don't want to use boost, have a look at what iterators must provide : STL documentation. Otherwise, you may use boost iterator library. See the iterator_facade tutorial which is very close to what you're asking.
7,459,855
7,460,026
Windows C++ framework recommendation
Does anyone know of a good C++ framework for Windows? I don't need it for GUI, but for some kind of a WINAPI C++ wrapper. I don't like MFC, and ATL is quite limited. These possibilities are nice, but its not wrapped enough, and in the end I always find wrap WINAPI myself. Does anyone know of a good framework?
For the most important non-GUI API tasks (files, network, threading), boost does a pretty good job.
7,459,867
7,459,909
Preventing a const member function from changing a member array
Apparently, a const member function is still allowed to change data that the class member are pointing to. Here's an example of what I mean: class MyClass { public: MyClass(); int getSomething() const; private: int* data; }; // ... data = new int[10];, or whatever int MyClass::getSomething() const { data[4] =...
In a const member function, the type of data changes from int* to int *const: int * const data; which means, it's the pointer which is const in the const member function, not the data itself the pointer points to. So you cannot do the following: data = new int[100]; //error as it's attempting to change the pointer i...
7,460,122
7,460,900
How to keep trace of the change of light position?
I am trying to make a very simple MFC OpenGL tutorial. There is a sphere. And the spere is the source of light(like sun). And there is two triangle. According to movement of the spere, I want to have the triangles lightend. But When I move the sphere, the surface of the triangle changed only for the first time. Next mo...
You should never place drawing calls in a input event handler. That's your main problem. The other problem is – so it seems – that you confuse OpenGL for a scene graph. OpenGL is a drawing API with no recollection of a scene, whatsoever. In your input handler you set some variables, issue a redraw event and then in the...
7,460,206
7,460,246
Why use unsigned chars for writing to binary files? And why shouldn't stream operators be used to write to binary files?
My first question is, why is it customary to use unsigned chars for writing to files in binary mode? In all of the examples I have seen, any other numerical value is casted to unsigned char before writing to the binary file. My second question is, what's so bad about using stream operators to write to binary files? I'v...
chars are the smallest type in C/C++ (by definition, sizeof( char ) == 1). Its the usual way to see objects as a sequence of bytes. unsigned is used to avoid signed arithmethic to get in the way, and because it best represents binary contents (a value between 0 and 255). To operate on binary files, streams provide the ...
7,460,373
7,460,375
Printing to a progress bar to the terminal from Java/C++
I want to update the percentage progress of my program on the screen. I have a progress bar that I print. I add a * when the progress is more than 10%, but I also want to write the actual percentage correct up to every digit. However, I do not want to write a new number every time, since it will have the following effe...
In C++ I believe you want to throw \r to bring you back to the beginning of the line (instead of \n) or you'll want to look at the curses library. Not sure, but you can probably do something similar in Java.
7,460,410
7,460,424
Lvalue to Rvalue conversions
From 4.1/2 The value contained in the object indicated by the lvalue is the rvalue result. When an lvalue-to-rvalue conversion occurs within the operand of sizeof (5.3.3) the value contained in the referenced object is not accessed, since that operator does not evaluate its operand. Out of curiosity, I was wond...
Yes. Without lvalue-to-rvalue conversion, it cannot read it's value. Loosely speaking, think of lvalue as some sort of container, and rvalue as the value contained in the container. C++03, section §3.10/7 reads, Whenever an lvalue appears in a context where an rvalue is expected, the lvalue is converted to an rvalue; ...
7,460,520
7,460,536
Warning: 'void checkGlError(const char*)' used but never defined
I'm compiling a Shared library using Android NDK r6b. All classes are C++. I have the following two classes: Utils.hpp #ifdef USE_OPENGL_ES_1_1 #include <GLES/gl.h> #include <GLES/glext.h> #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif #include <android/log.h> // Utility for logging: #define LOG_TAG ...
You've made it static. It only lives in that specific translation unit therefore. The solution is to remove the static keyword. The warning is telling you that in the header file you "promised" there would be a definition in that translation unity if one was needed, but one has not been provided and it was needed.
7,460,569
7,461,190
Parse a tile map into efficient horizontal and vertical bounding boxes
I'm working on a simple platformer game in C++, everything is working great except i want to group tiles into bounding boxes in order to have less passes of the physics function(i'm targeting both PC's and embedded devices so its all about speed). What the following function does is load a simple map format: "[char *he...
This is a little ugly, but I think it should work as a starting point. It works by scanning left to right, top to bottom looking for to find whole columns that are alike. The challenging part is keeping track of consecutive complete vertical blocks and outputting "partial" runs correctly. void find_bounds() { int...
7,460,753
7,460,781
Does a pointer returned by std::string.c_str() or std::string.data() have to be freed?
As far as i know, std::string creates a ident array-copy of its content when you call the c_str()/data() methods (with/out terminating NUL-char, does not matter here). Anyway, does the object also take care of freeing this array or do I have to? In short: std::string hello("content"); const char* Ptr = hello.c_str(); ...
No you don't need to deallocate the ptr pointer. ptr points to a non modifyable string located somewhere to an internal location(actually this is implementation detail of the compilers). Reference: C++ documentation: const char* c_str ( ) const; Get C string equivalent Generates a null-terminated sequence of char...
7,460,984
7,461,062
Matrix class operator overloading,destructor problem
I was trying to write a matrix class which would be able to find inverse,adjoint,etc. of a square matrix of any order. The constructor initializes an identity matrix of order n(passed to it). class Matrix { int** elements; int order; public: Matrix& operator=(const Matrix& second_inp) { if(this->order!=second_inp...
It is hard to tell what is going wrong, since you have not posted your constructors. In the exp3=exp1*exp2; a lot of things happen: First a new matrix c is constructed in the operator* function. Then the return c; statement calls the copy constructor and then the destructor. After that operator= is called and after th...
7,461,140
7,461,203
Is there an equivelant for Pascal's readkey; in C or C++?
I am looking for a Console function that waits for the user to press a key. I want it to be like Pascal's readkey; as in a Console Only solution. No GUI library / Graphics Library / Windowing Library / WinApi Calls (Windows). It should be cross-platform and (preferably) part of the C std library or C++ Class Library. S...
The C Standard library has no notion of a "keyboard buffer". input/output is mostly line-based (triggered when ENTER is pressed). You have a few options: use an external library like ncurses change the terminal buffering strategy with setvbuf() and use fgetc() (and wait for ENTER if you didn't change the buffering str...
7,461,152
7,461,214
Is it possible to compile a C/C++ source code that executes in all Linux distributions without recompilation?
Is it possible to compile a C/C++ source code that executes in all Linux distributions without recompilation? If the answer is yes, can I use any external (non-standard C/C++) libraries? I want distribute my binary application instead of distribute of source code.
No, you can't compile an executable the executes in all Linux distributions. However, you can compile an executable that works on most distributions that people will tend to care about. Compile 32-bit. Compile for the minimum CPU level you're willing to support. Build your own version of glibc. Use the --enable-kernel...
7,461,157
7,461,229
Passing sequence of 2D points as arguments to cvFitLine
I have the following code fragment: int count = (int)sizes.size(); CvSeq* seq = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint2D32f), memStorage); float line[4]; for (int i=0;i<count;i++) { CvPoint2D32f p; p.x = sizes[i]; p.y = depths[i]; cvSeqPush(seq, &p); } cvFitLine( seq, CV_DIST_L1, 1, 0.001, 0.00...
Quoting from the documentation of cvCreateSeq concerning the first parameter: seqFlags – Flags of the created sequence. If the sequence is not passed to any function working with a specific type of sequences, the sequence value may be set to 0, otherwise the appropriate type must be selected from the list of predefine...
7,461,173
7,461,352
Most efficient way to retrieve a timer?
I've never actually worked with timers before but I need one for my current project. So this might be a silly question: but what's the 'normal' way to retrieve a timer for a game, and is there a better/more efficient way? Thanks
Since you may want the time elapsed, and it might be so little, you might need to use the clock() function defined in time.h. Here what I found about it in the MSDN Library: Calculates the wall-clock time used by the calling process. clock_t clock( void ); Return Value The elapsed wall-clock time since the start of t...
7,461,318
7,461,500
Getting relative paths within a Mac .app bundle
I've developed a game in C++, OpenGL and OpenAL and I am trying to build it into an app bundle rather than a command-line executable. I copied and pasted the code from Relative Paths Not Working in Xcode C++ at the top of my main.cpp file (also tried it in the App_Prefix.pch) and I get a number of syntax errors. I've a...
Your code should be inside a function, for example main(). Currently your code is pasted at the file level. You can't have if statement or function calls there.
7,461,451
7,461,498
itoa in a template function
Code goes first: template <typename T> void do_sth(int count) { char str_count[10]; //... itoa(count, str_count, 10); //... } but I got some compile-error like this: error: there are no arguments to ‘itoa’ that depend on a template parameter, so a declaration of ‘itoa’ must be available error: ‘itoa’ w...
It appears that itoa is a non-standard function and not available on all platforms. Use snprintf instead (or type-safe std::stringstream).
7,461,484
7,825,031
Memory model ordering and visibility?
I tried looking for details on this, I even read the standard on mutexes and atomics... but still I couldnt understand the C++11 memory model visibility guarantees. From what I understand the very important feature of mutex BESIDE mutual exclusion is ensuring visibility. Aka it is not enough that only one thread per ti...
If you like to deal with fences, then a.load(memory_order_acquire) is equivalent to a.load(memory_order_relaxed) followed by atomic_thread_fence(memory_order_acquire). Similarly, a.store(x,memory_order_release) is equivalent to a call to atomic_thread_fence(memory_order_release) before a call to a.store(x,memory_order_...
7,461,556
7,461,577
What should a parser for a programming language do?
I have already written a lexer which returns tokens, and now I'm working on a parser. I have one problem. Imagine this code example: print("Hello, world!") The lexer returns four tokens (print, (, "Hello, world!" and )). The final program should print the string "Hello, world!". But what should the parser do? Should t...
The parser should generate an abstract syntax tree, which is an in memory representation of the program. This tree can be traversed after parsing to do the code generation. I'd recommend to read some good book about the subject, maybe one involving dragons.
7,461,642
7,461,738
Is there an efficient way to determine a distance?
This question is more about the algorithm and the right use of function rather than the actual code. In my code, I'm using map to simulate boxes. The maps elements are composed of vector<int> as keys and set<shared_ptr<foo> > as values. I'm doing a nested loop to go over all the boxes: mit1 = boxes.begin(); //mit1 is...
Same advice as with every collision detection: Use some algorithm or data structure that allows you to pre-filter candidates for your loop by their spatial distance, and allows to do this pre-filtering in O(n). A quad tree comes to mind, or a coarse-grained spatial map. Edit: To make the whole idea a little bit clearer...
7,461,774
7,461,785
operator<< overload in C++ for a class in class
i have the following classes: class mypipe { class node { public: char ch; node* next; node(){...} node(char c){..} } ; public: unsigned int size; node* head; and i need to overload the operator<<, to print the mypipe as it is now. then, ...
node is an inner class, which means you have to qualify its type: mypipe::node* curr = p.head -> next;
7,461,779
7,461,800
Is it possible to use to use QMultiMap::ConstIterator in own template class?
I want to iterate over a QMultiMap using QMultiMap<double, TSortable>::const_iterator it;` but the compiler complains error: expected ‘;’ before ‘it’ resulting in a error: ‘it’ was not declared in this scope for every usage. I tried ConstIterator, const_iterator and even the slower Iterator without any success. I...
GCC gives this error before the one you quoted: error: need ‘typename’ before ‘QMultiMap<double, TSortable>::const_iterator’ because ‘QMultiMap<double, TSortable>’ is a dependent scope which explains the problem. Add the typename keyword: typename QMultiMap<double, TSortable>::const_iterator it; and it will build.
7,461,793
7,461,807
Which operator do I have to overload?
Which operator do I have to overload if I want to use sth like this? MyClass C; cout<< C; The output of my class would be string.
if you've to overload operator<< as: std::ostream& operator<<(std::ostream& out, const MyClass & obj) { //use out to print members of obj, or whatever you want to print return out; } If this function needs to access private members of MyClass, then you've to make it friend of MyClass, or alternatively, you can d...
7,461,819
7,461,837
What is the C++ equivalent of PHP's hash_hmac function?
I'm porting a PHP application to C++. The PHP application is using this function: hash_hmac — Generate a keyed hash value using the HMAC method If I have this code, what is it actually doing? $sStr = hash_hmac ('sha256', $mydata,$mykey, $raw = true) I know it encrypts some data using sha256 and my key, but how can I...
I would consider looking into OpenSSL, a portable and complete cryptographic library (despite its name, it doesn't just do SSL). It has an HMAC library which you can surely wrap to get similar function. Here's an example on how to use OpenSSL' HMAC library, taken from another question on StackOverflow (annotations min...
7,461,866
7,461,911
RegExp string filtering - how to allow `-` sign?
So having such code that filters letters, and / ".:= how to allow -? #include <boost/regex.hpp> #include <boost/algorithm/string/regex.hpp> std::string filter_args(std::string args) { std::cout << boost::erase_all_regex_copy(args, boost::regex("[^a-zA-Z0-9=\"/.: ]+")); return boost::erase_all_regex_copy(args,...
Boost's default Regex behaviour is Perl-compatible, and man perlre says: You can specify a character class, by enclosing a list of characters in [], which will match any character from the list. If the first character after the "[" is "^", the class matches any character not in the list. Within a list, the "-" c...
7,462,035
7,462,945
Module information not working with DEBUG_PROCESS
I'm trying to create a process with DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS flags. For some reason when I try to use method such as "GetModuleFileNameExA" I get the "ERROR_INVALID_HANDLE" error. I know my process handle is correct, but it happens even if I call the method like so: GetModuleFileNameExA(processHandle, N...
If successful, the handle returned by CreateProcess has PROCESS_ALL_ACCESS, so that's not the problem. What is a problem is that right after CreateProcess Windows hasn't performed initialization yet, and thus not set up the module list. Trying to query the debuggee's modules (even the main module) will fail at that poi...
7,462,074
7,462,101
Dynamically allocating memory on stack
There is such code: #include <iostream> int main() { int a; int* p = new (&a) int(2); std::cout << a << std::endl; // delete p; error BLOCK TYPE IS INVALID std::cin.get(); return 0; } The output is: 2 Why is it possible to dynamically allocate memory on stack? (I thought that heap is the righ...
int* p = new (&a) int(2); This is called placement-new. It doesn't allocate memory. It constructs the object in the same memory of a. In placement new, it's the user who specifies the memory region where new operator constructs the object. In your code above, you specify the memory region by writing (&a) expression j...
7,462,133
7,462,142
Can the "friend" relationship be transferred among C++'s class?
suppose class A is the friend of class B, and B is friend of class C, is A the friend of C or C the friend of A, or both, or none ?
No, friendship in C++ is not transitive. From the C++03 standard, 11.4-8: Friendship is neither inherited nor transitive. Example: class A { friend class B; int a; }; class B { friend class C; }; class C { void f(A* p) { p->a++; // error: C is not a friend of A // despite being a friend of a ...
7,462,136
7,462,788
Echo effect to audio sound using Qt
I am developing one audio processing utility in Qt(C++). I can hear audio from speaker when I speak through mike using my qt code. I need to apply echo effect to this audio output. In my code I am receiving audio using a 16 bit byte array. How I can apply echo effect to this sound sample.
I think the simplest way to make an echo is to play the sound twice, near-simultaneously, with a slight delay between the two instances. You might also make the volume of the second instance a bit less than the first instance. You can do this by either mixing the sample stream together with itself (with an offset) and...
7,462,168
7,462,187
C++ prototype initialiser lists?
If I have the following code (simplified version of the problem): class TestA { public: int A,B,C; TestA(){A = 1; B = 5; C = 10;} }; //This is a referencing class to allow for universal and consistent operations class TestB { public: int &A, &B, &C; //Note references TestB(TestA &A) : A(A.A), B(...
If by "prototyping" you mean separation of function declaration and definition, this should work: class TestB { // ... TestB(TestC &C); }; TestB::TestB(TestC &C) : A(C.A), B(C.B), C(C.C) { };
7,462,567
7,462,585
Creating a text editor in c++ without using any graphics library [the function is undeclared error]
I am creating a texteditor in c++[non gui] , So far i have ended up with this code.. i get two undeclared errors... Why? #include <iostream> #include <fstream> using namespace std; int main() { int op; cout<<"do you want to open example.txt or overwrite?\nIf you want to overwrite enter 1 , if you want to vi...
Your main function can't see the edit and open functions because they appears after main. You can fix this by either: 1) Moving the edit and open functions above main; or 2) Adding a prototype of edit and open above main. Add this line of code before main, but after using namespace std: void edit(); void open();
7,462,587
7,462,610
Why is the syntax the way it is for implementing classes in c++?
I tend to write a class declaration in a source file and then decide I want to export it in a header. But this always means that I have to split it up and edit almost every function so that the class is declared in the header, and I have to put the functions individually in the cpp file. Why is it that I cannot leave ...
I tend to write a class declaration in a source file and then decide I want to export it in a header. But this always means that I have to split it up and edit almost every function so that the class is declared in the header, and I have to put the functions individually in the cpp file. If you always write the clas...
7,462,820
7,465,456
If I use g++ as my compiler, how do I scan a c++ file with the clang static analyzer?
I use g++ to compile my C++ project. When I try to use the clang static analyzer (scan-build) to check my code, I get an error: >> scan-build g++ main.cpp could not find clang line How do I use the scan-build tool with g++?
It appears that scan-build is having trouble recognizing "g++" as the compiler command. It expects "clang" or "gcc". If you replace "g++" with "gcc -lstdc++" to build your project, the scan-build tool will work properly. >> scan-build gcc -lstdc++ main.cpp main.cpp:7:3: warning: Assigned value is garbage or undefined...
7,462,833
7,462,872
C++ Checking for identical values in 2 arrays
I have 2 arrays called xVal, and yVal. I'm using these arrays as coords. What I want to do is to make sure that the array doesn't contain 2 identical sets of coords. Lets say my arrays looks like this: int xVal[4] = {1,1,3,4}; int yVal[4] = {1,1,5,4}; Here I want to find the match between xVal[0] yVal[0] and xVal[1] y...
You can do it with two for loops: int MAX=4; //number of elements in array for (int i=0; i<MAX; i++) { for (int j=i+1; j<MAX; j++) { if (xVal[i]==xVal[j] && yVal[i]==yVal[j]) { //DUPLICATE ELEMENT at xVal[j], yVal[j]. Here you implement what //you want (maybe just set the...
7,463,034
7,463,664
How deep do compilers inline functions?
Say I have some functions, each of about two simple lines of code, and they call each other like this: A calls B calls C calls D ... calls K. (So basically it's a long series of short function calls.) How deep will compilers usually go in the call tree to inline these functions?
The question is not meaningful. If you think about inlining, and its consequences, you'll realise it: Avoids a function call (with all the register saving/frame adjustment) Exposes more context to the optimizer (dead stores, dead code, common sub-expression elimintation...) Duplicates code (bloating the instruction ca...
7,463,305
7,463,965
C/C++ Pointers and Arrays help
I have the following C++ code and I can't seem to get it working. What I am trying to do is read numerous entries from the command line, separated by ('|') pipe characters, and then splitting the resulting strings by spaces. eg. mkdir C:/unixcode/shells|cd D:/margins/code | pwd| finger kobojunkie | last -l kobojun...
The command-line is managed by a program: the shell (probably cmd.exe in Windows or bash in Linux). That shell gets all the stuff written in the command line and parses it and executes the commands specified. Unless you are writing a shell, you cannot ever see the "|" of your example command-line inside the programs yo...
7,463,410
7,463,526
Is ios::in needed for ifstream's opened in binary mode?
What's the difference between these two? Isn't the in flag object thing redundant? Thanks. std::ifstream file1("one.bin", std::ifstream::in | std::ifstream::binary); std::ifstream file2("two.bin", std::ifstream::binary);
From the docs on ifstream class constructor: binary (binary) Consider stream as binary rather than text. in (input) Allow input operations on the stream. So when reading from a file, I would use std::ifstream::in flag not because it's required (or not) but because it would be a good programming practice to ...
7,463,690
7,463,761
C++ Organization on the File System
I come from a Java/AS3/Javascript background where all of my classes are organized into packages that help denote their functionality. In starting a C++ project I sought to mimic this file system structure in mostly the same way but I've been running into issues with the includes. Currently I have an src directory with...
Breaking it out like you've tried to do is reasonable and easy enough to accomplish. You just need to set your project's include paths. From Visual Studio, right click on the project name and click "Properties". From there, in the tree control on the left hand side, expand "C/C++", and then select "General" in the tr...
7,463,753
7,464,158
Variadic templates and new
I have this class template: template<class... T> class Test { std::vector<TestCase*> test_cases; public: Test() { // Here, for each T an instance should be added to test_cases. test_cases.push_back((new T)...); } }; This works fine for one template argument, but for multiple arguments I get this error: e...
vector::push_back expects one parameter so you can't expand the variadic template in the function call. Also I added a template parameter for the base class (from which all other classes derive). Here's something that compiles. struct base{}; struct d0 : base{}; struct d1 : base{}; struct d2 : base{}; #include <vecto...
7,463,776
7,465,018
Creating TCP Connections with Node.js in C++
I getting ready to write a small client module for Node.js using C++. The client will communicate with a remote server. I started by creating a class that communicates with the remote server, and I will eventually wrap that class with the main module class which inherits from node::ObjectWrap. Typically I would use the...
The node.js C++ interface is being rewritten for 0.6 Any 0.4 C++ code will break. This put's your in a painful place to do this C++ interface stuff. Basically the node.js team has written libuv that is their networking library which is an abstraction on libev & IOCP. The best "learning" resource you can find is the lib...
7,463,804
7,463,836
C++11 Atomics. Why does this compile, but not link?
I'm attempting to write a multi-producer, multi-consumer queue. I'm using G++ 4.6 on Arch Linux, it breaks on G++ 4.7 also. #include <atomic> #include <condition_variable> #include <memory> #include <mutex> #include <vector> #include <iostream> #include <string> #include <sstream> template <typename T> class concurren...
Because std::atomic exist only for certain Ts, mainly numeric types.
7,463,811
7,464,398
Calling constructors from constructors
In this code I present below I am having a problem. It manifests as a bad_alloc exception, and this is because the argument passed to reader, the CompressedBufferReader, is a bad string. class FileReader { FILE *file; protected: unsigned char *data; // local copy long size; public: FileReader(const c...
I don't see a problem in the way you use the constructors, which should cause the bad_alloc (though the code does seem clumsy). Let us look at the execution of the line that is causing the problem - CompressedFileReader::CompressedFileReader(const char *filename) : reader(FileReader(filename).getFileData()){} The ...
7,463,947
7,464,044
make and std::logic_error
I run into the following error when using make. So, I compiled the same program at the command line to check if there was a problem in my C++ code, but it works perfectly fine at the commandline. g++ -o Cmain.exe Cmain.o -lmysqlclient -lboost_date_time -L ../lib -L/usr/local/lib -L/usr/lib/mysql ./Cmain.exe terminate...
Edit from the edited question, it now became clear that CMain.exe is not being executed, but rather being built. The same story applies (see below), but I'll post more relevant hints once there is more new information. Hang on I can bet 80% that the program calls std::getenv getenv(...) and doesn't check the return...
7,463,982
7,464,004
Why does this code work, and what is the name of what is happening?
I saw the following code some time ago and nobody could answer me what was, neither knew about it. I am using Visual Studio 2010, as C++, in a file saved as cpp (at a project of win32 cmd program), then i declare the following: class People { private: string name; short age; public: People (string name,shor...
You mean the initialization lists? That's where you can initialize parent classes and member variables as part of your constructor. http://www.cprogramming.com/tutorial/initialization-lists-c++.html
7,464,061
7,464,175
Dynamic type dereferrencing?
In attempting to answer another question, I was intrigued by a bout of curiousity, and wanted to find out if an idea was possible. Is it possible to dynamically dereference either a void * pointer (we assume it points to a valid referenced dynamically allocated copy) or some other type during run time to return the co...
1) Dynamic references: No. Instead of having your variables hold just pointers, have them hold a struct containing both the actual pointer and a tag defining what type the pointer is pointing to struct Ref{ int tag; void *ref; }; and then, when "dereferencing", first check the tag to find out what you want to ...
7,464,068
7,464,182
Base class fields offset
I have some code that implements a kind of run-time reflection. In order to get a pointer to a field of a class inside a given instance, i basically take the pointer to the class instance and add a fixed offset that is calculated once for each field that is exposed to the reflection library. I kept the implementation q...
For this situation, you can use pointer-to-members: See it live: http://ideone.com/U4w7j struct A { unsigned int m_uiField; }; struct B : A { virtual void VirtualMethod() { } }; int main() { A instance_a; B instance_b; unsigned int A::* ptrA = &A::m_uiField; unsigned int B::* ptrB = &B::m_u...
7,464,100
7,511,522
Duplicate camera stream
I need to make a program that would allow me to capture camera stream with my 2 other programs simultaneously. Basically I need the functionality that ManyCams (http://www.manycam.com/) offers. How can I do this? I'm interested in a free c++ library, or some C#/C++ .net solution.
well, one easy step will be "share" rather than "duplicate" camera streams, your application can capture camera streams then provide api to share it between multiple applications. OpenCV worth a look.
7,464,195
7,464,247
Converting/parsing pointer strings and doubles
Assignment: Read in info from text file (done) Retrieve only parts of text file using substr method (done) Store info into instance variables (need help) Here is the code I am having trouble with: string* lati; lati = new string(data.substr(0, data.find_first_of(","))); double* latDub; latDub = new double(atof((char...
(char *)lati doesn't do what you think it does. What you're clearly trying to do there is get the char sequence associated with lati, but what you're actually doing is just squeezing a string* into a char* which is all kinds of bad. There's a member function on std::string that will give you exactly what you want. Yo...
7,464,372
7,464,472
Pointer problem using Vector containing structs
I am currently really stuck on how to solve the following problem: struct node { int a; node* b; } I will have two root nodes without parents and then to more nodes pointing to their parents vector<node> IholdAllTheNodes; node noparent1; <--- these get returned from a method node noparent2; IholdAllTheNodes....
Your problem is that you store nodes by value in vector. They are copied, potentially many times. Each time a node will be placed in different memory address. As result you'll receive different pointers to it, and old pointers will point to invalid location. As other answers suggested, use any kind of pointers to store...
7,464,791
7,464,801
Allocating 2d array of chars
Constructor This is how I'm allocating it: char **board = new char*[width]; for(i = 0; i < width; i++){ board[i] = new char[height]; for(j = 0; j < height; j++) board[i][j] = 0; } this->board = &board; Inside the class, it's: char ***board; Destructor: Now I want to delete it, so I wrote this (the bo...
You are storing a pointer to a variable on the stack, which becomes invalid as soon as the constructor returns. You should declare your class's data member as char **board and assign this->board = board. EDIT: See also @Kerrek SB's comment. The local variable is redundant. Just use the data member directly (without the...
7,464,906
7,464,923
Usage of if, else, and else if
What is the difference between: if (expr1) {stmt} else if (expr2) {stmt} else if (expr3) {stmt} else {stmt} And the same code block written as: if (expr1) {stmt} if (expr2) {stmt} if (expr3) {stmt} else {stmt}
In the first one, each block of statements is mutually exclusive; the structure guarantees that exactly one of them will get executed. This is not true for the second one. Consider: if (a == 2) { /* blah */ } if (a == 3) { /* blah */ } if (a < 5) { /* blah */ } If a == 2, then two of the blocks will get executed.
7,465,088
7,465,096
std::vector<unsigned short> somehow contains numbers > 300?
I have a std::vector<unsigned short> that somehow contains numbers that are greater than 300. unsigned short usually only permits 0 to 255, nowhere in the program attempts to add numbers that large and presumably attempts should fail. How might this have occurred? edit: Sorry about this, it's not much of a useful quest...
unsigned short usually only permits 0 to 255 This is incorrect; unsigned short must have a range at least 0 to 65,535 (216 - 1).
7,465,100
7,465,122
Develop Games for IOS/Android devices?
I started learning about lua language to develop games,i percept that most people uses Corona SDK to do so.I want to know if there is another program that i don't have to pay the annual tax of $199 to build and send the app to Apple? Is possible to develop this type in Xcode?
Xcode is an IDE for C, C++ and Objective variants of those languages. It has no (direct) support for Lua. Now, you could certainly write Lua interfaces for many of the functions that an iOS application has to handle. In that way, you could then code your application in Lua and just have a small stub of C/C++/Objective-...
7,465,229
7,465,251
writing part of an array to file in C++
I want to write k elements starting from k*i to a file. so in a for loop I write as below: testOut.write((char*) h_test[k*i] ,k*sizeof(float)); I get this error "invalid cast from type ‘float’ to type ‘char*’ " How should I correct this?
If you want to write them in binary, you can do as follows: testOut.write( reinterpret_cast<const char*>(h_test + k*i), k*sizeof(float)); h_test + k*i is the address of a float pointer, that you reinterpret to a const char* so that write can take it. Note that adding to a pointer increments the pointer taking into acc...
7,465,382
7,465,391
Visual studio 2008 error ? "LNK1104 : cannot open file "
Error 1 fatal error LNK1104: cannot open file 'C:\Users\hongo\Documents\VisualStudio2008\Projects\PruebaNodosLcmasmas\Debug\PruebaNodosLcmasmas.exe' PruebaNodosLcmasmas PruebaNodosLcmasmas This error happens in visual studio 2008 after I rebuild a solution too many times in little time. After that, I cannot get acc...
This happens when your executable is running while you compile. Close your executable. If it refuses to close, find it in task manager and close the process forcefully.
7,465,520
7,465,705
When to use conversion operators?
Considering the following example, the line int a = objT + 5; gives ambiguous conversion which is handled in two ways, using the explicit cast which i think shouldn't be necessary and replacing the use of conversion operators with member functions instead. and here, my question becomes should you still use conversions ...
Note that int d = objT; is unambiguous, as is double e = objT; Here the compiler can unambiguously choose a conversion operator because of the exact match between the type of the left hand side and the return types from those conversion operators. The ambiguous conversion results from objT + 5 (also note: long f = objT...
7,465,579
7,468,478
How can I deploy Qt applications to other systems?
I'm new to C++ and Qt but I've managed to make a simple test program and I was wondering how can I deploy it to other operating systems? Right now I'm on a Mac so how can I make it run on my PC? I've tried to find some answers but the only answers I've seen is how to deploy them already on Windows. Thanks for the help....
Easiest way is to run Windows somehow and compile & build a distribution there. You can use a virtual machine (VMWare/Parallells, slow) or dual-boot (faster), or a separate windows PC altogether. A VM is a good thing to have anyhow when you want to test your deployment, as it's easy to wipe the machine and re-run the i...
7,465,616
7,465,681
c++ cout a math function
You cin a value to the variable f. f could be something like: pow(5.957,-X*X*X*X)-cos(X*X) +20*sin(X*X) or some other complicated math function. I also tried to declare it directly as such. f = pow(5.957,-X*X*X*X)-cos(X*X) +20*sin(X*X); std::cout << "Bisection method on function, f = " << f << " "<<std::endl;...
From the looks of it, you are trying to define f as an actual mathematics function (in the direct way of doing it). That definitely won't work. But if you have a string, then f will output a string, ignoring the mathematics function. Remember, unlike other programming languages, C++ is very...temperamental. You can't ...
7,466,096
7,466,329
How can I convert a video file (mpeg, for example) into a collection of images?
How can I convert a video file (mpeg, for example) into a collection of images? Ideal answer would cover both C++ and Java using available libraries, and also how to manually strip the individual frames out of a video file for some common video format.
To extract all frames losslessly, use ffmpeg -i "$input_file" -f image2 "outdir/%05d.png" If you prefer a different output format, just change .png; by default ffmpeg will infer the file type from the extension. The option -f image2 tells ffmpeg to write to a series of images. The "outdir/%05d.png" gives a filename pa...
7,466,299
7,466,306
C++ increment issues
Lets say I have a method which controls some character movement like the following: void Player::moveRight( Uint32 ticks ) { if( speedx < maxspeed ) { speedx += accel; } x += speedx * ( ticks / 1000.f ); //collision if( x > (float)( 800 - width ) ) { x = (float)( 800 - width ); } } maxspeed = 300 an...
Change it to: if (speedx + accel > maxspeed) { speed = maxspeed; } else speed += accel; In this case, if acceleration causes the speed to go over the maximum it will simply set the speed to the maximum. Otherwise is will simply accelerate as normal. Or, you could do: speedx = min(speedx + accel, maxspeed);
7,466,642
7,467,042
Qt, draw ontop of label with image as background
Im working on a app where i have an image shown in a QLabel. setPixmap( QPixmap::fromImage( image ) ); I would like to draw masks ontop of the image and save it to a file. Thinking basic drawing tools like circle, polygon, rectangle. Im not sure how i would solve this? Should i make a widget that have members for set...
If you are going to be doing anything remotely graphically complex like what you describe, you're going to need to do it with QPainter or QGraphicsView.
7,466,835
7,466,897
if else statement confused c++
#include <iostream> using namespace std; int main() { int positiveInteger; cout << "Please input an integer up to 100." << endl; cin >> positiveInteger; int result = 0; for (int i = 0; i <= positiveInteger; i++) { if ( positiveInteger >= 0 ) { result += i; }...
If I got it right, you want to 1. input a number; 2.1 If the number is positive you loop through it. 2.2 If it's negative you show the error message. The problem is your loop, where the conditional is, checks if i (which is zero) is smaller then the number. However if you input a negative number i will be bigger then p...
7,467,102
7,467,126
My program always stops working :S (C++)
I made a program to get data from a file, it works, but then the program says it stopped working. Here is my code: #include <stdio.h> #include <windows.h> #include <iostream> using namespace std; string show() { FILE *in; char c; in = fopen("version.txt", "r"); if(in != NULL) { while((c = fg...
Your function is declared to return a string but there is no return statement. This is "undefined behavior" in C++ (only in main you are allowed to omit the return statement and in that case C++ will assume a return 0; automatically - but IMO it's nicer to also always write it).