question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
7,173,632 | 7,173,745 | No call to the copy constructor | Consider this:
#include <iostream>
struct A{
A(){
std::cout << "Create empty A" << std::endl;
}
A(const A& a){
// Why is this never called??
std::cout << "Never called" << std::endl;
}
};
A genA() {
A a;
return a;
}
int main(int argc, const char *argv[])
{
A a(genA()); // E... | This is called as Return value optimization.
Compiler can optimize your code so that it bulds the object directly in the location where it would have been copied too. Thus there will be no reason to use the copy constructor.
Note: The standard explicitly allows it do so.
|
7,173,718 | 7,173,864 | Show Child Window in Task Switcher | How can I make a modeless child dialog (instantiated using CreateDialogParam) show up in the windows task switcher (Alt-Tab strip)? Using the WS_EX_APPWINDOW window style forces the dialog to have a taskbar icon but not in the task switcher.
| Raymond Chen gives the full gory details here: https://devblogs.microsoft.com/oldnewthing/20071008-00/?p=24863
|
7,173,840 | 7,173,963 | Registering classes/functions/things before main() | Suppose I have a class called Poem.
class Poem{
virtual void recite() = 0;
}
And I have hundreds of .cpp and .hpp files which describe a subclass, like the following
class TheRaven : public Poem{
void recite() { std::cout << "NEVERMORE!" << endl; }
}
And the likes. And in the main function, I'd like to be abl... | This is an example for the Singleton design pattern. Don't use a static global, since the initialisation order is undefined across compilation units.
Instead use something like this:
PoemRegistry& PoemRegistry::getGlobal()
{
static PoemRegistry theRegistry; // construction guaranteed when first call
return theRegis... |
7,174,069 | 7,174,100 | Can you suggest text editor (linux) that has good customisation of highlighting? | I need a editor in which I could customise highlighting so that it could highlight sentences in which bad programming style (I have my own rules for this) would be underlined.
example "if(a==1)DoSomething();" would be underlined, and "if ( a == 1 ) DoSomething();" won't be underlined. Which text editor allows such cust... | Why, Vim and Emacs of course. Both are very customizable - whether you're leaning more towards regex/Vimscript/Python/Ruby/Perl or ELISP will probably decide your favourite. ELISP is somewhat more structured, and Emacs highlighter is a bit better, but unless you've worked with LISP before, it will look like chaos. The ... |
7,174,442 | 7,534,750 | CvNormalBayesClassifier | I'm using a CvNormalBayesClassifier.
I'm training it with some random data, like in the code I'm posting
CvMat* train = cvCreateMat( 100, 32, CV_32FC1 );
cvZero( train );
cvmSet( train, 0, 0, (double) 2 );
cvmSet( train, 0, 1, (double) 5 );
cvmSet( train, 1, 17, (double) 12 );
cvmSet( train, 1, 9, (double) 235 );
c... | I found that to get proper results from the ml library you need to create and access the classifier like below:
bayes = new CvNormalBayesClassifier();
bayes->train( samplesMat, responses );
The above code snip worked for me with some training data.
|
7,174,710 | 7,175,584 | Conversion from CString to char*/TCHAR* | I am well aware of techniques to convert CString to a C-style character. One of them is to use strcpy/_tcscpy, and others include using CStrBuf.
The problem:
char Destination[100];
CStringA Source; // A is for simplicity and explicit ANSI specification.
Source = "This is source string."
Now I want this:
Destination ... | Well, I don't want to say that this is in any way recommendable, but you could hijack some lesser-used operator for a quick hack:
void operator<<=(char * dst, const std::string & s)
{
std::strcpy(dst, s.c_str());
}
int main()
{
char buf[100];
std::string s = "Hello";
buf <<= s;
}
You could even rig up a mode... |
7,174,781 | 7,277,180 | boost-program-options: notifier for options with no value | One can use notifier for parsed options only if they have value_semantic.
What is the best way for no-value options to be automatically handled by the given notifier?
The simple approach is to make a dummy value_semantic with implicit assignment, so a user can pass the option without a value.
This leads to a possibil... | One guy OXPEHOMETP on a russian programmers forum gave me a pice of advice to use boost::program_options::bool_switch().
When defining an option with no value via value-permitted interface, one must pass not boost::program_options::typed_value() as semantics, but bool_switch(). This means that no value can be explicit... |
7,175,053 | 7,175,200 | Generate core dump as well as text dump linux | If I only set coredump limit to unlimted. Core dump file is getting generated by linux.
But If I do but signal handling as well as set core dump limit to unlimit. Linux doesn't generate core dump.
signal(SIGINT, SignalHandler);
signal(SIGSEGV, SignalHandler);
How to generate both text dump as well as core dump in li... | Set the signal handler to one shot mode (using the SA_RESETHAND flag to sigaction(2) for example) and call abort() at the end of your custom SIGINT/SIGSEGV signal handler.
|
7,175,291 | 7,175,448 | Advantage of wrapping classes in DLLs | I've just finished a phase in my project where I wrote a small infrastructure to carry out a certain task, made of a core class with several auxiliary classes.
The C++'ness is quite basic - single inheritance, some STL containers, that's it.
No threads - client runs the show.
What I would like to do now is wrap it all ... | I find it hard to see any benefit with this. I can see plenty of problems:
No type checking across a DLL boundary. Any version mismatches will result in runtime failures, harder to detect than compile time failures.
Extra deployment headaches. You may be tempted to update some but not all modules and so deal with comp... |
7,175,316 | 7,175,532 | template with enum fails to initialize its member with a POD template argument value | I am trying to create a lightweight template class having a static member initialized with the value provided as template argument( only enum are alowed ).
The code below doesn't build saying
error: wrong number of template arguments (1, should be 2)
error: provided for ‘template<field_id field_value,
inner_... | In the end your code probably should look like:
enum field_id{ FIELD_ID_1, FIELD_I_2 };
enum inner_type_id{ INN_ID_1, INN_ID_2 };
template<field_id field_value, inner_type_id inner_type_value>
// ^ no enum keyword
struct node
{
static field_id m_field_id;
};
template<field_id field_value, inner_type_id in... |
7,175,333 | 7,178,024 | How to create delegate for QTreeWidget? | Here is what I'm trying to do (all parents and children must have a close button on the right, in the future, only the hovered item will be able to show the **close ** button):
My delegate code:
class CloseButton : public QItemDelegate
{
Q_OBJECT
public:
CloseButton( QObject* parent = 0 )
: QItemD... | You can use the QStyledDelegate::paint function to draw the close icon, without using any widget, and the editorEvent to receive mouse events for the item, even if you don't use the editor or make the item editable.
class CloseButton : public QStyledItemDelegate {
Q_OBJECT
public:
explicit CloseButton(QObject ... |
7,175,405 | 7,176,619 | Compiler agnostic fortran name mangling function | I am dynamically linking to a fortran static object and need to be able (at run time) to take the name of the fortran function (which is a C++ string) and name mangle it appropriately for the compiler. Is there any pre-built function that would serve this purpose? In the statically linked case I am using autoconf's FC_... | Here's a quick and dirty C solution that abuses the existing macros to extract the mangling rules and print the mangled result. Most of this gets elided by the optimizer, so only the relevant cases exist. You should be able to adapt this to your code.
#include <stdio.h>
#include <string.h>
/* The autoconf macros, pred... |
7,175,474 | 7,229,780 | After hiding dialog based app on windows mobile platform, user cannot activate it anymore | I am struggling with one problem in Windows Mobile programming (dialog based app).
I have dialog based MFC application. App is created like this:
BOOL MyApp::InitInstance()
{
MainDlg dlg;
dlg.DoModal();
m_pMainWnd = &dlg;
return FALSE;
}
This works just fine. But it has a big problem. If user minimiz... | Well, I finally figured it out. I had turned off Title bar, therefore task manager didnt show my app, because it didnt have any window.
But after launching app, it has title at taskbar and titlebar. To remove title bar & border, I left these options:
[OK] Title Bar
Border - thin
In code I did this:
BOOL MyDlg::OnInit... |
7,175,776 | 7,176,145 | Specialize function by traits class | I'm writing a hash functor for use in a boost::unordered_map which will store boost::graph edge descriptors. Simple enough. Undirected and directed graph edges must be hashed differently however (at least in my case, the edges (u,v) and (v,u) are equivalent when the graph is undirected, so map[(u,v)] and map[(v,u)] mus... | Put hashing in a separate struct templated on directed category type.
template<typename Directed, typename Edge>
struct Hasher {
static std::size_t edge_hash(const Edge& e) {
std::size_t hash = 0;
boost::hash_combine(hash, e.m_source);
boost::hash_combine(hash, e.m_target);
return ha... |
7,175,837 | 7,176,121 | pointer wrapper class - behave just like a raw pointer | I'd like a pointer wrapper class that acts just like a raw pointer but also saves a special integer along with the pointer (Type's index in the array it came from)
I managed to have it behave mostly like a pointer. I am aware that the pointer comparison solution might not be optimal but that's not my main problem.
I wa... | template<typename Type>
class PtrWrapper
{
typedef struct { } NotType;
public:
Ptr() { }
Ptr(const NotType* nullPtr) { }
Ptr(Type* p, int index) { }
};
You can exploit the fact that literal NULL / 0 can be auto-cast to any pointer type. Create a type that is NOT T, and a constructor which takes a singl... |
7,175,959 | 7,176,060 | Change the value in std::map from iterator | My application merges two std::map instances. If there are no duplicates, the merge completes without intervention. However, if a duplicate is detected, then the method asks whether the new value should be ignored or overwritten. (This query may be answered by a rule table, message box to the user, or some other logic ... | You need to use Dictionary::iterator instead of Dictionary::const_iterator in the return from insert.
for (Dictionary::const_iterator i = other_dictionary.begin();
i != other_dictionary.end();
++i) {
// Use standard iterator here
std::pair<Dictionary::iterator,bool> ret = this_dictionary.insert(*i);
if ... |
7,175,982 | 7,176,027 | C++ overloaded member function error | hi i was making a program with 3 classes and when i was using a member initialization list i got an error saying "no instance of overloaded function "people::people" matches the specified type:
MAIN.cpp
#include <iostream>
#include "conio.h"
#include <string>
#include "birthday.h"
#include "people.h... | People.cpp should be:
people::people(string x, birthday bo) : name(x), dateOfBirth(bo) { }
|
7,175,988 | 7,178,234 | Connect to a MySQL database from C++ Through PHP | I have a dedicated Linux Server with my multiplayer game (C++/Sockets) on it and recently I acquired a MySQL server "service" for my web pages (I also have a little multiplayer game done in PHP) so I don't need to think about backups etc.
The MySQL service works wonderfully well for my web pages but I can't connect fro... | Your question basically suggests proxy for MySql requests with C++ client and PHP as server. While it is completely possible and there can be some good solutions(PHP can work with raw sockets, so creating a proxy shouldn't be so much of a problem) you have one more limitaion - you don't have root access so you can't cr... |
7,176,152 | 7,176,197 | Can we keep char[undetermined_during_compile_time_size] inside of boost::shared_ptr? | I could have a queue<char*> file_queue; but than I would need to clean up after each char*. I have a dinamic variable int buff_length; that would be length of each char in file_queue. It would be set once from a config file before queue creation. So I wonder - is it possible to keep char[buff_length] inside one boost::... | You can use a shared_array:
boost::shared_array<char> ptr(new char[buff_length]);
Any reason why std::string or std::vector<char> is not appropriate for your situation?
Note, with C++11 you can use the following:
std::unique_ptr<char[]> ptr(new char[buff_length]);
std::unique_ptr has a specialization to deal with ar... |
7,176,157 | 7,176,181 | Is there a standard C++ Hash Container? | I have a variety of textbooks that note that there wasn't a hash container originally incorporated into the STL, but most also say that most standard library implementations do have some form of hash container since it was a known shortfall.
These books aren't necessarily as up to date as possible, and I got a little c... | The new standard hash map container is called unordered_map. You can include it in your files by #include <unordered_map>. It is part of the now-approved standard C++11.
Before C++11, you had various things like hash_map which were (widely?) supported by some vendors so you could use them, but if you did, your code was... |
7,176,420 | 7,176,455 | c++ pass array to function question | How is it possible to pass an array parameter to a function, and calculate the size of the array parameter? Because every time i try to calculate it, the return value is always 4.
Thanks the fast replies. I'm going to pass the size of the array as well then. Or i give a shot to vectors. Thanks
| This is (one of) the difference between arrays and pointers. Taking the size of an array results in its size in bytes, whereas taking the size of a pointer yields the size of pointers on that system. However, whenever you pass an array to a function, it decays to a pointer, the size of which is always the same no matte... |
7,176,447 | 7,177,049 | Accessing a C++ function from a CXX test | I'm writing a few CXX unit tests for a class I have written. I have never written CXX tests before (also this is the only framework I can use). I am trying to call a function contained within my class so that I can test the output is what is expected, but I am unsure if you can do this, and if so, how.
Test.h:
class ... | In the first case, you're trying to call a member function without an instance of Test. You need a Test to call it on, as you've done in the second case.
In the second case, you're trying to call a member using the syntax for having a pointer to the object, '->', when you actually have an object. You want the second t... |
7,176,478 | 7,177,575 | Opencv C++ finding movement in a thresholded image | I am using openCv with C++ and I am trying to find a moving ball under different lighting conditions. So far I am able to filter an image by thresholding it using HSV color space. The problem with this is that it will pick up other object that have a similar color. It is very tedious to figure out the exact hsv range e... | Simplest approach would be frame differencing / background learning in an image sequence.
frame differencing: substract two successive frames, the result is the moving part (you will probably only get the edges of moving objects)
background learning: e.g. build an average over 50 frames, this would be your learned bac... |
7,176,792 | 7,176,842 | passing pointer to change its value but stay still | passing pointer to change its value but stay still
I am working on C++ with allegro library.
there is draw_tiles function.
void draw_tiles(def_small_world * s_world,BITMAP * dest){
BITMAP *TileMap=NULL;
loadTilemap(s_world->tilemap,TileMap);
for(int y = 0;y<SIGHTY*2+1;y++)
{
for(int x = 0;x<S... | You are passing the pointer by value, so a copy of the pointer is created. Inside loadTilemap, you are assigning a new value to the copy of the pointer - but that doesn't affect the original pointer.
Try passing the pointer by reference by changing the loadTilemap function signature to this:
void loadTilemap(int i,BITM... |
7,177,168 | 7,185,273 | A few questions about handwriting recognition | Do you advise zinnia for handwriting recognition?
I searched and find some libraries but some of them requires training for every different person's hand writing. Does zinnia require training for every different hand writing?
I read its site but could not find out.
Also i need a library in C++, i can find some can be a... | Zinnia doesn't generally require individual training. However, it performs better for characters with more strokes, so using it for Latin-based alphabets might not give you the best results. It is also dependent on correct stroke order, so if you train it with one way to write 'A', and the person using it writes it in ... |
7,177,221 | 7,177,304 | array doesn't decay to pointer if passed by const reference in a template function | This question comes from this one:
c++ pass array to function question
but since the OP accepted an answer I guess nobody will read it now.
I tried this code on g++. It seems that the array does not decay to a pointer when passed to this function (the function returns the proper result):
#include <iostream>
template <... | Array decay doesn't just happen -- it only happens when the program would fail to compile without it. When you pass an array by reference, there simply is no need for decay to kick in.
Note that the function template can also be written without dividing ugly sizeof expressions:
template <typename T, std::size_t N>
std:... |
7,177,253 | 7,177,308 | Can currying be used with lambda functions? | This piece of code fails to compile and I don't know if it is because it can not be done, lambdas do not inherit from binary_function, or it is just that I'm getting the syntax wrong
#include <functional>
int main(int argc, const char *argv[])
{
auto lambda = [](int x, int y) -> int { return x + y; };
auto sumFi... | Use:
auto sumFive = std::bind(lambda, 5, std::placeholders::_1);
Please forget entirely about bind1st and binary_function, etc. Those were crutches in the old C++ because of the lack of lambdas and variadic templates. In C++11, use std::function and std::bind.
|
7,177,397 | 7,177,510 | C++ forbid overwriting a virtual function | I use a class A from a library and want to add some functionality to it via an own class B.
The user of class B should derive from it as if he would derive from class A.
class A {
public:
virtual void func1()=0;
virtual void func2()=0;
...
}
class B: public A {
public:
virtual vo... | No, that's not possible in the current edition of C++, aka C++03. The upcoming C++11 standard will include the contextual keyword final which will make this possible:
// C++11 only: indicates that the function cannot be overridden in a subclass
virtual void MemberFunction() final { ... }
The Microsoft Visual C++ comp... |
7,177,425 | 7,177,991 | Container of templateStruct<T> with varying T | I have a simple struct which contains GUI controls in an application I'm working on.
The struct is defined like
template<class T>
struct guiControl
{
T minValue
T defaultValue
...
}
Each control is identified by a unique integer ID in my app. I would like to access the structs with a map<int, guiControl>,... | It would not make sense to access your controls in one map because they are of different type what means you cannot perform the same methods on them etc...
What you can do is define a general class that contains the elements every control should have and then derive special controls from that class:
template<class T>
... |
7,177,864 | 7,177,930 | C++ Vector Memory Usage - Is it ever freed? | I know that vectors double in size whenever their capacity() is exceeded. This operation takes some time which is why vectors are supposed to have amortized constant time for addition of elements with push_back().
What I'm wondering is... what happens when a vector shrinks so that its size() is less than half of the ... | No, it is never freed (i.e. capacity is never reduced) until destruction. A common idiom for freeing up some memory is to create a new vector of the correct size, and use that instead:
std::vector<type>(originalVector).swap(originalVector);
(inspired by "More Exceptional C++", Item #7)
|
7,177,884 | 7,178,022 | Can I use placement new(this) in operator=? | Background:
I have a complicated class with many variables. I have a sound and tested copy constructor:
Applepie::Applepie( const Applepie ©) :
m_crust(copy.m_crust),
m_filling(copy.m_filling)
{
}
Some of the member variable copy constructors called in the intializer list perform allocation.
Question:
I need to c... | As Herb Sutter in "Exceptional C++" states, it is not exception safe. That means, if anything is going wrong during new or construction of the new object, the left hand operand of the assignment is in bad (undefined) state, calling for more trouble. I would strongly recommend using the copy & swap idiom.
Applepie& Appl... |
7,177,887 | 9,894,692 | C++11 with gcc 4.6.1 on a mac | I'm new to the mac and trying to get gcc 4.6 working.
I installed MacPorts and installed gcc 4.6.1 (by executing sudo port install gcc46). I'm trying to compile a simple test code that compiles fine on Linux (with gcc 4.6.1 and 4.6.2) and Windows, but I'm getting errors that make me thing there is something wrong with... | We're getting there
gcc 4.7 (port) compiles this code just fine.
Xcode 4.3 comes with clang 3.1 which is supposed to support this, but it crashes when I try to compile. However I built clang from SVN and replaced the compiler Xcode is using and now it compiles and runs fine as well.
And it only took half a year.
|
7,178,095 | 7,178,241 | What conditions can cause clock() to return -1 (ie fail)? | I'm using clock() from time.h to provide a rough time elapsed mechanism for an operation I want performed around once per second. (I probably want to use time() but the majority of the question stands since time() also returns -1 on a failure). It's not critical to be precise since other thresholds are high enough th... | My friendly man page states the following:
If the processor time used is not available or its value cannot be
represented, the function shall return the value (clock_t)-1
Do note that clock() returns a value based on CPU time usage (on everything excluding Windows), if you want a wall clock time use time() instead.
|
7,178,179 | 7,184,051 | In Eclipse, how do I define standard paths for C++ include headers? | I write my C++ projects using the Eclipse IDE. Anytime I start a new project, I have to define all the include paths. Is there a way for me to define a set of standard header paths that have to be included in all projects?
| This is how to get settings between workspaces
In your old (working) project Do File/Export... C/C++ Project Settings and give it a file to write to
In your new workspace do File/Import... C/C++ Project Settings and select your file
This also works nicely for all the other customizations you might have such as key bind... |
7,178,334 | 7,178,391 | Linking/Registering a .so File | I've just compiled a test application using some libraries provided by a custom third party vendor. There is no installation/package manager. The application builds as expected. However, when I go to run it, it can't seem to find a necessary .so file (which I've got sitting in the same directory):
[diego@localhost Debu... | Run ldconfig after completing the build, as well as making sure that the current directory is inside your /etc/ld.so.conf file so that the current directory is a trusted directory to look for shared libraries.
|
7,178,517 | 7,178,726 | Problem in running exercice 2-4 from Learning Opencv, O'Reilly | i'm studing the grat book Learning oPENCV, o'Reilly, from Bradsky and Kaehler.
i'm on Ubuntu 10.10, previous example works fine but in 2-4 i have a problem.
this is the code:
#include "cv.h"
#include "highgui.h"
void example2_4( IplImage* image )
{
// Create some windows to show the input
// and output images ... | ./a.out tree.avi
You are passing a video file while the sample expect an image.
|
7,178,588 | 7,366,935 | Using Log4j CompositeTriggeringPolicy feature with log4CXX | I would like to combine both rolling time and rolling size in an appender, it seems there is no composite rolling in log4cxx, am I right ?
| No, there isn't. In fact, there is no such combined policy implemented in log4j, either, so it was not transferred to log4cxx.
I once had a task of writing such mixed-policy rolling file appender (in log4j, though). I did this by overriding FileAppender, esp. the method
// log4j
void setFile(String fileName, boolean ap... |
7,178,694 | 7,178,768 | How do I pass data to different threads | Suppose If I create 5 threads through CreateThread(). I'll need to pass intergers 1, 2, 3, 4, 5 to each thread but I also have to pass a this pointer. Neither I can pass more than one argument because CreateThread function takes only one, nor I can create a member variable in class because that will be shared between ... | Define a struct and pass an object of this struct.
The struct can be this:
struct ThreadContext
{
MyClass *m_this;
int m_int;
//add more members you need to pass more data
};
Then you can do this:
for ( int i = 0 ; i < 5 ; i++ )
{
ThreadContext *ctx = new ThreadContext();
ctx->m_this = this;
... |
7,178,816 | 7,178,972 | A custom Vector and Matrix class in C++ and operator[] | I have a vector class in C++ that relies on raw pointer. I dont use std::vector as I need to create vector objects from raw pointers for specifal cases. Here is very simple example of my class:
template <typename T>
class Vector
{ ...
private:
T * m_data; int m_size; bool dontFree; ...
public:
Vector(T *con... | Create a proxy class that overloads operator[] that you can give access to your matrix's array. Something like this:
template<typename T>
class Proxy
{
public:
Proxy(T * tp)
:rowStart(tp)
{}
T & operator[](const int columnIndex)
{
return rowStart[columnIndex];
}
private:
T * r... |
7,178,948 | 7,179,029 | Problem with functions accepting inner classes of template classes | I have a problem with inner classes in class templates. I have a template class (say: Matrix<T>), and a subclass (say: Matrix<T>::Row). Now I want to to write a function which operates on instances of the subclass (say: negate(Matrix<T>::Row &)). I tried to declare the function with template<class T> negate(typename Ma... | How should the compiler be able to deduce this? Imagine the following setup:
struct A { typedef int T; };
struct B { typedef int T; };
template <typename S> void foo(typename S::T);
Now when you say int x; foo(x);, there's no way to match this unambiguously.
The point is that you are not deducing a template parameter... |
7,179,062 | 7,179,144 | How to let C++ know that an operator has been overloaded for a class | Is it possible to write a template function for which a particular type of classes have some functions or overloaded operators? For instance
template <typename T>
void dosomething(const T& x){
std::cout << x[0] << std::endl;
}
In this context I'm assuming that x is a class that behaves like an array, that is, I ha... | You might need to provide a little more detail, as this short example works for me:
#include <iostream>
#include <vector>
template <typename T>
void dosomething(const T& x){
std::cout << x << std::endl;
}
template <typename T>
void dosomething_else(const T& x){
std::cout << x[0] << std::endl;
}
int main() {
... |
7,179,069 | 7,179,114 | Pointer to pointer syntax problem | Lets say I have the following:
void init_gpu(cuComplex* d_hhBuff)
{
cutilSafeCall(cudaMalloc((void **)&d_hhBuff, memsize));
}
and I call it with something like
cuComplex *my_buff;
init_gpu(my_buff);
Well, when init_gpu returns, it is NOT pointing to the device memory that cudaMalloc allocated.
How do I modify... | The problem is that you are passing the pointer by value. Change the function header to
void init_gpu(cuComplex *& d_hhBuff)
|
7,179,161 | 7,179,364 | Create a print function that takes an ostream as an argument and writes to that stream | Im currently anwsering exercise questions concerning operator overloading in C++. I have a question:
Create a simple class containing an int and overload the operator+ as a member function. Also provide a print( ) member function that takes an ostream& as an argument and prints to that ostream&. Test your class to show... |
So far in my study of c++ I havent really come across ostream's and as
such am not sure if its possible to explicitly create such a stream. I
have tried using: std::ostream o;
You must have missed something, because ostreams are important. std::cout is a variable of type std::ostream by the way. Usage is more o... |
7,179,312 | 7,179,670 | Cross Platform Code Organisation | I have this monitor class that gives access to instances of itself with a static function. When GetMonitor is called, the mMonitors map is searched and the instance is returned, if the instance doesn't exists, it is created.
class Monitor {
public:
static Monitor& GetPrimaryMonitor();
static Monitor... |
should I take a different approach of allowing the user to create as many monitor instances he/she wants? This seems wrong because it would be as if they would be creating a physical monitor whereas my approach gives access to shared resources already available
Yes, you absolutely should. For several reasons:
You ar... |
7,179,398 | 7,182,286 | Strange compiler message when using GetProcAddress() in windows.h | I'm developing a simple packet sender/receiver for some purpose (in Dev c++)..wanna add more features to it. But I'm stuck at a point where I'm getting a strange error "Too many arguments to function"..My code is
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
HINSTAN... | First, refer to the official documentation for pcap_open():
pcap_t* pcap_open ( const char * source,
int snaplen,
int flags,
int read_timeout,
struct pcap_rmtauth * auth,
char * errbuf
)
Then look at the definition of FARPROC in windef.h:
typedef INT_PTR (FAR WINAPI *FARPROC)();
You're... |
7,179,502 | 7,179,570 | Boost Spirit Roman Numeral Parser Example | Trying to learn boost spirit and the example given in the docs have me a little confused.
Referring to this code:
http://www.boost.org/doc/libs/1_46_1/libs/spirit/example/qi/roman.cpp
Particularly this segment of grammar:
start = eps [_val = 0] >>
(
+lit('M') [_val... | Both +lit('M') and *lit('M') are correct. But the former is more readable than the latter (semantically), in my opinion, as the former says add 1000 to _val if there is one match, and do it repeatedly. On the other hand, the latter is difficult to read, as one could read it as add 1000 to _val even for zero-match whi... |
7,179,907 | 7,180,025 | When does Endianness become a factor? | Endianness from what I understand, is when the bytes that compose a multibyte word differ in their order, at least in the most typical case. So that an 16-bit integer may be stored as either 0xHHLL or 0xLLHH.
Assuming I don't have that wrong, what I would like to know is when does Endianness become a major factor wh... | Very abstractly speaking, endianness is a property of the reinterpretation of a variable as a char-array.
Practically, this matters precisely when you read() from and write() to an external byte stream (like a file or a socket). Or, speaking abstractly again, endianness matters when you serialize data (essentially beca... |
7,179,974 | 7,180,423 | C++ Compiler Error (trying to create a static vector of vectors) | I'm trying to create a static vector-of-vectors and I'm finding that the following code compiles and runs under gcc-4.1.2 but under gcc-4.5.1 it fails to compile with the message
assign.cxx:19:48: error: no matching function for call to ‘to(boost::assign_detail::generic_list<std::basic_string<char> >&)’
Can anyone exp... | The problem stems from the fact that in your definition of to<>(), containerType is declared to have only one template parameter, when in fact std::vector<> has two template parameters.
The fact that this compiles in GCC 4.1.2 only indicates a bug in GCC 4.1.2 -- the code is still inherently incorrect.
Unfortunately, I... |
7,180,011 | 7,180,090 | How do I remove duplicates from a C++ array? | I have an array of structs; the array is of size N.
I want to remove duplicates from the array; that is, do an in-place change, converting the array to have a single appearance of each struct. Additionally, I want to know the new size M (highest index in the reduced array).
The structs include primitives so it's trivia... | You could use a combination of the std::sort and std::unique algorithms to accomplish this:
std::sort(elems.begin(), elems.end()); // Now in sorted order.
iterator itr = std::unique(elems.begin(), elems.end()); // Duplicates overwritten
elems.erase(itr, elems.end()); // Space r... |
7,180,195 | 7,180,289 | Terminate with bad_alloc exception, but no "new" in stack trace | C++ program is throwing this:
terminate called after throwing an instance of 'St9bad_alloc' what(): std::bad_alloc
Which it appears to be thrown from new, but the stack trace doesn't show any calls to new:
#0 0x0000003174a330c5 in raise () from /lib64/libc.so.6
#1 0x0000003174a34a76 in abort () from /lib64/libc.so.6
... | The new call may not be in the stack because it has already unwound at the point your application is terminating. I'd try to set a breakpoint at the moment the exception is thrown (e.g., using catch throw under gdb) -- at that point you'll see the cause of the exception in the stack.
|
7,180,278 | 7,180,313 | Variables not producing proper data | My variables aren't producing data like they should be. For whatever reason, my string is empty, yet when I try to execute my function, my character clearly passes the argument "holland" to the name parameter upon construction. Despite this, when I make a call to get_name(), the string is returned as empty. Ontop of th... | That's because you delete the memory before you've finished with it. Try this instead
Character * holland = new Character(holland_name, HUMAN, MALE);
std::cout << "testing, mic...1, 2, 3...testing, testing. Bow, chica wow wowww!!1" << std::endl;
std::cout << holland->get_id() << std::endl;
std::cout << holland->get_nam... |
7,180,540 | 7,180,624 | Managing Scope and Object Lifetime Within STL Vectors | Coming from a C# world, I'm struggling to make sure I don't introduce memory leaks and errors in a C++ project I've been assigned to. I'm writing code that uses structs to parse information from a buffer of data. Because the number of data structures that appear in the buffer can vary at runtime, an stl vector is use... |
Yes, the instance of parserObject that is declared within the for loop goes out of scope each time the loop iterates.
No, placing the parserObject into the vector doesn't keep that object in scope. The push_back() method will make a copy of that object that is now owned by the vector. You need to make sure your obje... |
7,180,731 | 7,180,901 | Ostream << overloading confusion | When you're overloading the << operator for a class (pretend this is defined as a friend in SomeClass), why do you both take a reference to the ostream and return that ostream?
ostream& operator<<(ostream& s, const SomeClass& c) {
//whatever
return s;
}
What benefit can returning the ostream be when it was alr... | This is not redundant, but useful for chaining calls. It's easier to see with functions like std::string::append, so I'll start with that:
std::string mystring("first");
mystring.append(" second");
mystring.append(" third");
can be rewritten as:
std::string mystring("first").append(" second").append(" third");
This ... |
7,180,823 | 7,180,973 | Scope of object in an array | Suppose you have an array of objects in C++ and you remove one of the objects from the array. When is that object's destructor called? Since C++ does not have automatic garbage collecting, it would seem strange if the destructor was called right after being removed from the array. But does the object stay allocated u... | When you declare a C++ array, it constructs all of the objects on the stack, and they stay there until the array itself is deleted:
std::string ArrayOfStrings[10]; //There are now ten strings here
Objects can't be "removed" from this kind of array. When ArrayOfStrings goes out of scope, it automatically deletes all t... |
7,181,078 | 7,184,757 | How to profile OpenMP bottlenecks | I have a loop that has been parallelized by OpenMP, but due to the nature of the task, there are 4 critical clauses.
What would be the best way to profile the speed up and find out which of the critical clauses (or maybe non-critical(!) ) take up the most time inside the loop?
I use Ubuntu 10.04 with g++ 4.4.3
| OpenMP includes the functions omp_get_wtime() and omp_get_wtick() for measuring timing performance (docs here), I would recommend using these.
Otherwise try a profiler. I prefer the google CPU profiler which can be found here.
There is also the manual way described in this answer.
|
7,181,108 | 7,182,946 | Using libcurl in C++ application to send POST data from value in .INI file | So I have a C++ application that takes a value from a key in a settings.INI file, uses libcurl to reach out to a PHP page, post that data, and it should return some different data.
And it actually works, aside from grabbing the data from the INI file. If I explicitely type in for the POSTFIELDS option for libcurl (e.i.... | I am guessing that you have _UNICODE defined, which means that TCHAR is wchar_t, CString is CStringT<wchar_t>, and the code:
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, Serial);
actually passes a wide char string to curl_easy_setopt() when the function is expecting a narrow char string. If your machine is little Endian... |
7,181,153 | 7,182,419 | Templates, function overloading and their order of appearence | I was trying to make a simplified version of my code for this question. In the process I encountered something that does not make sense to me. Can someone explain why I obtain the following result? Here is the code, it should compile and run in gcc.
#include <string>
#include <iostream>
#include <typeinfo>
using std::... | Okay, playing around with your code, I found it also performs correctly if you move ALL of the writeData templates and overload below the binaryWrite class definition.
When the compiler encounters binaryWrite::write, it checks to see if it has a definition for writeData at that point. It's selecting template <typename... |
7,181,210 | 7,181,687 | C-style initialization lists in C++, structs, and class constructors | I'm still on the road to enlightenment in C++, so bear with me...
Suppose I have a struct:
struct MyThing
{
int a, b;
};
I fancy creating one using the c-style shorthand, Fig.1:
MyThing mt = { 1, 2 };
Then suppose I decide to stick a method somewhere in my struct, and (being the kind of person that I am) I feel ... | Well, first of all, the example you say fails, does in fact, work. (It doesn't fail until you add the constructor)
Now, remember, that an object is just a piece of memory. Hence the binary image of
MyThing mt = { 1, 2 }; // Fig A
is exactly the same as
int mt[2] = { 1, 2}; // Fig B.
Hence to imple... |
7,181,361 | 7,181,678 | Enforcing correct parameter types in derived virtual function | I'm finding it difficult to describe this problem very concisely, so I've attached the code for a demonstration program.
The general idea is that we want a set of Derived classes that are forced to implement some abstract Foo() function from a Base class. Each of the derived Foo() calls must accept a different paramete... | Since your Derived class is-a Base class, it should never tighten the base contract preconditions: if it has to behave like a Base, it should accept BaseInput allright. This is known as the Liskov Substitution Principle.
Although you can do runtime checking of your argument, you can never achieve a fully type-safe way... |
7,181,372 | 7,181,452 | Why can I assign a new value to a reference, and how can I make a reference refer to something else? | I have couple of questions related to usage of references in C++.
In the code shown below, how does it work and not give a error at line q = "world";?
#include <iostream>
using namespace std;
int main()
{
char *p = "Hello";
char* &q = p;
cout <<p <<' '<<q <<"\n";
q = "World"; //Why is there no error on this... |
a) It cannot, the line you quote doesn't change the reference q, it changes p.
b) No the literal is constant, but p is a pointer which points at a literal.
The pointer can be changed, what is being pointed to cannot.
q = "world"; makes the pointer p point to something else.
You seem to think that this code
int i;
... |
7,181,809 | 7,181,861 | Passing anonymous classes to private member functions | Is it possible to use a class defined in an anonymous namespace as a parameter in a private member function? I haven’t found a way to forward declare AnonymousHelperClass in the header.
// C.h
class C
{
// ...
private:
void Boing(AnonymousHelperClass &helper);
};
.
// C.cpp
namespace
{
class AnonymousHelperCl... | No, because there is no way to name the type in the header file.
However, you could turn the private member function into a template:
// C.h
class C
{
public:
void Foo();
private:
template <typename TAnonymousHelper>
void Boing(TAnonymousHelper&);
};
Then define it in the source file and use it with the ... |
7,182,058 | 7,182,687 | Why does the constness of a reference affect whether it can be initialized with a variable of a different type? | Why does this code fail to compile?
double d ;
int & i1 = d // Compilation FAILS
While this one does?
double d ;
const int & i = d // Compilation Succeeds
Please, I am interested in knowing what was in mind of C++ designers that they allowed one behavior while disallowed another.
I know in either case it's immo... | Because it creates a temporary int where the double is converted, and mutable references cannot bind to temporaries, whereas const ones can.
The problem with allowing mutable references to bind to temporaries is relatively clear.
Derived* ptr;
Base*& baseptr = ptr;
baseptr = new Base;
ptr->SomeDerivedFunction();
|
7,182,100 | 7,182,139 | Does std::tr1::shared_ptr do mutual exclusion? | I have a class which contains a BYTE*, a reference counter and a CRITICAL_SECTION which protects both of them from concurrent access.
I wanna replace all that with a std::tr1::shared_ptr<BYTE>. The MSDN says that:
Multiple threads can read and write different shared_ptr objects at
the same time, even when the object... | It is up to you to ensure correct access to the data the std::tr1::shared_ptr points to. That data is yours. It only matters to the std::tr1::shared_ptr when it's time to delete it.
Regarding the std::tr1::shared_ptr object itself, you have the following guarantees:
you can safely read from the same instance from mult... |
7,182,229 | 7,182,276 | Linking to Shared Library in Qt | I've just created tinyxml as a shared library, and would like to figure out how to link it. How is this accomplished?
| You have to add includepath and libs in your pro file.
Something like the following. Just change your paths.
LIBS += -ltinyxml
LIBS += -L/libs/tinyxml/lib
INCLUDEPATH += /libs/tinyxml/include/
|
7,182,277 | 7,182,376 | Strange error when trying to declare enum in C++ Visual Studio 2010 | I'm having a strange issue compiling and old C++ Visual Studio 5 project in Visual Studio 2010. There is a nagging compiler error I cannot get rid of that appears to be related to the enumeration "DBTYPE". A snippit of the .h file is given below with a few extra lines incase the error is coming from above:
struct CBr... | Are you using OleDb somewhere? (or something that includes its headers) It defines a DBTYPE type (in oledb.h). That could cause a conflict.
|
7,182,290 | 7,191,710 | Can I change the status of individual members of a base class to private? | I am using wxWidgets where, if you have ever used it, you will know that there are a lot of public functions in the base class. I recently ran into a situation where I would not want a method SetText() be called directly from the derived class. That is, the derived class inherited the SetText() function but I do not wa... | There are actually two ways of doing this. Doug T. gave a very good overview of the first one - using private/protected inheritance and composition - so I won't go into that one.
The problem with using private/protected inheritance is that it masks everything. Then, you have to selectively expose the members that you... |
7,182,310 | 7,251,205 | OpenCV ARDrone compile problems | Long story short, I included OpenCV version 2.3.1 (currently the latest) in my modified ARDrone Win32 Client version 1.5 (currently not the latest) and have been struggling ever since to marry the two. I'm using Microsoft Visual Studio 2008 (full version).
To start off, the file I am working with the most in the Win32 ... | As it turns out, ARDrone included its own copy of "intrin.h", the header file that contains _InterlockedExchangeAdd normally. For some reason unknown to me, Microsoft Visual C++ prioritized this new copy over the original, and for some reason again unknown to me, ARDrone's version does not contain _InterlockedExchangeA... |
7,182,315 | 7,183,052 | Displaying a checker board with each square as an object - C++ QT | I'm new to Qt but not too C++. I'm trying to create a checker/chess board where each square is an object. What I'm trying to figure out is how to have each square object be a part of the board object I'm declaring and display that on the screen. I can display a widget on the screen by using MyWidget.show() in the main ... | A few things going wrong in the code:
You are creating the Square object on the stack. in the
Board::Board() constructor. The square is created and deleted right away when it gets out of the constructor. So create it on the heap.
The Square needs a parent so when you create a square do
square = new Square(this);
Yo... |
7,182,359 | 7,241,548 | Template instantiation details of GCC and MS compilers | Could anyone provide a comparison or specific details of how is template instantiation
handled at compile and/or link time in GCC and MS compilers? Is this process different
in the context of static libraries, shared libraries and executables?
I found this doc about how GCC handles it but I'm not sure if the informa... |
Point of instantiation
templates will be instantiated when actually used
Not exactly, but roughly. The precise point of instantiation is a bit subtle, and I delegate you over to the section named Point of instantiation in Vandevoorde's/Josuttis' fine book.
However, compilers do not necessarily implement the POIs cor... |
7,182,445 | 7,182,568 | 2D Array Memory Leak - Should be easy, I feel stupid | Very simple code:
signed int **ifftResults = (signed int **)malloc(sizeof(signed int *) * recordsPerBuffer);
for (int i=0; i < recordsPerBuffer; i++)
{
ifftResults[i] = (signed int*)malloc(sizeof(signed int) * fftLength);
}
Then later:
for (int i=0; i < recordsPerBuffer; i++)
{
free(ifftResults[i]);
}
free(iff... | The code presented as I'm writing this doesn't seem to be sufficient to answer the question of "why".
However, since you're using C++ you can make sure that there's no memory leak by using std::vector.
Like so:
// Allocation.
std::vector< std::vector< int > > fftResults( recordsPerBuffer, std::vector< int >( fftLength... |
7,182,566 | 7,182,585 | C++ filling an array with numbers then returning a pointer to it | Ive been faced with a problem recently that I can't think of a good way to solve. I'm using a case structure to attempt to set attributes to a "character" that will be passed to an object constructor.
Example:
//note this is inside a function with a return type of int*
int selection;
cin >> selection;
int * iPtr;
... | Yes - anArray is declared on the stack. When the function exits, its stack frame is reclaimed, so it's no longer valid to refer to that memory. If you want the array to persist, allocate it on the heap instead:
int* anArray = new int[6]; // and initialize
return anArray;
Just remember to clean it up later at some poin... |
7,182,614 | 7,182,992 | Can I get away with this C++ downcasting fib? | I have a C library that has types like this:
typedef struct {
// ...
} mytype;
mytype *mytype_new() {
mytype *t = malloc(sizeof(*t));
// [Initialize t]
return t;
}
void mytype_dosomething(mytype *t, int arg);
I want to provide C++ wrappers to provide a better syntax. However, I want to avoid the complication... |
Is it possible that, by some streak of luck, this does not actually violate the C++ standard?
I'm not advocating this style, but as MyType and mytype are both PODs, I believe the cast does not violate the Standard. I believe MyType and mytype are layout-compatible (2003 version, Section 9.2, clause 14: "Two POD-str... |
7,182,619 | 7,182,975 | Multithreading: a blocking wait with timeout | I'm using TinyThread++ to get clean and simple platform independent control over threading features in my project. I just came upon a situation where I'd like to have responsive synchronized message passing without pegging the CPU, while allowing a thread to continue to do a bit of work on the side while it is idle. Su... | Well the source code for the wait function isn't very complicated so making the required modificiations looks simple enough:
The linux implementation relies on the pthread_cond_wait function
which can trivially be changed to the pthread_cond_timedwait
function. Do read the documentation carefully in case I forgot abo... |
7,182,703 | 7,182,767 | Creating a custom C type string class in C++ | I have an assignment that I need to create a custom C type string class in C++. I am having trouble getting this to work. Currently my code crashes with a run time error right at the start. I also know many of my function are wrong but I want to get the member functions sorted before I go on and fix the other functions... | Your ctor is pretty much a mess.
You use i for two different things -- at the same time. You also copy the entire contents of str into strPtr once for each character in str.
Basically, you have to decide, are you going to use the C run-time library or not?
Using it:
TStr::TStr(const char *str)
{
strSize = strlen(s... |
7,182,707 | 7,288,679 | OpenGL Rending multiple triangle strips results in gaps | I am in the midst of my first foray into OpenGL using C++ and Qt as the supporting cast.
In what amounts to my playground for implementing a feature outside of the main application, I am attempting to draw what amounts to a mesh surface from a two-dimensional array of floats. The indices of this 2d array are used for t... | I ended up scrapping my rendering and using a library that provided what I needed (once I got it working). The library, for those interested, is QwtPlot3D. It needs some serious performance improvements for my needs, but it has allowed me to bypass this initial hurdle.
|
7,182,880 | 7,182,917 | more than one operator matches these operands | Suppose we have next code:
struct int64
{
long long value;
int64() : value(0) {}
int64(signed char i8) : value(i8) {}
int64(unsigned char u8) : value(u8) {}
int64(short i16) : value(i16) {}
int64(unsigned short u16) : value(u16) {}
int64(int i32) : value(i32) {}
int64(unsigned u32) : va... | You should write operator+ definitions for all the types you are supporting:
int64 operator+(int num) {
return int64(value + num);
}
int64 operator+(short num) {
...
}
...
You're adding an int to an int64 and assigning the result to an int64 but it doesn't have a copy constructor so it's converting it to som... |
7,182,972 | 7,183,216 | How can I implement assert macro as a method? | I want implement assert macro as a method in C++ like .NET Framewrk.
For example in C# we can invoke assert method like this:
Debug.Assert(index > -1);
and I want implement assert something like this:
#include <assert.h>
class debug
{
public:
static void my_asset(<condition>) // like assert macro
{
//... | The only way to get the line number, file, and text version is via macro. However:
#include <assert.h>
class debug
{
public:
static void my_assert(bool passed, const char* assert, const char* file, long line)
{
if (passed == false)
std::cout<<"failed assert "<<assert<<" in "<<file<<" at "<<... |
7,183,102 | 7,183,189 | Why am I getting Multiple Types in One Declaration? | Here is my class:
#include <iostream>
#include "gameobject.h"
#include "IXmlAssigner.h"
#ifndef CHARACTER_H
#define CHARACTER_H
//line 7...
enum Race {HUMAN, DARK_ELF};
enum Gender {MALE, FEMALE};
class Character : public GameEntity, protected IXmlAssigner
{
public:
Character();
Character(std::string xmlCharI... | #include "gameobject.h"
#include "IXmlAssigner.h"
Most likely you're missing a ; at the end of a class or structure declaration at the end of one of these headers.
|
7,183,107 | 7,183,300 | How to get the type of a variable in a macro? | I'm currently using this code for a foreach macro:
#define foreach(T, arr, it) for(T::iterator it = (arr).begin(), itend = (arr).end(); it != itend; ++it)
How can i get rid of the first parameter T and make the compiler figure out which type it should copy/paste in the code T::iterator ? It seems rather silly i need t... | Since this is pre auto and decltype, your best bet is using Eric Niebler's FOREACH macro.
Or upgrade your compiler to VC 2010 and just use auto.
|
7,183,144 | 7,183,218 | Is there anything to be gained by using (const int &var) formal parameters in place of (const int var)? | Is there anything to be gained by using const int &var formal parameters in place of const int var?
I know the advantage in large structs but for PODs the pointer is often of equal size to the actual data. So I guess the answer would be "No advantage". But I think perhaps the pass by value semantics copies once to the ... | Consider this:
Non-reference
Allocate an int on the stack
Copy the value to the stack
Call the function like usual
Use the variable on the stack
Reference
Allocate a pointer on the stack
Copy address of int to stack
Call the function like usual
Dereference the variable on the stack (possibly multiple times in the sa... |
7,183,239 | 7,183,303 | How do you create a global array of strings? | How do you create a global array of strings? I have tried declaring a string outside of main and dynamically initializing it using myString = new string[5];, but I receive the error "No viable overloaded '='" in Xcode. What am I doing wrong?
| Your code snippet is a little terse, but if your full declaration is
string myString = new string[5];
then the problem is that you are trying to assign an array of strings to a variable that's only designed to hold one particular string. You'll want to do
string *myStrings = new string[5];
where the global variable c... |
7,183,258 | 7,183,357 | Problem with C# protected memory | I'm PInvoking a native C++ DLL. Actually I've done it twice (two different C# programs, two different C++ programs). Both times I create the memory on the C# side. Both times I used fairly complex marshalled structs which I send by ref.
However, one of my programs run just fine.
The other one runs until the native C++ ... | If you need the Shared2_s instance to have a lifetime longer than just the call to the native method, you'll need to allocate it in unmanaged memory and clean it up again when done.
var pointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Shared2_s)));
var inst = new Shared2_s();
Marshal.StructureToPtr(inst, pointer, f... |
7,183,318 | 7,184,033 | eigen library selfadjointView problem | I am persistently getting error messages whenever I try to use the selfadjointView property of any matrix or sparse matrix using the eigen library. Below is a simple code to check that. In my program I do try with self-adjoint matrix:
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>
#in... | You have to specify the template argument, so it should read mat.selfadjointView<Upper>() or mat.selfadjointView<Lower>() . The first one means that it should use the entries in the upper triangular part of mat and fill the lower triangular part to make the matrix self-adjoint. The second one is the other way around.
|
7,183,359 | 7,183,690 | Access pixels with Mat OpenCV | I would like to access pixels in RGB with OpenCV 2.3.
I'm trying like this but it's like every pixels are equal frame after frame because I got no output. Images are from my webcam and I can see them.
Btw RED = 0;
THX
Mat frame;
Mat oldFrame;
VideoCapture cap(0);
cap >> oldFrame;
sumFramePix = oldFrame.cols * oldFrame... | Change
oldFrame = frame;
to
oldFrame = frame.clone();
You are creating two Mat objects that point to the same data. clone() makes a deep copy.
|
7,183,665 | 7,183,694 | How to solve "cannot open file 'LIBCD.lib' " in visual studio 2008? | trying to compile some code i downloaded, i get link error LNK1104: cannot open file 'LIBCD.lib'. i cant find this file anywhere on my computer. what is it, and can i download it from somewhere? is there another way to get the code to work?
| The first hit on Google for libcd says:
This file is the static library for the debug single threaded version
of the C runtime. Visual Studio 2005 no longer supports this version
of the C runtime: instead you need to use the multi-threaded version
(libcmtd.lib) or the dynamically linked (DLL) version (msvcrtd.li... |
7,183,741 | 7,183,750 | Access Last Element of Array | I'm trying to access the last element in an array in C++ (more specifically, I'm trying to convert an integer into a character array and then access the last digit). Here's what I've come up with so far:
int number_to_convert = 1234;
char * num_string;
sprintf(num_string, "%d", number_to_convert);
printf("Number: %d S... | For the last decimal digit of n, try n % 10.
To get the textual numeral character for that digit, use '0' + (n % 10).
For any other number base, replace 10 with that base.
The "because I can" way:
std::ostringstream s;
s << n;
char last_digit = *s.str().rbegin();
Or even:
const char last_digit = *static_cast<std::ost... |
7,183,761 | 7,197,766 | Sqlite: How to bind and insert date from C++? | Using C++ (Visual Studio) and sqlite. How do I bind a date to a parameter?
sqlite3_stmt *statement;
const char *sql =
"INSERT INTO employees "
"(full_name,"
"date_started)"
" VALUES "
"(@full_name,"
"@date_started)";
sqlite3_prepare_v2(database_, sql, -1, &statement, NULL);
... | Here's what I figured out. It's working but I'm open to better methods.
time_t rawtime;
struct tm *currentTime;
time ( &rawtime );
currentTime = localtime ( &rawtime );
const int TIME_STRING_LENGTH = 20;
char buffer [TIME_STRING_LENGTH];
// SQLite expected date string format is "YYYY-MM-DD HH:MM:SS" (there are other... |
7,184,003 | 7,187,319 | Load image from binary in MFC | Usually I do the image-loading using LoadImage with path or LoadBitmap with resource ID. But now the target image resource is stored in database(SQLite). So how can I use the binary data directly(avoiding store temporary file) retrieved from the db in MFC?
| Here's the solution I found out ,and it works fine in my project.
1.function for retrieve binary data from sqlite database.
int CSqlite::retrieveBinaryData(int id , byte *pdata)
{
ASSERT(pdata != NULL);
int rc,size;
sqlite3_stmt * stmt;
sqlite3_prepare(dbh,"select id,content,size from images where id =... |
7,184,183 | 7,184,300 | C++ templates with interface objects | I have the following code that doesn't compile.
class Base {
public:
virtual ~Base() { };
};
class Derived : public Base { };
class NotDerived { };
template <typename T>
class Group { };
int main() {
Group<Base> *g = NULL;
g = new Group<Base>(); // Works
g = new Group<Derived>(); /... | You could make Group< Base > a base class of all Group< T > T != Base.
class Base {
public:
virtual ~Base() { };
};
class Derived : public Base { };
template <typename T> class Group;
struct Empty { };
template <typename T>
struct base_for_group_t {
typedef Group<Base> type;
};
template <>
struct ... |
7,184,192 | 7,184,976 | Password protecting embedded firmware download | I need to protect against the users of our product from downloading firmware that is incompatible with the revision of the hardware that they're trying to download to. I'll describe what exists right now and what I'm looking for.
We have an alpha-numeric hardware part number and revision stored in EEPROM that is only f... | Forget the passwords.
The simplest way to do this is to include in the firmware file, at a known location, a list of compatible hardware IDs. This could be stored as a length-prefixed array. When a new firmware is to be loaded into a device, the device looks for its own hardware ID in the list, and rejects the firmwa... |
7,184,303 | 7,184,387 | printf a buffer with nulls | Is there some fancy printf syntax to ignore nulls when printing a string?
Example use case: printing a network packet that contains a bunch of null terminated strings.
My test code to illustrate the issue:
#include <cstdio>
#include <cstring>
void main()
{
char buffer[32];
const char h[] = "hello";
const c... | printf assumes strings are c-style (i.e. ending in null characters). You need to do one of the following:
1) use the write method of ostream (C++ style)
2) use the write command (from unistd.h, C style)
3) iterate through each character and print.
When I am debugging packets, oftentimes I will print out each characte... |
7,184,332 | 7,184,702 | allegro library 4.4 korean broken | I am working with allegro 4.4 library.
When I print a Korean character, the character is broken.
English character isn't in Allegro Manual.
Allegro says "Allegro uses UTF8 encoding by default."
I have no idea of what was wrong with the following code, and what to fix.
textout_ex(screen,font,"한글(korean)", 24, 2,
... | It sounds like you did not load a font that has Korean glyphs. Alternatively, the Allegro loading functions simply didn't load the Korean glyphs from the font file. So first check the font to see if it has the glyphs you need, then check Allegro's documentation to see how to make it load them.
Note: just because a libr... |
7,184,398 | 7,184,453 | C++ Usage of switch statement | int i = 10;
switch( i )
{
case 1:
// do sth1
break;
case 2:
// do sth2
break;
case 3:
// do sth3
break;
default:
// do sth default
break;
}
Question 1> When the switch statement executes, do we jump directly to the right case statemen... | Question 1: Depends on the compiler. C++ standard does not require that a jump table be set up.
In many cases, especially with small number of sparse cases, GCC, MSVC and other compilers will do clause-by-clause check (as if it were an if statement). To give an example, suppose your cases were 1, 15, and 1000000. ... |
7,184,621 | 7,184,649 | Why can't C++ infer the template type? | Why can't the compiler figure out these template parameters? Is there a way to make it do so?
(I'm using Visual Studio 2010.)
template<typename T, typename TFunc>
void call(TFunc func) { func(T()); }
void myfunc(void *) { }
int main() { call(myfunc); }
| T appears nowhere in the parameter list so T cannot be deduced from the function arguments. All types to be deduced must appear in deduced contexts in the parameter list. For example,
template <typename TReturn, typename TParameter>
void call(TReturn (*f)(TParameter))
{
f(TParameter());
}
|
7,184,698 | 7,185,101 | How do I convert a int to LPCTSTR? Win32 | I would like to display an int value in a win32 MessageBox. I have read some different methods to perform this cast. Can someone provide me with a good implementation.
New to Win32 programming so go easy :)
update
So this is what i have so far. It works.. but the text looks like Chinese or some other double byte chara... | LPCTSTR is defined like this:
#ifdef UNICODE
typedef const wchar_t* LPCTSTR;
#else
typedef const char* LPCTSTR;
#endif
std::string::c_str() returns a const char* only. You can't convert a const char* directly to const wchar_t*. Normally the compiler will complain about it, but with the LPCTSTR cast you end up forcing... |
7,185,135 | 7,185,176 | c++ multimap equal_range found nothing | How can I know the equal_range didn't find any match cases?
like:
multimap<string,string> mapdic;
pair<multimap<string,string>::iterator,multimap<string,string>::iterator> ret;
// insert some string pairs
ret=mapdic.equal_range(thisUpperCaseName);
if (???)//how to test equal_range find nothing?
{
}el... | :)
say your equal_range returns result of type pair
If your result.first == result.second then it means there is nothing.
If there is even a single element then result.first != result.second
if(ret.first == ret.second)
{
// empty range
}
else
{
//at least an element.
}
|
7,185,159 | 7,187,591 | QImage::load causes application to crash | I have no idea why but this code causes my application to crash. When I use a brand-new pointer to a QImage in the setPicture method, it doesn't! What could cause this behavior?
Canvas class:
#include <QtGui>
class Canvas : public QWidget
{
Q_OBJECT
public:
QImage *p;
Canvas();
void setPicture(QStrin... | The pointer to the Canvas class was declared and instantiated in the constructor of the Window class instead of using the privately declared pointer.
If I'm not mistaken, the pointer to the Canvas in the window's constructor went out of scope by the time the browseFile method was called.
Should have been:
class Window ... |
7,185,275 | 7,185,329 | How do I view the compiled machine code or byte code for a C++ function in Visual Studio 2010? | What is the best (quickest) way to view the code that the compiler generated from my files? I'm using mostly C++ but a solution that works for .NET languages would be very welcome as well.
| Within Visual Studio, go to the property pages for your project, then go to C/C++ → Output Files → Assembler Output. It should look something like this:
Note the corresponding compiler switches, all variants of /FA.
/FA: Assembly-Only Listing
/FAcs: Assembly, Machine Code and Source
/FAc: Assembly With Machine Code
... |
7,185,437 | 7,185,833 | Is there a range class in C++11 for use with range based for loops? | I found myself writing this just a bit ago:
template <long int T_begin, long int T_end>
class range_class {
public:
class iterator {
friend class range_class;
public:
long int operator *() const { return i_; }
const iterator &operator ++() { ++i_; return *this; }
iterator operator ++(int... | The C++ standard library does not have one, but Boost.Range has boost::counting_range, which certainly qualifies. You could also use boost::irange, which is a bit more focused in scope.
C++20's range library will allow you to do this via view::iota(start, end).
|
7,185,474 | 7,185,547 | Why does this functor ("lambda") give a weird warning? | When I compile and run this with Visual C++ 2010:
#include <iostream>
int main() {
int subtrahend = 5;
struct Subtractor {
int &subtrahend;
int operator()(int minuend) { return minuend - subtrahend; }
} subtractor5 = { subtrahend };
std::cout << subtractor5(47);
}
I get the correct a... | The first two warnings are just letting you know that the implicitly declared member functions cannot be generated due to the presence of a reference data member.
The third warning is a Visual C++ compiler bug.
All three warnings can be ignored with no ill effects, though you can easily make all three go away by making... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.