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,874,362 | 7,874,452 | How to use two functions, one returning iterator, the other returning const_iterator | So I have a function called find, which has two versions:
template <typename T>
typename btree<T>::iterator btree<T>::find(const T& elem)
{
//Implementation
}
and the other is the const_iterator version:
template <typename T>
typename btree<T>::const_iterator btree<T>::find(const T& elem) const
{
//Implement... | All the standard containers implement conversion of non-const to const iterators (as specified in the requirements for the Container concept):
The type of iterator used to iterate through a container's elements. The iterator's value type is expected to be the container's value type. A conversion from the iterator type... |
7,874,464 | 7,874,496 | C++ vector of pointer to object - max_size() | I have a class apples
class apples
{
private:
double x;
double y;
double z;
public:
//some methods
};
I want to store the pointer to apples objects in a vector.
I am doing this so that i create any object in any file & use any object in any file.
I used the following code to determine the m... | This is library limitation for storing elements in a vector.
vector::max_size() :
Returns the maximum number of elements that the vector container can
hold.
This is not the amount of storage space currently allocated to the
vector (this can be obtained with member vector::capacity), but the
maximum potential siz... |
7,874,549 | 7,874,641 | Dumping values in Windbg and padding | I am dumping a class in Windbg (by dt) and for a bool member I see the value fffffffffffffff8 (bin: ...1111111111111111000). It is a valid value (including padding) or not?
PS: i'm investigating a dump that may be a memory corruption so .. can't be sure.
PS2: my bool is in class between a pointer and a size_t. Compile... | It's not a valid bool value -- bool should only show up as 0 or 1. Since you're seeing 0xf8, the memory is either not initialized or overwritten. (Note that for some reason, WinDbg will only read a single byte and then sign-extend it to 64-bits.)
|
7,874,590 | 7,874,796 | Implement no-op functor using boost::bind | I have a function void get(boost::function<void(void)> callback) { callback(); }.
I want to make a call like get(boost::bind(/* don't know what to put here*/)); without implementing any other functions, variables or structs, so that the callback does nothing.
Is it possible to implement such "no-op" callback in C++03 ?... | You could use something like boost::bind(std::plus<int>(), 0, 0), which should be optimised away to nothing.
It would make the code rather clearer if you relaxed your restriction and defined a no-op functor instead.
|
7,874,613 | 7,890,577 | play mp3 sound buffers on linux | I want to be able to play an mp3 audio sound buffer on Linux which I am receiving on a specific port. This a continuous live stream. I have looked at pulseaudio, portaudio, mpg123 amongst many others but can't seem to know what to do.
The mp3 sound is received from another computer on network where it is converted usin... | Have you looked at madplay?
http://www.underbit.com/products/mad/
http://alcor.concordia.ca/manpages/sys1/madplay.1.html
It can read MP3 data from standard input. You may redirect the data you read from the socket to madplay's standard input with a simple program, or even with a shell command:
netcat <hostname> <port... |
7,874,624 | 7,879,758 | How can we create custom slider? | I want to create a slider which contain a different slider handle and i want to paint it according to slider handle position in the slider.
| If I understand you correctly, you want a slider that changes not only its position but also its appearance as you slide, right? For example, a mix of QDial and QSlider, ie. a slider with a turning knob.
If so, you will need to subclass either QSlider or QAbstractSlider (or QDial) and do the painting in your own paintE... |
7,874,735 | 7,874,765 | Model slowing down the game - opengl | I have a problem while running my game. The model that I import in the game is quite big, making the fps drop down. That's okay but when I get the camera off from the model, it still stays slow. As other games do, when looking at a high resolution model, the game slows down but when not looking at it, it gets faster. H... | You need to implement clipping, so that you don't render the object (i.e. pass it through the graphics pipeline) when it's not visible.
There are many techniques and algorithms/data structures for this, ranging from manual view frustum-testing, to more advanced spatial-querying data structures (BSPs, quadtrees, octrees... |
7,874,816 | 7,874,898 | Sharing Common objects - warning "defined but not used" | I have a number of C++ classes, alot of them (not all) share two "static size variables" e.g.
share.h
/*Other variables in this header used by all classes*/
static size width=10;//Used by about 60%
static size height = 12;//used by about 60%
So I placed them in a header file along with other objects that all cla... | Either declare them const, or declare them extern and define them in exactly one source file. A compiler should expect constants to be defined (in header files) but not used, and not give a warning for that.
Defining static variables that you don't use is often a sign of an error, so the warning is useful in that case.... |
7,875,069 | 7,875,089 | Get ID of executing Process/Thread in C++ Builder | Let's say I have a class with the function
class foo
{
...
void bar() {
OutputDebugString(........);
// mode code
}
}
Is it possible to print the ID of the current thread (or if it's the main application) that is executing the function using OutputDebugString?
I have a large application I'm debugging ... | Have a look at the GetCurrentThread function.
|
7,875,138 | 7,878,573 | How does boost::function support template class with different length template parameters | I want to use boost preprocessor to declare template classes with different template variable length, basically like what boost::function does.
#if !BOOST_PP_IS_ITERATING
#ifndef D_EXAMPLE_H
#define D_EXAMPLE_H
#include <boost/function>
#include <boost/preprocessor/iteration/iterate.hpp>
#define BOOST_PP_ITERATION_PAR... | You need to declare the template class with the most parameters first, with default values for all parameters except the first one. The template classes with less parameters can then be defined as specializations of the main template class. Example:
#include <iostream>
template<class A, class B = void, class C = voi... |
7,875,161 | 7,886,364 | gSOAP Webservice, Error while compiling | Im using Netbeans IDE 6.9 with G++ Compilingtools on Ubuntu 10.10. If i try to compile my webservice i get the following errors:
build/Debug/GNU-Linux-x86/main.o: In function `main':
/home/mark/NetBeansProjects/stonService/main.cpp:11: undefined reference to `stonSoapBindingService::stonSoapBindingService()'
/home/mark... | i found the solution to my problem, it was because i didnt had all functions in the wsdl file in my main.cpp!
|
7,875,241 | 7,875,317 | Activating C++11 support in Clang | I've downloaded and built clang version 3.0 in order to play around a bit with C++11 features, however I get this error (even though I am using the -Wc++11-extensions flag).
S:\llvm\code>clang++.exe -Wc++11-extensions variadic.cpp
variadic.cpp:4:19: warning: variadic templates are a C++11 extension [-Wc++11-extensi... | You are getting a warning, not an error.
The -W switch is used to enable compiler warnings. So for my understanding, by using -Wc++11-extensions you tell the compiler to warn you if you are using C++11 extensions.
And thats exactly what happens here.
|
7,875,551 | 7,875,578 | Why string-to-float conversion may not work? |
Possible Duplicate:
Precision of Floating Point
Can you compare floating point values exactly to zero?
floating point issue
In my c++ code I have the string: "0.55".
And I want to convert it to float value "0.55", but all function I used give me the float value "0.55000001".
Why? How can I take the clear value?
Last... | Floats are not exact. This is because there are infinite number of possible values, but only finite number of bits to represent them!
So because 0.55 cannot be represented, it gives you the value 0.55000001 instead.
More info can be found in: what every programmer should know about floating points arithmetics
|
7,875,581 | 7,875,721 | C++: Get index of char element in array | I need to get number of character in array.
const char myarray[5] = {'0', 'a', 'e', 'f', 'c'}; // Create array of char
int number=0; // Create variable
number = getposition(myarray, 'f'); // Now number equals to 3
number = getposition(myarray, 'z'); // -1, because array doesn't have this char
My task is easy because a... | A little bit more C++:
#include <algorithm>
int getposition(const char *array, size_t size, char c)
{
const char* end = array + size;
const char* match = std::find(array, end, c);
return (end == match)? -1 : (match-array);
}
A lot more C++:
template <typename T, size_t N>
int getposition(const T (&arr... |
7,875,764 | 7,875,821 | Using QSharedPointer with new[] yields "Mismatched free() / delete / delete[]" in valgrind | I have the following code:
QPair<QSharedPointer<unsigned int>, int> someclass::somefunction() {
int siz = data_size();
QSharedPointer<unsigned int> buffer(new unsigned int[siz]);
// Fill the buffer...
return qMakePair(buffer, siz);
}
At some point, the QSharedPointer returned by this function will go... | One way to fix this is to write a custom deleter and pass that to the constructor of QSharedPointer like so:
template <typename T_>
void do_delete(T_ buf[])
{
delete[] buf;
}
And then
QSharedPointer<unsigned int> buffer(new unsigned int[siz], do_delete<unsigned int>);
I am not sure whether there is a more elegant... |
7,876,156 | 7,876,635 | OpenMP: run two functions in parallel, each by half of thread pool | I have a CPU consuming function do_long that I need to run on two different datasets.
do_long(data1);
do_long(data2);
do_long() {
#pragma omp for
for(...) {
// do proccessing
}
}
I have N threads available (depends on machine). How to tell OpenMP that I want that both do_long
functions are run in para... | One approach is to do it using nested parallelism:
void do_long(int threads) {
#pragma omp parallel for num_threads(threads)
for(...) {
// do proccessing
}
}
int main(){
omp_set_nested(1);
int threads = 8;
int sub_threads = (threads + 1) / 2;
#pragma omp parallel num_threads(2)
{
... |
7,876,215 | 7,876,319 | Should I join a thread that has been killed? | I have many joinable threads that at some point need to all stop. The threads are pthread, but are created through RTAI's user-space interface (never mind the RTAI though).
For each thread I have a variable that I can set to tell them to quit. So what I do is:
set that variable for each thread so that they stop
Wait a... | Killing a thread doesn't change whether you should join it or not. If
the thread hasn't been detached, then you need to join it, or you will leak
resources in the system.
|
7,876,241 | 7,881,314 | Portable text based console manipulator | Applications can manipulate text based consoles or terminals, and change their colors, set cursor position. The supported approaches are:
For Unix-like systems: There is ANSI escape code.
For Windows systems: There is APIs like SetConsoleTextAttribute.
...
but, is there any lightweight and portable C/C++ library whic... | Alright, i finally found a portable and easy to use library: rlutil.h
Usage:
#include <iostream>
#include "rlutil.h"
int main()
{
for (int i = 0; i < 16; i++)
{
rlutil::setColor(i);
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
but, i will be glad for other suggestion... |
7,876,594 | 7,876,646 | String vs byte array, Performance | (This post is regarding High Frequency type programming)
I recently saw on a forum (I think they were discussing Java) that if you have to parse a lot of string data its better to use a byte array than a string with a split(). The exact post was:
One performance trick to working with any language, C++, Java, C# is
t... | He's saying that if you break a chunk text up into separate string objects, those string objects have worse locality than the large array of text. Each string, and the array of characters it contains, is going to be somewhere else in memory; they can be spread all over the place. It is likely that the memory cache will... |
7,876,609 | 7,876,960 | Do Ribbon based MFC applications work on Windows pre-Vista/7? | Can MFC applications with Ribbon toolbars built under VS2010 be run on versions of Windows that were released before the ribbon was designed - e.g. XP or W2K, not just Vista or W7?
If no, what (if anything) can be done to make them work?
| Yes, they will run on XP with SP3.
But not for older systems, as applications compiled with VS2010 require at least XP SP3 to run (requirement of the C-Runtime library).
|
7,876,644 | 7,876,794 | Why does this code crash | Well this is a layman's attempt on blurring an image, i am not using any specific [already known] alogrithm, i am implementing my own technique.
float k[][5]= { .01, .01, .01, .01, .01,
.01, .01, .01, .01, .01,
.01, .01, .01, .01, .01};
for( row = 0; row < rows; ++row)
{
... | Your j index is out of bound for array k.
It can not be greater than 5 !
In 5th for you should change upper bound to 5 not 6.
|
7,876,649 | 7,876,781 | C++ Multithreading and Events | I have a C++ application which has the following structure:
Class AAA: has some functions and one of them function that opens a thread.
Class BBB: has some functions and one of them function that opens a thread.
Class CCC: call AAA and BBB that both internaly in their functions open the treads.
In AAA thread in some ca... | I don't understand too much your problem, is a bit too generic.
And you didn't specify what kind of multithreading libraries are you using.
To send messages between threads usually Message Queues are used, with wait handles, lock and semaphores to synchornize them.
Of course you need a safe multithreading queue to send... |
7,876,839 | 7,886,926 | Reading Shared Memory from x86 to x64 and vice versa on OSX | If I create a SM from 64 bit application and open it on 32 bit application it fails.
//for 64 bit
shared_memory_object( create_only, "test" , read_write) ;
// for 32 bit
shared_memory_object (open_only, "test", read_write);
file created by 64bit application is at path as below:
/private/tmp/boost_interprocess... | I found the solution to the problem and as expected it is a bug.
This Bug is present in tmp_dir_helpers.hpp file.
inline void get_bootstamp(std::string &s, bool add = false)
{
...
std::size_t char_counter = 0;
long fields[2] = { result.tv_sec, result.tv_usec };
for(std::size_t field ... |
7,876,947 | 7,878,148 | c++ including eigen in my makefile | This seems to be the correct answer to my problem, however I think it's more the way I am writing my makefile as I already have the steps described in the link below (I know how to build things).
How to write a makefile for a C++ project which uses Eigen, the C++ template library for linear algebra?
Error:
SASAGeometry... | (Note, read comments to get gist of the final solution. I will update the answer when I have clarification from the original poster of the question.)
Sometimes it is the obvious, which is easy to miss. Please check that your user has read permissions for all files and directories in /usr/local/include/eigen2 and /usr... |
7,877,001 | 7,877,035 | Match fixed-size array of CRTP class | its templates again ;-) Given the following template member functions and CRTP class:
template<typename T>
struct base
{
...
};
struct derived : public base<derived>
{
...
};
struct some_class
{
template<typename T>
void match(base<T>* array, size_t count)
{
...
};
template<typename... | An array of Derived cannot be converted to an array of Base. If you ever did anything with the array except access the first element in the first constructor, it would be Undefined Behaviour.
Taking the reference correctly protects you from this situation, as the code doesn't compile. However, it will compile by decay... |
7,877,016 | 7,877,141 | File path of .exe File in windows 7 | I am working in a C++ project. I need to obtain the path of a installed software. (Eg. skype.exe) Is there any way to find the path via C++ coding or via Widows command prompt
| Depends what you are needing it for, and how generic you want it.
You can use GetEnvironmentVariable to get the PATH variable, and search these paths.
You can use the App Paths registry key, as Gabe says. See also...
Usually there are pretty clear application-specific ways to find the path via the registry. Either via... |
7,877,074 | 7,877,871 | doxygen line breaks for lenghty c++ template types | I've got a compile-time recursive type that looks somewhat like this:
template <typename DataType, typename LeftNode, typename RightNode>
struct fixed_tree{
fixed_tree(const DataType& data, const LeftNode& left, const RightNode& right) : data_(data),left_(left),right_(right){}
DataType data_;
LeftNode l... | IMO that's definitely something you should typedef out. Including the entire type when so long is poor practice. Doing so would solve the doxygen issue, as well as making a much simpler type (I can see typos coming from the current one quite easily). If that tree is deep, you should also pass by reference.
In doxygen, ... |
7,877,293 | 7,877,437 | Non-type variadic function templates in C++11 | I saw a blog post which used non-type variadic templates (currently not supported by gcc, only by clang).
template <class T, size_t... Dimensions>
struct MultiDimArray { /* ... */ };
The example in the post compiles fine but I failed to get it to work with function templates.
Can anyone help figuring out the correct s... | You are simply confusing type names and non-type names. What you want simply doesn’t work.
You can probably use variadic non-type templates in functions, but not as (non-template) arguments:
template <int N, int... Rest>
int max()
{
int tmp = max<Rest...>();
return N < tmp ? tmp : N;
}
std::cout << max<3, 1, 4... |
7,877,335 | 7,877,592 | How can I ease the syntactic overhead of checking iterator values in C++? | Basically, I'm a bit tired of writing:
std::map<key_t, val_t> the_map;
...
auto iterator = the_map.find(...);
if(iterator != the_map.end()) { // note the "inversed" logic and logically superflous end() call
...
}
What really made sense would be:
if(auto x=the_map.find(...)) {
... // x could either be an iterator o... | You could write a class template auto_iterator_impl and use it through a function template auto_iterator which returns an instance of auto_iterator_impl, which can be implicitly converted into true or false:
A working implementation with minimal functionalities and consideration:
template<typename C>
struct auto_iterat... |
7,877,383 | 7,885,646 | Can I trust local variable value when analyzing a dump with Windbg? | I see strange things like a pointer values changing the values (0 or something valid) between 2 calls with no change. Same with a enum values. The values are simply forwarded, no chances to be modified. The dump is minidunp.
| You can use dv /V to reveal if a local variable is living in a register.
Like here:
0:000> dv /v
@ecx this = 0x0018fe10
To get rid of this, you must remove optimization when compiling.
|
7,877,553 | 7,877,634 | Very surprising perfs of fprintf vs std::ofstream (fprintf is very slow) | I was running some benchmarks to find the most efficient way to write a huge array to a file in C++ (more than 1Go in ASCII).
So I compared std::ofstream with fprintf (see the switch I used below)
case 0: {
std::ofstream out(title, std::ios::out | std::ios::trunc);
if (out) {
ok = true;
... | fprintf("%d" requires runtime parsing of the format string, once per integer. ostream& operator<<(ostream&, int) is resolved by the compiler, once per compilation.
|
7,877,993 | 7,878,439 | C++ create array of objects (from different classes) | I need to create a array that holds objects from multiple classes.
Example
class baseClass
{
//
};
class first : baseClass
{
//
};
class second : baseClass
{
//
};
How do I create array that can hold first and/or second object inside it?
It is somewhat of a home-task for me so I am forced to use arrays, I ... | baseClass *array[10];
baseClass **array2 = new baseClass *[size];
This is the simplest and most dangerous way. You have to be careful about the lifetime of the objects in order to avoid leaking or double freeing. You also have to be careful with the array's allocation and deallocation, especially if you have to change... |
7,878,124 | 7,878,196 | Are Local class, Inner class and Nested class are the same things in C++? | Are Local class, Inner class and Nested class mean same things in C++?
| Local Class and Nested class are different beasts.
A Nested class is a class declared within the scope of another class.
A Local class is declared within a function definition.
Inner class is a non standard C++ term, So I am not sure how to define it.
Nested Classes:
IBM Documentation as a nice documentation here.
To... |
7,878,182 | 7,878,720 | SymLoadModule64 and GetCurrentProcess from C# | I want to use the dbghelp library to get some type and program information from a pdb file. Now, because I like C# much more than C++, I'm currently trying to get it working from within C#. I'm currently stuck at a call to SymLoadModule64. I've got a working call in C++, looking like this:
const TCHAR* pModName = argv[... | The process handle that you pass as the first parameter to SymLoadModule64 can be an arbitrary value, it does not actually have to be a valid handle to a process. However, for every process handle you want to use, you must first initialize dbghelp for that value by calling SymInitialize.
As for GetCurrentProcess, the v... |
7,878,244 | 7,880,144 | Converting std::function<void(string, string)> to a generic std::function<void()> | I'm trying somme features of c++0x (under gcc 4.5):
I know it's possible to convert a std::function<void(string, string)> to std::function<void()> when arguments are specified at compilation; but is it possible when arguments are submitted at runtime ?
#include <iostream>
#include <utility>
#include <string>
using na... | The question doesn't really make sense.
I know it's possible to convert a std::function<void(string, string)>
to std::function<void()> when arguments are specified at compilation;
but is it possible when arguments are submitted at runtime ?
If you're talking about doing this to set the arguments "at compilation":... |
7,878,361 | 7,878,434 | boost: readline for tcp client | I'm developing a tcp server in c++ using boost. I'd like process incoming data line by line and am looking for a socket.readLine method. However, I can only find a read_some() method. I don't what the definition on "some" is, but I don't think the string necessarily ends with a "\n".
So how can I implement socket.read... | I assume you are using boost::asio. If so, there is a read_until() function that does what you want.
http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/reference/read_until.html
|
7,878,768 | 7,878,814 | When to use merge sort and when to use quick sort? | The wikipedia article for merge sort.
The wikipedia article for quick sort.
Both articles have excellent visualizations.
Both have n*log(n) complexity.
So obviously the distribution of the data will effect the speed of the sort. My guess would be that since a comparison can just as quickly compare any two values, no m... | While Java 6 and earlier versions use merge sort as the sorting algorithms, C# uses QuickSort as the sorting algorithm.
QuickSort performs better than merge sort even though they are both O(nlogn). QuickSort's has a smaller constant than merge sort.
|
7,878,906 | 7,878,968 | Curious DllImport issue, when passing a LONG parameter memory corruption | I've created a DLL function for using inside C# using DLLImport but having troubles in calling the method, as I'm getting memory corruption problems;
[DllImport("mydll.dll", EntryPoint = "callinmydll")]
public static extern int testdllcall(double *firstinput, long firstcount, double *secondoutput, long secondcount);
H... | In Win32 C, a long is still 32-bits. Your C# signature is using a long which is 64-bits. Your second and forth parameter should be an int in the C# signature.
See this table for more information.
So your signature looks like so:
[DllImport("mydll.dll", EntryPoint = "callinmydll")]
public static extern int testdllcall(d... |
7,879,062 | 7,879,094 | How do I convert uint8_t (Uint8 in SDL) to a string? | (I have just answered this question after searching for a while, so I am asking and answering this question here for it to be here when it's needed. There are similar, but not quite the same, questions.)
| Cast it to int. This can be consumed by a stringstream or otherwise converted for string use.
Where colour was a struct SDL_Color containing Uint8 (a defined alias for uint8_t) members, the solution was
stringstream ss << "[colour=" << (int)colour.r << ", " << (int)colour.g << ", " << (int)colour.b << "; light=" << lig... |
7,879,233 | 7,879,793 | Getting VBOs to work | I have problems getting OpenGL to work, basically I am getting alternate black and grey screens. I have it working fine using the fixed function pipeline (glBegin(), glEnd() and glTexCoord...) I think I am doing something very wrong, pretty new to this stuff. Any help would be appreciated.
struct Quad
{
float x0, y... | You seem to be trying to use some odd combination of vertex arrays and VBOs. Try this walkthrough.
Strange things:
gl*Pointer() calls should use zero-based "pointers" instead of real pointers if you're using VBOs.
Your Quad struct is kinda weird. I'm not quite sure you can write
usable stride values for it. Try an... |
7,879,274 | 7,879,995 | Memory Access violation C++ Borland | class Register
{
private:
DWORD ax,dx,cx,bx; // POH
DWORD bp,sp;
DWORD flag, ip;
public:
//====================================================
Register()
{
ax = 0x0;
dx = 0x0;
cx = 0x0;
bx = 0x0;
bp = 0x0;
memset(&this->s... | This is why (as far as I can tell given what you posted)
Register *PReg;
PReg is not valid. Sure, you declare it, but you never initialize it, so its value is indeterminate and dereferencing it results in undefined behavior. You need to new it or initialize it with a valid pointer from somewhere else. Simply declar... |
7,879,326 | 7,879,356 | How to apply transform to an STL map in C++ | In C++, I'm using transform to change all the values of a map to uppercase.
std::map<std::string, std::string> data = getData();
// make all values uppercase
std::transform(data.begin(), data.end(), data.begin(),
[](std::pair<std::string, std::string>& p) {
boost::to_upper(p.second);
... | You are missing the const in the first type of the pair.
[](std::pair<const std::string, std::string>& p) {
However this is not your problem: You cannot use a map as the OutputIterator, as they do not support assignment. You can, however mutate the second argument using std::for_each.
Good old map_to_foobar:
std::for_... |
7,879,364 | 7,882,929 | gtkmm builder from glade file doesn't work | My gtkmm program won't show any windows. Compile works fine. These are the messages I get when running:
(process:2312): GLib-GObject-CRITICAL **: /build/buildd/glib2.0-2.24.1/gobject
/gtype.c:2706: You forgot to call g_type_init()
(process:2312): GLib-CRITICAL **: g_once_init_leave: assertion
`initialization_value... | Add the following line as your first line in main:
Gtk::Main kit(argc, argv);
According to the Gtkmm Hello World tutorial:
First we instantiate an object called kit. This is of type Gtk::Main. Every gtkmm program must have one of these.
This object is the responsible to initialize all the GTK+ library, that includes... |
7,879,385 | 7,879,484 | Qt respond to keyPressEvent in child QWidget | I have a QWidget derived class as such:
class tetris_canvas : public QWidget
{
Q_OBJECT
public:
tetris_canvas(QWidget * parent = 0);
~tetris_canvas();
protected:
void paintEvent(QPaintEvent *event);
void keyPressEvent(QKeyEvent *event);
};
//Never hits this keyPressEvent!!!
void tetris_canvas::ke... | The QWidget::keyPressEvent says this:
A widget must call setFocusPolicy() to accept focus initially and have focus in order to receive a key press event.
So you should do that. (Since you're not showing your constructors, I'm guessing you missed that part.)
Also the line after that says:
If you reimplement this hand... |
7,879,529 | 7,942,186 | Consolidating code for merge_sort - Validation | I found this example of merge_sort here at cprogramming. I'm tyring to break down the algorithm to understand the alogrithm with in the context of quick sort another SO post.
EDIT:
I've updated/fixed the code and posted it as an answer below. This is a working merge_sort.
| The code posted here could use some improvements in readability...Here they are. Verified this is a working merge_sort:
#include "c_arclib.cpp"
void merge_helper(int *input, int left, int right, int *scratch)
{
if(right == left + 1)
{
return;
}
else
{
int i = 0;
int length = right - left;... |
7,879,584 | 7,879,659 | Boost example doesn't compile on VS2010? | I was trying to get one of the boost examples from the website to work:
http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/example/http/client/async_client.cpp
but whenever I built and tried to execute, I kept getting the following from VS2010:
1>------ Build started: Project: highfreqdemo, Configuration: Debug W... |
Add directive to 'StdAfx.h' or rebuild precompiled header
Your project is configured with precompiled header support but you have not included the precompiled header in your source file.
The precompiled header file (in this case, StdAfx.h) needs to be included at the very top of every source file that is configured ... |
7,879,630 | 8,210,848 | Using C++0x in Xcode 4.2 project via CMake | I'm using CMake to generate a project file for Xcode 4.2 on OSX Lion, and I'm using some of the C++0x features in LLVM like nullptr and auto. In order to use these, Xcode requires that 2 project settings be set:
C++ Language Dialect set to C++0x [-std=C++0x]
C++ Standard Library set to libc++ (LLVM C++ standard library... | after digging into this for a little, these are the commands to set the appropriate xcode settings:
set(CMAKE_XCODE_ATTRIBUTE_GCC_VERSION "com.apple.compilers.llvm.clang.1_0")
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++0x")
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++")
set(CMAKE_CXX_FLAGS "${CMAK... |
7,879,722 | 7,879,750 | C++ - Access map reference | Sorry. a trivial question on reference map access
if I have:
map<int,string> *items= new map<int,string>();
I do this?
string x = &items[100];
| So, first I ask; why are you dynamically allocating your map? It kind of defeats the purpose of using it in the first place. The map will internally use dynamic allocation for it's items, but the map itself is cheap and you lose the ability to deterministically manage its memory via scope. So, your code becomes:
map... |
7,879,746 | 7,879,770 | C++ - Instantiate derived class depending on context | let's say I have 200 classes named class1, class2, etc derived from class, and a integer between 1 and 200. Is there a way to instanciate specifically one of the derived class depending on the value of my integer? Obviously I could just manually check for every value but I am wondering is there is anything in C++ that ... | You will have to do a switch on your integer, and instantiate the specific class. If you have this int -> class logic somewhere else in your program, you could consider representing it with a compile-time map. Look at Boost.MPL, specifically boost::mpl::map.
|
7,879,789 | 7,879,983 | how to write a appropriate pattern in pcre with C | Now I have a string which has many substring like "href="http://www.AAA.com"" and other characters,
Here my question,In my C code I write :
char pattern[] = "/^href.*>$/g";
and I want to pick up all the urls in the long string. But it doesn's work.Can SomeBody help me? Your help will be appreciated.
Here is the Code:
#... | Try this regex.
myregexp = pcre_compile("href\\s*=\\s*(['\"])(.*?)\\1", 0, &error, &erroroffset, NULL);
Sample code :
pcre *myregexp;
const char *error;
int erroroffset;
int offsetcount;
int offsets[(2+1)*3]; // (max_capturing_groups+1)*3
myregexp = pcre_compile("href\\s*=\\s*(['\"])(.*?)\\1", 0, &error, &erroroffset... |
7,879,908 | 7,881,744 | How do i handle concurrent task with blocking calls in C++? | Lets make this example simple. In C++ I have a performance critical application and it makes numerous calls to the database which blocks. However i need the data before going on so i do need to wait. I would like to yield and let another task run.
Threads are expensive so i have that in mind. My question is since i nee... | threads are not expensive if they are used correctly, and when they are the right tool for the job (alternatives exist). typically, threads are 'expensive' if you:
create them too often
you are distributing the workload incorrectly (are there too many active threads? are your tasks too small? are they all competing fo... |
7,880,058 | 7,880,112 | Double hash before parameter in function call | I see this line in C:
#define log(format, args...) snprintf(buffer + strlen(buffer), 1023 - strlen(buffer), format, ##args);
What does the double pound / hash mean before the last param in snprintf()?
| In standard C, the "##" is for concatenating tokens together within a macro. Here, this macro is not in standard C, but in "Gnu C", the dialect implemented by GCC. The "##" is used to remove the comma if the extra arguments (in args) turn out to be empty. See the GCC manual.
|
7,880,082 | 7,880,199 | Image blurs only at some parts not all | I am trying to blur an image.
I am using a kernel called k[][3]= { 1, .01, 1, .01, 0, .01, 1, .01, 1};
The code is as follows:
void blur(IplImage *notgray)
{
IplImage *img = cvCreateImage(cvGetSize(notgray), notgray->depth, 1);
cvCvtColor(notgray, img, CV_RGB2GRAY);
int rows=img->height,cols=img->width,row,... | You set sum = 0; at the wrong place. Since it is only reset at the start of each row, each pixel will be whiter and whiter and...
|
7,880,153 | 7,880,191 | C++ class type as argument | If I have an interface and many classes that implement this interface, can I now pass as argument only the type of the class and not the object?
something like this:
Interface *creatClass(class : Interface){
return new class();
}
EDIT:
template <class T>
IFrame *creatClass(){
return new T();
}
void dfg(){
... | It's called "Template".
template <class T>
T *creatClass(){
return new T();
}
You'll have to call it this way:
class InterfaceImpl : public Interface {...};
// ...
InterfaceImpl *newImpl = creatClass<InterfaceImpl>();
edited
You can also try this, to ensure you only create instances of Interface:
template <class ... |
7,880,170 | 7,880,480 | A variable that is read-only after assignment at run-time? | Fairly new programmer here, and an advance apology for silly questions.
I have an int variable in a program that I use to determine what the lengths of my arrays should be in some of my structures. I used to put it in my header as a const int. Now, I want to fork my program to give the variable different values dependi... | I'd use a function-static variable and a simple function. Observe:
int GetConstValue(int initialValue = 0)
{
static int theValue = initialValue;
return theValue;
}
Since this is a function-level static variable, it is initialized only the first time through. So the initialValue parameter is useless after the first... |
7,880,174 | 7,880,612 | Recovering a function pointer from a boost::any | I want to use boost::any to store heterogeneous function pointers. I get an exception when I try to use boost::any_cast to recast to the function pointer.
Is what I want to do even allowed?
.h:
typedef void(*voidFunction)(void);
struct functionInfo{
CString functionName;
boost::any functionPointer;
};
... |
Is what I want to do even allowed?
Absolutely. As long as you cast it back to exactly the type you gave it.
And that's your problem. You don't. foo2 is not a voidFunction. Therefore, you cannot cast it to one.
The purpose of boost::any is to have a void* that is guaranteed to either work correctly according to the C+... |
7,880,312 | 7,880,538 | PInvoke with pointers - C++ to C# | The following is a PInvoke block in C++ that I'm trying to convert to C#:
typedef PVOID JHANDLE ;
typedef UINT32 JRET ;
#define JEXPORT __declspec(dllimport) JRET
JEXPORT
JInitialize (
OUT JHANDLE* ppHandle,
IN PVOID context,
IN UINT32 flags
) ;
I tried the following call, but it threw a... | You are missing the CallingConvention in your [DllImport] declaration, it is Cdecl.
|
7,880,380 | 7,880,584 | alternative to BOOST_FOREACH with std::set? | What's the best alternative to BOOST_FOREACH when you want to iterate over std::set?
When I try and do what seems to be a reasonable method for iterating over a set I get compile errors. This code:
set<string> nameSet;
string aName;
BOOST_FOREACH(nameSet, aName) {
cout << aName << endl;
}
generates this compile erro... | Works for me. Maybe you have the parameters to BOOST_FOREACH reversed.
#include <set>
#include <string>
#include <iostream>
#include <boost/foreach.hpp>
int main(int ac, char **av) {
std::set<std::string> nameSet(av+1, av+ac);
BOOST_FOREACH(const std::string& aName, nameSet) {
std::cout << aName << "\n";
}... |
7,880,384 | 7,880,409 | Const Correctness - Const Pointer As Function Argument | consider a function like
char* strcpy (char* destination, const char* source);
The given value at (address) source is const because the author of the function wants to show that the value of source will not be changed by strcpy. The pointer itself is not changed by strcpy to. Why not to write
char* strcpy (char* desti... | The pointer itself is passed by value, so there's no point.
|
7,880,389 | 7,880,900 | endianness when using part of int array | I'm trying to pullout values from a uint8_t array.
But I'm having troubles understanding how these are represented in the memory.
#include <cstdio>
#include <cstring>
#include <stdint.h>
int main(){
uint8_t tmp1[2];
uint16_t tmp2 = 511;//0x01 + 0xFF = 0x01FF
tmp1[0] = 255;//0xFF
tmp1[1] = 1;//0x01
fprintf(std... | Don't think of endianness as "within bytes". Think of it as "byte ordering". (That is, the actual bit ordering never matters because humans typically read values in big-endian.) If it helps to imagine that the bits are reversed on a little-endian machine, you can imagine it that way. (in that case, your example would h... |
7,880,658 | 7,880,855 | What is the scope of a 'while' and 'for' loop? | What is the scope of a while and for loop?
For example, if I declared an object within the loop, what is its behavior and why?
| In the following examples all the variables are destroyed and recreated for each iteration of the loop except i, which persists between loop iterations and is available to the conditional and final expressions in the for loop. None of the variables are available outside the loops. Destruction of the variables inside th... |
7,880,811 | 7,881,442 | How to Doxygen comment generated code | I'm using the C preprocessor to generate elements in an enum. Is there a way to write doxygen comments for the generated elements? I can't just run it through the preprocessor before doxygen since that will strip the doxygen comments.
Example:
#define ATTRIBUTES \
X(TITLE, "title") \
X(FILENAME, "filename") \
X(GENR... | Try the following
In the Doxygen configuration file, tell it to process the macros.
In the macro definition, add the Doxygen comments after each member:
#define ATTRIBUTES \
X(TITLE, "title") /**!< title element */ \
X(FILENAME, "filename") /**!< file name element */ \
X(GENRE_ID, "genre_id") /**!< title eleme... |
7,880,841 | 7,881,087 | shared_ptr<void> t(new char[num]) means memory leak? | shared_ptr<void> t(new char[num])
means memory leak?
If so, what is the correct practice in this case.
should I use shared_array<> instead?
I'm editing the bytes pointed by 't' manually for later transfer in a TCP Stream.
|
means memory leak?
No, it means undefined behavior. (Which could have any symptom, including memory leak.) The call to delete must match the call to new. Yours doesn't. You allocate with new[] but destroy with delete.
If so, what is the correct practice in this case. Should I use shared_array<> instead?
There are ... |
7,881,003 | 7,881,068 | Why is shared_ptr<void> not specialized? | shared_ptr<void> is special in that it, by definiton, will invoke undefined behavior by calling delete on a void*.
So, why is there not a shared_ptr<void> specialization which throws a compile error?
| shared_ptr<T> is special in that it is by design allowed to hold a pointer to any pointer type which is convertible to T* and will use the proper deleter without UB! This comes into play with shared_ptr<Base> p(new Derived); scenarios, but also includes shared_ptr<void>.
For example:
#include <boost/shared_ptr.hpp>
st... |
7,881,021 | 7,881,084 | how to avoid duplicate inclusion of a header file | I have the following code:
#ifndef GOOGLESET_PHP_H
#define GOOGLESET_PHP_H
zend_class_entry *googleset_ce;
#endif /* GOOGLESET_PHP_H */
For some reason if I include this header file in more than one cpp file, the compiler shouts that I am declaring googleset_ce more than once. Shouldn't the conditional macros above b... | You need to use the extern keyword:
#ifndef GOOGLESET_PHP_H
#define GOOGLESET_PHP_H
extern zend_class_entry * googleset_ce;
#endif // GOOGLESET_PHP_H
Otherwise the compiler thinks you are declaring the variable in every file that includes this header.
This is one reason global variables are frowned upon.
|
7,881,052 | 7,882,303 | Qt QThread trouble using signal/slot going from worker to gui | I have a Qt application that was developed using Qt Creator and the GUI tool that accompanies it. I have a main thread, TheGui and a worker thread that is created by the main thread, WorkerThread (called thread).
The problem I'm having is when I create a slot in the GUI by using
public slot:
void updateTable(string s... |
Because the signal and the slot are on distinct threads, the connection between them has the Qt::QueuedConnection type. And for queued connections, Qt has to be able to save a copy of the signal parameters, to pass them later to the slot.
So, to inform Qt that the type is copyable, you have to register it with Qt's m... |
7,881,058 | 7,881,090 | In Linux C++, how do you read an environment variable of a specified user? | I know that getenv() returns a value of specified environment variable of the current user, but my code requires root privileges so getenv() would only use the sudo environment variables. I also know that SUDO_USER tells which user is invoking sudo, which is the user environment I want use for getenv().
char* gnome_env... | getenv doesn't tell you about the environment variables of the current user, but the current process. Users are free to have as many environments as they want(and can create processes), for example with the export shell built-in. In every call to execve, the calling program is free to create an entirely new environment... |
7,881,120 | 7,893,153 | Are .Net OpenCV wrappers worth using? | So we have this Image processing course at the university and we'll be using OpenCV extensively. Problem is, OpenCV uses C++ but I'm much more fluent in C# than C++. I know that there are wrappers for OpenCV (OpenCVDotNet, SharperCV, EmguCV,...) But I don't know which to choose.
My questions are :
Which one wraps most... | I have not used EmguCV, but I have used OpenCV for a while now.
From SharperCV's website:
The Emgu CV.Net wrapper is our current recommendation if you want to use OpenCV.
And, OpenCVDotNet looks more like an academic sandbox, so if it were me, I would use EmguCV for any of my research projects that involved C#. Mainly... |
7,881,149 | 7,881,209 | In C++11, when are a lambda expression's bound variables supposed to be captured-by-value? | I have a Visual Studio 2010 C++ program, the main function of which is:
vector<double> v(10);
double start = 0.0; double increment = 10.0;
auto f = [&start, increment]() { return start += increment; };
generate(v.begin(), v.end(), f);
for(auto it = v.cbegin(); it != v.cend(); ++it) { cout << *it << ", "; }
cout << en... | With a lambda expression, the bound variables are captured at the time of declaration.
This sample will make it very clear: https://ideone.com/Ly38P
std::function<int()> dowork()
{
int answer = 42;
auto lambda = [answer] () { return answer; };
// can do what we want
answer = 666;
return... |
7,881,190 | 7,881,602 | Why does Stroustrup's book demonstrate default function template arguments, which weren't allowed at the time? | Can anyone explain me why in chapter 13 of the third edition of C++ Programming Language, Stroustrup illustrates default parameters for function templates, although they are not supported by C++ (pre C++11)? This is the example given by Stroustrup in section 13.4.1:
Explicitly specifying the comparison for each call i... | The author himself explains this on his web site:
Due to an unfortunate oversight, the standard simply bans default arguments for template parameters for a function template. Voted to be corrected in the next standard.
|
7,881,260 | 7,881,321 | Rendering transparent 3d shape(quad) with equal z-order | I render two quads with OpenGL with equal z. When I have DEPTH enabled I get following image, but when it is off I get what I need one fruit over another. Is it possible to draw quads with equal z, as I want? My OGL settings:
glEnable(GL_BLEND); glEnable(GL_ALPHA_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)... | The z-buffer doesn't care about transparency and so you have to sort the drawing order of your quads by their approximate depth.
I would change their depth to be different (you can use an orthographic projection to have them appear the same size) and then draw the further quad first.
Also, it is never a good idea to d... |
7,881,332 | 7,881,360 | C++11 for_each and lambdas optimization | I'm testing the following code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
int main(int argc, char* argv[])
{
std::vector<int> v(10000000);
clock_t then = clock();
if(argc <= 1)
std::for_each(v.begin(), v.end(), [](int& it){ it = 10098; });
else
for(auto it = v.b... | From a first glance, I can say at least that those expressions are not equivalent. Try with this instead:
for(auto it = v.begin(), end = v.end(); it != end; ++it) *it = 98775;
Also, since the exact type of the lambda is passed to for_each, there are pretty good chances that the compiler will inline it resulting in c... |
7,881,384 | 7,889,361 | boost::serialization - is there a portable way to binary-serialize std::wstrings? | I want to serialize some data-structures between a 32bit process and a 64bit process on the same windows machine with boost::serialization.
This answer suggests using eos::portable_iarchive, but when I tried that, I got a STATIC_ASSERT failure:
// implementation only valid for narrow string
BOOST_STATIC_ASSERT(sizeof(C... | From what I've read, the standard approach to serializing wide-character strings is to first encode them as UTF-8 narrow-character strings. This may be more overhead than you want, though.
There's an alternative implementation of a portable binary archive in the Boost.Serialization example directory. The Boost.Serial... |
7,882,010 | 7,882,040 | c++ pointer to function | I'm making a class Button; which constructor is getting a pointer to function, to execute on click. Is there any easy way to define the function I want to give it? Like without name.. for example when I'm creating the button, just to open the scopes and write the function without special name. Because I have to create ... | C++11 introduces lambdas, which are anonymous functions capable of capturing variables.
See our FAQ: What is a lambda expression in C++11?
|
7,882,049 | 7,882,088 | How to insert a new node to a single-linked list, where we do not have a pointer pointed to its head? | Given a pointer that points to an intermediate node (non-head, non-tail) on a single-link list . How to insert a new node just before the node pointed to by the given pointer ?
Example,
Given single-linked list:
A -> B -> C -> D -> E
Given a pointer pointed to C (ptr = &C), and a new node F, how to get
A -> B -... | You should be able to implement this by inserting a new C node to the right, and writing F in the data field of the initial C node.
|
7,882,086 | 7,883,395 | How to allocate SP_DEVICE_INTERFACE_DETAIL_DATA? | SP_DEVICE_INTERFACE_DETAIL_DATA is a variable-length structure, beginning with a field containing its size followed by an array (not a pointer to one).
What is a convenient way to allocate this structure with a desired array length?
| I did it like MSalters suggested:
std::vector<char> rawbuf(sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA) + bufferlen);
SP_DEVICE_INTERFACE_DETAIL_DATA* pDIDD =
reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(&rawbuf[0]);
Edit:
Following Raymond Chen's example (as also discussed on his blog) I could allocate th... |
7,882,529 | 7,882,562 | Double astrisk syntax & Help calling member functions | I'm working a program where there's an Airline class. The Airline class contains a vairable to an array of dynamic Flight objects.
In the Airlines class I have (which can't be edited or changed, this was the header file given to me for the assignment):
//Airline.h
class Airline {
public:
Airline(); ... | Since you are dealing with pointers instead of actual objects, try this:
if(array[i]->getflightNum() == flightNum){ // Notice I am using -> instead of .
found = true;
return array[i];
}
|
7,883,280 | 7,883,286 | Why doesn't scope-resolution work here? | What is the reason why the function bar() can't be overloaded here?
namespace foo
{
void bar(int) { }
struct baz
{
static void bar()
{
// error C2660: 'foo::baz::bar' : function does not take 1 arguments
bar(5);
}
};
}
| It cannot be overloaded because they are at different scopes. The first bar is at foo::bar while the second one is at foo::baz::bar.
The name bar from the outer namespace is hidden by the new declaration. It has to either be called explicitly, or made visible by a using declaration:
static void bar()
{
using foo::b... |
7,883,284 | 7,883,689 | unfound entry point deflateSetHeader at zlib1.dll | I'm trying to install GTK+ 2.16, using Code::Blocks, I set the "gtk" environnement variable and everything. It compiles successfully, the problem rises in run-time when it says "No entry point found for procedure deflateSetHeader in the dynamic library zlib1.dll".
Anyone has an idea about this ? Is this some kind of bu... | Sounds like you have an old version of zlib installed that doesn't contain the deflateSetHeader call. You should locate your dll and replace it with a newer version and/or reinstall a newer version of gtk.
Since Code::Blocks requires this call in zlib1.dll (the source of the failure) it will not be able to run without ... |
7,883,561 | 7,883,579 | Why the linker complains about multiple definitions in this template? | This little piece of code triggers the linker's anger when included on at least two translation units (cpp files) :
# ifndef MAXIMUM_HPP
# define MAXIMUM_HPP
template<typename T>
T maximum(const T & a, const T & b)
{
return a > b ? a : b ;
}
/* dumb specialization */
template<>
int maximum(const int & a, const in... | Its because complete explicit template specializations must be defined only once - While the linker allows implicit specializations to be defined more than once, it will not allow explicit specializations, it just treats them as a normal function.
To fix this error, put all specializations in source file like:
// heade... |
7,883,608 | 7,883,624 | Getting a segmentation fault in c++ using pthreads | I'm writing a program with threads for my Operating Systems class. It must compute n values of the Fibonacci series in one thread and output the results in the main thread. I keep getting a segmentation fault when n > 10. From my testing, I discovered that the compute_fibonacci function is executed correctly, but for s... | num = new int(atoi(argv[1]));
This is declaring a single int initialized with the integral value from argv[1]. Looks like you want to declare an array instead:
num = new int[ atoi(argv[1]) ];
|
7,883,773 | 7,883,821 | Basic C-style string copy | I'm trying to do a C-style string copy but something is not working right. What am I doing wrong?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
char string_a[20]="Good day!";
char string_b[30]="Hi!";
int i=0;
cout << "string a: " << string_a << endl;
cout << "st... | You cannot do:
string_a++
if string_a is defined as an array. That only works for pointers and arrays decay to pointers only in specific circumstances.
If you change:
while (*string_a++ = *string_b++) {
cout << ++i << endl;
}
into:
char *pa = string_a, *pb = string_b; // a "specific circumstance" :-)
while (*... |
7,883,793 | 7,883,832 | Overloaded operator<< returning ostream& | I had the following code in a sample application:
ostream& operator<< (ostream& os, const ReferenceTest& rt)
{
os << rt.counter; //In this scenario, rt has a public int called counter
}
I was surprised to learn that this code compiled without issue using GCC 4.6.1. It fails when using Visual Studio 2010 for the ... | Did you compile with warnings enabled? I get warning: control reaches end of non-void function with g++.
You certainly don't want a compiler to stop at the first error in your code. You want it to catch as many as it can in one swell foop. To do this, the compiler has to patch your buggy code so it can press on. In thi... |
7,883,818 | 7,883,918 | GUI harness for MFC DLL? | I have a CWinApp-based application that is built as a DLL that is loaded by another 3rd party application as a plugin. My app exposes an exported StartPlugin() method that creates a CDialog derived dialog. This exported function is somehow called by the 3rd party application. I'd like to be able to run my DLL outsid... | Use the Visual Studio wizard to create a MFC application, probably Dialog based. Have a button on the dialog to run your plugin. In the button code do a LoadLibrary with the name of your DLL, then call GetProcAddress to get a pointer to the StartPlugin function. Then you can call StartPlugin.
|
7,883,838 | 7,883,898 | Different ways of calling functions C++ | I know this is a very basic question, but after a few google searches and clicking on multiple links, I still couldn't find an answer.
My question is what is the difference between the " . " and the " -> " in function calling in C++ language?
For example, I have a program with 2 different data structures.
Semaphore aa... | Use the . operator when you're accessing members using the object itself, or a reference to the object.
struct Foo
{
void bar() {}
};
Foo foo;
Foo& fooref = foo;
foo.bar();
fooref.bar();
Use the -> operator when you're accessing a member via a pointer to the object. Continuing the above example
Foo *fooptr = &foo;... |
7,884,132 | 7,884,140 | Specify cmath's pow function and not locally declared one | When calling ans+= c[i] * pow(x,i);, xCode is complaining "Too many arguements to function call, expected 1 have 2". I have a locally defined function as follows:
Polynomial pow(unsigned int n) const;
and a constructor:
Polynomial(const double t = 0.0);
How can I specify that I would like to use cmath's pow ... | Well, assuming you're keeping all your own stuff out of the std namespace (and, if you're not, you should be, since that was the entire raison d'être of namespaces), you can just use std::pow().
See the following code for an example:
#include <iostream>
#include <cmath>
int pow(int x, int y) { return -1; }
int main() {... |
7,884,232 | 7,896,754 | Animate my Detected objects in OpenCV | I was wondering how it is possible to create effects like a glowing ball or a glowing line in my video frames in OpenCV. Any tips on where I can start or what can I use so I can create simple animations in my output?
Thanks in advance!
| These effects are simple to accomplish with primitive OpenCV pixel operations. Let's say you have your ball identified as a white region in a separate mask image mask. Blur this mask with GaussianBlur and then combine the result with your source image img. For a glow effect, you probably want something like Photoshop's... |
7,884,237 | 7,884,267 | Error: Vector iterator not dereferencing | I just inserted into a vector and all is well, when I went to insert next, with the vector iterator currently pointing at vectorname.begin(). Since I only have one value, the guard I have should stop it from iterating, but it breaks for some reason. I feel like I'm not accessing the end correct, or stopping the iterati... | It seems you are missing proper conditioning in the while loop and that's why it's always true (also put braces when you have various operators in place). Your condition should be,
while((iter->myX != destX) && (iter->myY != destY) && (iter !=
this->playerVector.end()))
Following is another simple version of your w... |
7,884,705 | 7,884,883 | Efficiency of premature return in a function | This is a situation I encounter frequently as an inexperienced programmer and am wondering about particularly for an ambitious, speed-intensive project of mine I'm trying to optimize. For the major C-like languages (C, objC, C++, Java, C#, etc) and their usual compilers, will these two functions run just as efficientl... | There is no difference at all:
=====> cat test_return.cpp
extern void something();
extern void something2();
void test(bool b)
{
if(b)
{
something();
}
else
something2();
}
=====> cat test_return2.cpp
extern void something();
extern void something2();
void test(bool b)
{
if(b)
... |
7,884,782 | 7,885,086 | C++ popen to run PHP | i'm using popenRWE from http://www.jukie.net/bart/blog/popenRWE and making the script below
int pipes[3];
int pid;
const char *const args[] = {
"php ",
NULL
};
pid = popenRWE(pipes, args[0], args);
char *cmd = "<?php echo 'hello world';?> ";
cout << "write: " << write(pipes[0], cmd, strlen(cmd)) << endl;
cout... | There are three problems with your code:
There is no executable named "php ". There is just "php" (notice that there is no space). The reason why this does not work is beceause popenRWE uses execvp which does not start a shell to execute the command but it expects the filename of the binary you want to executed (it se... |
7,884,930 | 7,885,010 | Why this while loop executes twice before asking for name | I have a function which validates a user's first and last name. However, the while loop executes twice, and I can't find out why.... any help
string getName()
{
string name = "";
bool stop = false;
string::iterator it;
while(!stop)//name validation loop
{
cout << "enter name: ";
... | It may happen if there is still some newspace character in cin buffer. std::ws extracts white spaces like newline character, space, tabulator from stream before right text. Try that:
string getName()
{
string name = "";
bool stop = false;
string::iterator it;
while(!stop)//name validation loop
... |
7,885,037 | 7,885,043 | Preprocessor Directive "Using" | From my previous knowledge in learning C, I know that preprocessor directive like #include , #define is ain't a statement that's why as the name implies , it is process before the program is compiled , therefore there's no need for us to append a ; at the end of it.
In C++, it introduces me a new directive that is usin... | using is not a preprocessor directive. It is seen and analyzed by the compiler proper.
The fact that you often don't put a ; at the end of #define macros is because they are processed as "simple" text replacement by the preprocessor, e.g:
#define SOMETHING "abcd";
...
if (strcmp(thing, SOMETHING) == 0) { ... }
...
... |
7,885,104 | 7,885,353 | Unexpected copy-construction caused by reference: what am I doing wrong? | I have some complex template code where the copy-constructor of OPC is being called even though I am only creating a reference to OPC (the actual instance is OP_S, which as a child class of OPC, should not result in a copy-construction call).
I am using gcc 4.6.1
The code is below.
#include <stdio.h>
class OPC
{
p... | auto opc declares an object, not a reference. It is the same as if you had said OPC opc.
If you want opc to be a reference, you need auto& opc.
|
7,885,284 | 7,888,257 | wxWidgets: wxString encode using wxCSConv wxMBConv | I want to encode a .html file (wxString) into hex. I tried to achieve this by
data = wxString((const char*)html_stuff, wxCSConv(wxFONTENCODING_UTF8), sizeof (html_stuff));
Thank you!
| The code you posted is converting from UTF8 to unicode
http://docs.wxwidgets.org/2.9.2/classwx_string.html#86a2ec232912c97ed44ba34651d98123
UTF8 uses 1 to 3 bytes to encode each character - it is used to send documents in HTML so browsers can display them. Unicode uses 2 bytes to encode every character - it is used by... |
7,885,384 | 8,470,218 | Include Boost C++ library in android | I have been trying to marry Boost and android on windows for long time and tried lot of approaches but still no luck. I want to make a sample program using Boost library in android. I am following this tutorial here.
As this tutorial suggested i have kept my Boost lib in ****(Android NDK)\sources\boost_1_44_0**** comp... | My question contained almost complete steps for including BOOST library in Android. But still there are some important points you should remember while working with this.
Delete auto generated obj and libs folder Each time before you compile your native code.
If you are going to write your native code in C++, add ... |
7,885,426 | 7,886,015 | Initializing boost::random::discrete_distribution in VC2010 | I am trying to implement one of the first examples from boost::random documentation in Visual Studio 2010 SP1, using the native library (TR1).
Before when using the library, I found out that I can just use the built in VC2010 random functions and they work just like the boost ones, but here I cannot use the native fu... | The VC2010's std::tr1::discrete_distribution doesn't conform to the latest C++11 spec (hence the namespace tr1), and doesn't yet provide all the ways to construct it. In matter of fact, it seems that the only way to construct it in VC2010 is by either default-initializing it, or by providing a generator that gets calle... |
7,885,479 | 7,885,548 | Move Constructors and Static Arrays | I've been exploring the possibilities of Move Constructors in C++, and I was wondering what are some ways of taking advantage of this feature in an example such as below. Consider this code:
template<unsigned int N>
class Foo {
public:
Foo() {
for (int i = 0; i < N; ++i) _nums[i] = 0;
}
Foo(const F... | First off, there's a general sort of advice that says you shouldn't write any copy/move constructor, assignment operator or destructor at all if you can help it, and rather compose your class of high-quality components which in turn provide these, allowing the default-generated functions to Do The Right Thing. (The rev... |
7,885,581 | 7,885,620 | VC++ on Visual Studio 2010: Release builds using debug heap | I'm benchmarking/optimizing a slow C++ application, and in taking some stackshots I found that the release build of my application is using the debug heap, as some of the stack traces found would indicate:
ntdll.dll!string "Enabling heap debug options\n"() + 0x11056 bytes
This is a 64-bit application running on Win... | The debug heap is used when a program is run under debugger (profilers often manifest themselves as debuggers). In order to bypass it the program should be started without debugging, then the debugger should be attached to a running process.
|
7,885,777 | 7,886,206 | Rule of three and inheritance | class A defines copy operator, destructor and operator=. (Rule of Three)
If B inherits from A:
the destructor will be called automatically
I need to chain the constructor
operator= ... should I define it explicitly for the class B?
| No, it's unnecessary.
If you read carefully the Rule of Three, you will notice that nothing is said about a base class, the decision is made solely on the class proper attributes and behavior.
(Check this example on ideone)
#include <iostream>
struct A {
A(): a(0) {}
A& operator=(A const& rhs) { a = rhs.a; return ... |
7,886,242 | 7,888,080 | Do namespace aliases affect build times in large codebases? (C++) | I have some (not many) namespace aliases declared in headers. Some of the headers have pretty high visibility in a large codebase. I stopped using them for the most part years ago, but some still linger. I've also removed some of them along the way, but I did not time before/after. Before I go and remove them, I was wo... | Disclaimer: I can only speak from my limited experience with the clang compiler.
In clang, a namespace alias definition will not cause all symbols from the source namespace to be copied into the current declaration context (i.e. scope). Instead, the compiler will emit a namespace alias declaration record into the conte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.