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
5,354,967
5,355,240
Create a packet generator using c#,java or c++
i want to create my own packet generator, so that i am able to create packets of TCP,ICMP (ping, echo), UDP. I also want to set all the headers of packet and control all the flags my self, i mean i want to turn on the flags like SYN,FIN etc. I don't have any idea how to start it.. Any help/suggestions will be appreciat...
There are a bunch of headers you can use to create your functions for creating packets: #include<linux/if_ether.h> #include<linux/ip.h> #include<linux/udp.h> Once the packets have been created use the following to transmit over the interface: socket() bind() Hope this helps to start!
5,355,081
5,355,242
Why can't I instantiate operator<<(ostream&, vector<T>&) with T=vector<int>?
In thinking about C++ iterator question, I wrote this sample program: #include <vector> #include <iostream> #include <iterator> #include <algorithm> template <class T> std::ostream& operator<<(std::ostream&os, const std::vector<T>& v) { os<<"("; std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ", ...
Two words: name lookup. Here is a simplified example of what you are trying to do, without any Standard Library headers required: template <typename T> void f(T) { } namespace ns { class C { }; void f(int) { } void test() { f(C()); } // doesn't work :'( } int main() { f(ns::C()); // w...
5,355,163
5,355,217
writing binary data (std::string) to an std::ofstream?
I have an std::string object containing binary data which I need to write to a file. Can ofstream f("name"); f << s; be problematic in any way? I need to read the data back exactly as it was originally. I can of course use fwrite(s.c_str(), s.size(), 1, filep), are there any pros / cons to either method?
You should be ok as long as you open the ofstream for binary access. ofstream f("name", ios::binary | ios::out); f << s; Don't forget to open your file in binary mode when reading the data back in as well.
5,355,241
5,363,535
Generating function declaration using a macro iteration
I'm trying to generate a function declaration using a macro /* goal: generate int f(int a, float b) */ template<typename P> struct ptype; template<typename P> struct ptype<void(P)> { typedef P type; }; #define NAMEe #define COMMAe #define COMMA , #define NAME(N) N PARAMS #define PARAMS(P, ...) COMMA ## __VA_ARGS__ ...
P99 has a macro that does exactly what you want, I think, namely P99_PROTOTYPE. It has a "signature" of P99_PROTOTYPE(RT, NAME [, AT]*) where RT is the return type (may be void) and AT are the argument types. The list of argument types may be empty, in which case it is substituted by void. Beware that P99 is made for...
5,355,305
5,355,346
C function **ntohl** gives linker error (unresolved externals)
The function ntohl gives a linker error for me: error LNK2001: unresolved external symbol _ntohl@4 fatal error LNK1120: 1 unresolved externals I have included #include <winsock.h> Is there a specific reason for that? (or can this function be easyly done manually?)
You need to link with Ws2_32.lib See the MSDN documentation for ntohl, which says "Library: Ws2_32.lib".
5,355,496
5,355,634
Template Instantiation for Library Use
I'm building an image processing library in C++(0x) which relies heavily upon templates, and I'm worried about the effect these templates will have on users' compilation times. For example, I have defined my image class as ns::Image, and I have several pixel types such as ns::PixRGB, ns::PixRGBA, ns::PixHSV, etc... ...
This is called an explicit instantiation. In a header file, somewhere after the ns::drawCircle<T,S> function template has been defined: namespace ns { extern template void drawCircle<>( Image<PixRGB<byte> >& img, PixRGB<byte> color, Circle); } In a *.cpp file in your library: namespace ns { template v...
5,355,685
5,355,702
string object in c++
I was reading a book on c++ when I encountered the following example: #include <iostream> #include <string> using namespace std; int main () { const char *message = "how do you do\n"; string s(message); cout << s << " and its size:" << s.size() << endl; } I wanted to know what exactly does it do. How can we pas...
s(message) actually calls the constructor of std::string, which constructs a new object of this type from the given character array pointed to by message. s is just an arbitary name given to the string object. std::string is C++'s idiomatic object for working with strings, it is usually preferred over raw C strings. Co...
5,355,715
5,356,019
Boost spirit is too greedy
I'm in between a deep admiration about boost::spirit and eternal frustration not to understand it ;) I have problems with strings that are too greedy and therefore it doesn't match. Below a minimal example that doesn't parse as the txt rule eats up end. More information about what i'd like to do : the goal is to parse ...
Here's my version, with changes marked: #include <boost/spirit/include/qi.hpp> #include <iostream> namespace qi = boost::spirit::qi; int main(int, char**) { auto txt = qi::lexeme[+(qi::char_("a-zA-Z_"))]; // CHANGE: avoid eating spaces auto rule = qi::lit("Hello") >> txt % ',' >> "end"; std::string str = "Hel...
5,355,724
5,355,795
How to retrieving variable value in C++ if you know the variable address
Greetings, I have recently started to code in C++ and have come across a problem to which I was unable to find the answer, so I thought maybe somebody else might know the answer. Is it possible to retrieve a variable value from another program if you know a variable address? Imagine that I have a memory address display...
On today operating systems, the programs handle virtual addresses, not physical ones. Shortly, a specific address for one programs will not point to the same physical location for other programs. To do what you want on modern operating systems, you can, for instance, set up a shared memory location. But there is a lot ...
5,355,797
5,355,860
Placing code in between conditions of an 'if' statement
I currently have an if statement, executing from within a function, that looks like this, but which doesn't compile, although I know it's because of the code I'm executing in between conditions 2 and 3. What I'm trying to do is create a function that will inserted a new node into a sorted linked list of integers at the...
This is... actually really easy. Because you're returning from each block, you don't need else at all! if (ListIsEmpty) // condition1 { // some code return true; } // you don't have anything that needs to happen here, but you *could* // since if condition1 is met control leaves the function immediately if (Li...
5,355,931
5,358,637
Adding #include <boost/thread/mutex.hpp> breaks my ActiveX control?
Is there a known problem with the boost::mutex header when used inside an ActiveX control? (Boost version v1.39) If I create an MFC ActiveX Control project in Visual Studio 2008 called "DefaultOCXControl" then I can build it, the control registers itself as part of the build, and can be inserted into the ActiveX Test C...
Have you tried linking boost::thread dynamically (define BOOST_THREAD_DYN_LINK)? I had this kind of problems when using boost::thread with a mixed C++/.NET project and linking just boost::thread dynamically was the solution (here a possible explanation: http://article.gmane.org/gmane.comp.lib.boost.user/22617/match=clr...
5,355,971
5,355,994
C++: adress of variable returned? How do I get this string to return, and then concat a small string onto it?
function: //http://www.cplusplus.com/reference/clibrary/ctime/strftime/ char* get_current_time() { time_t rawtime; struct tm * timeinfo; char buffer [80]; //main.cpp:73: warning: address of local variable ‘buffer’ returned time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (buffer...
Returning a LOCAL address is a bad bad bad idea. In C++, std::string solves most of such issues. Prefer using it. Also, forget about strcat, and use + or/and += with std::string. Re-writing your code: std::string get_current_time() { time_t rawtime; struct tm * timeinfo; char buffer [80]; time ( &raw...
5,356,050
5,356,074
Simulating nested functions in C++
In C the following code works in gcc. int foo( int foo_var ) { /*code*/ int bar( int bar_var ) { /*code*/ return bar_var; } return bar(foo_var); } How can I achieve the same functionality of nested functions in C++ with the gcc compiler? Don't mind if this seems like a beginner question. I am new to...
Turn your function into a functor as Herb Sutter suggests in this article
5,356,072
5,356,083
const char to char problem
How do I convert from char to const char? How do I implement type casting without changing the char SendBuf? Here is my code: .cpp // main() char SendBuf[6] = "Hello"; sendto(..., SendBuf, ...); // sendto structure int sendto( __in SOCKET s, __in const char *buf, __in int len, __in int flags, __in const struc...
Write the assignment like this: const char *SendBuf = "Hello"; You don't have to do anything about the function call. (A const char* parameter will take a char* variable as input.)
5,356,094
5,356,127
Constructor question (C++)
At my "Portfolio" constructor it thinks my debugger thinks that I am trying to have a return type set to it. I dont understand why. #include <iostream> #include <iomanip> using namespace std; class BankAccount { private: int accountNum; double accountBal; double annualIntRate; public: BankAccount(int, double balance ...
You are missing the semicolon at the end of class Portfolio { ... };. The compiler then proceeds to get confused on the next thing in the file.
5,356,139
5,356,245
Passing array as a parameter
I read in a book that, int f (int P[2][4]) cannot accept A[2][3], but B[3][4] is fine. what is the reason for this? Especially when we create dynamic allocation using pointers, this should not be a problem. Thanks
The reason is that function parameters never really have array type. The compiler treats the declaration int f(int P[2][4]); as though it really said int f(int (*P)[4]); P is a pointer to an array of four ints. The type int [3][4] decays to that same type. But the type int [2][3] decays to the type int (*)[3] inst...
5,356,185
5,356,820
Overriding the CRT's implementation of _purecall
I'm currently working on a DLL that is an extension to a closed, working project. I want to catch every pure-call bug, so I googled it up and found out about the _purecall handler. My question is about it's implementation. What's happening behind the scenes? The compiler itself takes my handler function address(if I de...
The answer depends heavily on how your compiler implements the purecall handler. If the compiler simply replaces the "pure" function pointers in your virtual function tables, then you're safe from modifying the parent process behaviour. But some compilers implement custom purecall handlers by calling your handler from...
5,356,269
5,356,346
What's the right way to specialize a template when using "extern template"?
I am hoping someone can point out the correct way to specialize a method in a template class while using "extern template class" and "template class" for explicit instantiation with gnu c++. I've tried to boil down this problem with the simplest example that mimics my real problem. It appears that declaring "extern te...
extern template class A<long>; This line says that A<long> is to be explicitly instantiated according to the definitions the compiler has already seen. When you add a specialization later, you break that meaning. Add a declaration of your specialization to the header file. template <typename T> struct A { /*...*/ }; ...
5,356,477
5,356,521
Problem starting old programs created in VS6
I have some old programs that I created 7-8 years ago in C++ in Visual Studio 6.0. I tried to start them today, but I had no luck. When starting up the program (or any other program I created at the time), I get the following error message: I can see at least that MFC42D.DLL and MSVCP60D.DLL is present in the program ...
You need a program like dependencywalker, that would show you all the DLLs that your programs need. Then you would have to find all those DLLs. Another option is to find a copy of VisualStudio 6 and install in on your machine. A third option is to get a more recent version of Visual Studio, and to try to recompile you...
5,356,627
5,438,300
Original article from the C++ report 95 about the CRTP online anywhere?
I've just learned about the CRTP Pattern and am looking for the original work. The reference of wikipedia says Coplien, James O. in (1995, February). "Curiously Recurring Template Patterns". C++ Report: 24–27. I also found it on ACM, however it's not available for download :( I wonder if anybody still has it.
I just uploaded it to http://sites.google.com/a/gertrudandcope.com/info/Publications/InheritedTemplate.pdf. Enjoy.
5,356,686
5,356,754
What does it mean to pass a parameter of function type in C++?
A while back I found that it's possible to write a C++ function that takes a parameter of function type (not function pointer type!). For example here's a function that takes a callback function that accepts and returns a double: void MyFunction(double function(double)); My question is what it means to have a variable...
Just like void f(int x[]) is the same as void f(int* x), the following two are identical: void MyFunction(double function(double)); void MyFunction(double (*function)(double)); Or, in official language (C++03 8.3.5/3), when determining the type of a function, After determining the type of each parameter, any parame...
5,356,706
5,356,936
Export type into python
I want to export singleton into python using boost.python and use it there. Here is the code: class ConfigManager : public boost::serialization::singleton<ConfigManager> {}; inline ConfigManager &configManager() { return ConfigManager::get_mutable_instance(); } BOOST_PYTHON_MODULE(ConfigManager) { bp::class_<Confi...
copy_non_const_reference will try to copy your reference to a Python object, you should use instead bp::reference_existing_object, I tried here and the error message disappeared
5,356,795
5,356,931
What's the Java equivalent to C++'s for_each template?
In the following code you're able to apply any Function f (e.g., add, subtract, etc.). How do I do that through Java? template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function f) { for ( ; first!=last; ++first ) f(*first); return f; }
There are two major changes you'll need to make to this code to make it work in Java. First, you'll need to replace the STL-style iterators with Java-style iterators, which fortunately isn't too hard. Second, you'll have to change the use of a function pointer or functor parameter with an object of a different type, ...
5,356,925
5,357,002
Why is the output not expected to be what it is?
Had been going through this code: #include<cstdio> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {1,2,3,4,5,6,7}; int main() { signed int d; printf("Total Elements in the array are => %d\n",TOTAL_ELEMENTS); for(d=-1;d <= (TOTAL_ELEMENTS-2);d++) printf("%d\n",array[d+1]); ...
The reason is that in C++ you're getting an implicit promotion. Even though d is declared as signed, when you compare it to (TOTAL_ELEMENTS-2) (which is unsigned due to sizeof), d gets promoted to unsigned. C++ has very specific rules which basically state that the unsigned value of d will then be the congruent unsigne...
5,356,946
5,357,058
C++ 2D growing array like MATLAB
I have read some posts about dynamic growing arrays in C, but I can't see how to create a 2D growing array (like in MATLAB). I have a function to construct an array for some image processing, but I don't know what will be the size of this array (cols and rows). How can I create this? I read something about malloc and r...
Simplest is with pointers int nrows = 10; int ncols = 5; double* matrix = new double[mrows*ncols]; And then you can access it as if it's a 2D array like. So if you want matrix[row][col], you'd do int offset = row*ncols+col; double value = matrix[offset]; Also, if you want the comfort of Matlab like matrixes in C++, ...
5,357,053
5,357,141
Enum in C++: how to pass as parameter?
I have in my class definition the following enum: static class Myclass { ... public: enum encoding { BINARY, ASCII, ALNUM, NUM }; Myclass(Myclass::encoding); ... } Then in the method definition: Myclass::Myclass(Myclass::encoding enc) { ... } This doesn't work, but what am I doing wrong?...
I'm not entirely sure why you're using "static class" here. This boilerplate works just fine for me in VS2010: class CFoo { public: enum Bar { baz, morp, bleep }; CFoo(Bar); }; CFoo::CFoo(Bar barIn) { barIn; }
5,357,411
5,357,685
Export template function
what's the right way to export template function from c++ into python using boost.python? Here is the code: template<typename T> T getValue(const std::string &key, const T &defaultValue = T()) {} // Export into some python class: class_<ConfigManager>(...) .def("GetValue", getValue<int>) .def("GetValue", getValue<floa...
You should read the relevant Boost documentation regarding default arguments. I'll summarize below. The problem here is that default arguments are used when calling functions in C++. Get rid of them and you'll see the problem from Python's perspective: // this function *must* be called with two parameters template<typ...
5,357,422
5,357,527
Please explain this expression
class TestPtr : protected QSharedPointer<Test> where Test is an abstract interface class. The TestPtr class should serve as the smart pointer class. Does this mean class TestPtr is derived from the class Test ? Is class test enclosed in a smart pointer? I read that QSharedPointer is a template class. Could somebody p...
What it doesn't mean That TestPtr derives from Test -- it does not. That class Test is enclosed in a smart pointer (but close: it means that instances of TestPtr will actually be smart pointers to Test without letting the world know about it except as the author of TestPtr explicitly chooses to) What it means It mean...
5,357,445
5,357,556
select() max sockets
Just more asynchronous stuff! Alright, so I now have a working asynchronous socket program for my main chatting application, and it's working really well! However I have one concern.. While using select() what is the maximum number of file descriptors that I can use in each set? I've read about a limit of 1024... If th...
Yes, the FD_SETSIZE has a limit of 1024. You can easily check that by looking at the select.h header. People have tried to increase the limit, but the reports vary from "working" to "crashing" after a while. If you need that many connections, use poll instead. A very good article to read.
5,357,680
5,357,737
Reading file per bytes
I have a simple program: #include <cstring> #include <fstream> using namespace std; int main(int argc, char **argv) { cout << "Creating test.txt file..." << endl; // Writing to file fstream fWrite; fWrite.open("./_test_data/test.txt", fstream::out | fstream::trunc); if (fWrite.fail()) { c...
Use fRead.read(&character,1) instead of fRead >> character. But you can also delete the cout << (int)character << endl; in the if statement.
5,357,801
5,712,738
Objective-C ID3 framework?
I am trying to add/replace album art of MP3 files. Is there an Objective-C framework that will allow me to do this? If not, what the best way to do this? I don't mind using C or C++ but it's better if it's in Objective-C. Thanks! Update: I found an audio framework called SFBAudioEngine which can edit metadata of severa...
Since Objective-C is a strict superset of C itself, I would suggest compiling a library that handles ID3 tags (id3lib or libid3tag come to mind) and use their functions directly or build a class around what they provide. Good luck!
5,357,843
5,357,938
Is there a way to work out all the required dependencies but without doing "./configure" - C
For those who have compiled from source knows how much of a pain it is to run "./configure" only to find that X library or missing, worst yet it spits out a silly line saying a cryptic lib file is missing, which you then have to go to a web browser type in the missing file cross you fingers that Google can find the ans...
Given that there's no mention of a specific pkg has been mentioned, I assume this is a generic "how to avoid using configure" question. From a source tarball, no there is no automated way to work the dependencies out. That's what configure is for (you can always read the Makefiles and autoconf files and understand the ...
5,357,869
5,357,960
error while loading shared libraries
I have a project organized as \bin\cmain \lib\libxmlrpc_client++.a \lib\libxmlrpc_client++.so.4 \lib\libxmlrpc_client++.so.4.16 My c program cmain need to dynamically link clib.so.4. While I compile the code, I use -L.../lib to indicate directory lib and use -lxmlrpc_client++. However, my code get error while loading...
You need to tell the dynamic linker where to look for the libraries. Assuming this is some sort of UNIX/Linux system, this can be done either via setting the LD_LIBRARY_PATH environment variable before executing the program: export LD_LIBRARY_PATH=/path/to/lib ./run-my-program or by setting the run-time linker path d...
5,358,252
5,358,271
Alternative to Eclipse for C and C++ development?
I have been using Eclipse for C and C++ development for some time. Unfortunately Eclipse has it's faults (speed, the crappy integrated console, and some bugs that pop up from time to time). For C++ development Qt Creator is a very good choice, but I need something for both C and C++. I don't really need the integration...
Have you tried NetBeans? There is a plugin for C/C++ development.
5,358,527
5,358,539
Error: expected constructor, destructor, or type conversion before ‘::’ token
I am getting an error when trying to compile my class. The error: Matrix.cpp:13: error: expected constructor, destructor, or type conversion before ‘::’ token Matrix.h #ifndef _MATRIX_H #define _MATRIX_H template <typename T> class Matrix { public: Matrix(); ~Matrix(); void set_dim(int, int); // Set di...
Matrix::~Matrix() { } Matrix is a class template. You got the constructor definition right; the destructor (and any other member function definitions) need to match. template <typename T> Matrix<T>::~Matrix() { } Matrix<int> m = new Matrix<int>(); This won't work. new Matrix<int>() yields a Matrix<int>*, with w...
5,358,684
5,358,723
get the offset of a tuple element
I have wrote the following code to get the offset of a tuple element template<size_t Idx,class T> constexpr size_t tuple_element_offset() { return static_cast<size_t>( reinterpret_cast<char*>(&std::get<Idx>(*reinterpret_cast<T*>(0))) - reinterpret_cast<char*>(0)); } This is actually si...
Is it legal C++? If by "legal" you mean "well-formed," then, yes. If by "legal" you mean "valid and will work on any compiler and Standard Library implementation, then, no, because std::tuple is not POD. Why I am allowed to call std::get (which is not constexpr) inside a constexpr function? Basically, a constexpr...
5,358,751
5,361,701
Qt custom look and feel?
can I force my Qt application to use different look and feel just like it is done in KDE ?
You can always change styles of widgets using QApplication::setStyle. There are a few predefined options available in Qt4. In main.cpp do something like this #include <QPlastiqueStyle> int main(int argc, char *argv[]) { [...] QApplication::setStyle(new QPlastiqueStyle()); } This way your application will alwyas...
5,358,924
5,358,943
generic container for exceptions
handling exceptions is important for code safety and to prevent undesired conditions as input for subsequent routines/algorithms. On the other hand, tough, filling the code with try/catch/throw statements makes it less readable. Is there any programming technique that helps to avoid mixing exception handling and algor...
Aspect Oriented Programming allows you to create advice's on e.g. how to handle exceptions globally. See this MSDN Magazine article or this slideshow for more information. AOP using Unity 2.0 is also a good example.
5,358,971
5,358,981
Is it possible to get access to the virtual pointer in a polymorphic class
Is it possible to get access to the virtual pointer i.e pointer to the virtual table in a polymorphic class.
In general, no, the standard is agnostic about how the virtual dispatch is implemented, so as far as it is concerned virtual classes may not even have a vptr and a vtable. The vptr is an implementation detail, you should look at your compiler documentation to check if there's a documented way to access it (but I've nev...
5,359,012
5,359,055
C++ run timing IDE perhaps?
is there an IDE or perhaps a piece of software that could time my C++ programs? I'm currently using Visual Studio 2010 so if there's a functionality to help with that, I'd appreciate it.
You will want to use a Profiler. There are plenty of options out there, but start with what you have natively in VS - please read Find Application Bottlenecks with Visual Studio Profiler Taken from here Determining the speed of a particular operation is often known as profiling. The term "profiling" can also be us...
5,359,017
5,359,477
QTableWidget - putting multiple lines of text in one row
Is it possible to put multiple lines of text in one row of QTableWidget?
I can think about 2 ways to force tablewidget to render multi-line text: Setup QStyledItemDelegate item delegate and render text yourself in the delegates paint method. Here you can find an example of you could do the same thing to a listview. Another solution would be to set QTextEdit as a cell widget to the table wi...
5,359,180
5,359,214
Safely using C symbols and headers?
I am looking for a way to degrade gracefully in the absence of a header or symbol. Consider my safe file: #import "FooHeader.h" // override some method that needs a symbol from FooHeader -(id)myImplementation:(FooSymbol)aSymbol { ... } What I would like to do is check for the existence of FooHeader.h before attempti...
This is typically done with autoconf. You create a file called configure.ac. In your configure.ac, you add AC_CHECK_HEADER([FooHeader.h], .... When you run ./configure on your project, the Makefile CFLAGS will get a -DHAVE_FooHeader definition. Inside your C file you use #ifdef HAVE_FooHeader. I don't have an exampl...
5,359,258
5,362,303
OpenGL: How to render perfect rectangular gradient?
I can render triangular gradient with simply just one triangle and using glColor for each corner. But how to render perfect rectangular gradient? I tried with one quad, but the middle will get ugly seam. I also tried with texture of 2x2 size, it was like it should be done: proper blending from each corner, but the text...
Indeed, the kind of gradient you want relies on 4 colors at each pixel, where OpenGL typically only interpolates input over triangles (so 3 inputs). Getting the perfect gradient is not possible just with the standard interpolants. Now, as you mentioned, a 2x2 texture can do it. If you did see precision issues, I sugges...
5,359,324
5,359,784
eclipse's auto-generated .h file guards
In eclipse, when a c++ class is created, .h file's auto-generated with guard XXXX_H_. In my limited, little experience, the guard is always be in the form of XXXX_H without the trailing _. So, I'm just curious and wondering why the _ is over there. Thanks in advance.
The trailing _ might be added to avoid collision with user-defined identifiers. For example, you might have a header file named get.h and at the same time you can conceivably have your own macro (or variable, or function) named GET_H. So, using GET_H for include guard in get.h would easily lead to problems. The standar...
5,359,453
5,359,466
P/Invoke problem (unbalanced stack)
I am trying to make a wrapper for a native c++ .dll using P/Invoke. The source code for the .dll has the following entry point specified: // .h-file CHROMAPRINT_API ChromaprintContext *chromaprint_new(int algorithm); And the method implementation: // .cpp-file ChromaprintContext *chromaprint_new(int algorithm) { Ch...
You most likely need to specify the calling convention. Try the following: [System.Runtime.InteropServices.DllImportAttribute("libchromaprint.dll", EntryPoint = "chromaprint_new", CallingConvention=CallingConvention.Cdecl)] By default, this uses Winapi (which is effectively StdCall) to make it easier to cal...
5,359,484
5,359,507
Overloading comparison operators in derived class right private inheritance
I've got two classes here. A Base class: class A { int x; public: A(int n):x(n){} friend bool operator==(const A& left, const A& right) {return left.x==right.x;} }; and a derived class that inherits from A privately: class B : private A { int y; public: B(int n,int x):A(x),y(n){} friend bo...
You can cast the instances to A& and use the equality operator for class A: if (static_cast<A&>(left) == static_cast<A&>(right)) { // ... }
5,359,692
5,359,777
sequentially reading a text file in C++
In C++, I want to sequentially read word from a text file, and store each word into an array? After that, I will perform some operation on this array. But I do not know how to handle the first phase: sequentially reading word from a text file and store each word into an array. I should skip those punctuations, which in...
This sounds like homework. If it is, please be forthright. First of all, it's almost always a bad idea in C++ to use a raw array -- using a vector is a much better idea. As for your question about punctuation -- that's up to your customer, but my inclination is to separate on whitespace. Anyway, here's an easy way to d...
5,359,718
5,359,724
Initialization of Static Class members
If i try to initialize obj_s it asks me to make it const - and i cant do that for i have to keep count of my Created Objects. #include<iostream> class A { static int obj_s=0; public: A(){ ++obj_s;cout << A::obj_s << "\nObject(s) Created\n"; } }; int main() { A a,b,c,d; } The code below keeps gi...
[Solved] The code is giving the error because the object is not getting created in the second case, and in the first its not initializing, the way its supposed to - Here's the fixed Code: #include<iostream> class A { static int obj_s; public: A() { obj_s++; std::cout << A::obj_s << "\nObject(s) Creat...
5,359,914
5,359,958
Problems with dereferencing a pointer (and returning it)
Here I have a function that creates a string, assigns it to a string pointer, and returns it. I tried returning a regular string and it worked fine. But then when when I integrated the pointers and de-referenced them, my program crashed. When I tried to debug it, this is the message I got: Unhandled exception at 0x0002...
The problem is that you are dereferencing the cTime_ variable without actually allocating the memory first. I am not sure if that is a global variable or a member variable but you need to use the "new" operator first to allocate it's memory. So you return the pointer to (address of) this variable back to the caller of ...
5,359,930
5,359,954
Memory Allocation of Static Members in a Class
I posted a question recently: Initialization of Static Class members. Now please check this code: #include<iostream> class A { static int obj_s; public: A() { obj_s++; std::cout << A::obj_s << "\nObject(s) Created\n"; } }; int A::obj_s = 0; int main() { } Even though one has not crea...
Obviously, it takes memory. And int A::obj_s=0 is exactly what it does: it defines the variable along with it's memory. In fact, when we say we defined a variable X, that means we define a memory of sizeof(X), and that memory region we label as X. More about static members: A::obj_s is a static member of the class A. ...
5,359,994
5,360,136
Hexdump macro (C/C++)
I have a working hexdump function but it seems to be overkill for printing a single variable. So I am trying to make a macro for it. So far this works almost perfectly: #define PRINT_FMT2(val,des,fmt) printf(#des" = "fmt": "SRC_STRN,val) // SRC_STRN is a macro that evals to string literal containing file and line# #...
Macros should be used sparingly because they are highly bug prone, and difficult to debug. In this case, you won't get any performance gain from using a macro, because a short function like this is probably going to get inlined. You will get a readability gain by using a function. There are also many language features...
5,360,129
5,360,140
How to signify no more input for string ss in the loop while (cin >> ss)
I used "cin" to read words from input stream, which like int main( ){ string word; while (cin >> word){ //do sth on the input word } // perform some other operations } The code structure is something like the above one. It is compilable. During the execution, I keep inputting something lik...
Your code is correct. If you were interactively inputting, you would need to send a EOF character, such as CTRL-D. This EOF character isn't needed when you are reading in a file. This is because once you hit the end of your input stream, there is nothing left to "cin"(because the stream is now closed), thus the while ...
5,360,168
5,360,178
What's the most recommended cross platform C++ library?
Is there something like jQuery that works the same in all browsers in the c/c++ world that will work consistently in all platforms?
Depends on what you want to do. Boost is one of the most used one.
5,360,309
5,360,382
C++ memory cache data structure
I was wondering if there is an equivalent of the MemoryCache class from .net in C++? (http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx) I'm loading audio files/images frequently in my program and I'd like to avoid reloading audio/video if I've recently used it by keeping it in a memory c...
Use boost to implement an LRU cache? LRU implementation in production code
5,360,412
5,360,432
Deleting the object you are listening to?
Here is my issue: I'm making a game GUI API. It has a mouse listener. Lets say the mouse listener is instructed to delete whatever widget it is listening to. The problem is that, when it deletes it, the iterator is destroyed to so it crashes: for(std::vector<AguiMouseListener*>::iterator it = mouseListeners.be...
You could use a std::list instead of a std::vector. When you remove items from it, you won't invalidate iterators, so you can keep looping You could build up a vector/list of objects that are to be deleted once the loop has finished. Once the loop completes, loop through your new collection, delete them, and remove ...
5,360,491
5,360,496
How I can detect memory leaks of C++ application in Linux (Ubuntu OS)?
How I can detect memory leaks of C++ application in Linux (Ubuntu OS) ? What is the program you can advise me for this goal ?
Check out Valgrind, it should be in the Ubuntu repository. it can give you detailed information about memory usage in C++ programs. Kind of like a debugger for memory usage. valgrind --tool=memcheck <your_app> <your_apps_params>
5,360,501
5,360,531
C++ function called without object initialization
Why does the following code run? #include <iostream> class A { int num; public: void foo(){ num=5; std::cout<< "num="; std::cout<<num;} }; int main() { A* a; a->foo(); return 0; } The output is num=5 I compile this using gcc and I get only the following compiler warning at line 10: (wa...
You haven't initialized *a. Try this: #include <iostream> class A { int num; public: void foo(){ std::cout<< "num="; num=5; std::cout<<num;} }; int main() { A* a = new A(); a->foo(); return 0; } Not initializing pointers (properly) can lead to undefined behavior. If you're lucky, your po...
5,360,594
5,360,624
glibc detected memory corruption
I have the following function. 129 string cmdline::compile_sOpt(const cl_option *options) 130 { 131 assert(options != MEM0x0); 132 133 string sOpt; 134 int i =0; 135 while(options[i].lo_name != MEM0x0){ 136 sOpt += options[i].so_name; 137 if(options[i].has_arg == required_argument || 138 ...
You've probably trashed the stack or heap. The error would suggest it's more likely to be the heap, but there's no guarantee stack corruption isn't the cause. The corruption is occurring prior to this function being called. Update0 memset off the end of an array Is a classic case of corruption that would cause this,...
5,360,627
5,386,820
C/C++ Post-increment by more than one
I'm reading bytes from a buffer. But sometimes what I'm reading is a word or longer. // assume buffer is of type unsigned char * read_ptr(buffer+(position++)) That's fine but how can I post-increment position by 2 or 4? There's no way I can get the += operator to post-increment, is there? Reason is, I have this big ...
Well, I did answer my question in the edit... Basically what I wanted was a single expression which evaluates to the original value but has a side effect of incrementing by an arbitrary amount. Here are some macros. #define INC(x,inc) (((x)+=(inc))-(inc)) #define INC2(x) INC(x,2) #define INC4(x) INC(x,4) #define INC8(...
5,360,852
5,361,014
Lib Files and Defines
I'm using a couple of external libraries and I'd rather not have to include all their source and header files in my main source directory or in my project file. One option would be to compile the libraries as lib files and link them like that. However I'm not sure the defines get evaluated before or after the lib file ...
Library is a binary file, so all defines obviously already in. Just to make order, defines are evaluated as 1st stage of compilation process - the step is called preprocess. At this stage, for each cpp files created one file containing all #include'ed in it files recursively and all macros are evaluated. Any way 3rd p...
5,361,039
5,361,054
Incompatibility between C and C++ code
The given C code #include <stdio.h> int x = 14; size_t check() { struct x {}; return sizeof(x); // which x } int main() { printf("%zu",check()); return 0; } gives 4 as output in C on my 32 bit implementation whereas in C++ the code #include <iostream> int x = 14; size_t check() { struct x {}; ...
In C++ class declaration struct x {}; introduces the name x into the scope of check and hides x (previously declared as int at file scope). You get 1 as the output because size of empty class cannot be zero in C++. In C, an inner scope declaration of a struct tag name never hides the name of an object or function in an...
5,361,120
5,361,143
undefined reference to, but it is defined
I have a class A with virtual inline getters and setters. From A there are two classes B and C derived. And I have a class D, derived from B and C. Creatung an object from D and using the getName() results in "undefined reference to getName()". Removing "inline" doens't work. The header file is included correctly. What...
Your code compiles fine with/without inline : with inline and without inline But remember this otherwise : in a virtual inheritance, you've to initialize the base explicitly IF the base class constructor takes parameter as, class D : public B, public C { public: D(string s) : A(s), B(s), C(s){} ...
5,361,220
5,361,339
Empty struct in C vs empty struct in C++
Why is empty struct in C a constraint violation? Why does this rule get changed in C++? Are there any historical reasons?
since you don't have inheritance in C you don't need them. If you just want to have a distinguishable pointer type you can use pointers to incomplete types. struct opaque; struct opaque* stranger = 0; should work fine.
5,361,346
5,361,835
C++ rookie (streams)... How to read strings from file where the string has a space (e.g., Tom Smith)? Trouble using getline instead of >>
I wrote a template function for reading in string or numerical data from files and saving the data in vectors of either strings or ints/doubles. I then use the data to perform calculations with another code I wrote. Advance apologies, because I think this is a simple question... I can't read in string data where ther...
I've written some code to solve part of your problem: parsing the names. You can adapt it to your needs. Note: this is not the fastest way to solve this, but it is a simple way that is hopefully easy to understand. Test.cpp #include <iostream> #include <iomanip> #include <fstream> #include <string> #include <vector...
5,361,404
5,361,468
Organizing library dependencies
I've noticed that there seem to be two approaches to linking: a flat and a hierarchical way. Let me illustrate with two examples: A Visual Studio solution can contain multiple projects with one of them being the main project. My usual approach is then to add all required libs to the main project and none to the other...
It usually comes down to static vs shared libraries. If you use static libraries, then the main program must usually (always?) be linked against every library that it depends on, either directly or indirectly, hence a flat linking structure. For shared libraries (or DLLs in Windows), each library bundles up its own dep...
5,361,646
5,361,693
what to do with the destructors in an interface
When I write interface classes in C++, I choose either of the following 2 options class Interface { public: virtual R1 f1(p11, p12 , ...) = 0; ... virtual Rn fn(pn1, pn2 , ...) = 0; virtual ~Interface() {} } or class Interface { public: virtual R1 f1(p11, p12 , ...) = 0; ... virtual Rn fn(pn1, pn...
As I understand, the purpose of making virtual function pure virtual is to force the derived classes to either provide implementation for it or choose the default implementation by explicitly writing Base::f() in the Derived::f(). So if that is true, then what is the purpose of making virtual destructor pure virtual? ...
5,361,705
5,361,908
error: no matching function for call to
i want to use a method of anothre class in another one,but i get error below,whats the problem? TIA error: no matching function for call to ‘PositionInfo::PositionInfo()’ here is my code: PositionInfo Pos; double metr=Pos.GetBallDistToTeammate(5); and PositionInfo.h class is: PositionInfo(WorldState *pWorldState, Inf...
Default constructor PositionInfo::PositionInfo() { /* code */} is missing in your cpp file.
5,361,968
5,362,029
Running C/C++ code in a webbrowser?
I'm new to webdevelopment and I am looking for some tutorials or resources about how to run C++ code in a browser. I soon going to do a degree project which implements a sound service in a browser (like flash I guess) using a provided DLL + my own program, so I'm looking for some starters on where to look. I don't have...
In almost all normal cases you would not want to have C++ code running in your web browser. Running C++ code is in most cases akin to giving full control of your computer to the running code. It can basically do anything, from installing viruses to deleting everything on your hard drive. This is something you would not...
5,362,044
5,362,132
How to use cpp (c pre-processor) with include path
I am writing a parser which operates on C/C++ source files. As 1st stage of parser I need to use some already available preprocessor, so that I can get away with directives such as #define, #ifdef. For g++, the available tool is 'cpp' (or g++ -E ...). I had 2 questions: My parser is written in C++, so what could be th...
system is the most cross-platform way possible. But if your code is single-platform, you can have better control over the execution of subprograms by using platform's native API. Like ShellExecute in windows. There are a variety of places non-standard include files can be located, such as in the same directory as the s...
5,362,145
5,362,478
OF_SHARE_DENY_NONE doesn't share read?
I am creating a video in my app with AVIFileOpen(&pfile, fn, OF_WRITE | OF_CREATE | OF_SHARE_DENY_NONE, NULL); and I can't acces the avi file while it is creating. What's the problem ? Thanks
I debugged into the function and it is calling CreateFile() with dwShareMode = 0 (exclusive); somewhere along the way it is losing the share mode. Didn't work with OF_SHARE_DENY_WRITE, either. I guess it's just a bug. This was on Windows XP SP3.
5,362,154
5,364,785
Approximation of 2D-function with weight coefficients
I need to approximate a table-defined 2D-function like that x0 y0 x1 y1 ... xn yn for every point I have a "weight" (root-mean-square error for this measure). I need to write a function like this: typedef std::vector< double > DVector; void approximate2D( const DVector & x , const DVector & y , const DVe...
To minimize the total squared closest distances to the line a x + b y = r, you can't use matrix equations, since the problem is no longer linear. The distance to the line can be defined as follows. Then the function you want to minimize is f(a,b,r). This task is simplified somewhat when a2 + b2 = 1. If you expand that...
5,362,178
5,362,200
OpenFileDialog: opening directories
I'd like to be able to select directories (in addition to single files) in the dialog. As it is now, when I click 'open' when the directory is selected, it descends into the directory, while I want it to return the path to the directory. Additionally, how would I read such path? I don't see any property that would retu...
The easy way is to use a FolderBrowserDialog instead. This dialog is designed to allow the user to select a folder. You can also enable the user to create a new folder, if you like, straight from the dialog box. You shouldn't try and allow the user to select either a file or a folder from the same dialog. I don't think...
5,362,189
5,362,314
Can a C++ smart pointer fully encapsulate its data?
Is it possible to wrap a raw C++ pointer in a smart pointer-like class, which will allow a user to update using familiar operators such as array and indirection: int i; my_ptr<int> ptr(i); ptr[i] = 42; yet, will absolutely deny that user access to the underlying raw addresses. So, this should not succeed: int *p; p = ...
Filter access through a proxy class, such as this(incomplete example): template<typename T> class proxy { proxy(T & v) :value_(v) {} proxy & operator=(const T & v) { value_ = v; return *this; } private: T & value_; }; That class needs some more work, but once complete, if your operator[] returns one of tho...
5,362,250
5,363,249
What easy zlib tutorials are there?
I'm looking for a good tutorial on zlib. I'm interested only in decompressing the archives. I also want to know how I can access a desired file inside an archive, preferably by filename alone, if that can be done in zlib at all.
Well there are many zlib articles , tips and tutorials. Some of them are 1) Bobobobo's Blog This article basically tells you how to use zlib, and there is a snippet of code that will get you going. This project shows you how to use zlib. Its a console project, because there's no need to create a window to demonstrate ...
5,362,352
5,364,857
How to enable shared library build while using CMake for LLVM?
The problem: Ubuntu 10.10 doesn't supply LLVM CMake modules (/usr/share/llvm) or (/usr/local/share/llvm) when installing LLVM 2.8 from Ubuntu repositories. So I'm now compiling LLVM 2.8 using CMake by myself and then installing it like this: cmake .. make make install This will install CMake modules I need to link LLV...
After a lot of investigation (google, source and llvmdev mail-list), I discovered that this problem is in fact an issue with the 2.8 release, the compilation of shared libraries using CMake in that release is broken. I'm porting my library now to the version 2.9rc1 which is working fine and was already scheduled to be ...
5,362,443
5,362,530
How to print out a string in a pre-given position of a line in C++
I have an assignment to implement a light text editor in C++, one of the functionalities can be simplified to the following requirement. For instance, I have two strings: "stackoverflow" and "stackexchange". I am asked to print "stack" at the leftest position and overflow" at the rightest position. I am having two ques...
1) You can use the std::setw() and std::right manipulators, which allow to set the field with and the adjustment flags in the stream: #include <iostream> #include <iomanip> std::cout << "stack" << std::right << std::setw(188) << "overflow" << std::endl; 2) You can use the facilities built into std::string to find the...
5,362,445
5,362,504
Pointing to Static Class Member
class A { static int x; }; How to get the Address of x using pointer-to-member ?
Since it's static, this should be this syntax: int *px = &A::x; //x is static member For non-static member, this is the syntax: int A::*py = &A::y; //y is non-static member Example: struct A { static int x; int y; }; int A::x=100; int main() { int *px = &A::x; int A::*py = &A::y; A ...
5,362,573
5,362,639
EXP to Taylor series
I'am trying to expand exp(x) function to Taylor series. Here is code: double CalcExp(){ double eps = 0.0000000000000000001; double elem = 1.0; double sum = 0.0; int i = 1; sum = 0.0; do { sum += elem; elem *= x / i; i++; } while (elem >= eps); return sum; } The problem is when I enter big X or negative X m...
For big X values (around 700 and above), you'll hit the range limit for doubles (10^308) and cause an infinite loop. You can't do much about it, you should either limit X input range or use some big number library to have extended range. Another workaround is to add this to your loop: if (sum > 1E305) { // we'll mos...
5,362,932
5,362,964
c++ Assigning objects in object declaration
I come from a Java background and recently decided to try creating a C++ Qt GUI application "for fun". I've been struggling with many of the finer differences between Java & c++, but I've learned a lot. I'm attempting to match "java-style" syntax as closely as possible in my C++ coding. While this may or may not be a...
//Java MyObject o = new MyObject(); //C++ MyObject o = MyObject(); These are not equivalent. The c++ version creates a new object, on stack, something java can only do with primitive types. Once o goes out of scope it will be destructed. What actually happens above is logically MyObject o(MyObject()); (incorrect actu...
5,362,994
5,363,021
compile code as a single automaticly merged file to allow compiler better code optimization
suppose you have a program in C, C++ or any other language that employs the "compile-objects-then-link-them"-scheme. When your program is not small, it is likely to compromise several files, in order to ease code management (and shorten compilation time). Furthermore, after a certain degree of abstraction you likely ha...
Pointless with a modern compiler. MSVC, GCC and clang all support link-time code generation (GCC and clang call it 'link-time optimisation'), which allows for exactly this. Plus, combining multiple translation units into one large makes you unable to parallelise the compilation process, and (at least in case of C++) ma...
5,363,460
5,366,375
CUDA pointers to device constants
I have the following constant defined on the CUDA device: __constant__ int deviceTempVariable = 1; Now I tried getting the address of deviceTempVariable using two methods, and I'm getting different results. The first is a direct memory access from a CUDA kernel as follows: __global__ void cudaPointers(pointerStruct* d...
A pointer created in the kernel is clearly usable on the device. It's probably a physical address, although some GPUs might be starting to add virtualization (MMU and TLB). It looks like cudaGetSymbolAddress is giving you an address usable from the host processor. It's different because device memory has been mapped ...
5,363,501
5,363,550
Issue with using shared_ptr with custom equality operator and STL
There seems to be an issue when using shared pointers together with a custom equality operator and an std::list. I put together the following example code to demonstrate the issue. Before trying to compile this: I'm using gcc version 4.5.2 20110127 with the following commandline: g++ -g -O0 -std=gnu++0x test.cpp The so...
This is because when you compare two shared_ptr<T>, you are comparing the reference, that is, the memory address that the two instances point to, not the underlying values.
5,363,542
5,364,069
Complex circular dependency
what is the the best practice of solving circular dependency in C++? I could use the forward declaration, but then I get the pointer to incomplete class type is not allowed error. Does that mean that two classes that uses each others pointer cannot be dependent? Also, I thought about forward declaring each class and th...
You just need to use forward declaration correctly: Put all code in cpp files Put just class declaration in header file In header file: Use forward declaration if you only use a pointer or a reference. Otherwise you to include header file. (Do Not add unrequired includes) In cpp file include all header files you re...
5,363,575
5,363,598
Count how many times each distinct word appears in its input C++
#include <iostream> #include <string> #include <sstream> #include <map> int main() { std::string input; std::cout << "Enter input: "; std::getline(std::cin, input); std::map<std::string, int> m; std::map<std::string, int>::iterator it; std::istringstream iss(input); std::string words; ...
Because map automatically constructs an item with the default constructor, when you access a key that doesn't exist yet, you can simply say: while (iss >> words) { ++m[words]; } The default value of new items will be 0 (see this question). Your previous map logic was fine except that you had the condition reversed...
5,363,609
5,363,715
Memory managment in a GUI
The main thing I'm wondering is, let's say a button's action causes itself to be deleted. By this I mean, an action listener has been added to the button, and that action event would like for the button to be destroyed when it is called. But it can't just call delete on it, it needs to some how mark it for deleting and...
Usually in a GUI there is a message loop for handling asynchronous input messages. Assuming you have such a thing, the normal approach is to post a message to this queue which will result in the control being deleted. Because the message queue is pumped after your event handler completes you have no problems.
5,363,748
5,363,841
Constructor not returning usable object
I have a problem with the constructor, which is not working as I'd expect. If I try to initialize my class like that, it will work and I get a usable object: vector<float> v; MyClass<2> a(v); However, if I try to build a class like below (which should be equivalent) the results are quite unexpected. There is no error...
MyClass<2> a(vector<float>()); This is not a variable declaration. It is the declaration of a function named a that returns a MyClass<2> object and takes as an argument a "pointer to a function that takes no arguments and returns a vector<float>." Confusing? Yes. This is what is referred to as the "most vexing par...
5,363,796
5,363,824
equivalent of C struct in C#
Could someone help me with what the equivalent of this C code is in C#? struct { int left, right; } stack[MAX]; Thanks!
public struct PickAName { public int left; public int right; } private const int MAX = 666; PickAName[] stack = new PickAName[MAX]; or: Stack<PickAName> stack = new Stack<PickAName>();
5,363,924
5,364,002
How to use a pointer to a templated type
I apologize for the beginner nature of this question. I can't seem to get a pointer to a templated type to work. For example, here is a header file: #include "TemplatedClass.h" using namespace std; class PointList { public: PointList(TemplatedClass<Point> *p); //snip }; This doesn't seem to be legal. What have ...
You need to provide the definition of the Point class by including a header where that class is defined. For example : #include "TemplatedClass.h" #include "Point.h" // if this header contains the Point's declaration using namespace std; class PointList { public: PointList(TemplatedClass<Point> *p); //snip }; ...
5,364,063
5,364,121
How to check if window is "Always on top"?
In my useful hotkeys program, i have a global hotkey which sets your current foreground window to be Topmost/Not topmost by calling SetWindowPos(hwnd, HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); SetWindowPos(hwnd, HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); at the moment i have to have two separate hotkeys, Win+Z...
I think you can do this: DWORD dwExStyle = ::GetWindowLong(m_hWnd, GWL_EXSTYLE); if ((dwExStyle & WS_EX_TOPMOST) != 0) { // do stuff } Here's the MSDN link - http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx And here's the MSDN link to the extended styles - http://msdn.microsoft.com/en-us/library/ff700...
5,364,442
5,364,462
Is it possible to write constructor assignment operator only mentioning specially -copied members?
Let's say I have class with N members. Most member are copyable. Only one member needs manual copying code. Is there method to write copy assignment operator in such a way that I write code only for nonstandard member, and letting compiler generate copying code for all/other members ?
Yes, of course, wrap your member in a separate class with a user-defined copy-constructor. And for the class you are talking about, write no user-defined copy constructor. E.g. class MyMemWrapper { define copy constructor }; class MyClass { member 1; member 2; ... MyMemWrapper };
5,364,597
5,364,963
Does this section of code require a mutex?
I am trying to implement a crude thread interrupt. The 'interruptRequested' variable is being checked pretty often. In Operating Systems class we learned about starvation -- Is that possible here or in a similar situation? I know that the example program behaves as I would expect when I run it, but it could just be a f...
yes, you must first use a mutex to protect reads and writes to interruptRequested, in respective blocks. even if it appears to work as expected, it may not actually. a 99% success rate is not acceptable in software. as well, your test program is trivial - chances are good that it would (silently or mysteriously) fail i...
5,364,685
5,364,712
Segfault when inserting a new element into a sorted linked list
I am using the following function to insert a new node into a sorted linked list of integers // Insert new element template <class Type> bool list<Type> :: Insert (const Type& NewElement) { Node *NewNode, *TempNext, *TempPrevious; NewNode = new Node; NewNode -> Element = NewElement; for (TempNext = He...
Notice that if the list is empty, TempPrevious will an uninitialized pointer. When you try running the for loop on an empty list, TempNext will immediately be NULL and you won't execute the statement TempPrevious = TempNext. Since you never set TempPrevious to have a default value, it will be uninitialized, and so th...
5,364,727
5,364,759
Making a vector of linked lists?
How can I make a vector of linked lists? For example I have a struct of properties (for the linked-list) defined as follows: typedef struct property { string info; property* implication; } property; And then I have a class object: class objects { private: vector<property> *traits; public: void giveProp...
in class objects, you have declared a pointer to a vector of properties, when really you want a vector of property pointers: class objects { private: vector<property*> traits; // Note where * is public: void giveProperty(property *x) { traits.push_back(x); // Note that x is already a pointer, no n...
5,364,777
5,364,812
Get function which initiated QNetworkRequest in replyFinished()
i have following problem: I have a class Foo which encapsulates a web-api. the interface has following functions: Foo::addItem( QString id ) Foo::updateItem( QString id ) both function initiate a QNetworkRequest with the same URL but the usage of the data is different. Therefore i need to know in slot function Foo::re...
In your original QNetworkRequest you can set an attribute with setAttribute(Attribute code, const QVariant & value) Attribute is an enum and there is a reserved code for just this situation, QNetworkRequest::User. (See: Attribute) In your QNetworkReply, you can pull the QNetworkRequest with request() then get the Att...
5,364,902
5,364,933
Understanding the life time of an object, scope, RAII
In the below code, when I pass an unnamed A variable to the ctor of B, the variable is destructed after the line. According to this answer : Temporary objects are destroyed at the end of the full expression they're part of. A full expression is an expression that isn't a sub-expression of some other expression...
You have one of the tricky parts of C++ It is pure chance that member_a has the value 20. You are hitting what is refereed to as undefined behavior. When a class retains a reference to an external object it is the responsibility of the programmer to make sure that the lifetime of the object lasts longer than the object...
5,364,915
5,364,955
c++: read() Hangs when reading response from server
I have two versions of this code. In one version if the user inputs the phrase "GET /index.html" the server responds properly. In the second version, the "GET /index.html" phrase is built in without prompting the user. The second version hangs when reading a response from the server, any idea why? First Version - Promp...
The request must be terminated with 2 carriage return and line feed pairs, this is missing in your second example. char charI[] = "GET /index.html\r\n\r\n";
5,364,957
5,365,184
In Qt 4.7, how can a pop-up menu be added to a QToolbar button?
I am newbie to Qt and am currently playing about with Qt Creator and raw C++ code. I have managed to get some simple functionality working, including a menu and toolbar by adding QAction objects to both. However I am having some difficulty: What I would like to do is have a menu option which has a submenu, e.g. New, wi...
I believe QToolButton widget should work fine for what you're trying to do, see if and example below would work for you: QMenu *menu = new QMenu(); QAction *testAction = new QAction("test menu item", this); menu->addAction(testAction); QToolButton* toolButton = new QToolButton(); toolButton->setMenu(menu); toolButton...
5,365,153
5,365,167
What happens when a casted pointer has an increment operator?
For example: int x[100]; void *p; x[0] = 0x12345678; x[1] = 0xfacecafe; x[3] = 0xdeadbeef; p = x; ((int *) p) ++ ; printf("The value = 0x%08x", *(int*)p); Compiling the above generates an lvalue required error on the line with the ++ operator.
The cast creates a temporary pointer of type int *. You can't increment a temporary as it doesn't denote a place to store the result. In C and C++ standardese, (int *)p is an rvalue, which roughly means an expression that can only occur on the right-hand side of an assignment. p on the other hand is an lvalue, which me...
5,365,336
5,365,407
How to reproduce C++ double rounding issue
Floating point precision is limited in C++ and for novice programmers that often causes trouble when rounding values. When teaching students it is often useful to demonstrate the floating point precision number rounding issue. What possible ways do you know to demonstrate such rounding issue consistently on all C++ com...
First, we should note that, in IEEE754 floating point, 1.5, 0.5, and 2.0 are all exactly represented. So, in this specific example, 1.5 will never be 1.499999999999. Having said that, I think the thing to do is to expose your students to numbers are not exactly representable. Say, 1.1. Here is a sample program: #inclu...
5,365,604
5,365,656
Semicolons in a class definition
I was reading this gotw and here's a code sample from there: struct X { static bool f( int* p ) { return p && 0[p] and not p[1:>>p[2]; }; }; The question was: how many errors should a compliant compiler give: I answered one, because this code is equivalent to struct X { static bool f( int* p ) { retu...
Yes, a semicolon is explicitly allowed after a function declaration in a class specifier. As a result, currently in the C++0x draft, the following is valid too: The first semicolon belongs to the function definition, the second to the class specifier delegating to the function-definition non-terminal. struct A { voi...