question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,162,345 | 6,162,391 | send data struct over network between C/C++ server, C/C++ and C# clients | My client will communicate with clients using a struct/class called annoucement. I suppose I will write the server in C++. There will be many different classes that inherit annoucement. My problem is to send these classes over network to a client
I thought maybe I should use iovec. However I don't know if there is anyt... | Don't try to define your protocol in terms of structs.
Define the format of an announcement, i.e. what bytes in what order constitute an announcement, and then define how multiple announcements are transmitted in sequence.
Once you've got this wire format defined, you can implement parsers and writers in each programmi... |
6,162,417 | 6,162,422 | C++ constructor default value header file | I'm trying to create a constructor with a default value. The complication comes from the use of separate header and code files for the class. I've got a header file that contains:
class foo {
bool dbg;
public:
foo(bool debug = false);
}
And a code file containing:
foo::foo(bool debug = false) {
dbg... | The default can only go in the header file. And using defaults in constructors (or other functions) is rarely a good idea, in my experience - it usually smacks of a kludge somewhere. Not to say there aren't a few in my own code!
|
6,162,420 | 6,162,483 | DLLs for current process | how can one tell (using non-CLR C++) which DLLs is a given running process (by ID) using? With file system paths to those DLLs and EXE.
Thank you in advance.
| If you are trying to do this in code, you are probably looking for the EnumProcessModules function (or K32EnumProcessModules depending on operating system. See the link for more details). There is an EnumProcessModulesEx that can give you a little more more information. Simply give it a handle to the process you want t... |
6,162,601 | 6,162,672 | Read binary file c++ | I'm trying to read an image into a char array. Here is my try:
ifstream file ("htdocs/image.png", ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize;
char* fileContents;
if(file.is_open())
{
fileSize = file.tellg();
fileContents = new char[fileSize];
file.seekg(0, ios::beg);
if(!file.read(fi... |
Returns the size of the file. size of your image.png is 1944 bytes.
cout << "size: " << fileSize << endl;
Returns the sizeof(char*), which is 8 on your environment. Note that size of any pointer is always the same on any environment.
cout << "sizeof: " << sizeof(fileContents) << endl;
The file you are reading is a bi... |
6,162,731 | 6,162,835 | Compare to newline windows C++ | I have this simple code:
string isNewline(string text)
{
string toReturn;
text == "\r\n" ? toReturn = "(newline)" : toReturn = text;
return toReturn;
}
this function never returns a "(newline)" string, so I'm guessing that my comparison with newline character is wrong. How can I correct this?
PS. Window... | There is nothing wrong with your isNewline function.
The problem is how you get the string to be passed to isNewline function.
I suspect you use something like getline(fin,aLine) to get the string like below?
while(getline(fin,aLine)){
cout<<aLine<<endl; //aLine will never contain newline character because getline ... |
6,162,836 | 6,162,879 | 2D tile based game, shows gaps between the tile sprites when I zoom in with the camera? | I am using the D3DXSPRITE method to draw my map tiles to the screen, i just added a zoom function which zooms in when you hold the up arrow, but noticed you can now see gaps between the tiles, here's some screen shots
normal size (32x32) per tile
zoomed in (you can see white gaps between the tiles)
zoomed out (even w... | Welcome to the world of floating-point. Those gaps exist due to imperfections using floating-point numbers.
You might be able to improve the situation by being really careful when doing your floating-point math but those seams will be there unless you make one whole mesh out of your terrain.
It's the rasterizer that gi... |
6,162,994 | 6,163,016 | send() crashes my program | I'm running a server and a client. i'm testing my program on my computer.
this is the funcion in the server that sends data to the client:
int sendToClient(int fd, string msg) {
cout << "sending to client " << fd << " " << msg <<endl;
int len = msg.size()+1;
cout << "10\n";
/* send msg size */
if (... | Probably the clients exits before the server has completed the sending, thus breaking the socket between them. Thus making send to crash.
link
This socket was connected but the
connection is now broken. In this
case, send generates a SIGPIPE signal
first; if that signal is ignored or
blocked, or if its handler... |
6,163,040 | 6,163,385 | Strange behavior of copy-initialization, doesn't call the copy-constructor! | I was reading the difference between direct-initialization and copy-initialization (§8.5/12):
T x(a); //direct-initialization
T y = a; //copy-initialization
What I understand from reading about copy-initialization is that it needs accessible & non-explicit copy-constructor, or else the program wouldn't compile. I ver... | Are you asking why the compiler does the access check? 12.8/14 in C++03:
A program is ill-formed if the copy
constructor or the copy assignment
operator for an object is implicitly
used and the special member function
is not accessible
When the implementation "omits the copy construction" (permitted by 12.8/1... |
6,163,053 | 6,163,314 | How to create loop templates in php | As we can define loop templates in C++, for making coding shorter:
#define fo(a,b,c) for( a = ( b ); a < ( c ); ++ a )
Is there any way to do the same in PHP?
| Disclaimer: Well, this is not exactly preprocessor macro, but due to "dynamic" nature of PHP, preprocessors are not needed/used. Instead however, you are able to wrap functions in other functions, like in the example below.
Yes, you can do this by creating your own function that is being passed also a callback. Here is... |
6,163,139 | 6,163,185 | 0xC0000005: Access violation reading location of an Integer? | It seems normally people receive these errors when working with pointers, array, structs, etc. I'm getting it on every integer in a class, which confuses me. I'm sure I'm just missing some small technical detail (I'm a bit new to this).
The exact error is:
First-chance exception at 0x003e6616 in Mine.exe: 0xC0000005... | According to the error message, your code is trying to access address 0x00000008, which is very close to 0. This means you probably have a null pointer of type Grid * somewhere and you are calling a function on it.
You should either ensure that the pointer is not null, or check it. For example:
Grid * grid = ...;
if ... |
6,163,172 | 6,163,284 | c++ pass auto matrix to function |
Possible Duplicate:
How do I use arrays in C++?
i have a problem.
i have to use auto darray(matrix).
const int size_m=10;
const int size_n=10;
void process(int *x)
{
//i can pass array, all is well, i work as with dynamic allocated array
for(int i=0;i<size_m;scanf("%d",&x[i]),i++);
}
void input_m(int **x) ... | First of all, see the answer to this question. Your code should compile if you change void input_m(int **x) to void input_m(int x[size_m][size_n]) (assuming that both size_m and size_n are constants). Note that, as stated in the question that I linked to, "in general, to pass 2D arrays to functions you need to specify ... |
6,163,243 | 6,163,427 | in send() will it be ok to place the flag MSG_NOSIGNAL? | I've asked a previous question
I'm running a server and a client. A SIGPIPE signal crashed my server because of a broken pipe. I read that the above flag prevents that signal from being raised. My program now works and doesn't crash. But, i wonder what will be the over implications. What happens if i prevents SIGPIPE f... | Well, you shouldn't mind: it is just a different way of handling errors.
And using MSG_NOSIGNAL seems more elegant is a better way than ignoring SIGPIPE, since you may need this feature in another place of your program.
|
6,163,252 | 6,163,274 | Constructor confusion | I always think I know C++ pretty well, but sometimes I'm surprised by even the most fundamental things.
In the following scenario, I'm confused as to why the constructor Derived::Derived(const Base&) is invoked:
class Base
{ };
class Derived : public Base
{
public:
Derived() { }
Derived(const Base& b)
... | d = b can happen because b is converted to Derived.
The second constructor is used for automatic type conversion.
It's like d = (Derived) b
Derived isa Base, but Base isn'ta Derived, so it has to be converted before assignment.
|
6,163,257 | 6,163,281 | Putting a switch inside of do...while | So I have a do... while statement that is supposed to repeat unless the user enters one of four things. Those four things have a break and they set the variable that controls the while to true, where the default is false. If the user does not enter one of the four answers, the variable will stay false, which should mak... | The condition inside the while is an "accidental" assignment, not a comparison. It needs to read while (q5_valid == false) or more idiomatic while (!q5_valid).
|
6,163,364 | 6,163,386 | C++ statement compiler error | i have a statement in my program which does a comparision of elements of a two vectors
if(!*(it2+3).compare(*(lines_in_file.begin())))
the compiler error i am getting is:
test_file.cpp:140: error: 'class __gnu_cxx::__normal_iterator<std::string*, std::vector<std::string, std::allocator<std::string> > >' has no member... | The problem is that the operator "." have greater precedence that "*" so this should solve the problem.
if(!(*(it2+3)).compare(*(lines_in_file.begin())))
|
6,163,387 | 6,163,480 | Export template function | I have templated function connect:
template<class InstanceClass>
CL_Slot connect (InstanceClass *instance, void(InstanceClass::*function)(Param1, Param2))
It connects for some signal passed function from InstanceClass.
In my example, I want to connect some of classes for the keyboard event (KeyDown).
In c++ I write:
g... | Why don't you just add
extern template<>
CL_Slot connect<SomeClass> (SomeClass *instance, void(InstanceClass::*function)(Param1, Param2));
note: extern might need to after template<> -- don't remember
If you must have C linkage add a wrapper function (it will inline the templated function).
Note: MSVC has nonstan... |
6,163,588 | 6,163,626 | Stopping endless loop when int = (something that's not an integer) | So this is a problem that I've been having since I started programming (Not that long ago. I still don't know why I started with C++). When I have some integer variables and the user's input defines them, if the user inputs something other than an integer the program freaks out and runs an endless loop of the last comm... | If you want to know exactly what your mistake was, then we'd need to see your code, but the usual idiom is like this:
int i;
while (std::cin >> i) {
// do something with the user's input, i
}
if (std::cin.fail()) {
std::cout << "not a number!\n";
}
If failure occurs and you want to get past the invalid input so ... |
6,163,683 | 6,198,257 | Cycles in family tree software | I am the developer of some family tree software (written in C++ and Qt). I had no problems until one of my customers mailed me a bug report. The problem is that the customer has two children with their own daughter, and, as a result, he can't use my software because of errors.
Those errors are the result of my various ... | It seems you (and/or your company) have a fundamental misunderstanding of what a family tree is supposed to be.
Let me clarify, I also work for a company that has (as one of its products) a family tree in its portfolio, and we have been struggling with similar problems.
The problem, in our case, and I assume your case... |
6,164,198 | 6,164,216 | Should I leave a QFile (or fstream) open? | I usually use two methods to write to files, either with Qt's QFile or STL's fstream.
I have a long-running (several minutes) simulation which logs data to a file. Performance-wise and design-wise, is it a good idea to:
Keep it open the whole time
Close and open on every write
Somewhere in-between (1) and (2)
Several... | Performance wise, it would definitely be better to keep it open for the life of the application, just because less work opening and closing files means less time spent doing things that don't move the application closer to completion, which will slow the program down. As for design, just make sure to close the file bef... |
6,164,616 | 6,164,638 | Pointers to Functions (C++) | I am studying a C++ tutorial. I can't understand this example on Pointers to Functions.
Here it is:-
// pointer to functions
#include <iostream>
using namespace std;
int addition (int a, int b)
{ return (a+b); }
int subtraction (int a, int b)
{ return (a-b); }
int operation (int x, int y, int (*functocall)(int,int))... | The type of addition is int (&)(int,int) which can decay into a pointer of type int (*)(int,int) which is same as that of operation function's third parameter. So you can pass addition as third argument to the function operation.
The type of subtraction is also the same as that of addition. In your code, the address o... |
6,164,775 | 6,164,910 | WaitForMultipleObjects failing c++ | I am currently writing a program that will run mulitple programs in groups all at once and others on their own.
if( WAIT_FAILED == WaitForMultipleObjects(numberOfProgramsRan, &information[i].hProcess, TRUE, INFINITE) ) {
wcerr << L"Failure waiting for process" << endl;
}
numberOfProgramsRan is th... | If you only wait on a single process (index i) you should use WaitForSingleObject. If you're waiting on multiple processes you need to pass in an array of handles as others have said - not a pointer into PROCESS_INFORMATION.
If you insist on using WaitFoRmultipleObjects for a single object use:
WaitForMultipleObjects(... |
6,164,817 | 6,164,836 | When should I consider making a library header-only? | Obviously template libraries need to be header only, but for non-templates, when should you make things header-only?
| If you think your non-template library could be header-only, consider dividing it into two files anyway, then providing a third file that includes both the .h and the .cpp (with an include guard).
Then anyone who uses your library in a lot of different TUs, and suspects that this might be costing a lot of compile time,... |
6,164,953 | 6,164,989 | How should I manage dependencies in C or C++ open source projects? | I've got a few open source applications. These depend on a few third party components, notably Crypto++ and Boost. There are a couple of options to take:
Put third party code into version control, and include it with distributions of my code. On one hand, this is the easiest for people to use because they can compile ... | Option 3: Don't include it in your code distribution but instead include a (link to a) download, which should match the most recent version you support.
Also, explicitly list your dependencies and the most recent versions you support.
This allows users to do however they want. Want your code with dependencies? Load bot... |
6,165,003 | 6,165,021 | Return type is not identical to nor covariant with return type "MediaDevice*" of overridden virtual function "MediaFactory :: FMediaDevice" | I have following abstract factory:
#include "MediaDevice.h"
class MediaFactory {
public:
MediaFactory();
virtual ~MediaFactory();
virtual MediaDevice * FMediaDevice (int type) = 0;
};
and following factory which inherits from abstract facotry:
#include "MediaFactory.h"
class JVCMedDevFactory : public Me... | From the error message, it seems like either JVCCdPlayer or JVCVcrPlayer (or both) is not derived from MediaDevice. Is that so?
You've to derive both from MediaDevice. Make sure your definitions look like this:
class JVCCdPlayer : public MediaDevice
{
};
class JVCVcrPlayer : public MediaDevice
{
};
Or somewhere in th... |
6,165,078 | 6,167,077 | Keep a central list of subclasses but avoiding static instances | I have a slightly nasty setup which I am trying to figure out a good way to overhaul.
I have a class Fractal with a couple of pure virtual functions to do work. Each instance also has a human-readable name. I want to build a menu of all these subclasses so the user can switch between them - but, being lazy, I want to a... | Recall that static libraries are pre-C++ technology, so it’s not unreasonable for their implementation to assume that unreferenced code is unwanted (as indeed it still is in C++ when one is not playing this particular trick).
As such you need to specify the object files explicitly for each executable that needs them, a... |
6,165,105 | 6,170,897 | Detecting Cycles During Insertion | I have a directed graph. New edges are added and removed dynamically at run time. If an edge that is about to be added to the graph creates a cycle, then that edge should not be added. How would I do this with BGL?
typedef boost::adjacency_list<
boost::listS, boost::vecS,
boost::directedS
> Graph;
int main(in... | I edited evgeny's code because it wouldn't compile, and u and v were mixed up. The changes were not accepted, so here is the solution that works for my question.
bool should_we_add(Graph &G, int u, int v){
std::vector<int> distances(num_vertices(G), 0);
breadth_first_search(G, vertex(v, G),
visito... |
6,165,130 | 6,165,138 | Regex matching url authority parts | I need to match these parts of the following string:
(user)@(hostname):(port)
User and port can optionally be matched.
First I managed it with this regular expression:
(?:([^@]*)@)?([^\:]+)(?:\:(\d+))?
This matches for foo@bar:80
foo
bar
80
But when it comes to a IPv6 host like foo@[2001:0db8:85a3:08d3:1319:8a2e:037... | (?:([^@]*)@)(\[.+\]|([^:]+))(?:\:(\d+))?
But you'll have to strip off the [] if it's an IPv6 addr. Should be fairly trivial though.
You could also do it with optional [ and ] before and after, and then lookaround assertions... but that's REALLY ugly; your fellow programmers will thank you if you just KISS and use the ... |
6,165,153 | 6,165,162 | Execute Program Without Clicking | Is there a way for a program to be executed without clicking on it? Is it possible for it to be executed the minute you receive the file?
I want to build a c# application that executes any file sent to the machine from another machine connected to it. I want to do this without remote desktop, so I would check a checkbo... | Do you realize what you are proposing? If this was possible, every machine out there would be infested with the nastiest viruses.
Why don't you build a server part that you leave running on your remote machine and then have it execute whatever your heart pleases.
|
6,165,449 | 6,165,546 | c++ error: invalid types 'int[int]' for array subscript | Trying to learn C++ and working through a simple exercise on arrays.
Basically, I've created a multidimensional array and I want to create a function that prints out the values.
The commented for-loop within Main() works fine, but when I try to turn that for-loop into a function, it doesn't work and for the life of me... | C++ inherits its syntax from C, and tries hard to maintain backward compatibility where the syntax matches. So passing arrays works just like C: the length information is lost.
However, C++ does provide a way to automatically pass the length information, using a reference (no backward compatibility concerns, C has no ... |
6,165,577 | 6,165,621 | Are there any frameworks for C#, or C++, that facilitate recording videos of desktop applications? | I'm researching the various ways of recording videos of desktop applications, specifically video games.
My first thought is something more lower level, like on the DirectX front - perhaps hook some DirectX method and record that way. I was hoping there would be a toolkit or full-blown framework for making this easier.
... | Alternatively use VLC (VideoLan) and bundle this with your application.
http://wiki.videolan.org/C_Sharp
Beware license restraints though... I'm not sure what license VLC uses.
|
6,165,583 | 6,165,593 | '<<' & '>>' operators overloading | I've been writing a complex numbers header from scratch for a school class but I'm stuck on the extraction and insertion operators overload, I've been reading a lot about that topic but I still don't get it
friend ostream& operator << (ostream &tmp, Cmplx ¶m)
{
tmp<<param.Re<<"+"<<param.Im<<"i";
return tmp;... | You didn't show your use of it, but in this case I can see what's up.
You're doing something like std::cout << (Cmplx1 + Cmplx2);.
The result of (Cmplx1 + Cmplx2) is a temporary; temporary expressions may not be bound to references.
For example:
int f() {
return 3;
}
int& x = f(); // ill-formed
However, as a speci... |
6,165,674 | 6,165,685 | Basic C++ programming question | I am in process of learning c++. I am working on creating a linkedlist data structure. One of the functions that displays the values of nodes in the structure does not work. For some reason the while loop that traverses through nodes doesn't work in the display function, hence I can't see the values in those nodes. Doe... | You never set p to a non NULL value.
if(p==NULL)
{
p = new node;
p->data = num;
p->link = NULL;
}
|
6,165,683 | 6,166,043 | String issue with assert on erase | I am developing a program in C++, using the string container , as in std::string to store network data from the socket (this is peachy), I receive the data in a maximum possible 1452 byte frame at a time, the protocol uses a header that contains information about the data area portion of the packets length, and header ... | Your comment doesn't make sense:
BigBuff.erase(hdr->PackLen + 20); //assert here when len is packlen is 235 and string len is 1458;
BigBuff.erase(hdr->PackLen + 20) will erase from hdr->PackLen + 20 onwards till the end of the string. From the description of the code - seems to me that you're erasing beyond the en... |
6,165,762 | 6,165,804 | C++ On Demand Creation | I'm reading a book where the following code appears.
TTextInBuffer::TTextInBuffer(const char *pInputFileName, TAbortCode ac)
: pFileName(new char[strlen(pInputFileName) + 1])
pFileName is declared as a const char, so I'm assuming that the second line creates a new char in pFileName. I would just like to know the spec... | When this constructor is called, the initializer list here is executed:
: pFileName(new char[strlen(pInputFileName) + 1])
The strlen() call finds the length of the pInputFileName string based on its contents. It basically walks it as a char array until it finds a NULL and then returns the result. This is being done in... |
6,165,813 | 6,166,046 | Using my own prebuilt shared library in an Android NDK project | I came across this post that is almost what I need:
How to compile a static library using the Android NDK?
Basically, there are certain parts in my project that are never updated, so I am trying to avoid having them built every single time I update the Android.mk file to add something.
The above answer shows how to g... | In the documentation of Android.mk, check the PREBUILT_SHARED_LIBRARY script description. Put the .so file in lib (not libs) directory and write an Android.mk file next to it that looks something like:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := Myaccessories
LOCAL_SRC_FILES := libMyaccessories... |
6,165,928 | 6,165,962 | OpenGL bible 5th edition code problems | I have seen 2 posts with this same question but one was with visual studio and the other didn't work so here goes. i am attempting to compile the first source code that comes with the opening bible 5th edition...but i am trying to do so with the code::blocks ide.
i thought i had freeglut installed correctly(as i can ru... | You have to add proper libraries to link against with.
For C::B,
Go to Project
Select Build Option
Select Linkers
Add OpenGL, Glu32 libraries to your project.
Response to your EDIT:
Follow the steps in here: http://www.sci.brooklyn.cuny.edu/~goetz/codeblocks/glut/
|
6,165,967 | 6,165,981 | private Load() method for classes, how do they work | I'm pretty new to c++ and I have run into some code I am having trouble with, hopefully someone can enlighten me. It's what I understand to be a singleton class, it's used to hold the settings for an application. The class has a private constructor, and a private Load() method. It also instantiates itself as a private ... | The only method that has special significance is the main function, which gets called automatically when you start the program. Load however, has no special significance. Its purpose is to avoid the loading the data when constructing the object, just in case it gets passed around everywhere (and all the copies would en... |
6,166,337 | 6,174,263 | Does C++ support compile-time counters? | For the purpose of introspection, sometimes I've wanted to automatically assign serial numbers to types, or something similar.
Unfortunately, template metaprogramming is essentially a functional language, and as such lacks global variables or modifiable state which would implement such a counter.
Or does it?
Example c... | Well… yes, template metaprogramming lacks side effects as it is intended. I was misled by a bug in older versions of GCC and a little unclear wording in the Standard to believe that all those features were possible.
However, at least the namespace-scope functionality can be achieved with little use of templates at all.... |
6,166,382 | 6,166,405 | Reading and Huffman compressing 4-byte binary string STD C++ Linux Environment | I am working on some homework for Huffman coding. I already have the Huffman algorithm completed, but need to slightly alter it to work with binary files. I have some spent some time reading related problems, and perhaps due to my lack of understanding of data types and binary files, I am still struggling a bit, so hop... |
Does this look like a good way to handle the data?
Instead of casting a pointer, I would suggest using union of int and char [4] and passing pointer to the char array as you should be. Don't know what's the rest of the logic, so can't say if the actual handling (which is not in the code you posted) is done in a good ... |
6,166,437 | 6,166,544 | 64bit Applications and Inline Assembly | I am using Visual C++ 2010 developing 32bit windows applications. There is something I really want to use inline assembly. But I just realized that visual C++ does not support inline assembly in 64bit applications. So porting to 64bit in the future is a big issue.
I have no idea how 64bit applications are different f... | Visual C++ does not support inline assembly for x64 (or ARM) processors, because generally using inline assembly is a bad idea.
Usually compilers produce better assembly than humans.
Even if you can produce better assembly than the compiler, using inline assembly generally defeats code optimizers of any type. Sure, yo... |
6,166,476 | 6,798,117 | Setting video capture properties no longer works in OpenCV 2.2? | Prior OpenCV 2.2, I was able to do
VideoCapture capture(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
in order to modify the frame size. But after when I compiled my application against OpenCV 2.2, setting the properties no longer works (the video is displayed correctly tho... | This problem has been solved in OpenCV 2.3, even with my old Logitech QuickCam Ultra Vision webcam.
|
6,166,611 | 6,166,640 | Passing a method as constructor parameter | I've been trying to create a new variable of type Cmplx (which is my class name) whose data values are 0 and arg()(arg being a method of my class)
Thing is that the resulting variable has a value of 0,0.
Is there any work around or am I doing something wrong?
Also, the code:
#pragma once
#include <conio.h>
#include <st... | It looks like you don't actually want to pass the method itself - you want to call the method and pass the returned value into the constructor. That's exactly what you're doing here, and it should be fine. In other words, what you've got is already broadly equivalent to:
Cmplx<long double> log()
{
long double tmp =... |
6,166,639 | 6,166,664 | c++:how to get balance (in banking system) | i'm doing this project Banking System
This system tracks customers’ accounts in a bank. Each account has a number, name, and balance. The system provides the following functionalities: create new account, withdraw, deposit, and close account.
The system has the following interface:
Choose:
1- Add new account
2- Withdra... | Problem 1:
You have made a typo in method which gets you the balance & the one which you are calling, rename Bank::disp_det() to Bank::getbalance()
void Bank::getbalance()
{
cout<<"Account Details";
cout<<"Name of the depositor : "<<name<<endl;
cout<<"Account Number : "<<acno<<endl;
cout<<"Balanc... |
6,166,651 | 6,166,734 | Reference to std::array of different sizes instead of std::array in a base class | I have the following problem. Consider the classes
class face {
virtual std::vector<ptr>& get_vertices(void) const = 0;
};
class triangle : public face {
private:
std::vector<ptr> vertices;
public:
std::vector<ptr>& get_vertices(void) const { return vertices; };
};
class quadrilateral : public face {
priv... | std::arrays of different sizes are different types, so I cannot see any way to do what you want. But what if you return the begin() and end() const iterators to whatever container you hold internally, or an small range object containing both? That way you decouple the size of the container from the interface, leaving i... |
6,166,749 | 6,166,760 | Is the expression (a=b) = k UB? | Is (a = b ) = k undefined behavior if a,b and k are of int type and properly initialised?
thanks
| Looks UB to me. a is getting modified more than once b/w two sequence points.
The result of (a=b) is an lvalue1 which is a reference to a
1 The result of the
assignment operation is the value stored in the left operand after the assignment has taken place; the result
is an lvalue ($5.17/1).
|
6,166,805 | 6,166,816 | Templated class linking error when used to declare object in other class | I created a templated data class (CAnyData, please see its header file copy for your reference), with which I declared some variables in my another class (CConstantDataBlock, please see its header file copy for your reference). As you may see, the latter one is nearly an empty class. But when I compiled my project, the... | It seems that you do not have definitions for several of the methods of CAnyData, including the default constructor and the destructor. When you use these in your CConstantDataBlock-class, the constructor and destructor are required though.
Since CAnyData is a class-template, all definitions should be written directly ... |
6,166,813 | 6,166,837 | Methods overloading while inheritance in C++ | I have a legacy code:
struct Iface1
{
virtual ~Iface1() {}
virtual void foo(const int arg1) const = 0;
};
struct Iface2
{
virtual ~Iface2() {}
virtual void foo(const int arg1, const int arg2) const = 0;
};
/// Composite interface
struct Iface12 : Iface1, Iface2
{
};
I need to create a decorator for composite... | You need explicitly import foo into the Iface12 class, so you'll get two overloaded functions Iface12::foo.
struct Iface12 : Iface1, Iface2
{
using Iface1::foo;
using Iface2::foo;
};
The member functions with the same name overload each other only when they are declared in the same class, if you want to overload a... |
6,166,941 | 6,167,172 | C++ To C# - One little function | Can you help me to transfer that code to C#?
HWND Notepad = FindWindowEx( GetDesktopWindow( ), 0, "Notepad", 0 );
SendMessage( GetDlgItem( Notepad, MB_TYPEMASK ), WM_SETTEXT, 0, (LPARAM)"Hello Notepad, what's up?" );
Thank you in advance
UPDATE:
I want to send key presses to background window.
I don't want to use Sen... | As far as I know such a low level funcionality is not available in WinForms, hence you should call WinApi via pinvoke which will result in almost literal rewrite of this code to c#
Start here
GetDlgItem
GetDesktopWindow
FindWindowEx
|
6,167,017 | 6,167,073 | Why is the dtor being called (using annoymous/lambda func) | I am trying to mimic a finally like effect. So i thought i should run a quick dirty test.
The idea was to use Most Important const to stop destruction and to put the finally block in a lambda. However apparently i did something wrong and its being called at the end of MyFinally(). How do i solve this problem?
#include ... | // WRONG! returning a reference to a temporary that will be
// destroyed at the end of the function!
template<typename T>
const D<T>& MyFinally(T t) { return D<T>(t); }
You can fix it my introducing a move constructor
template<typename T>
class D{
T fn;
bool exec;
public:
D(T v):fn(move(v)),exec(true){}
... |
6,167,040 | 6,167,046 | Compilation error "Undefined symbols" on osx | I am trying out a very simple cpp program on osx just to get myself familiar with the osx platform, so I am very surprised to encounter any error message.
Here is the code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, world!" << endl;
return 0;
}
I compile it by running
gcc -Wall hell... | Use g++ instead of gcc since you’re compiling a C++ program:
g++ -Wall hello.cpp -o hello
Alternatively, use clang++ since Apple haven’t updated GCC in a while and it’s unlikely they’ll ever update it:
clang++ -Wall hello.cpp -o hello
|
6,167,079 | 6,172,097 | How to convert multiple source files into one .a file | i have just found out that Code Blocks (and MingW compiler) only takes .a library files rather then .lib what is the easiest way to convert .lib to .a files... any tutorials etc would be appreciated.
Edit
let me modify my question slightly how can you convert numerous source files into one .a archive file.
| The .lib (and .a also) works under two different capacities:
As an import library for a shared Dll that your program depends on.
As an archive library created from one or more object files compiled from source.
You didn't really specify in your question which form you're working with. If you're looking to do the sec... |
6,167,082 | 6,167,117 | C++ : List iterator not incrementable | Getting this error while trying to erase the last element of a list. I debugged the code and was able to figure out what causes it and where, here's my code:
for(Drop_List_t::iterator i = Drop_System.begin(); i != Drop_System.end() && !Drop_System_Disable; /**/)
{
if(Player->BoundingBox.Intersect(&(*i)->Boundin... | Your algorithm is flawed because you did not understood what erase returned.
When you use erase, it removes the element pointing to by the iterator, and returns an iterator to the next element.
If you wish to iterate over all elements of a list, it means that whenever erase was used you should not further increment it.... |
6,167,167 | 6,167,206 | why erase operation from a map doesn't invalide iterator | I'm wondering why an erase operation from a map inside a loop according to a predicate keep the iterator in a valide state, but not for a vector
| Vector::erase invalidates iterators to all elements after the first element that was erased. This makes sense, as the vector is storing its data in an array. When an element is deleted, all elements after it need to be shifted along, e.g.
int test[] = {0, 1, 2, 3, 4, 5};
^
In the above w... |
6,167,190 | 6,167,372 | compile error in pointer return | I have the BST class same as in this thread
BST.hpp
template<class T>
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
T data;
tree_node( const T & thedata, tree_node * l = NULL, tree_node * r = NULL )
: data( thedata ), left( l ), right( r ) { }... |
Change this declaration :
struct tree_node* minFunc( tree_node** node);
into this
tree_node* minFunc( tree_node** node);
Change it's definition accordingly.
Double pointer is a sure sign of bad design
Did you include a header defining struct tree_node?
EDIT
The definition should be
template <class T>
typename ... |
6,167,285 | 6,167,309 | May a reference be more efficient than a pointer? | I'm wondering whether sometimes (depends on the platform or compiler or context in code etc) a reference can be more efficient than a pointer?
|
May a reference be more efficient than a pointer?
Nopes! Not necessarily. The Standard doesn't say that either.
Most compilers implement reference mechanism via use of pointers. References were added to C++ to support operator overloading and not for efficiency.
|
6,167,301 | 6,167,339 | How to get the length of a _bstr_t | I am copying a wstring to a _bstr_t using:
_bstr_t name;
SysFreeString(name); // Free previous string, if any.
name = SysAllocString(Member[k].Membername);
Now before I use "name" I want to check if it contains at least 5 characters. In other words, I want to check the length of it.
I didn't find a "count... | name.length()
http://msdn.microsoft.com/en-us/library/zthfhkd6%28v=VS.100%29.aspx
|
6,167,381 | 6,167,522 | Debug Managed and Unmanaged code together | My main startup project is in c++. the solution involves also managed c# code.
When I debug - I have breakpoints only on the unmanaged sections (on managed breakpoint it states : "The breakpoint will not currently be hit. invalid file line "
I checked the reference and saw that there is dll and pdb there.
What could it... | how to set mixed-mode debugging
http://msdn.microsoft.com/en-us/library/kbaht4dh(v=vs.100).aspx
And don't miss the link in the bottom.
|
6,167,482 | 6,167,511 | Compile-time lookup from integer to type via C++ templates | Is there a way to implement a compile-time type dictionary via C++ templates?
e.g. if I have a number of classes like these:
class ProtocolMajor1Minor2 { ... };
class ProtocolMajor4Minor3 { ... };
...
class ProtocolMajor12Minor21 { ... };
...is there a way to use C++ templates that would allow me to do something l... | No, templates are compile-time construct, so you cannot use variables as template arguments.
For this to work you need to do something like this (i.e. not use runtime-provided variables):
template <int A, int B>
struct LookupMap { };
template <>
struct LookupMap<1, 2> { typedef Type1_2 innertype; };
// ...
template <... |
6,167,515 | 6,167,549 | Simulating finally block in C++0x | Inspired from the other topic, I wrote this code which simulates a finally block:
#include <cassert>
#include <iostream>
struct base { virtual ~base(){} };
template<typename TLambda>
struct exec : base
{
TLambda lambda;
exec(TLambda l) : lambda(l){}
~exec() { lambda(); }
};
class lambda{
base *pbase;
p... | In this initialization:
lambda finally = [&]{a=2; std::cout<<"finally executed";};
The implicitly defined copy constructor for lambda may be used. This will just copy the raw pointer pbase which will then be deleted more than once.
E.g.
$ g++ -std=c++0x -Wall -Wextra -pedantic -fno-elide-constructors lambdafun.cc
$ .... |
6,167,598 | 6,175,873 | Why was pair range access removed from C++11? | I just discovered that at one point, the C++11 draft had std::begin/std::end overloads for std::pair that allowed treating a pair of iterators as a range suitable for use in a range-based for loop (N3126, section 20.3.5.5), but this has since been removed.
Does anyone know why it was removed?
I find the removal very un... | I think the 2009 paper "Pairs do not make good ranges" by Alisdair Meredith is at least part of the answer. Basically, many algorithms return pairs of iterators that are actually not guaranteed to be valid ranges. It seems they removed the support for pair<iterator,iterator> from the for-range loop for this reason. How... |
6,167,599 | 6,167,689 | Idiomatic C++ for finding a range of equal length strings, given a vector of strings (ordered by length) | given a std::vector< std::string >, the vector is ordered by string length, how can I find a range of equal length strength?
I am looking forward an idiomatic solution in C++.
I have found this solution:
// any idea for a better name? (English is not my mother tongue)
bool less_length( const std::string& lhs, const std... | I expect that you could write a comparator as follows:
struct LengthComparator {
bool operator()(const std::string &lhs, std::string::size_type rhs) {
return lhs.size() < rhs;
}
bool operator()(std::string::size_type lhs, const std::string &rhs) {
return lhs < rhs.size();
}
bool oper... |
6,167,609 | 6,169,318 | some problem with AfxMessageBox() MFC function | I am making a program for loading a picture from camera using Open.Cv ..
And i am getting error in AfxMessageBox() statement..
program:
BOOL CObjectBoundDetectDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM... | Two possibilities:
You may, although I doubt this, have to scope it globally. To do that, try
::AfxMessageBox("Camera have no connection",MB_OK|MB_ICONSTOP);
The other is that use are building for unicode and it thinks the string is multi-byte. To do that, try
AfxMessageBox( L"Camera have no connection",MB_OK|MB_ICONS... |
6,167,761 | 6,167,784 | Hash table collision, how to get the right value? | For example, the hash of 'a'(key) and 'b'(key) both refer to the position 10, and I use '+1' method to handle collision, so the position of 'b' is now 11.
So, if I try to get b(key), the hash function returns 10, and how to tell the hash function to return 11 which is supposed.
| You need to compare the key at (10) with the value you are searching for, and if they are not the same, goto the next position,(11) in this case and repeat. Hash tables generally require that the values being stored can be tested for equality.
However, this flavour of hashing has lots of problems - you are better off s... |
6,167,809 | 6,168,852 | How much bad can be done using register variables in C++ | I just came to know that we can use registers, explicitly in C++ programs. I wonder what if i declare and use all available registers in a single C++ program and run it for considerable amount of time. How badly will my system behave and what (if any) measures will be taken by the os to come out of the situation.
| The register keyword indicates to the compiler that the variable does not need to be addressable in main memory. Thus the compiler can be sure that there are no pointers to the value and optimize accordingly.
A common misconsception: the register keyword
register Keyword (see the non-Microsoft specific part)
"register... |
6,167,820 | 6,167,925 | Qt - 4.7.3 - How to make static build | I used 4.7.2 for the past months. Now I downloaded 4.7.3. Now I am searching to type "configure -static". But I don't know where the hell "the qt path". Can anybody shed a light on this issue.
|
Download the source package here. Download and install your favorite perl distribution. I must warn you that Strawberry perl comes with its own toolchain and that may get used instead of the MinGW you downloaded. Use ActivePerl if you don't want any trouble, or build it yourself.
Unzip it to say, C:\Qt-source so that ... |
6,167,834 | 6,168,074 | min and max Variadic Template variant in C++11? | Am I right in reading the standard that from min and max (and minmax for that matter) there are new initializer_list variants, but no Variadic Template variants?
Thus, this is ok:
int a = min( { 1,2,a,b,5 } );
but this is not:
int b = min( 1,2,a,b,5 ); // err!
I guess, many people would expect that Variadic Templates... | Your interpretation is correct. N2772 contains more in-depth rationale.
|
6,168,107 | 6,168,353 | How to implement a good debug/logging feature in a project | I am making a smallish project, total of about 3-4 people. I want to have a solid way of debugging the application, by logs for example. Are there any good resources on how to structure it and such? I've heard a lot from project managers that a good logging feature is critical to each project, but I'm not sure how to d... | I found this Dr. Dobb's article, Logging In C++, very useful regarding this subject.
Also on Dr. Dobb's: A Highly Configurable Logging Framework In C++
If all you want is a dead simple thread safe logging class which always outputs to stderr then you could use this class I wrote:
#ifndef _LOGGER_HPP_
#define _LOGGER_... |
6,168,419 | 6,168,441 | C++ output operator overload | I've been working on this school assignment. The assignment told us to make an object which had it's output operator ( << ) overloaded.
Here's my code:
#include <ostream>
using namespace std;
template <class T>
class CustomObject {
string print() {
string text = "";
for (int i = 0; i ... | CustomObject<int> co();
That's a function declaration. Leave out the parenthesis.
std::cout << co();
Why are you appling operator() to co? Again, leave out the parenthesis. This should work:
CustomObject<int> co;
std::cout << co;
Alas, building and returning a string from a print method is hardly idiomatic C++. Here... |
6,169,030 | 6,169,112 | movement binding in c++ using ncurses | I can't get this movement binding to work. I'm using the ncurses library, update_ch and oldch are global variables. KEYERR is a macro set to -120 (I just don't handle those keypresses). I'm trying to restrict the player so he can't hold up, down, left, or right, but he has to keep pressing them to move. It's not wo... |
I'm trying to restrict the player so
he can't hold up, down, left, or
right, but he has to keep pressing
them to move.
I am pretty sure this isn't possible with curses. If I remember correctly curses only receives characters from a terminal. It doesn't control anything about the process.
Measuring the time betw... |
6,169,040 | 6,169,068 | how to use “iterator” for call by reference? | I have defined a dynamic memory as * indexs (vector of vector) to store set of values. Then, I appended this memory. Afterthat, I want to get a print of these values. For that I am using another function as follows. For that function, I am calling above values by references. I don’t know proper way to use iterator to p... | indexs is not a pointer, it's a reference, that's all. You need to say
indexs.begin()
and not
indexs->begin()
(etc).
|
6,169,125 | 6,169,143 | Order of destruction of elements of an std::vector |
Possible Duplicate:
STL containers element destruction order
Is there a guarantee the the elements of an std::vector would be destroyed from last to first?
| 2003:5.3.5/6 says about delete[]:
The delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).
... |
6,169,159 | 6,169,185 | c++ initialize 2d array of pointers with null? | class A {
private:
B* my2DArray[max1][max2];
};
How to initialize my2DArray with NULL here?
| Define your own constructor that value initializes the array, setting all of its elements to null pointers. That's done by providing () initializer for the member, which also works for arrays.
class A
{
public:
A():my2DArray() { }
private:
B* my2DArray[max1][max2];
};
|
6,169,251 | 6,169,281 | Function argument as reference to avoid checking for NULL | If I have a function that takes in a pointer which should never be NULL, I usually do something like this:
void Foo(const somePointer* ptr)
{
if (ptr == NULL)
{
// Throw assertion
return;
}
// Do something
}
So now I check every time whether the pointer is NULL and if it is not set to NULL in the firs... | Well, if you never ever want a non-existent object passed in, use a reference (Note: non-existent, not non-valid).
If you want that possibility, use a pointer.
|
6,169,532 | 6,170,418 | How do I distribute a program created with Visual C++? | I have created a program with VC++ by the first time, and when I send the .exe file to other people they can't open it. It doesn't crash because of an error, it simply doesn't open. What do I have to do if I want other people to correctly use my program?
Thank you.
| Make sure to bundle your application with vcredist_x86.exe found on this page:
http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&FamilyID=a7b7a05e-6de6-4d3a-a423-37bf0912db84
|
6,169,646 | 6,169,661 | C++ Invalid Conversion | The following code produces the compilation error, invalid conversion from 'const char*' to 'char*'. Both ptrInputFileName and ptrFileName are both declared as const char*. Any suggestions on how to get this to compile? Thank you.
TextInputBuffer::TextInputBuffer(const char *ptrInputFileName)
: ptrFileName(new cha... | strcpy takes the the destination as non-const pointer char* and ptrFileName is const char*. No implicit conversion possible and I wouldn't recommend an explicit conversion. Just make ptrFileName non-const.
|
6,169,655 | 6,169,671 | Need help with returning a 2D array C++, please | I'm trying to create an array and pass it to functions, which then return it, but I don't know the correct way of returning.
I've been looking around tutorials and trying stuff out, but haven't managed to solve this.
I'm new to C++ and thought it would be similar to Java, but apparently it isn't.
This is where I've got... | You need to use a vector. C++ stack-based arrays cannot be dynamically sized- oh, and you can't convert [][] to **, the conversion only works for the first dimension. Oh, and you can't assign to arrays, either.
The simple rule is, in C++, never use primitive arrays- they're just a headache. They're inherited from C, wh... |
6,169,706 | 6,169,936 | Lisp Interpreter in a C++ Program | I'm not sure I'm phrasing this right, but I'm pretty sure I'm looking for a LISP interpreter I can put in my C++ program.
The ideal situation I'm imagining is a function or something to which I can pass either a string, file, or filename containing the LISP code and then use the output from the LISP code in other parts... | There is also ECL ("Embeddable Common Lisp"). It has the advantage, that it provides the full Common Lisp standard. Unfortunately, the documentation with respect to embedding is... well... a little bit scarce.
I never used it myself, so I cannot really tell, whether this would actually be an easy thing to embed into yo... |
6,169,801 | 6,170,223 | order of function call. is it compiler or situation dependent? | It came to my attention the following fact: order of function evaluation, for example in a sum, is unspecified in the standard, and can therefore be performed in any order.
This raises the question: is it compiler dependent, optimization dependent, or potentially even execution dependent (I doubt it, it may involve res... | Answering your second question:
Edit: I want to clarify. The fact that order is unspecified in the standard, does not imply it's unspecified for a particular compiler (which may choose to make it specified in the documentation, I assume). Unspecified behavior may make you non-portable, but the compiler may behave cons... |
6,169,847 | 6,170,043 | how to choose libc6 or libc6-dbg | Im bug checking a c program and would like to install valgrind, the system then tells me that I should also install libc6 with debug symbols libc6-dbg.
Now my question is, when I in the future compile with gcc, which version of libc will be used?
How do I choose which libc6 I'm compiling against?
I'm not asking how to ... | libc6-dbg is not a separate library from libc6 — it's the debugging symbols for libc6, so that you can get accurate tracebacks within libc.
|
6,169,986 | 6,170,030 | Bug that disappears when attempting to study it | This is the most weird thing that has ever happened to me when programming in C++.
This is my main file:
#include <iostream>
#include "lib/utils.h"
using namespace std;
int main(int argc, const char *argv[]) {
cout << bin2dec(101000010);
return 0;
}
and this is lib/utils.cpp:
#include <iostream>
#include "ut... | You're not initializing dec.
int dec = 0;
|
6,170,224 | 6,188,891 | Qt paint figures at one window |
I create class Widget, it creates window, this class paints something on the window (i.e. it works as I want).
I create yet one class, Circle, I want to paint on the window of class Widget.
I pass adress of Widget and try to paint on Widget using QPainter paint (address of Widget); (in the instance of Circle) but i ... | well , thank you for your attempts to help
but all that i was needing:
this -> setParent(widget);
in costructor Circle::Circle, if somebody'll want to see my solve,one can see that figures are moved
source code is here source code
|
6,170,319 | 6,170,369 | Sharing files between projects in Visual C++ 10 | I've got a relatively simple setup in Visual Studio 2010- a main application and a DLL it depends on. I have a header that defines it's interface- how can I set up the header to be included in both projects? They are both in the same solution.
| See my answer to this question, but its just that you are using a dynamic library.
In summary, the main application project should reference the DLL project for the purposes of linking, and the main project should include folder references so the compiler can access header files.
|
6,170,422 | 6,170,561 | How to write the letter ñ in textbuffer gtkmmTextView? | When I try to insert the ñ in textbuffer TextView the CMD displays the following error:
(textEditor.exe:696): Gtk-CRITICAL **:
gtk_text_buffer_emit_insert: assertion
g_utf8_validate (text, len, NULL)'
failed
Source example (c++ and gtkmm):
Glib::RefPtr<Gtk::TextBuffer> refTextBuffer = textView->get_buffer();
re... | It's wanting a UTF-8 value and you've selected something in the upper ASCII range that doesn't map to UFT-8. Looking here and then here it appears you need to use the value of 0xC3 0xB1 to get the desired affect. A quick guess for the code that should work for you is...
refTextBuffer->set_text("\xC3\xB1"); //Hex versio... |
6,170,543 | 6,170,599 | C++ platform compatibility | An object foo is written to a new file on platform 1 as:
write( file, &myFoo, sizeof(struct foo) );
...and then read on platform 2 using:
read(file, &myFoo, filesize(file) );
The foo object has the following definition:
struct foo
{
char a;
int b;
long c;
char* d;
};
What kind of issues might ... | When you do this you need to watch out for:
Data type sizes (char is the only one you can trust)
Alignment / padding
Endianness
Pointing to invalid memory
Floating point representation
ASCII vs EBCDIC ? (yeah, seriously ?)
Probably others
|
6,170,867 | 6,170,891 | c++ (g++-4.x) problem with templates | I have this simple code:
template<template <class> class Generator>
class TestHelper {};
template<class Writer>
class Test
{
typedef TestHelper< Test > Helper;
};
It's works great on last g++ versions, but, in 4.4 or 4.5, I get this error:
test.cpp:7: error: type/value mismatch at argument 1 in template parame... | It's because inside the body of class Test<Writer>, naming Test without providing the template arguments automatically assumes the same arguments (e.g. Writer).
For example, this allows you to write the copy constructor as:
Test(const Test&);
instead of
Test::Test(const Test<Writer>&);
You can overcome this by qualif... |
6,171,108 | 6,171,271 | Save output to disk using FMOD | I am using FMOD to play some sounds and I would like to save the resulting mix to the disk.
I have been trying the system->recordStart(0, sound, true) path, but that saves the microphone input of the device.
In some way, I would like to redirect the speakers output to the disk
Thank you
Marc
| To redirect everything that would go to the speakers to disk simply use the function System::setOutput and pass in a value of FMOD_OUTPUTTYPE_WAVWRITER. Make sure you call this function before you call System::init, when you are done call System::release and a wav file will appear next to your executable.
You can also ... |
6,171,126 | 6,171,140 | Making a char** with std::? | I have an opengl function that requires a const char**. So essentially a vector of strings. I was wondering if this could be done using the C++ Standard Library without making a vector of const char* which would demand heap allocation.
| If you're wanting to avoid heap allocation:
const char* arrayOfStrings[] = {
"first string",
"second string",
"third string"
};
And you can use arrayOfStrings as a const char**.
If you have a vector of const char*s you can just get the address of the first element to obtain a const char**:
&vec[0];
Howeve... |
6,171,132 | 6,171,165 | Non-blocking console input C++ | I'm looking for a (multiplatform) way to do non-blocking console input for my C++ program, so I can handle user commands while the program continually runs. The program will also be outputting information at the same time.
What's the best/easiest way to do this? I have no problem using external libraries like boost,... | I would do this by creating separate a thread which calls normal blocking IO functions and pass it a callback function which it would call when it got input. Are you sure you need to do what you said you want to do?
As for outputting information at the same time, what would happen if the user was in the middle of typin... |
6,171,350 | 6,171,363 | how to pass data to running thread | When using pthread, I can pass data at thread creation time.
What is the proper way of passing new data to an already running thread?
I'm considering making a global variable and make my thread read from that.
Thanks
| That will certainly work. Basically, threads are just lightweight processes that share the same memory space. Global variables, being in that memory space, are available to every thread.
The trick is not with the readers so much as the writers. If you have a simple chunk of global memory, like an int, then assigning ... |
6,171,403 | 6,171,433 | QFile seek performance | It appears that QFile when working with a regular file (not a special Linux I/O device file) is random access, meaning that a seek operation has constant-time complexity O(1).
However, I haven't been able to confirm this. In general, when jumping to a specific position in a file (for writing or reading), does std::fstr... | The short answer is "yes, for practical purposes". The long answer is... It's complicated.
Seeking on a file stream ultimately calls lseek() on the underlying file descriptor, whose performance depends on the kernel.
The running time will depend on what file system you are using and how large the files are. As the f... |
6,171,513 | 6,171,904 | Should I use static work pool or dynamic work pool (of threads)? | I'm running a pthreads program that works very nicely, however I don't see the speedup I would expect. I suspect that I spend to much time creating and destroying my threads.
I'm at no time running more threads than I have cpus.
Over a period of 20 minutes I'm creating a approximately 5000 threads.
My question is if i... | First you should measure where your app is spending all of it's time. That comes out to about 4 or 5 thread creations per second, which is a lot but probably not where you're spending all of your time.
That said, however, if you're always limiting yourself to N threads, where N is the number of CPUs, the you should ... |
6,171,522 | 6,171,541 | c++ clear the contents of a file after a specific position | I would like to use either fstream or preferably QFile to remove the contents of a file after a specific position (that's not the beginning or the end of the file). So I first jump to that position with QFile::seek(long) or equivalent in constant time, and then I would like to remove the remainder of the content, also ... | You can use QFile::resize to resize the file to the size you want. I bet it uses truncate behind the scenes (see Andrew's post).
|
6,171,630 | 6,171,719 | Why isn't operator overloading for pointers allowed to work? | As per the comment under this answer, references were introduced primarily to support operator overloading which quotes Bjarne Stroustrup:
References were introduced primarily
to support operator overloading. C
passes every function argument by
value, and where passing an object by
value would be inefficient o... | Because if it was allowed, then it would not look good, and wouldn't be as intuitive as its with reference.
Suppose it is allowed, then you would write:
struct A{};
A a, *pa, b;
a = pa ;//doesn't look good, also not intuitive. (not real C++)
It doesn't look good, because on left side you've non-pointer, on right side... |
6,171,759 | 6,171,775 | How's a temporary implemented in C++? | In the following 'a' is a temporary.
cout << 'a';
It isn't restored in the data section (const/static does) and shouldn't be in the stack (local variable does). Where is it?
UPDATE
Are non-lvalue and rvalue the same thing?
| Unless you have a really horrible compiler or machine architecture, 'a' is not stored as data anywhere. It's an immediate operand in the asm, e.g.
mov $0x97, %eax
|
6,171,814 | 6,171,991 | Why is it undefined behavior to delete[] an array of derived objects via a base pointer? | I found the following snippet in the C++03 Standard under 5.3.5 [expr.delete] p3:
In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual des... | Base* p = new Base[n] creates an n-sized array of Base elements, of which p then points to the first element. Base* p = new Derived[n] however, creates an n-sized array of Derived elements. p then points to the Base subobject of the first element. p does not however refer to the first element of the array, which is wha... |
6,171,946 | 6,171,969 | Shifting a string of characters? | I'm writing a program that solves Caesar ciphers in C++. It takes a string of the alphabet and shifts it to the left each loop: "abc....yz" --> "bcd.....yza". The problem is after another loop it goes: "bcd.....yza" --> "cde.....yzaa".
char temp; // holds the first character of string
string letters = "abcdefghij... | I think you need letters to be 27 characters, not 26, and instead of letters += temp (which grows the string every time), use letters[26] = temp[0].
...at which point you can just ditch temp entirely:
string letters = "abcdefghijklmnopqrstuvwxyz.";
while (true)
{
letters[26] = letters[0];
for (int i = 0; i < 26... |
6,172,232 | 6,177,338 | Is it undefined behaviour to delete a null void* pointer? | I know that deleteing a null pointer is a no-op:
In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.
(C++ Standard 5.3.5 [expr.delete] p2)
And also that deleting a void* pointer is undefined behaviour because the destructor can't be called as there are no obj... | I wonder how you can reach up a situation where you are deleting a pointer only if it is null. But staying in language lawyering mode...
In C++ 03
5.3.5/1
the operand of delete shall have a pointer type or a class type having a single conversion to a pointer type.
void* is a pointer type so a null void pointer meets... |
6,172,355 | 6,172,384 | how to Convert Lat ,long to an XY coordinate system (e.g. UTM) and then map this to pixel space of my Image | I have a very small area map , which I downloaded from Openstreet map(PNG) and also its OSM(.osm) file which contains its Lat ,long.
Now I want to convert Lat ,long to an XY coordinate system (e.g. UTM) and then map this to pixel space of my Image which is of size (600 x 800 ). I know its a two way process ,like to k... | GPS Coordinates to Pixels
Assuming this map does not cross prime meridian
Assuming pixel 0,0 is upper left, and pixel 600,800 is lower right.
Assuming map is Northern Hemisphere Only (no part of map is southern hemisphere)
Determine the left-most longitude in your 800x600 image (X)
Determine the east-most longitude i... |
6,172,378 | 6,172,412 | How can I close an application using my program? | I am trying to disable Norton auto protect. I don't actually want to close the program. If you click on the Norton icon it gives you the option to disable it.
I would like to write a program that clicks the button for me. I am just not sure how to go about this. I am using C++ and I have Visual Studio and Windows XP.
| Do you want to close an application or disable an application (like disable java update etc)? If you are talking about closing an application using your program, you can use "TerminateProcess()".
If you are talking about disabling application, share with us particular use-case exactly what do you want to achieve?
|
6,172,495 | 6,172,571 | CString Substring problem | I am having trouble with substrings that I will implement with file i/o. I have char data[21],char world[21], and char eat[21] that will be substrings of char in[300] (the names dont mean anything btw). I came up with some substring code and instead of getting the substring I wanted, I get the whole string and some fun... | Change char world[21], data[21], eat[21]; to
char world[21] = {0};
char data[21] = {0};
char eat[21] = {0};
strlen of char world[21] is not defined if its not initialized`
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.