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,806,000
6,806,219
Call function when items are added or removed from a vector
I'm writing a widget kit for the Nano-X window system. In my base class view, I have a vector defined: std::vector<RSMKit::View *> children; Is it possible to call a function (GrReparentWindow in this case) when an item is added or removed from the vector so that the newly added widget can be shown?
No. Do not inherit from std::vector. Just encapsulate it. template<typename T> struct MyVector { private: std::vector<T> items; public: void push_back (const T& x) { // Do something here items.push_back(x); } // etc };
6,806,050
6,806,065
In my version of the game "hangman" i am getting an error in a function
#include <iostream> #include "randword.h" #include <fstream> #include <time.h> #include <cstdlib> using namespace std; bool hangmachine(char a[],string randi,char v){ //the Problem is in this function bool retus=0; for (int cc=0;cc<randi.length();cc++){ if(v==randi[cc]){ retus=1; char a[cc]=v; //Error: variabl...
This line: char a[cc]=v; is a variable declaration, which doesn't even compile, as the array size should be fixed at compilation time, that is, it has to be either a number or a const integer. It isn't, so you gcc tries to create a variable length array, but then you try to initialize it which will fail. You just want...
6,806,173
7,302,165
Subclass/inherit standard containers?
I often read this statements on Stack Overflow. Personally, I don't find any problem with this, unless I am using it in a polymorphic way; i.e. where I have to use virtual destructor. If I want to extend/add the functionality of a standard container then what is a better way than inheriting one? Wrapping those containe...
Maybe many people here will not like this answer, but it is time for some heresy to be told and yes ... be told also that "the king is naked!" All the motivation against the derivation are weak. Derivation is not different than composition. It's just a way to "put things together". Composition puts things together givi...
6,806,338
6,806,363
Given a cctor, can the assignment operator always be safely created by the compiler?
I was thinking about the swap() idiom. If we have a valid copy constructor, why cant the compiler generate a "swap" function behind the scene, by swapping the "this" pointers? I am probably looking at this too simplistically, but i'm wondering why it cant be done.
I suppose it could, but it doesn't. The default versions of the constructors and assignments just construct/assign member-by-member. If you already need to write your own copy constructor (which apparently is a warning sign and should only happen in rare cases), your class has something non-trivial going on, and that m...
6,806,350
6,806,374
Coming from C++ to AS3 : what are fundamental AS3 data structures classes?
We are porting out game from C++ to web; the game make extensive use of STL. Can you provide short comparison chart (and if possible, a bit of code samples for basic operations like insertion/deletion/searching and (where applicable) equal_range/binary_search) for the classes what are equivalents to the following STL c...
The choices of data structures are significantly more limited in as3. You have: Array or Vector.<*> which stores a list of values and can be added to after construction Dictionary (hash_map) which stores key/value pairs maps and sets aren't really supported as there's no way to override object equality. As for binary...
6,806,492
6,806,602
Boost Graph edges with indexes
I am trying to define a graph with undirected edges from a set of pair(int,int) edges (where each int represents a vertex index). Each such edge has an index of its own. The catch is that I want that the internal vertex index of the graph will be consistent with the original vertex indexes. I also like to be able to e...
Since you use vectors to define collection of vertices there is one-to one correspondence between vertex indices and vertex descriptors. You just need to define you graph object as follows: Graph g(N); Where N is number of vertices. This allocates N vertices, each vertex descriptor is a number from 0 to N-1. To get ed...
6,806,517
6,820,680
Boost Asio callback doesn't get called
I'm using Boost.Asio for network operations, they have to (and actually, can, there's no complex data structures or anything) remain pretty low level since I can't afford the luxury of serialization overhead (and the libs I found that did offer well enough performance seemed to be badly suited for my case). The problem...
As suggested, posting a solution I found to be the most suitable (at least for now). The client application is [being] written in QT, and I need the IO to be async. For the most part, the client receives calculation data from the server application and has to render various graphical representations of them. Now, there...
6,806,637
6,822,470
Convexity defects C++ OpenCv
I would be grateful to you if you could help me with this issue :) Relating to this question cvConvexityDefects in OpenCV 2.X / C++?, I have the same problem. The OpenCV C++ wrapper has not the function cvConvexityDefects that appears in the C version, so I tried to write my own version. Part of the code is (please not...
I raised this question because I wasn't able to figure out a solution (it is not only today that I was dealing with the matter hehe), but after all I was able to manage the problem! I had to change the way I calculated the convex hull, using the index array form. So now we have a vector< int > instead a vector< Point ...
6,806,933
6,817,593
App is crashing while trying to debug it [corruption heap]
I have the following problem: I have a command line application.When I run it from command line it works fine, but when I try to debug it I got the following message: *Windows has triggered a breakpoint in orb_app.exe. This may be due to a corruption of the heap, which indicates a bug in orb_app.exe or any of the DLLs...
The problem solved. The option /MDd was used instead of /MD to generate the full debug info.
6,807,029
6,807,050
Passing arguments to the class constructor in a declaration of another class
I've got sth like that: #include <iostream> using namespace std; class FirstClass { public: FirstClass(int _vx) : vx(_vx) {} int x () {return vx;} private: int vx; }; It's pretty obvious, that I have to write: int main () { FirstClass Object1(666); cout << Object1.x(); retu...
You've got to pass the initialization value to FirstClass in the constructor of SecondClass, like this: class SecondClass: { public: SecondClass() : Member1(666) {} Firstclass Member1; };
6,807,217
6,807,328
Can "struct hack" be implemented this way?
Struck hack is used to allocate more memory than the initial need of the struct itself so that you can reference the out-of-bounds part of the array such that you stay inside the memory actually allocated. Here's how it works. struct Foo { // .. size_t size; int data[1]; }; const size_t SIZE = 100; Foo *p = (Foo...
Accessing an array outside of it's bounds is undefined behaviour. For example, your debugger might decide to insert canary arrays each side of the array. The smart thing to do would be to just use a std::vector, that's what it's for. The struct hack is an old C-ism and redundant in C++.
6,807,369
6,807,379
Undefined reference to constructor, generic class
I'm just learning template programming in C++ and have a problem with linker unable to find my class'es constructor's definition. What can be the cause? Code below. Logger.h template <class T> class Logger { public: Logger(NodeHandle& nh, char* topic, short pubFrequency); virtual ~Logger(); void publish();...
You need the templated implementation to be in the header. Any code referencing the templated code needs to "see" the implementation so the compiler can generate the code from the template.
6,807,617
6,807,667
2D array of char pointers --> Segmentation fault?
I have to create a 2-Dimensional array of char pointers. The array will store a list of names and surnames - row 0 will hold names and row 1 will hold surnames. This is the code I have written so far (this file is included in the main file): #include "myFunction.h" #include <iostream> #include <string.h> using namespa...
If you're using c++, consider using a 2D array of std::string as it'll be a little cleaner. Also, multi-dimensional arrays are always horrible to work with as they make code unreadable and cause a lot of chaos (as you don't often get confused by which dimension represents what). So, I strongly urge you to consider usin...
6,807,833
6,822,453
Efficiently calling a Python function
I'm embedding Python into my game. The scripts will be used to define the character AI, how entities react to game events, etc — this means there's going to be a script for every type of entity in the game. Each script will have a function like createEntity() or something which will return the constructed entity. What ...
Your question does not specify whether space efficiency (i.e. memory), time efficiency, or labor efficiency is most important to you. Merely because you are considering a hybrid C++ / Python application, I assume that labor efficiency is a significant factor. Because you are developing a game, I assume that there wil...
6,807,850
6,807,881
Reinventing the Wheel: the time class
I am trying to reinvent the wheel and I want to create a time class in c++, I do want this class to be dependent of any c/c++ std libraries, why ? because I am writing a small OS for fun, but I can't seem to find to find information regarding how I would start. can anyone lead me in the right direction ? most of the se...
Older PCs have an RTC (Real Time Clock) the never ones use HPET (High Precision Event Timer). Dig into the linux kernel source if you want to see how to program them. Unices also have a clock associated with the running process which is only ticking when the process is running, this is entirely an OS feature. Update: h...
6,808,073
6,808,096
managed c++ .NET extract file from resource, wrong file size
Hi im trying to extract a file from my embedded resource but the issue is that the file size is not correct, it should be around 3500KB but it comes out as 5850KB or so. Assembly ^myAssembly = Assembly::GetExecutingAssembly(); Stream ^myStream = myAssembly->GetManifestResourceStream("cool.exe"); ...
Binary data isn't text. The StreamReader is converting your data to UTF8, which isn't what you want. You need to copy the raw bytes by calling Write and Read.
6,808,099
6,808,142
C++ how to create nested class for forwarding your methods?
So my Idea is simple - to have a class that can have its own public methosds and a nested class that would forvard only some of that public methods (pseudocode): class API { public: go(); stop(); friend class B { public: void public_request() { request(); } ...
Yes, but you have to provide an instance of the outer class when you create the inner one... the two types are [mostly] independant, so B is not associated with any specific instance of API. More pseudo-code struct API { void go(); struct B { B(API& api) : api(api) { } void go() { api.go(); } }; ...
6,808,352
6,808,403
Non-type function template parameters
I am reading C++ Templates Complete Guide and came across this non-type function template parameters code (I have added the main() and other parts except the function definition and call): #include <vector> #include <algorithm> #include <iostream> template <typename T, int value> T add (T const & element){ return el...
Strictly speaking, you couldn't refer to the specialization of a function template by simply giving a template argument list. You always had to have a target type around (like, a function parameter type you pass to, or a cast type you cast to, or a variable type you assign to). That was the case even if the target typ...
6,808,471
11,311,522
Global variable seg fault
I am getting a segmentation fault and I cannot figure out why. I have a global TcpClient object that has a pointer to an Agent object. I am trying to access the agent pointer in a function when the segmentation fault occurs. In main, I have the cout statements before and after I set the agent member in TcpClient and bo...
I have a function called communicate (which just lets server and client talk to each other) that calls the getCommand function I posted above. Right before I call getCommand, there was a memset call for a local char*. All I did was remove that line and the segmentation fault went away. Thanks for help everyone.
6,808,472
6,812,076
restrict qualifier on member functions (restrict this pointer)
Note: To clarify, the question is not about the use of the restrict keyword in general, but specifically about applying it to member functions as described here. gcc allows you to use the __restrict__ (the GNU++ equivalent to C99's restrict) qualifier on a member function, effectively making this a restrict qualified p...
Either I am missing something, or your question does not make sense. this is not that different from any other argument to a member function, so why are you surprised that GCC allows you to apply restrict to it? Regarding applying it to an assignment operator, you rightly point out that it would obviate the need for a...
6,808,541
6,808,948
Finding a JRE from C++ (windows)
I'm making a small launcher program for my Java program, the idea being that i can set memory requirements, associated libraries, and stuff like that before calling Java. However, i'm increasingly finding that there doesn't seem to be a set-in-stone way to call Java from ANYTHING. It is no longer the case that there'...
First, finding the JRE location, setting memory requirements and stuff like that is highly recommended to implement using one of available scripting languages. Due to the language of BAT files is relatively poor you can use VBS or JScript and run them using utility named cscript. Concerning to the fact where JRE is. ...
6,808,768
6,808,926
Working with Arrays in C
I am new to C and C++ and I need help with arrays. I have an array initialized to zero with 500 elements(myDataBinary). Now I have one more array ith values in it say 1,2,3....Now by reading the values (1,2,3...) from(my_data[10]) i want to make the corresponding elements in myDataBinary "1" and rest should be "0". I h...
sizeof operator gives the size of an object (or type) in bytes. The canonical way to determine the number of elements in an array x is: sizeof x / sizeof x[0] This does not depend upon knowing the type of the elements of x, and will work even if you change it. sizeof my_data / sizeof(int) doesn't have that property....
6,808,851
6,808,898
Specialising a template to include template templates
I am teaching myself template programming in C++, so some of my assumptions may be wrong - please correct me if you see any errors. I am trying to use an STL list as a template parameter to a function. The function is supposed to be used with all sorts of data types, so I have defined the function as template<class T> ...
You want to declare those parameters template<template <class T, class Allocator> class listPlaceholder, class T, class Allocator> void function(listPlaceholder<T, Allocator> param) { // do something with every element in param (I actually need to know it's a list) typename listPlaceholder<T, Allocator>:...
6,808,902
6,815,657
Where are we getting the value of this parameter?
In a program in the Learning OpenCV book: void onTrackbarSlide(int pos) { cvSetCaptureProperty(g_capture,CV_CAP_PROP_POS_FRAMES,pos); } And, in another location: if(frames!=0) { cvCreateTrackbar("Position","Example3",&g_slider_position,frames,onTrackbarSlide); } Where are we retrieving the value of pos in the onTrack...
Check the docs and you'll see the function signature is: cvCreateTrackbar(const char* trackbarName, const char* windowName, int* value, int count, CvTrackbarCallback onChange) Notice that the last parameter has the type CvTrackbarCallback. Obviously, this is not a built-in type, but a type defined by OpenCV. So we go ...
6,808,945
6,809,059
WaitForSingleObject with thread handle get stuck while running regsvr32.exe
I have thread A that is creating another thread B, than thread A is waiting using WaitForSingleObject to wait until thread B dies. The problem is that even though thread B returns from the thread's "thread_func", thread A does not get signaled!. I know that because I added traces (OutputDebugString) to the end of the t...
You could be hitting a problem with the loader lock. Windows, has an internal critical section that gets locked whenever a DLL is loaded/unloaded or when thread is started/stopped (DllMain is always called inside that lock). If your waiting thread A has that critical section locked (i.e. you are waiting somewhere from ...
6,809,275
10,051,898
unresolved external symbol "_hypot" when using static library
I'm trying to recompile my old game which links the Ruby library, but I keep getting this error: ruby18-mt-static-release.lib(math.obj): error LNK2001: unresolved external symbol _hypot Is there any workaround for this that doesn't require me finding the source code to this library and rebuilding it? I'm using Visu...
I had a similar problem. Apparently hypot used to be a linkable function but is now (I have VS 2010) an inline function that calls _hypot. In math.h this is the only function where this is done. I don't have source for the existing library I am using and it has hypot linked to it so it can't use the inline version. If ...
6,809,372
6,809,682
How to properly use an XMVECTOR member variable
I have a simple IRenderable class that has members for position, scaling, and rotation: XMFLOAT3 _position; XMFLOAT3 _scaling; XMVECTOR _rotation; I am attempting to set them with the constructor. The first method here gives an access violation 0x00000000 trying to set _rotation (_position and _scaling are both set fi...
To work around the bug Eitenne mentioned, I simply made an AxisAngle struct: struct AxisAngle { XMFLOAT3 Axis; float Angle; AxisAngle() : Axis(XMFLOAT3(0, 0, 0)), Angle(0) { } AxisAngle(XMFLOAT3 axis, float angle) { Axis = axis; Angle = angle; } }; Using this in place of the XMVEC...
6,809,388
6,810,428
G++ wrong ELF CLASS Error
I was trying to compile a C++ program on Fedora 15 x64. And got the error: ./game: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory. I read somewhere that all I need to do is install glibc.i686 I installed that and now another error is coming even after using the "-m64" option with g++ error while lo...
The original issue that you had suggests that ./game is a 32-bit dynamically-linked executable, which was failing to run because the 32-bit dynamic linker (/lib/ld-linux.so.2) wasn't installed; installing the 32-bit glibc package fixed that. If ./game is a 32-bit executable which requires libplayer_1.so as a dynamic li...
6,809,764
6,885,264
C++ Semi-Transparent Window SDL
I wish to have a semi-transparent SDL background (nothing to do with sub-surfaces or images), such that instead of having a black background it is actually transparent, but the other things I draw are not. My current code is a slightly modified copy of Code::Blocks' SDL project, similar to how various applications hav...
I think what you're trying to do is in fact a shaped window (parts of the window are transparent depending on a mask that you provide). It seems there's no way to do that with SDL 1.2, however there is a SDL_SetWindowShape function just for this in SDL 1.3 for which you can find a pre-release snapshot here but it's not...
6,809,795
6,893,383
"No newline at end of file" warning, even after putting in a newline
I've been trying to learn C++ lately, and all has been going well until today. I'm trying to make a very simple application that basically just asks a user for a number and then displays the factorial of that number. When I try to compile the file in Cygwin (g++ factorial.cpp -o fact), I get the following warning "war...
It ended up that not initializing a boolean variable to false was the issue. However, I'm not sure whether it was actually the initialization that was the problem, or just the fact that the text editor might not actually save a file if you just append whitespace to the end of it. For those wondering, this was happening...
6,809,870
6,809,918
C++ strings and arrays
I'm Having problems with to of the questions on my C++ homework. Write a program to analyze gasoline price in the past 10 days. First, ask the user to enter the prices. Then do the following: (a) Calculate and display the average price in the first 5 days and the average price in the second 5 days (b) Compare...
I sugest doing as following: double average1=0.0; for(int i=0;i<5;++i) { average1 += values[i]; } average1/=5.0; double average2=0.0; for(int i=5;i<10;++i) { average2 += values[i]; } average2/=5.0; Also, take a look at std::vector, it may help you in further exercises: http://www.cplusplus.com/reference/stl/vec...
6,809,890
6,809,976
C++0x lambda for makecontext argument #2
I'm having trouble passing a C++0x lambda function as the second argument to makecontext (from ucontext.h). The signature of makecontext is: void makecontext(ucontext_t*, void (*)(), int, ...); Previously, I was able to apply a C-style (void (*)(void)) cast, to the global scope functions I used. A reinterpret_cast wou...
[](int i){} is a captureless lambda that has a single int parameter and returns nothing; it is thus implicitly convertible to void(*)(int): a pointer to a function that takes a single int and returns nothing. Assuming the makecontext function is capable of handling functions with different types (it appears from its ...
6,809,914
6,809,990
SDL make image before screen not working
I'm messing around with SDL, and I decided to make a program that opens images as the background to the main 'screen', and make it dynamic, so different sized images will result in different sized screens. The problem is, I can't figure out why it's not letting me. I can compile, but the program will error when I try t...
You cant invoke SDL_DisplayFormat without invoking SDL_SetVideoMode once before. I fixed your code: SDL_Surface * screen = SDL_SetVideoMode(512, 512, bpp, SDL_SWSURFACE); SDL_Surface * background = open_image("hello.bmp"); screen = SDL_SetVideoMode(background -> w, background -> h, bpp, SDL_SWSURFACE);
6,809,998
6,810,023
Where is function overriding done?
Where in the process of creating the program, compiler, linker etc., is the overriding of functions and operator overloading done? I'm particularly interested where it is done in C++, Ruby and Python.
Function overloading is (at least in C++) handled internally inside the compiler. The idea is that the code that the compiler ultimately generates will be hardcoded to call the appropriate function, as if the functions all had different names and you called the function uniquely suited to the arguments. More generall...
6,810,003
6,841,735
CUDA Thrust return type
I am currently trying to use the Thrust library and I am having issues with the return types. device_vector<int> input(5); input[0] = 0; input[1] = 2; input[2] = 5; input[3] = 7; input[4] = 8; pair<int*, int*> result= minmax_element(input.begin(), input.end()); gives the error: error : no suitable con...
When naming a template parameter, ForwardIterator does not name any particular type. For our purposes, we can think of it as a placeholder for the type of iterator given to thrust::minmax_element: template<typename ForwardIterator> thrust::pair<ForwardIterator,ForwardIterator> minmax_element(ForwardIterator first, F...
6,810,419
6,810,639
C++/CLI double pointer typecasting to ref IntPtr for C# access
I am writing a wrapper around C DLL in C++/CLI so that it can be accessed in C# through a managed assembly. Using direct P/Invoke to access C functions via C# is not possible because C DLL raises exceptions which cannot be correctly caught using P/Invoke (exception message is lost when moving across C/C# boundary). So ...
That's an out parameter, not really ref, correct? Try void InitDB_clr(IntPtr% handle) { void* ptr /* = handle.ToPointer() */; InitDB(&ptr); handle = IntPtr(ptr); } Uncomment the initializer if it needs to be in/out.
6,810,530
6,810,555
std::map vs. self-written std::vector based dictionary
I'm building a content storage system for my game engine and I'm looking at possible alternatives for storing the data. Since this is a game, it's obvious that performance is important. Especially considering various entities in the engine will be requesting resources from the data structures of the content manager up...
Map: std::map has guaranteed logarithmic lookup complexity. It's usually implemented by experts and will be of high quality (e.g. exception safety). You can use custom allocators for custom memory requirements. Your solution: It'll be written by you. A vector is for contiguous storage with random access by position, so...
6,810,629
6,810,647
Storing noncopyable (but movable) object in std::pair
I am trying to store a noncopyable (but movable) object inside an std::pair, as follows: #include <utility> struct S { S(); private: S(const S&); S& operator=(const S&); }; int main() { std::pair<int, S> p{0, S()}; return 0; } But I'm getting the following compiler error with gcc 4.6: In file inc...
You need to provide a move constructor. The following compiles without errors. #include <utility> struct S { S() {} S(S&&) {} S& operator=(S&&) {} S(const S&) =delete; S& operator=(const S&) =delete; }; int main() { std::pair<int, S> p{0, S()}; return 0; } EDIT: It seems that if you in...
6,810,656
6,810,672
creating an array of structs in c++
I'm trying to create an array of structs. Is the code below valid? I keep getting an expected primary-expression before '{' token error. int main() { int pause; struct Customer { int uid; string name; }; Customer customerRecords[2]; customerRecords[0] = {25, "Bob Jones"}; customerRecords[1] = {26, ...
Try this: Customer customerRecords[2] = {{25, "Bob Jones"}, {26, "Jim Smith"}};
6,810,861
6,811,044
SQLite sqlite3pp C++ api: how to load all sqlite3pp::transactions that can be found in db into some vector or set?
So I found out that sqlite3pp C++ SQLite db engine API has some concept of rollbackable transactions. I wonder if thows transactions can be extracted from db file for example after application restart? And if so how to load all of tham in order thay have happened into some vector? (This would make creation of db items...
According to the SQLite 3 docs: If sqlite3_close() is invoked while a transaction is open, the transaction is automatically rolled back. This is true whether you're using the API directly or indirectly with sqlite3pp. So you cannot preserve DB transactions across application restarts (since database connections are a...
6,811,037
6,811,142
What's the use of the private copy constructor in c++
Why do people define a private copy constructor? When is making the copy constructor and the assignment operator private a good design? If there are no members in the class which are pointers or handles to a unique object (like file name), then wat other cases are there where private copy constructor is a good idea? S...
Some objects represent particular entities that can't or shouldn't be copied. For example, you may prevent copying of an object that represents the log file used by an application, corresponding to the expectation that a single log file will be used by all parts of the code. Use of an accidentally or inappropriately ...
6,811,209
6,811,214
Include guard not working
I have as follows in my trackerFrame.h file. It is included by trackerFrame.cpp and main.cpp and for whatever reason I am getting multiple definition problems from it when I try to compile all pertaining to the wxWidgets event table macros. #ifndef TRACKER_H #define TRACKER_H #include <wx/wxprec.h> #ifndef WX_PRECOMP ...
Your include guards are correct. The problem is most likely here: BEGIN_EVENT_TABLE(mainFrame, wxFrame) EVT_MENU(wxID_EXIT, mainFrame::closeProgram) END_EVENT_TABLE() According to the wxWidgets wiki on event tables, the event table needs to be defined into a .cpp file. So you would have a tracker.cpp file that...
6,811,273
6,811,281
Getting fatal error when including <stdlib>
I got a fatal error that the file or directory <stdlib> is not found on ubuntu 11.xx when I typed #include <stdlib>. Is <stdlib> deprecated/removed, or is there something wrong with my GCC installation?
In C++ code, include 'cstdlib' instead. #include <cstdlib> If you are using C, include 'stdlib.h' #include <stdlib.h> In c++ code, always prefer the cXXX include instead of XXX.h
6,811,280
6,811,303
What happened to local pointer?
My questions are marked in code comments in the snippet below. int *foo(){ int a = 10; int b = 20; return &b; } int *foo2(){ int aa = 44; int bb = 40; return &bb; } int main(int argc, char* argv[]) { int *p = foo(); int *p2 = foo2(); int a = 700; int *b = & a; // cout<<*b<<e...
In foo() and foo2() you are returning pointers to local variables. These locals have automatic storage and it is undefined behavior to use a pointer to them once they go out of scope. Therefor p and p2 contain nothing useful. It might work, it might not. I can't understand your question very well, so I hope I got it...
6,811,508
6,811,550
Dynamic memory allocation of objects in C++
I'm trying to dynamically allocate (it's not so dynamic as it is right now, but eventually it will be) memory for objects in a very simple C++ program. I'm new to classes and have only recently started playing with C++, leaving C behind. Here's the code: #include <iostream> using namespace std; class Test { private:...
Perhaps we should look at the declarations, expanded you have: Test a(10); Test *b; Test *c; You have defined b and c as pointer-to-Test, but you seem to want c to be an array of pointer-to-test. The declaration for c you intended was likely: Test **c; which you would initialize: c = new Test*[2]; for (int i=0; i<2;...
6,811,681
6,811,771
redefining or adding a classes member function dynamically/ during execution
Hey i'm trying to make a very simple GUI using SFML, and i want to be able to attach a function to my Button class in the constructor, as so the user can define what happens when the button is pressed. I've worked a little before with GLUT and noticed these declerations: glutReshapeFunc(Resize); glutDisplayFunc(Draw);...
You can store a callback using e.g. std::function (for C++0x; boost::function is also available and has a similar interface). #include <functional> class Button { public: template<typename T> explicit Button(T const& t): callback(t) {} void press() { callback(); } private: std...
6,811,736
6,811,825
Including a .idl file in a C++ project
I'm building a project in C++ which uses DirectShow's video capture library to connect to a camera. The video card manufacturer (BlackMagic) has provided .idl (Interface Definition Language) files which add new capture graphs to the standard collection. Thing is, I've never come across a .idl file, and the very vague "...
For example: you have an AFileName.idl 1. Add the AFileName.idl to you project: Right Click on The project->Add->Existing Item... 2. Click Right on The AFileName.idl from the project->Compile 3. The step 2 will generate AFileName_h.h, AFileName_i.c, AFileName_p.c,... 4. Now you can #include "AFileName_h.h" and use it,...
6,811,816
6,814,413
Doxygen: strip top level namespace
When working with library ABC, it natural that all names are included into the same top level namespace. Is it possible to remove top level namespace from class names, but show inclosed namespaces?
There is no such option inside of Doxygen. Still you can use preprocessor to make it work. #ifndef DOXY_PARSER #define LIB_NAMESPACE_STARTS namespace lib_namespace { /##/ #define LIB_NAMESPACE_ENDS } /##/ #define LIB_NAMESPACE lib_namespace #else #define LIB_NAMESPACE_STARTS /##/ #define LIB_NAMESP...
6,811,867
6,812,008
Misunderstanding concerning g++, dynamic and static linking on linux vs windows
I'm a little confused by what I've learned today. I hope somebody can help me out. I understand the concept of dynamic and static linking, but the problem is as follows. On windows, or at least the paradigm on windows, you can have a .lib (which is like .a) and .dll (which is like .so, except... different) and you must...
On windows, or at least the paradigm on windows, you can have a .lib (which is like .a) and .dll (which is like .so, except... different) and you must statically link in the .lib which contains code that calls functions from the dll at runtime. Is this correct? Yes and no. That is one way that DLLs work on Windows, ...
6,811,990
6,812,021
C++ typename as variable
Suppose I have a template class MyClass. Is it possible to store the type of the template as an variable of the class? If so how? I'm curious if it's possible to do something like this. Template <typename T> class MyClass; Template <typename T> class AnotherClass; MyClass<int> myClassInstance; AnotherClass<oneInstan...
They can be static variables, you can nest typedefs. template<typename T> class MyClass { public: typedef T type; }; AnotherClass<MyClass<double>::type> anotherClassInstance; However, accessing a member variable like you posted is impossible in C++.
6,812,053
6,812,100
How to capture a mouse over event for Windows Form Button
Hi I am currently designing a simple UI using Windows Form, there's a few buttons here and there. I've been searching but cannot find how to catch a mouseover event for the button. Do you guys know any way to capture the mouseover event for the button?
Use MouseEnter, MouseHover and/or MouseLeave event of the button control. Read more at MSDN at http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousehover.aspx
6,812,161
6,812,192
Should I unlock if I call another function inside of a function?
Let's say I have a simple code like this functionA(){ lock(lockA); //doing something with a shared data; functionB(); unLock(lockA); } functionB(){ lock(lockB); //doting something with another shared data unLock(lockB); } I was wondering if I should unlock before I call functionB o...
If A and B are absolutely not correlated and you won't do anything else with A after you call function B you should unlock first. There is no need to keep the mutex if you are not going to access A any more. You should be careful of deadlocks though if you use two lock and do not always obtain them in the same order. L...
6,812,389
6,812,448
Avoiding Brackets for Class Template Having Default Parameter
I have a class template similar to the one that follows below that is designed to contain some configuration settings used when parsing CSV files: template <typename InputIterator = default_all> class icsv_params { // Iterator to a data structure containing the columns // that should be read. typedef InputI...
Unfortunately this is C++ syntax. IIRC, in C++0x, there are associated namespaces (which solve your second question). For the first one, a typedef should do, à la STL: template <typename InputIterator = default_all> class basic_icsv_params { ... }; typedef basic_icsv_params<> icsv_params:
6,812,454
6,812,564
cin.getline not executing c++
For some weird reason my input line cin.getline(oneLine, 80); is completely ignored when I put it in this else if block. I can't understand why because when I move it somewhere else in the program, it works. else if (choice == "user-id") { cout << endl << "Enter a full name e.g. John Smith "; ...
Your std::cin object is in a bad state (std::cin.good() == false) from a previous input operation. For example, you might have tried to read a number, but there were only nun-numeric characters in the input buffer. Always check for input success before continuing using a std::istream. Note: Don't use the old input fun...
6,812,623
6,812,794
How to apply sizeof() operator to non-static class member methods?
struct MyClass { int foo () { return 0; } }; unsigned int size = sizeof(MyClass::foo); // obviously error Can we apply sizeof() to member methods from outside the class ? Do we need to declare object to get it ? Edit: I know that above code will give error (that's why word 'obviously'). Wanted to know if we can at...
You cannot obtain the size of a member-function, but you can obtain the sizeof a pointer-to-member-function: int size = sizeof( &MyClass::foo ); The same goes for non-member functions (and static member functions), the size of the function cannot be obtained. It might be misleading because in most contexts, the name o...
6,812,827
6,813,162
I drag and drop a Table View widget (Qt). How to resize it after filling the elements?
I am working in Ubuntu/c++ language. I have the following QTable : ui1->tableView_->setVisible(false); QStandardItemModel *itemmodel_ = new QStandardItemModel(0,1); itemmodel_->setHeaderData(0, Qt::Horizontal, tr("File")); ui1->tableView_->setModel(itemmodel_); //.. add new rows in the table ui1->tableView_->re...
It seems like you didn't add your TableView to any layout. You need to add it to any layout in your form. For example: QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(tableView); Layout is a container for widgets. It purpose is adding positioning and resizing rules for its widgets. For example QVBoxLayo...
6,813,355
6,819,060
QTable - how to resize a table view?
I drag and drop a Table view on my form application. I would like to know how can I programatically resize the table base based on the numbers of rows that i add. Appreciate if you can show mw some code. thx
You can use the setFixedHeight method, the tricky part is how to calculate the correct height. There are a couple of things that will greatly affect the desired height - other than the number of rows. a) Whether or not the horizontalHeader is shown b) Whether the rows are uniform heights. Let's assume it is visible, an...
6,813,493
6,813,521
STL: calling bind2nd with ptr_fun for "const T &" types
Calling std::count_if(vec.begin(), vec.end(), std::bind2nd(std::ptr_fun(foo), 17)) works fine with bool foo(int, int), but I can't make it work with bool foo(const int &, const int &) Is there a way to make that work or do I have to write my own adaptor function?
The second argument is a number, and cannot be converted to const int &. You can use boost::bind to do the trick: std::count_if (vec.begin(), vec.end(), boost::bind (foo, _1, 17)); EDIT: As of my first response, yes, you cannot use a variable instead of the number. I think the problem is bind2nd and ptr_fun not being ...
6,813,548
6,813,684
Why does one need templates/generics? Isn't inheritance enough?
I've heard a lot of people saying that C++ templates are very powerful. I still don't seem to understand the advantages of using them instead of using inheritance. And as I am mainly a Java developer, thought that generics and templates were one and the same thing, but accordingly to Wikipedia: Although C++ templates,...
Templates and inheritance fulfill different roles, and it's fairly rare where you can choose between them. One very simple description should be that templates provide a common implementation for different interfaces, where as inheritance provides a common interface for different implementations. In their usual role,...
6,813,624
6,813,666
Does derived class' member functions inherit virtualness from base class?
Say we have the following two classes, A is the base class with virtual destructor and B is the derived class whose destructor doesn't have 'virtual' qualifier. My question is, if I going to derive more classes from B, will B's destructor automatically inherit the virtualness or I need to explicitly put 'virtual' befor...
From C++ standard (section 10.3): If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, [...] then Derived::vf is also virtual (whether or not it is so declared). So yes.
6,813,629
6,815,333
How do I use gdb for multi threaded networking program
I am working on a networking programming using epoll. I am getting a segmentation fault error but since it's running on multi thread, it is hard to find where it exactly gets the error by using logs. I was trying to using gdb so I can see the stack trace. If I run this on gdb then I am getting this error from the epol...
You need to fix your program to handle EINTR correctly. EINTR ("Interrupted system call") is NOT a fatal error; it just means "please retry that system call again". So your code that calls epoll_wait() should detect it and just silently retry the call. Something like this: int rv; do { rv = epoll_wait(epfd, even...
6,813,636
6,813,794
Risk of damaging your computer by altering memory in C++
I know some Java and am right now trying C++ instead and apparently in C++ you can do things like declare an int array of size 6, then change the 10th element of that array, which I'm understanding to be simply the 4th byte after the end of the section of memory that was allocated for the 6-integer array. So my questio...
It depends on your system. Formally, an out of bounds access is undefined behavior. On a modern general purpose system, each user process has its own address space, and one process can't modify, or even read, that of another process (barring shared memory), so unless you're writing kernel code, you shouldn't be able ...
6,813,827
6,815,460
Is it possible to create a control in C++ and use in Java activity?
I want to create a control in C++ and use it in my java based activity. Just like we create an instance of TextView or ImageView, I want to create an instance of my native control and show it in some Java based activity's view. Is it possible first of all? If yes are there any tutorials or demo related to it? Thanks
There is no such thing as a "native control" in Android. Your UI widgets need to be written in Java.
6,813,830
6,814,038
Combine values of two maps based on keys
This is kind of last resort.. So I have two maps. typedef std::map <string, vector<float> > Dict; typedef std::map <string, string> Dict1; The contents of the first map look like this: Dict = {A: -3.1, 2.1, 1.1}; {B: -4.5, 5.6, 7.2}... Strings from the second map are same as keys from the first one. Dict1...
std::map<string, vector<float>> d; std::map<string, string> d1; std::map<vector<float>, vector<float>> d2; // Fill the maps here for(std::map<string, string>::iterator i = d1.begin(); i != d1.end(); i++) { d2[d[i->first]] = d[i->second]; } This is a fairly trivial operation with a basic working knowledge of the ...
6,813,946
6,818,259
word count from text..is it possible using a trie?
i know word count Qs has been asked many times and MAP seems to be the unanimous choice for it. But i felt that MAP might take a lot of space if the text is huge and number of unique words are very high. So why not use a Trie? The leaf node will store the frequency of each word. Or is it that Map is a clear winner ...
From here we can estimate the words in the english language to about 1M. From here we get the formula for memory usage of a map. Now we can calculate that if your text is all words of the language, your map will take about (average word length 6 characters) (32 bytes for short strings (Windows) + 4 bytes int) * 1M + (n...
6,813,990
6,814,063
How to access a C++ Class in a C# code?
I have following problem statement. Export a C++ class in the dll (un-managed). Create and use an object of this class in C# code. For the first part I have the classDLL.h as follows `` #include <iostream> __declspec(dllexport) class pABC{ private: int x; public: void func(); }; The respecti...
[DllImport("pABC.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern void func();
6,814,031
6,814,160
Help ,clarify my doubt on Unqualified Name Lookup :ISO n3290 Draft
According to this link A point from C++0x draft : n3290 Shall this program is correct ? EX: namespace X {}; enum Foo { X = 0, #1 Y, Z = X // X refers to the enum, not the type }; Iam getting error while execution this program like // #1 'X' redeclared as different kind of symbol But in the ...
There is a difference in that the original question had a struct X instead of namespace X. The namespace name is visible in this scope, and so is Foo::X as enum names "leak" into the surrounding namespace. That creates a conflict. In C (and therefore also in C++) the name of a struct/class/union is in a separate "tag n...
6,814,646
6,814,691
convert string to _T in cpp
I want to convert string or char* to the _T but not able to do. if i write _tcscpy(cmdline,_T ("hello world")); it works perfectly, but if i write char* msg="hello world"; _tcscpy(cmdline,_T (msg)); it shows an error like: error C2065: 'Lmsg' : undeclared identifier Please give me a solution. Thanx in advance.
_T is a macro, defined as (if UNICODE is defined): #define _T(a) L ## a which can work only with string-literals. So when you write _T("hi") it becomes L"hi" which is valid, as expected. But when you write _T(msg) it becomes Lmsg which is an undefined identifier, and you didn't intend that. All you need is this funct...
6,814,919
6,820,556
strange c++ template method specialisation issue
I've come across a strange problem with method specialisation. Given this code... #include <string> class X { public: template< typename T > void set( T v ); }; template<> void X::set( const std::string & v ) { } template<> void X::set( int v ) { } int main( int, char *[] ) { X x; std::string y; ...
Probably this article will explain the situation. You might expect the specialization void X::set( const std::string& ) will participate in overload resolution. However, surprisingly, specializations don't participate in overload resolution. In the call x.set( y ), the compiler deduces the type of T in the primary temp...
6,815,015
6,815,086
What are steps required to compile Octave on Windows as shared lib for use in development?
I want to use Octave in my C++ app. I downloaded latest source Release from here but I do not get how to build it and get some lib folder for dlls and include folder for includes. So how to build Octave for integration into an app - as a shared, or better, a static library?
There is a guide to building Octave with MinGW on the Subversion repository.
6,815,085
6,818,405
Best place to load caption strings in MFC?
Where is the best place to load caption strings in a MFC application? I'm loading control captions in the OnInitialUpdate method of my views and loading menu items captions in the OnCreate method of my frame.
I dont believe there are more than 100 of captions in your program. You can load them in InitInstance itself - no harm. If there are more than few hundreds of captions to load, it would take the GUI to appear (irrespective of where you load, since GUI/total thread is one). In that case, you should load all important r...
6,815,198
6,815,299
Why would I make copy constructor and assignment operator private and implemented in C++?
Inspired by this question. Usually the reason to make copy-constructor and assignment operator private is to make the class non-copyable so that objects can only be created and destroyed, but not copied - most of the times it is because copying them would make no sense. In such cases the copy constructor and the assign...
There are two cases that come to mind immediately: friends: Say that, as part of your design, you have two highly coupled classes where one needs to be able to copy the other (say, as in a factory model or some such), but you don't want to let the whole world be able to copy it. wrappers: Say you want to be able to c...
6,815,383
6,815,410
how to test C or C++ snippet quickly?
I am using Ubuntu and Eclipse as an IDE for C/C++. I currently have a big project in Eclipse. Sometimes, I want to test some small functions written in C/C++ but I don't want to re-create a new project in Eclipse. It is much time consuming and slow. I want to ask if there is any better way to do this ? (In the past, I...
Use online compiler like Ideone or Codepad. Ofcourse, they dont provide you auto code completion feature & other fancy features but that is the price you pay for quick & easy way of checking stand alone functions.
6,815,559
6,815,897
C/C++ framework for distributed computing (MPI?)
I'm investigating as to whether there is a framework/library that will help me implement a distributed computing system. I have a master that has a large amount of data split up into files of a few hundred megabytes. The files would be chunked up into ~1MB pieces and distributed to workers for processing. Once initiali...
MPI seems reasonable option for your task. It uses the SPMD architecture, meaning you have the same program executing simultaneously on possibly distributed or even heterogeneous system. So the choice of process with rank 0 being the master and others being the workers is not mandatory, you can choose other patterns. I...
6,815,561
6,816,018
Good reference for C++ iostreams?
I am struggling understanding C++ iostream library -> "What and why only" . I found a library at IBM named "IBM C/C++ Legacy Class Libraries Reference" , which can seen here: IBM C/C++ Legacy Class Libraries Reference Alternate link i want to ask that , is this good reference for c++98 iostream (it goes with standard...
I agree it is difficult. Try the following book. Standard C++ IOStreams and Locales: Advanced Programmer's Guide and Reference Angelika Langer & Klaus Kreft Addison-Wesley, January 2000 ISBN: 0201183951
6,815,574
6,815,701
Embedded Python: Getting func obj from imported module
I have a Python module that I import from my C++ code (I'm embedding Python). This module contains a function create() that I want to get a hold of in my C++ code (i.e. store it in a boost::python::object instance). Here's what I tried. A run-time error occurs on the indicated line in my C++ code. The error occurs beca...
You need to do main_namespace["hero"].attr("create"). Import creates only one name in the namespace, and it's a module object. Names cannot have dots in them — . is a getattr operator — so hero.create is the same as getattr(hero, 'create'). You could also use boost::python::import directly, instead of execing import st...
6,815,679
6,822,246
how to select multiple columns in QTable
I am working in c++/ubuntu. I've created a QTable : 1 | 2 ------- aaaa|bbbb cccc|dddd ....|.... I would like to ask how can i select the entire row 2: cccc |dddd. I did: QModelIndexList indexes = ui->tableView->selectionModel()->selection().indexes(); for (int i = 0; i < indexes.count(); ++i) { QM...
If you're using a Q3Table, theres an enum for handling selections which is set using this function. If you're using QTableView (which is recommended) there is a similar enum and function to set it. I hope this helps. As Raiv said in his comment, we can help you more if you clarify your question.
6,815,685
6,820,451
Move semantics - what it's all about?
Possible Duplicate: Can someone please explain move semantics to me? Could someone point me to a good source or explain it here what are the move semantics?
Forget about C++0x for the moment. Move semantics are something that is language independent -- C++0x merely provides a standard way to perform operations with move semantics. Definition Move semantics define the behaviour of certain operations. Most of the time they are contrasted with copy semantics, so it would be u...
6,815,977
6,816,122
How to debug when program crashes on delete?
When delete executes the program crashes. I tried following code to check for corrupted heap block but if condition results false. int rc; if (_HEAPOK != (rc = _heapchk())) { switch(rc) { case _HEAPEMPTY: puts("The heap has not been initialized."); break; case _HEAPBAD...
I assume that you want to know why the code snippet is crashing in your posted link. The problem is in this line. *(ptr - 1) = 'x'; // i.e. ptr[-1] = 'x'; After doing ptr = malloc(), you execute above command. Pointer is writing in the memory area which is going out of range; which results in undefined behavior. Lucki...
6,816,373
6,816,605
What happens during and after boost::python::import?
The Boost documentation does not specify this. When I use boost::python::import, where exactly is the specified module imported? My guess would be in '__main__' (just to make sure). Also, what happens when the module object goes out of scope? Given the wording in Boost's docs — "Returns: An instance of object which hol...
The underlying mechanism is PyImport_ImportModule, and no, it doesn't touch __main__. Successfully imported modules are inserted into sys.modules dict, so the object is not freed when you DECREF what the function returns — there is still at least that one reference alive.
6,816,448
6,819,256
boost::thread data structure sizes on the ridiculous side?
Compiler: clang++ x86-64 on linux. It has been a while since I have written any intricate low level system code, and I ussualy program against the system primitives (windows and pthreads/posix). So, the in#s and out's have slipped from my memory. I am working with boost::asio and boost::thread at the moment. In order ...
When you look at "size overhead" for any type of synchronization primitive, keep in mind that these cannot be packed too closely. That is so because e.g. two mutexes sharing a cacheline would end up in cache trashing (false sharing) if they're in-use concurrently, even if the users acquiring these locks never "conflict...
6,816,769
6,816,878
how to speed up my program's startup
My program needs to load many big wordlist files, so it always takes a long time to start up. it's so inefficient to recover quickly in crash. I have a raw idea, but I am not sure if it's feasible. Is it possible to load the files into shared memory and just attach to it when starting up? Could you give me some ideas ...
It's definitely possible, provided you design a format which supports static initialization, or is just raw data. There are two possibilities: if you can design a raw data format (nothing but PODS, and no pointers); and if portability isn't a concern, including accross different versions of the compiler (you provide ...
6,816,793
6,816,879
OpenGL error 1282 with glEndList()
I've got a little segment that generates a display list that looks like this: glNewList ( CDisplayList :: GetBaseList () + 2, GL_COMPILE ); { glBegin ( GL_QUADS ); glPushMatrix (); // // Move to slightly lower position. // glTranslatef ( 0.0f, -1....
You need to move the transformation matrix manipulations out of the glBegin/glEnd pair. This is what the documentation says: Only a subset of GL commands can be used between glBegin and glEnd. The commands are glVertex, glColor, glIndex, glNormal, glTexCoord, glEvalCoord, glEvalPoint, glArrayElement, glMaterial, a...
6,816,914
6,816,952
How to read exe file in binary code - C++
How can I make program in C++ that will read .exe or another file in binary code?
#include <fstream> int main() { std::ifstream in("yourfile.exe", std::ios::in | std::ios::binary); /// in.read (buffer, buffer_size); } For a detailed example on how to read binary files in C++, see this link or do your own googling.
6,816,971
6,817,012
Returning function-local variable as reference
I found this source code: inline GUID& WString2Guid(wstring src) { static GUID result; HRESULT hr = ::CLSIDFromString(W2OLE(const_cast<WCHAR*>(src.c_str())), &result); if (FAILED(hr)) { //ERROR: The string '%s' is not formatted as a GUID! throw(E_INVALIDARG); } return result; } Wha...
No. result is a static local variable, so it will exist even after the function exit. Don't confuse this with non-static local variable. :: in ::CLSIDFromString tells the compiler to choose CLSIDFromString from the global namespace, in case if there are many definition of CLSIDFromString defined in other namespace(s),...
6,817,441
6,817,658
Questions about EOF and EOL
I am trying to understand EOF and EOL, and how C++ iostream actually works. While taking the the input through getchar() or getche() into a char variable, I found that if I write lines like: char a; a = getche(); // it returns char '\r' if pressed enter a = getchar(); // it returns char '\n' if pressed enter Why th...
While taking the the input through getchar() or getche() in char variable, I found that if I write line like: char a; a = getche(); // it returns char '\r' if pressed enter a = getchar(); // it returns char '\n' if pressed enter Firstly, getche is a POSIX function from conio.h that is non-standard and depre...
6,817,773
6,818,426
Screen Capture for subsequent Computer Vision Processing
What should I use to perform screen capture on Windows for subsequent image processing? I seek to do follow-up image processing in OpenCV.
Well the most straightforward thing to do is to use an off the shelf video capture tool to create an AVI file and then have image processing software operate on that, after the fact. To get up and running: CamStudio is free and open source and has a simple gui. VirtualDub is also FOSS and is more powerful, but less...
6,817,984
6,817,998
Why header string is required for cout?
Why in the below code without including "string" header I can declare string variable. But compiler complains only for cout, when I try to print the string. What information "string" header consists of ? #include <iostream> //#include "string" int main () { std::string str="SomeWorld"; std::cout<<str<<s...
Because the header defining std::basic_string is most likely (indirectly) included by <iostream> (std::string is a typedef based on std::basic_string<char>). The overload for operator<< for std::cout however is only defined in <string>.
6,817,993
6,818,008
Writing elements of std::map through iteration
I have written the following code... PagesMap::const_iterator end = pagesMap.end(); for ( PagesMap::const_iterator it = pagesMap.begin(); it != end; ++it ) { .... it->second = 0; // Here I get the error //pagesMap[it->first] = 0; } Now at line where I have it->second = 0;, I get... error: assig...
It's because you are using a const_iterator; try changing to an iterator instead.
6,818,199
6,818,221
Why use typedef for declaring a structure?
Possible Duplicate: Difference between 'struct' and 'typedef struct' in C++? Is there a difference between typedef struct{ .... } mystruct; and struct mystruct{ .... }; ?
In C, the syntax to declare a struct is struct mystruct var;, so developers often typedef an anonymous struct to make declaring as simple as mystruct var;. C++ allows you to define structs without the struct keyword, so the typedef is used less often.
6,818,606
6,818,721
How to programmatically clear the filesystem memory cache in C++ on a Linux system?
I'm writing a benchmark tool in C++ where I want to clear the filesystem memory cache between experiments. I'm aware of the following console commands: sync echo 3 > /proc/sys/vm/drop_caches My question is how can i do this programmatically directly within C++? Any help is appreciated!
Just write to it : sync(); std::ofstream ofs("/proc/sys/vm/drop_caches"); ofs << "3" << std::endl;
6,819,075
6,819,150
How to make template function friend of template class
I have a template class with private constructor and destructor: template <typename T> class Client { private: Client(...) {} ~Client() {} template <typename U> friend class Client<T>& initialize(...); }; template <typename T> Client<T> initialize(...) { Client<T> client ...
Ignoring the ellipses (which I assume mean "a bunch of parameters that aren't relevant to the question"), this should work: template <typename T> class Client { private: Client() {} // Note private constructor public: ~Client() {} // Note public destructor // Note friend template function syntax templa...
6,819,082
6,819,160
std::getline on std::cin
Is there any good reason why: std::string input; std::getline(std::cin, input); the getline call won't wait for user input? Is the state of cin messed up somehow?
Most likely you are trying to read a string after reading some other data, say an int. consider the input: 11 is a prime if you use the following code: std::cin>>number; std::getline(std::cin,input) the getline will only read the newline after 11 and hence you will get the impression that it's not waiting for user in...
6,819,232
6,819,330
how to solve the middle block problem(consider edge blocks and leave any block in the middle of row)
I need to solve this algorithm problem. In the diagram, there are many rows with different no. of blocks. Each block is either good or bad. The block with no. 1 on it is good block and rest are all bad. I need to do the grouping of these blocks in 2 in order to find whether the resultant of these groupings is good or ...
It seems like throwing away the exact middle block isn't a good solution. With a row of size 7, you should be able to make 3 pairs, but if you discard the center one, you'll only get two pairs usable. Try taking blocks from both ends alternately: A pair from the left, then a pair from the right, then the next pair inw...
6,819,283
6,820,349
How to include a included header file from one project to another? VS2008
I have a project called Configurationhandler, and I have included a header file xerces\DomParser.hpp in Configurationhandler.h And ConfigurationHandler.h is included in HouseKeeper.h. But when I try to build, the ConfigurationHandler builds without errors, but HouseKeeper project gives an error saying it can't find the...
Assuming HouseKeeper is a different project, you'll need to add the path to the directory containing ConfigurationHandler.h into your HouseKeeper project settings.. I don't have VS2008 handy, but on VS2005, it would be: Right-click on the project in the Solution Explorer Select properties Under Configuration Propertie...
6,819,324
6,819,421
How to cast (and Marshall) CityHash std::pair<uint64,uint64> from C# to C++ and vice versa
CityHash allows us to generate 128-bit hashes, but the 128-bit representation of an integer is defined as a pair of uint64s (as seen in the header of CityHash.h): typedef boost::uint64_t uint64; typedef std::pair<uint64, uint64> uint128; I have a .NET wrapper that allows me to call the 64-bit version of city hash: pub...
You can't cast between pointers to these types, they don't have compatible layout. You'll have to copy the data between arrays of each type, one field at a time. Do this inside the C++/CLI code, and let the C# code see nice .NET arrays.
6,819,475
6,819,515
What's the advantage of using if(0 == foo()) rather than (foo() == 0)?
I found that some programmers would like to code like this in the comparator operator. I found it is more difficult to read... if (0 == foo()){ .... } Is there any different between foo() == 0 in term of readability ? What's the advantage of using 0 ==foo()?
No I think the best reason to do it like this: 0 == foo is to make sure you don't forget one = which would make it if (0 = foo) which will usually raise a compiler error rather than if (foo = 0) which creates a hard-to-find bug.
6,819,642
6,819,697
Pointer conversion issue with Ternary operator
I know the ternary operator has some surprising restrictions, but I was a bit baffled that this fails to compile for me: void foo(bool b) { int* ptr = ((b) ? NULL : NULL); } Obviously that's the minimum needed to show the problem. The error is: [BCC32 Error] Unit11.cpp(20): E2034 Cannot convert 'int' to 'int *' ...
NULL is a macro that expands to 0 (or some integral constant expression with a value of 0, for example, (1 - 1)). It's not otherwise "special." Any integral constant expression with a value of zero is usable as a null pointer constant, which is the reason that int* ptr = 0; is permitted. However, here, the expression...
6,819,699
6,819,837
Const vector of non-const objects
In defining a function in an interface : virtual void ModifyPreComputedCoeffs ( std::vector < IndexCoeffPair_t > & model_ ) = 0; we want to specify that the vector model_ should not be altered in the sense push_back etc operations should not be done on the vector, but the IndexCoeffPair_t struct objects in the model_ ...
The C++ const-correctness concept is IMO way overrated. What you just discovered is one of the big limitations it has: it doesn't scale by composition. To be able to create a const vector of non-const objects you need to implement your own vector type. Note that for example even the standard library had to introduce ne...
6,820,097
6,820,141
C++ - Smart Pointers - Passing derived class shared pointer to base through template
I have the following and having difficulty resolving the error please help. i have the following class as template definition somewhere. template<class ConcreteHandlerType> class SomeAcceptor: public ACE_Acceptor<ConcreteHandlerType, ACE_SOCK_Acceptor> In some other file, i initialize this class in the constructor cla...
From your code, it looks like you want mAcceptor to be assigned NULL (0), if that is the case you don't need to initialize it at all, as the default constructor will take care of that. But, since you call a function on that (NULL) pointer immediately, its not immediately clear exactly what you want to do. If you want ...