question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,645,592 | 5,645,616 | Large number of threads in C++ and Efficiency | I've currently written a program in C++ that sometimes uses over 300 threads. In my program, I have an array of structs and the length of the array equals the number of threads. Let's assume that I have 400 structs and therefore, 400 threads.
In a single iteration of a for loop, I apply a function to each of the 400 s... | There is absolutely no benefit to spawning 400 CPU-bound threads unless you have 400+ processor cores in your target machine.
It would be impossible to tell you with any certainty how to better distribute your workload without knowing what sort of computations you're performing, and on what kind of data.
As a shot in t... |
5,645,730 | 5,671,765 | Real world use-case for the `at()` indexing function in the C++ std library? | C++'s container vector, deque, ... provide the at(index) accessor function in addition to operator[index] to access container elements.
The difference between this member
function and member operator function
operator[] is that deque::at signals
if the requested position is out of
range by throwing an out_of_r... | One use case I've consistently found at() useful in is facilitating parsing of complex user input. For example, in analysing C++ code, I find myself moving along an array of lexical tokens as I check for grammatical constructs. The logic is often like "if this token is an Identifier and the next one is an Equals then... |
5,646,171 | 5,646,657 | Pass socket from .NET to unmanaged C++ code | I currently have a .NET program initiating a connection to a server. Sometimes I need to call a special unmanaged C++ code, which uses the connection to the server.
How to pass and use socket connection from .NET in unmanaged C++ code?
Thanks in advance!
| The Socket class has the Handle property, which could be used.
Socket.Handle @ MSDN
I was skeptical about whether this would work, but I was able to get it to work with no fuss at all.
To start, I made an unmanaged C++ dll to export a single function that can do something with a socket. Here's the function I created.
#... |
5,646,194 | 5,745,621 | (Embedding Mono) Parallel activation of domains | I'm wondering if it's possible to activate multiple Mono domains and execute them in parallel from native code:
I use the following code to activate a domain:
///Create a new domain.
m_domain = mono_domain_create();
///Activate the domain.
mono_domain_set(m_domain, 0);
///Invoke some function ...
mono_runtime_invoke (... | Yes this can be done. Given that the Mono virtual executable runs alongside your C application when it's embedded (and shares the same address space), The best approach would be to launch each domain in a separate process. The easiest way to do this would be to have your code fork multiple processes and each process wo... |
5,646,457 | 5,646,578 | Undefined reference to 'main' error in crt1.o function _start | I've having problems with my Makefile.
I'm trying to create a program from 2 files - main.cpp that contains the main function, and modules.c that contains the definitions of the functions that are called in main(). modules.c only contain function definitions, no main function.
My Makefile is as follows:
CC := gcc
CXX :... | Here are a couple of hints:
-o $@ $< is not needed for .o files, so remove that from those targets.
-Wall makes more sense when used while compiling not linking. So I would add it to the CC and CXX line instead (or better, to the CFLAGS and CXXFLAGS).
the clean target should be a dependency of the .PHONY target, so th... |
5,646,665 | 5,648,679 | Transforming a parameterization by two classes to a parameterization by one class | The following code has a little bit of unpleasantness.
#include <cassert>
template<typename S> struct PA1 {}; template<typename S> struct QA1 {};
template<typename S> struct PA2 {}; template<typename S> struct QA2 {};
template<typename S> struct PB {}; template<typename S> struct QB {};
template<typename S> struct P... | As I understand the question and its predecessors, the task is a specialization of function template on a class template regardless of its template parameter.
Generic solution:
#include <cassert>
//remember the value of the argument S to retrieve it later
template<typename S> struct PA1 { typedef S S; };
template<typen... |
5,646,932 | 5,647,229 | C Checking or Converting Exponents | I have exponents in the represented format of: "1.45e004" or "1.45e-04" or "-1.45e004".
[please note the minus sign in the third one]
Checking (==, !=, >, <, <=, >=, etc) does not work on exponents [incorrect or no results are returned] in their current format.
However, converting an exponent using fabs works for the ... | It's unclear why your are calling fabs() in this line:
printf("%f\n",fabs(T1)); //Fails to show the minus sign
That's what fabs() does, it makes negative numbers positive. Perhaps you want this:
printf("%f\n",T1);
Comparison of two floating point numbers can be done directly:
double x = 12.345e67;
double y = 6.543e-2... |
5,647,047 | 5,647,131 | Problem with template and lambda C++0x | #include <iostream>
#include <algorithm>
#include <array>
using namespace std;
template<class T>
void func(T beg, T end)
{
typedef decltype(*beg) type;
std::for_each(beg, end, [](type t) { cout << t << endl; });
}
int main()
{
std::array<int, 4> arr = { 1,2,3,4 };
func(arr.begin(), arr.end());
r... | That's probably acceptable, however as your code appears to expect iterators exclusively, I think that the following would be more appropriate:
typedef typename std::iterator_traits<T>::value_type type;
Or even better (given how you're using it):
typedef typename std::add_reference<
typename std::add_const<
... |
5,647,069 | 5,647,196 | Which of these codes will run faster | I have recently begun to think about optimisation, now I know there are many books and articles but I have a particular scenario i'm interested in.
A.
for (i = 0; i < limit + 5; i++)
cout << test;
B.
limit2 = limit +5;
for (i = 0; i < limit2; i++)
cout << test;
What I want to know is would the second piece of cod... | You're focusing on an optimization that almost certainly doesn't matter, regardless of how it gets compiled. Focus on picking the right algorithms and design for the rest of your code. Profile to find out what's slow and optimize the areas that take the most time. Typically 10% of the code takes 90% of the time. You're... |
5,647,269 | 5,647,542 | Reading unflushed page from another process | I have a producer process, that writes to a mmap'd file and a consumer process that reads from it. This is on Linux.
If the producer makes a change to the mmap and its not instantly flushed, when the consumer access it what happens? Will it get the old version from the disk, or is it clever enough to get the unflushe... | From the mmap() manual page:
MAP_SHARED
Share this mapping with all other processes that map this object.
Storing to the region is equivalent to
writing to the file. The file may not
actually be updated until msync(2) or
munmap(2) are called.
Bottom line: changes will be immediately visible to other processes... |
5,647,289 | 5,647,573 | Which Qt Widget to scroll through widgets? | I am currently working on a Qt project for my school. For this project I need to list an unknown number of elements in a window without resizing its content.
I've used some VBoxLayout in the past, but it isn't what I am searching at all. This widget resizes its content depending on the number of elements it contains. W... | If your display elements are simple, the easiest solution is a QListWidget. This will automatically resize itself and inform the QScrollArea when you add items. You just have to call myScrollAlrea -> setWidget (myListWidget) to initialise, and then myListWidget -> addItem (myListWidgetItem) to add new items.
|
5,647,311 | 5,657,460 | Is there a Boost.Bimap alternative in c++11? | Is there a usable alternative to Boost's bimap in C++0x?
I would like to avoid Boost, but fully embrace C++11. If necessary, a slimmed down version of Boost's bimap would work for me (I need a constant bimap to switch between enums and corresponding strings) throughout my program. The map will be compile-time constant,... | My feeling is a lot of the work that goes into Boost libraries is making them work with other libraries/STL.
If you don't need that capability, you could just use a class with a std::map<X*, Y*> and std::map<Y*, X*>. Then have methods like the following: add(X,Y), remove(X,Y), get_left(X) and get_right(Y).
If you want ... |
5,647,437 | 5,979,352 | How to set the name of an bho (visible in the addon options in ie) | How can I rename the name of a browser helper object. The normal information in the properties of the dll are all fine. However when I open Internet Explorer to view the Addons the name of my Addon is NameIEBHO Class
The DLL is signed
The VERSIONINFO is set (it includes CompanyName, FileDescription, FileVersion, Inte... | This information is stored in .rgs file in your project. Look for a string like
ForceRemove {29DFE920-26AD-4377-8FCB-0E7A34A41199} = s 'NameIEBHO Class'
|
5,647,456 | 5,648,501 | c++ LNK2001: unresolved external symbol problem | Greetings.
I have searched for a solution, but I think this problem is personal code specific, hence my posting here.
I'll get straight to the point.
In my main I have two objects.
Computer *computer = new Computer();
Player *player = new Player();
In the computer class, in the header I have the following:
private:
... | This is a linking error and it has nothing to do with instantiations or parameters.
You haven't provided the linker with the definitions for those functions. If you defined them in Strategy.cpp you need to compile that and add it as an argument to the linker. How you do that depends entirely on what tools you're using ... |
5,647,503 | 5,784,314 | With a single file descriptor, Is there any performance difference between select, poll and epoll and ...? | The title really says it all.
The and ... means also include pselect and ppoll..
The server project I'm working on basically structured with multiple threads. Each
thread handles one or more sessions. All the threads are identical. The protocol
takes care of which thread will host the session.
I'm using an inhouse s... | The main difference between epoll vs select or poll is that epoll scales a lot better when run in a single thread. I don't know how this would compare to using a multithreaded server using select or poll.
Look at this http://monkey.org/~provos/libevent/libevent-benchmark2.jpg
The reason for this(as far as I can tell) ... |
5,647,543 | 5,647,575 | implementing simple input stream | I want to write a simple istream object, that would simply transform another istream.
I want to only implement readline (which would read a line from the original stream, would process it, and return the processed line), and have some generic code that upon read would use my read line, cache it, and give the required a... | Have you looked at boost.iostreams? It does most of the grunt work for you (possibly not for your exact use case, but for C++ standard library streams in general).
|
5,647,733 | 5,673,611 | Using SQL lite from sources - how to create a DB file and put into it some data? | So we want to use SQL lite directly from source (mainly because we create a crossplatform opensource app and there are no crossplatfrom lib distributions of SQL LITE) So we download sqlite-amalgamation and create a simple static lib from it. We include sqlite3.h and sqlite3ext.h to our project file and than what - how ... | I found this tutorial as well as this video very helpful to get started. The video should help you set up the project so that you can create and connect to a simple db. The code from the first tutorial is almost identical to the example on the sqlite homepage. Despite lack of in-depth explanation the tutorial was extre... |
5,647,850 | 5,661,129 | Better handling of missing/wrong key in boost::program_options | Is there a way to know which key was involved when a call like the following fails ?
boost::program_options::variables_map vm;
...
int foo_bar = vm["some_key"].as<int>();
If the key is missing from the map, or is not convertible to int, I get a rather uninformative bad_any_cast, and I can't know any of the following:
... | Marco,
there's no way to get better diagnostics without modifying the library.
However, please note that in general, I am not sure exceptions in this case are supposed to be very detailed:
- If you use wrong type to access variable, you've got a coding error. You can easily track that down with a debugger
- If you acce... |
5,647,930 | 5,648,104 | Question about in c++, vector push_back(),I am not sure how to fill inside the() | I have a question about vector push_back().I am writing a code to acquire image into the buffer and store them inside a vector.I checked that I may need to use push_back(),But I am not sure right now how should I format pImageBuffer that I can store it into the vector.Maybe it is another easy question,but I have been t... | You have a const uint8_t*, but your container stores uint8_t*.
Also note that you're adding a 100th, 101st, 102nd element there, not filling the 0th, 1st, 2nd...
You may want:
std::vector<const uint8_t*> images(100);
size_t i = 0;
while (i < 100) {
// ..
const uint8_t* pImageBuffer = (uint8_t*)Result.Buffer();
i... |
5,648,065 | 5,648,162 | How does "this" pointer happen to point to different objects? | Suppose I have a class:
class test {
public:
void print();
private:
int x;
};
void test::print()
{
cout<< this->x;
}
and I have these variable definitions:
test object1;
test object2;
When I call object1.print() this happens to store address of object1 and so I get x from object1 printed and when I c... | Each non-static member function has an implicit hidden "current object" parameter that is exposed to you as this pointer.
So you can think that for
test::print();
there's some
test_print( test* this );
global function and so when you write
objectX.print();
in your code the compiler inserts a call to
test_print(&obje... |
5,648,172 | 5,648,539 | What is the correct way to force an app to core dump and quit? | I just came across some code which used the kill system call to send a SIGSEGV signal to an app. The rationale behind this was that this would force the app to core dump and quit. This seems so wrong to me, is this normal practice?
| SIGQUIT is the correct signal to send to a program if you wish to produce a core dump. kill is the correct command line program to send signals (it is of course poorly named, since not all signals will kill the program).
Note, you should not send random signals to the program, not all of them will produce a core dump. ... |
5,648,286 | 5,648,315 | JNI - automatically attach all newly spawned threads from process to JVM? | I call a dll from Java using JNI. The DLL calls another thirdparty library which spawns a bunch of threads and sends callbacks to my dll. I want these callbacks to be attached to the JVM. What is the best way to do this? I think since the threads call the callback method, the callbacks aren't attached to the JVM, so I ... | You have to manually call AttachCurrentThread() (and DetachCurrentThread()) from each thread that needs to call into the VM. There is no automatic mechanism.
|
5,648,937 | 5,649,601 | A simple addition,substraction,multiplication and division program | A simple C++ calculator program to calculate addition, subtraction, multiplication and addition...
#include <iostream>
#include <string>
using namespace std;
int main()
{
//input declarations as doubles for total and counter
double total = 0, counter =0;
//input declarations sign and Q as character
cha... | As a simple exercise I have refactored your program to make it simpler. I don't promise it works, but it should give you a nice foundation to build on:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//input declarations as doubles for total and counter
double total = 0, counter =0;
//inp... |
5,649,082 | 5,869,627 | Use of new operator -compiled error C2661: 'CObject::operator new' : no overloaded function takes 4 arguments (Multiple Inheritance) | I have the below class in header file
class CodeListSqlGenerator : public ICodeListSqlGenerator,public CDialog
{
........
public:
CodeListSqlGenerator(IIntelligentCodeListUpgraderParameter *i_intelligent_codelist_upgrader_parameter);
}
When I use a new operator in .cpp file to create an object of type CodeListSq... | DEBUG_NEW macro has to be change,. check whether you have included preprocessor #undef new,
Try to write the #undef new before the new keyword
|
5,649,158 | 5,650,006 | QHash of function pointers for variable setting after XML parsing: insane? | I am parsing and storing data I get from a server in XML format. The application is a thin client that asks for server-side data like this very frequently. A few of the variables will be uris that trigger more network calls. The data is in the form:
<object>
<var1>value</var1>
...
<varN>value</varN>
</obj... | I'd recommend you another, "easier" solution which will help you to:
1) Have much less code and make your code readable
2) Do not overwhelm another objects with function calls
So you can use QObject properties to do that. And your code would look like as simple as:
// parsing the XML here via QXmlStreamReader
...
QObje... |
5,649,270 | 5,650,155 | How to write conditions in loop bodies? | This is probably a bit subjective, but I'm in fact looking for answers that contain some reasoning.
I've met the following two programming styles for conditions in loop bodies. This:
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].isEmpty())
continue;
doSomeStuff();
doSomeMoreStuff();
}
... | The fact is that the second increases cyclomatic complexity and may lead to the arrowhead antipattern.
In addition, keeping all your "code should not pass this point" checks at the beginning allows you to group them together, which means they are easier to maintain imho.
|
5,649,493 | 5,652,872 | Can I enumerate users in Well Known Groups? | (How) can I enumerate programmatically Users in Well Known groups (SidTypeWellKnownGroup) ?
Ex: "Autenticated Users" or "Domain Users"
| You can probably do this in WMI, but I'm not that familiar with it; I prefer using the plain old C APIs anyway. You can use the Network Management functions to do this. Given the group name, you can use NetGroupGetUsers to get all the members of a group. To get the group name you can use CreateWellKnownSid (or Alloc... |
5,649,796 | 5,651,823 | Return a new array with specified values? | Is there a way to write the following function code
int* returnFilledArray() {
int* arr = new int[2];
arr[0] = 1;
arr[1] = 2;
return arr;
}
somehow like that? (create and fill the array as one liner).
int* returnFilledArray() {
return new int {1,2};
}
if have tried various combinations, but I allways get some sy... | You cannot do what you are trying to do in Standard C++ (03) without using special libraries.
|
5,649,939 | 5,649,988 | Is there way to use a boolean in C++ as a bitmap? | Is there way to use a boolean in C++ as a bitmap?
Code example:
bool boolean = false;
boolean &= ~(1 << 0);
boolean |= 1 << 2;
boolean |= 1 << 1;
cout << "boolean : " << boolean << endl;
bool bit1 = boolean & (1 << 2);
bool bit2 = boolean & (1 << 1);
bool bit3 = boolean & (1 << 0);
cout << "bit1 : " << bit1 << endl;
... | Are you possibly thinking of something like std::bitset?
A bitset is a special container class that is designed to store bits (elements with only two possible values: 0 or 1, true or false, ...).
The class is very similar to a regular array, but optimizing for space allocation: each element occupies only one bit (whic... |
5,650,199 | 5,650,423 | Using template instead of switch | I want to perform a set of tests in my code that are similar but change only depending on a parameter.
I could write this using a switch statement:
bool doTest(EnumSensorFamily family, const StructSensorProposal& proposed)
{
switch (family)
{
case FAM1:
return (ExpectedFam1 == proposed.Fam1SensorId);
brea... | Building off Andrew's answer...
Note that the EnumSensorFamily family must be known at compile time. If it is not known until run time, then you'll have to write a switch to choose the template, putting you back where you started.
Another way to do this is with the Traits pattern:
template <EnumSensorFamily family>
st... |
5,650,269 | 5,651,861 | Fastest way to clear every kth bit in boost::dynamic_bitset | What is the fastest way to clear every kth bit in a boost::dynamic_bitset, optionally from offset j?
Currently I'm doing this which is pretty darn slow (pseudocode):
for (i = j; i < bitset.size(); i += k) {
bitset[i] = 0;
}
Millions of bit-clears have to be done, so that's why I'm looking for a fast way to do it.... | For very large bitsets, compute a mask n bits long (where n is your native size, e.g. 64 for x86_64) as Nim suggested, apply it.
If your native length is not a multiple of k, shift it accordingly.
So if you have a native length of 10 and want to set only every 3rd bit of a 30 bit-long bitset, you'd need 3 passes like t... |
5,650,373 | 5,650,469 | Forms autosave question | I am making an application in c++ and qt and i am wondering how i can autosave my forms instead of pressing the save button everytime. Since i have never done it before,i am thinking autosave is only for the web.What is the best way to approach this?.
| You don't need to. A QTextBox will not lose its value suddenly, only when it's destroyed. And unless you arrange it otherwise, that doesn't happen before the destructor of the form finishes. So you can always get the textbox content, even from the destructor.
|
5,650,393 | 5,651,235 | C++ enable_if (or workaround) for member operator | template<typename T>
struct foo
{
T* p;
foo(T* x) : p(x) {}
~foo() { if(p) delete p; }
T& operator*() const { return *p; }
};
int main()
{
foo<int> i(new int);
foo<void> v(new int); // <= illegal use of type 'void'
}
If T = void then I don't want to implement the operator*(). How can I achi... | The C++11 standard solved this for std::unique_ptr like so:
typename std::add_lvalue_reference<T>::type
operator*() const { return *p; }
|
5,650,447 | 5,650,520 | Quicksort implementation, can't find error | I want to implement this quicksort algorithm with some different pivot strategy but there is some logical error in it. Can you please help me find it?
#include <iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
int arr[100],i,pivot,left,right,sum=0,a,n=10;
int partition();
void quickSort(int* ,int ,in... | Your pivot value will always be the value of arr[(i)/2], which is arr[2], no matter which portion of the array you happen to be sorting at the time. Pass the values of left and right to partition so it knows which values to consider for the current call to quickSort.
Also, the values of left and right that you pass for... |
5,650,629 | 5,650,679 | Can derived class access private static member function | I have a code like this, it seems it works. I have no idea why private static method can be accessed like this.
class Base
{
public:
static void f(){std::cout<<"in base\n";};
};
class Derived:private Base
{
};
int main()
{
Derived::f();
return 0;
}
| Refused by all compilers I've tried (several g++ version, como online, IBM xlC) excepted sun CC. My guess is that it is a bug in your compiler.
|
5,650,701 | 5,653,093 | Read arbitrary-length bytes from file to string C++ | Now that I am quite familiar with Python, decided to learn C++, so I am very n00b but sure willing to learn.
I had made a script to read from a very tightly-specified file format (.EDF, for medical signals), with an ascii header defined by field sizes in bytes. So, I read 8 bytes for the first field, 80 bytes for the s... | Assuming there are no spaces in the fields except for the padding, you can read them into C++ strings using:
/* Read field of n bytes */
std::string read_field(std::istream &edfreader, size_t n)
{
// there's no need for new;
// in fact, new may lead to a memory leak if you forget to delete
std::vector<char>... |
5,650,780 | 5,651,267 | Does it have to be hard to overload functions across namespaces? | I have been writing some code with basically this structure
namespace util {
void read (int &);
template <typename T>
void read (T &);
}
void foo ();
using namespace util;
namespace { // A
void read (MyType &, int);
void do_something () {
MyType t;
int i;
// using util::r... | Yes, it's hard. In fact, it's impossible.
The best you can do is to hide names. You're right to employ using (B) to get around the complications that name hiding brings into the mix, when you're also overloading functions — D should still function in this case. Please show the error you got for it.
|
5,650,790 | 5,651,174 | Compiler switch to disable const_cast semantics in c-style casts? | Recently I stumbled over code such as this:
void foo(const Bar* b) {
...
takes_nonconst_param_fn((Bar*)b);
...
Obviously, the developer didn't know what he was doing, but if the compiler hadn't silently accepted the c-style-cast and at least required a proper const_cast, he may have though twice before committin... | GCC has the option -Wcast-qual to warn when a C-style cast removes a type qualifier. Combined with -Werror, you can prevent it completely if you want.
|
5,651,169 | 5,651,190 | warnings in playing with bits | BYTE original = 0xF0F0;
BYTE bMask = 0x0000;
BYTE wMask = 0xFFFF;
BYTE newBits = 0xAAAA;
/*& operation with "0bit set 0" & "1bit give no change to original byte" */
cout<<"Original o: "<<bits(original)<<endl;
cout<<"NewBits: "<<bits(newBits)<<endl;
cout<<"BMask m: "<<bits(bMask)<<endl;
cout<<"WMask m: "<<bits(w... | E.g. 0xF0F0 requires 16 bits - 2 bytes. Try with an unsigned short instead of BYTE
|
5,651,170 | 5,651,206 | C++ Multi-Thread Execution Speed Slow-Down | I am writing a multi-threaded c++ application. When thread A has a very computationally expensive operation to perform, it slows down threads B, C, and D. How can I prevent this?
| On windows you can use Sleep(0) to release the remainder of your timeslice for other threads that are waiting.
|
5,651,295 | 5,651,371 | boost.asio test problem | I'm new on boost.asio.
I have a problem when I try a simple example.
in my header file I have:
#include <boost/asio.hpp>
#include "boost/bind.hpp"
#include "boost/date_time/posix_time/posix_time_types.hpp"
and I need this private variable:
boost::asio::ip::udp::socket socket_;
I have this error at compile time:
error... | The list of all UDP socket constructors if found here. As you can see, you must provide at least a reference to a boost::asio::io_service object.
If this is a private variable, provide this reference in the class constructor's initializer list. The following will compile:
#include <boost/asio.hpp>
class Socket
{
bo... |
5,651,412 | 5,651,441 | how to make a method for this code | I have simple question: I dont know how to make a method for codes like this:
//how should i put these two lines in a method?
if (agent.GetWorldState().GetPlayMode() == PM_Before_Kick_Off)
{
agent.Move(Vector(-1, -1));
}
Thanks.
| It sounds like you're asking how to write a method to wrap that code. If so I think you want the following (assuming the type of agent is Agent)
void TheMethod(Agent& agent) {
if (agent.GetWorldState().GetPlayMode() == PM_Before_Kick_Off) {
agent.Move(Vector(-1, -1));
}
}
|
5,651,568 | 5,652,023 | Converting C++ to MATLAB | I am trying to convert some C++ code to MATLAB and having an issue. Would someone please explain a single line of code from below.
int *image = (int *) malloc(size*sizeof(int)) ;
bool diff = true;
while (diff)
{
diff = false;
for (unsigned int itt = 0; itt < size; itt++)
{
diff = diff ... | First of all, ImageSize = (Image); is not correct. This will simply assign Image to ImageSize. Use ImageSize = size(Image); instead.
Secondly, you are using double indexing in you Matlab code, while the C++ code is using single indexing.
while(diff)
diff = false;
for n=1:numel(Image) %# Total pixels in the imag... |
5,651,898 | 5,652,108 | Changing around arrays | I'm doing a lot of different things with manipulating arrays without vectors, I was wondering if any one could help me with shifting elements in an array and expanding an array while initializing the new space with elements. I feel like I'm very close to completing this code, but I'm hitting a block.
#include <iostream... | There are only two compile error: int newArray; should be int* newArray; and #include <cstring> is missing (necessary for memcpy())
Also, the line display(myArray, SIZE); was probably meant to be display(arraPtr, SIZE); and likewise display2(myArray2, SIZE); -- otherwise you're only displaying the original arrays, not... |
5,651,962 | 5,653,972 | OpenCV+Visual Studio 2008 - Program runs fine in debug but access violation in regular execution | I'm working on a computer vision program at the moment with OpenCV in C++. It seems to work 100% fine with a live feed from a webcam but when I tried to feed in a stream from an avi file it started crashing with an "Access Violation" error. I can't see why this would be the case because the only difference between the ... | I would suspect uninitialized variables. Many debuggers initialize all variables, including those that are not.
|
5,651,983 | 5,652,292 | Why would a program run when launch from windows but not the command prompt? | I wrote a small C++ program in VS2k8. When I launch it from windows (double click the exe file) it runs fine. When I go to the command prompt and try to run it it will hang and eventually crash. I've created test programs with simple outputs that work fine both ways.
Is there something I'm missing? I'm relatively new t... | Might suggest that the current directory on start up is different and this is causing your issue as you make some assumptions about the current path or drive?
|
5,652,071 | 5,652,300 | proper way to swap unions? | I have a class which has a union as one of its members. I also am a big fan of the copy/swap idiom. It occurred to me that there doesn't appear to be any correct (in the sense of the standard) to swap unions!
Here's the best that I could come up with:
char tmp[sizeof(U)];
memcpy(tmp, &u1, sizeof(U));
memcpy(&u1, &u2, s... | Simply:
#include <algorithm>
std::swap(u1, u2);
Unions are both copy-constructible and assignable, so there is no problem.
|
5,652,073 | 5,652,119 | How can i get process original file name for a process? | say, i've a binary called vlc.exe, if i rename it to abc.exe, it still runs fine. But if you see properties of abc.exe, you can see an attribute "Original FileName" and its value is vlc.exe. So, is there an api to get this "Original FileName"?
Thanks in advance.
| See Version Information Functions on MSDN.
You'll need to GetFileVersionInfo to get the version info data, then VerQueryValue for the OriginalFilename entry.
|
5,652,130 | 5,660,277 | What's the best practice for sequential dialogs in Visual C++? | I have an application that has to calculate some numbers based on some input data. This data can either come from a file or can be entered manually (it's only 5-6 values). I want to present a dialog box that basically asks "Do you want to load data from file or enter it manually?". If "load" is selected, I want to pres... | It seems that at least a significant fraction of your users will understand the numbers involved; they're not "magical". Therefore, it would make sense to show them after loading. You can nicely integrate this with the manual entry option.
Design one dialog with the 6 entry fields. Add a "Load" button that fills in the... |
5,652,152 | 5,653,576 | Smart pointer and external code interaction via JNI | I'm wondering what the best way is to have a pointer (via memory address) to an object in a C++ library which makes liberal use of smart pointers (ns-3). At the moment, I use path-based lookup and I'm concerned about its efficiency, since it seems to do full tree traversal for each call. If I maintain a standard pointe... | That was basically our solution. On the Java side, objects are held as simple ids, with a very simple algorithmic mapping of the id to a pointer (a reinterpret_cast, in fact). For objects managed by reference counted pointers, the "object" pointed to by the id is a reference counted pointer.
And just in case: don't f... |
5,652,209 | 5,652,408 | dynamic_cast issues: typeid object is not equal, but name is equal | I found that dynamic_cast didn't work in a situation where I expected it to, and looking at the typeid of the objects at runtime has made the situation even less clear. I just want a cast from base to derived, and I can't figure out why it's not working.
I have a class structure something like this:
class BoundaryCondi... | typeid behaves strangely when you're crossing library boundaries - See e.g. When can typeid return different type_info instances for same type? for some cases. In particular, on linux you will need -rdynamic to ensure that type info objects from a library aren't removed, and thus inaccessible to the executable using th... |
5,652,345 | 5,652,387 | Cannot (again) assign correct value to signed short | Why this gives zero as an output? I suspect some compiler work in it but why?
signed int sint_ = numeric_limits<signed int>::min() << '\n';
cout << "signed int: " << sint_ << '\n';
| This is because of the accidental << '\n' on the first line. Its effect is to left shift the bits of the minimum value by 13 positions (13 being the character code of \n). Since the bit pattern of the most negative value is 1000...0, the result becomes 0.
|
5,652,642 | 5,652,694 | C/C++ CSS Parser with CSS3 support? | Is there any CSS parser for C/C++ with CSS3 support? I found a few but they all don't support CSS3 yet.
| If you need CSS3 support before any libraries support it, you could try a non-validating solution such as htmlcxx.
|
5,652,834 | 5,652,896 | c++ CreateProcess() won't work with app and args with forward slash "/" - worked with App=NULL | Solution:"
ShellAndWait(NULL, _FinalShellStrCmd, "WAIT", 240, 1);
Using stringstream to combine App and Arg into _FinalShellStrCmd, leave first arg as NULL. It worked fine with either forward or back slashes. Thanks all again.
I am using boost to get current path, then I get "d:/bin/test.
Now, I try to call Shell... | You already have the answer: CreateProcess doesn't work with forward-slashes. Fix the slashes => the code works. Certain user-facing APIs and interfaces are more accepting than others
|
5,653,102 | 6,040,995 | Android, SWIG and bidirectional communication | I have a C++ api I can't change which:
exposes object (easy)
exposes interfaces that have to be derived by caller (classical trigger-listener design pattern).
I managed to wrap this API to python using SWIG and the director feature, which allows cross-language derivation.
However, when I tried to compile it using ndk... | Android does support RTTI and exceptions from NDK r5. Just add -fexceptions and -frtti compilation flags and also add line APP_STL := gnustl_static to the Application.mk file.
|
5,653,168 | 5,653,203 | Problem understanding references and copies in c++ | First off, I apologize if I'm not using the right terms in my question title. It is entirely possible. I am starting to learn c++, and I will admit I'm having a really tough time with references and copies. In reference to my code below, I have the following questions:
In main.c, is the argument passed to the Carri... | (1) Since Carrier::add does not take its argument by reference, it is passed a copy. To have it take a reference, change its signature to
void Carrier::add(Plan const &p);
(2) When you do push_back, a copy is created regardless of whether you pass a Plan by reference or by value/copy; that's part of the semantics of s... |
5,653,204 | 5,653,314 | compiling outdated c++ package: undefined reference errors | I'm trying to compile a system called SNoW in Ubuntu using g++ 4.4.5. The software seems to have been last updated for g++ 3.1.4, as I found a switch inside one of the files that checked for it and the highest case was 3.1.4 +.
I had to update a few of the headers to get past compiler errors ... cstring instead of str... | While the declaration of the static member might be in the Fex.h header, there needs to be a single definition of the member somewhere (generally it would be in a Fex.cpp file):
const char * Fex::logo[ /* you'll need some size here, too */ ];
I seem to recall that GCC would automatically gen up a definition for thes... |
5,653,276 | 5,653,305 | Parallel computing using computers in LAN? | I'm writing a C++ project to solve the Travelling salesman problem using genetic algorithms. Naturally, I'd like to make it faster using a bunch (about 40) computers in the same LAN. The computers are all running Windows XP... So, the question is what are the ways to parallelize it using the given equipment
Update:
You... | You'll need to use some form of communication to synchronize the processes between the systems. A common API for this type of application is to use Message Passing Interface (MPI). There are quite a few implementations for MPI/MPI-2 that work on Windows XP.
|
5,653,356 | 5,653,438 | Doxygen fails to parse templated return type | I'm currently documenting my code with Doxygen. It seems though as if Doxygen cannot handle templated return values. My problem:
/**
* Retrieves all edges from the graph.
* @param gID The ID of the graph.
* @return A list containing pairs of vertices, denoting the edges in the graph.
*/
int GetEdges(const int&... | Maybe Doxygen doesn't support the new way of declaring templates? Older C++ standards (I think up to C++03), allow only list<pair<int,int> >. You should have a space between the two > signs at the end, because otherwise the compiler will interpret them as a >> (right shift) operator.
Some newer compilers regonize this ... |
5,653,372 | 5,909,937 | buildbot vs hudson/jenkins for C++ continuous integration | I'm currently using jenkins/hudson for continuous integration a large mostly C++ project. We have separate projects for trunk and every branch. Also, there are some related projects for the Java code, but the setup for those are fairly basic right now (we may do more later though). The C++ projects do the following:... | Both are open source projects, but you do not need to change buildbot code to "extend" it, it is actually quite easy to import your own packages in its configuration in which you can sub-class most of the features with your own additions. Examples: your own compilation or test code, some parsing of outputs/errors to be... |
5,653,562 | 5,653,596 | how to create an empty doubly linked list? | if i have the following node class
class Node {
public:
Node() { next = NULL; prev = NULL; }
~Node() {}
public :
Node *next;
Node *prev;
T data;
};
how do i create an empty linked list in the function
LinkedList::LinkedList()
my linked list classs has the following functions
void append(T item);
T get(int idx);
... | Doubly linked lists usually have a reference to the first and (sometimes) last element in the list.
Node *first, *last;
In your constructor, just set these to NULL. Then make an isEmpty method which checks for this condition, and you're done.
LinkedList::LinkedList()
{
first = NULL;
last = NULL;
}
bool Linked... |
5,653,635 | 5,654,277 | mathematical vector class through composition | I started to write a class which would act much like the std::vector but with some mathematical operations. Mainly things like the norm of the vector and overloading important mathematical operators (+,- etc.) which will add, subtract things element wise.
The class is posted below, I have used boost::operators to write... | This fixes a number of problems with the program:
#include <boost/operators.hpp>
#include <boost/iterator.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <vector>
//publicly inherits important boost::operators classes
template <class T>
class Coords: boost::arithmetic<Coords<T>
,boost::arithmeti... |
5,653,958 | 5,654,136 | template type into binary representation | #include <iostream>
using namespace std;
template<class T>
void toBinary(T num)
{
char * numi = reinterpret_cast<char*>(&num);
for (int i = 1; i <= sizeof(T); i++)
{
for( int j = 1 ; j <= 8; ++j )
{
char byte = numi[i];
cout << ( byte & j ? 1 : 0);
}
}
cout <... | I guess, if I really wanted to fix this code as-is, I would do it like so:
#include <iostream>
#include <string>
using namespace std;
template<class T>
void toBinary(const T& num)
{
const char *const asbytes = reinterpret_cast<const char* const>(&num);
for (const char* byte=asbytes + sizeof(T) - 1; byte>=a... |
5,653,971 | 5,654,975 | C++ error relating to IXMLDOMNode* | I'm having trouble compiling one of our legacy COM components. I get the following compiler error:
error C2501: 'IXMLDOMNode' : missing storage-class or type specifiers
error C2061: syntax error : identifier 'IXMLDOMNode'
On this line of code in a .h file:
IXMLDOMNode* CreateChildNodeOfItem(IXMLDOMNode* pNode, DO... | I changed the way I'm including msxml and it seems to have fixed the compiler errors. I changed:
#include <msxml.h>
to
#import <msxml.dll> raw_interfaces_only
using namespace MSXML;
|
5,654,015 | 5,654,024 | Windows C++ Thread Parameter Passing | In Windows c++, the following creates a thread:
CreateThread(NULL, NULL, function, parameter, NULL, &threadID);
This will run "function" in a new thread and pass it "parameter" as a void* or LPVOID.
Suppose I want to pass two parameters into "function", is there a better looking way of doing it besides creating a data... | No, that's the only way. Just create a struct with the 2 data members and pass that as void*
|
5,654,159 | 5,654,289 | Why not enforce 2's complement in C++? | The new C++ standard still refuses to specify the binary representation of integer types. Is this because there are real-world implementations of C++ that don't use 2's complement arithmetic? I find that hard to believe. Is it because the committee feared that future advances in hardware would render the notion of 'bit... | (Edit: C++20 now imposes 2's complement representation, note that overflow of signed arithmetic is still undefined and shifts continue to have undefined and implementation defined behaviors in some cases.)
A major problem in defining something which isn't, is that compilers were built assuming that is undefined. Chan... |
5,654,225 | 5,654,301 | C++ header file includes <> paths | Quick background. I'm using the following:
Windows XP
Visual Studio 6.0
When you specify a #include like the following where does it look for this header file:
#include <msxml.h>
Is it looking at an environment variable to determine which paths to look at? If so which one?
| If you're using the IDE, it sets the various search paths through GUI options in in Tools->Options->Directories.
(See also Visual Studio 2008 (C++) additional directories for debugging?.)
|
5,654,330 | 5,654,386 | privately or publicly inherit from boost::non_copyable? | Which practice would you recommend, and why?
class Foo : public boost::noncopyable {};
vs.
class Foo : private boost::noncopyable {};
I can't imagine needing to use an instance of Foo as a boost::noncopyable, so I'm leaning toward private inheritance in this case.
| boost::noncopyable does not declare a virtual destructor, i.e. is not designed to be the base of public inheritance chain. Always inherit from it privately.
|
5,654,345 | 5,654,540 | this pointer as a pointer to objects | suppose employee is a class....print is its non-static member function which prints the value of its private data member x...now i read that if print is a constant function the this pointer passed to it by the compiler is of the type
const employee* const
and if print is a non-constant function the type of this p... | Consider ice cream cones. Suppose you go to the ice cream shop and order a "vanilla cone." You'll get a cone with a scoop of vanilla ice cream. You can then add a cherry on top, but it's still what you ordered, though -- a vanilla cone.
Objects are kind of like the ice cream cone. The const-ness is like the cherry ... |
5,654,406 | 5,654,444 | help with doubly linked list? | I have a class LinkedList clas that has a class called Node
class Node {
public:
Node() { next = NULL; prev = NULL; }
~Node() {}
public :
Node *next;
Node *prev;
T data;
};
In the same LinkedList class i have the following function defininitions, because it is all in a header file
public:
LinkedList();
~LinkedList... | Would it be as simple as?
LinkedList<T>::LinkedList() {
head = NULL;
current = NULL;
}
Yes.
|
5,654,660 | 5,654,776 | Why doesn't std::noskipws work, or what is it supposed to do? | First off my understanding is that
cin >> std::noskipws >> str;
should stick a whole line from cin like "i have spaces" into str. However this only puts "i" into str. This could be a false assumption in which case what does std::noskipws do?
I know there is a function std::getline and that does work but simply for e... | std::noskipws tells the istream to not skip any leading white space when attempting to read a type. When there is no leading white space, then the flag has no impact.
|
5,655,142 | 5,655,685 | How to check if input is numeric in C++ | I want to create a program that takes in integer input from the user and then terminates when the user doesn't enter anything at all (ie, just presses enter). However, I'm having trouble validating the input (making sure that the user is inputting integers, not strings. atoi() won't work, since the integer inputs can b... | When cin gets input it can't use, it sets failbit:
int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
// user didn't input a number
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
// next, request user reinput
}
When cin's failbit is set, use ... |
5,655,179 | 5,655,376 | Using .find() with struct as key in map in C++ | I do not have access to BOOST or STL; my struct and map looks similar to the following psuedo:
struct s_map_key{
int a;
int b;
bool operator<(const s_map_key& smk) const
{
if (a < smk.a)
{
return true;
} else if (a == smk.a)
{
... | operator< is all you need for find or anything else. However, your implementation has a bug. It returns true if the operands are equal.
find and other Standard Library components use the assumption that a == b iff ! (a < b) && ! (b < a), so if a and b are equal, < must be false for find to work.
else if (b == s... |
5,655,181 | 5,655,238 | How to turn on gcc warnings for a forgotten return statement? | How do I turn on gcc warnings for a forgotten return statement?
It is supposed to warn me in cases like the following:
int foo() {
std::cout << "haha";
}
I know -Wall turns that warning on, but it enables too many other warnings.
| According to gcc's online documentation, -Wall turns on:
-Waddress
-Warray-bounds (only with -O2)
-Wc++0x-compat
-Wchar-subscripts
-Wenum-compare (in C/Objc; this is on by default in C++)
-Wimplicit-int (C and Objective-C only)
-Wimplicit-function-declaration (C and ... |
5,655,216 | 5,655,300 | map<string, vector <pair<int, int> > > pushing back into pair? | I have this map<string, vector <pair<int, int> > > variable and I'm pushing back a value, but code::blocks is telling me that pair does not have a member function called push_back. What should I do to get it to push back pairs rather than pair<>.push_back()?
This is basically what im doing:
map<string, vector <pair<in... | Not sure about you problem.
Following code works fine for me:
map<string, vector <pair<int, int> > > T;
pair<int, int> p;
p.first = 1;
p.second = 10;
T["Hello"].push_back(p);
cout << T["Hello"][0].first << endl;
|
5,655,283 | 5,655,690 | Why are DWORD values commonly represented in Hexadecimal? | I am trying to understand why a DWORD value is often described in Hexadecimal on MSDN.
The reason why I am analyzing this is because I am trying to understand fundamentally why all these different number data types exist. A local mentor alluded to me that the creation of DWORD and other Microsoft types had something t... | Everything within a computer is a bunch of 0s and 1s. But writing an entire DWORD in binary is quite tedious:
00000000 11111111 00000000 11111111
to save space and improve readability, we like to write it in a shorter form. Decimal is what we're most familiar with, but doesn't map well to binary. Octal and Hexadeci... |
5,655,388 | 5,655,457 | What C++ packages do i need to run a program? | I created a C# application that uses a C++ dll and im trying to create an install package that will allow this to run on other computers whether they have VS or not, the problem is i don't know what C++ libraries i need to let it do this. When i run just the application on a blank virtual machine it says
" xxxx has en... | That question can be tough to answer. If you have the source of the c++ dll you should be able to see its dependencies unless the person used a lot of com or load library calls. One of the best tools I used to get c++ depencany info was depends.exe. One thing to check if its your code is that you are not using debug... |
5,655,624 | 5,655,706 | Getting The Size of a C++ Function | I was reading this question because I'm trying to find the size of a function in a C++ program, It is hinted at that there may be a way that is platform specific. My targeted platform is windows
The method I currently have in my head is the following:
1. Obtain a pointer to the function
2. Increment the Pointer (& coun... | No, this will not work:
There is no guarantee that your function only contains a single ret instruction.
Even if it only does contain a single ret, you can't just look at the individual bytes - because the corresponding value could appear as simply a value, rather than an instruction.
The first problem can possibly b... |
5,655,729 | 5,655,759 | Need help with C++ Loops Exercise | From Cay Horstmann's "C++ For Everyone"
Chapter 4: Loops
Write a program that adds up the sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17)
I don't know how to make the computer "see" the numbers like separate them
| n % 10 gets the value of the one's digit. You can figure it out from there right?
|
5,656,271 | 5,658,767 | General game (RTS) scripting basics | I've been into several tutorials and links for how to integrate scripting into games--but most of these don't start early enough in the process for me. I am trying to wrap my head around the basic structure of an effectively scripted game. Here are the basics:
I'm working on starting a basic 2d RTS game in C++. The ... | icnivad's recommendation for Programming Game AI by Example is an excellent one, it's chock full of practical information.
In terms of actual engines, Unity does the job and lets you script in C#, but for someone, such as yourself, who wants to learn the nuts and bolts, it may hide too much and do too much for you. Ir... |
5,656,298 | 5,698,622 | Using boost::archive with boost::iostreams to compress data | I want to write a serialize function for a class that can optionally compress the data. I would like to use the compression facilities provided in boost::iostreams. Does anyone know how to do this?
struct X
{
X() {}
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
... | The only way I can see to do that is compress the data first and then use ar.load_binary and ar.save_binary. To compress the data, you could use a filtering_stream with std::ostringstream as sink and an appropriate compression filter.
Any reason you don't want to push the compression down the stack (that is, build your... |
5,656,664 | 6,960,726 | C++, Classes, Const, and strange syntax | I was re-reading c++ primer(4th ed.) today - the section on member functions and const references etc, and I came up with this wierd little program:
using std::cout;
using std::endl;
class ConstCheater
{
public:
ConstCheater(int avalue) : ccp(this), value(avalue) {}
ConstCheater& getccp() const {return *ccp;}
... | I'd say the answer by Tony that you marked as correct is incorrect, and the answer by Michael Burr is correct.
To put what he said more clearly (for me at least):
There are two potential places for misunderstanding:
The way implicit const works
The way that this is interpreted during construction of a const object
... |
5,656,691 | 5,656,792 | What is wrong with this variadic templates example? | The base class is :
#include <memory>
namespace cb{
template< typename R, typename ... Args >
class CallbackBase
{
public:
typedef std::shared_ptr< CallbackBase< R, Args... > >
CallbackPtr;
virtual ~CallbackBase()
{
}
virtual R Call( Args ... args) = 0;
};
} // namespace cb
Derived ... | The problem might make sense with a simpler example. Try identifying the problem here:
template <typename T>
struct id { typedef T type; };
template <typename T>
void foo(typename id<T>::type x);
foo(5); // error
The problem is that the compiler cannot deduce what T should be; it's not directly used anywhere. You'd ... |
5,656,816 | 5,656,920 | Convert/Port PDWORD code in C# | I'm converting some code from C++ to C#, and I need some insight on how to deal with lines like these:
PDWORD rgb32_data = (PDWORD) malloc(640*480*4);
From what I understand, the PDWORD type represents an unsigned integer (32bit). What would be a good C# strategy to implement a similar structure?
EDIT: I figured out... | According to MSDN, PDWORD is defined as:
typedef DWORD* PDWORD;
So it's a pointer to a DWORD, which MSDN also says is an unsigned 32-bit integer - in other words, a uint.
Note that your line of C++ code allocates memory for an array of 640 * 480 = 307,200 DWORDs.
You could translate this directly as:
uint[] rgb32_dat... |
5,656,824 | 5,656,873 | QT undefined reference errors when trying to compile | I added a class IcecastServer to my QT-project, added the header-file to the pro file and added some code. Everytime I compile it the following errors occur:
release/icecastserver.o:icecastserver.cpp:(.text+0x39): undefined reference to _imp___ZN10QTcpServerC1EP7QObject'
release/icecastserver.o:icecastserver.cpp:(.t... | First you need to #include <QHostAddress> somewhere assuming that commented out line is what caused the problem.
You may also to check some project settings to see if you have all the correct inputs.
Edit: More detail
QtNetwork requires QT network lib inputs. Assuming once again that you are using QtCreator as not muc... |
5,656,939 | 5,656,961 | Rudimentary 3D graphics in C++ .NET | I am looking to implement an extremely rudimentary FPS game with extremely rudimentary 3D graphics using C++ .NET and DirectX.
I'm not interested in any third party libraries or anything special like that.
Having never done graphics based programming besides 2D stuff I don't really know where to get started or even how... | This looks as though it may give you a push in the right direction:
http://zophusx.byethost11.com/tutorial.php?lan=dx9&num=0
I always found that OpenGL was easier to learn though. So unless it's necessary for you to use DirectX, I'd suggest you have a quick look at GL and see what you think.
|
5,657,011 | 5,657,118 | Why boost does not create a thread in such case (C2248) and how to create it? | So I have code like:
using namespace boost::asio::ip;
using namespace std;
void request_response_loop(boost::asio::ip::tcp::socket& socket)
{
http_request request(socket);
http_response response;
response.body = "<head></head><body><h1>It Rocks!</h1></body>";
response.send(socket);
socket.close();
... | To expand on Ben's answer, boost::shared_ptr<> is the usual mechanism here:
void request_response_loop(boost::shared_ptr<tcp::socket> socket)
{
http_request request(*socket);
http_response response;
response.body = "<head></head><body><h1>It Rocks!</h1></body>";
response.send(*socket);
socket->close... |
5,657,123 | 5,657,144 | How to simulate printf's %p format when using std::cout? | unsigned char *teta = ....;
...
printf("data at %p\n", teta); // prints 0xXXXXXXXX
How can I print variable address using iostreams? Is there a std::??? feature like std::hex to do this kind of conversion (address -> string), so std::cout << std::??? << teta << std::endl will print that address?
(no sprintf's, please ... | Cast to void*:
unsigned char* teta = ....;
std::cout << "data at " << static_cast<void*>(teta) << "\n";
iostreams generally assume you have a string with any char* pointer, but a void* pointer is just that - an address (simplified), so the iostreams can't do anything other than transforming that address into a string,... |
5,657,269 | 5,657,714 | QPointer for abstract base class | I am writing an expression-parsing library.
It is written with Qt, and I have a class structure like this:
QCExpressionNode-Abstract Base Class for all pieces of an expression
QCConstantNode-Constants in an expression (extends QCExpressionNode)
QCVariableNode-Variables in an expression (extends QCExpressionNode)
QCBina... | I don't see any reason why you can't do this. Take this example:
class Parent : public QObject
{
public:
virtual void AbstractMethod() = 0;
};
class Child: public Parent
{
public:
virtual void AbstractMethod() { }
QString PrintMessage() { return "This is really the Child Class"; }
};
Now initialize a QPoi... |
5,657,388 | 5,659,038 | CUDA combining thread independent(??) variables during execution | Guys I apologize if the title is confusing. I though long and hard and couldn't come up with proper way to phrase the question in a single line. So here's more detail. I am doing a basic image subtraction where the second image has been modified and I need to find the ratio of how much change was done to the image. ... | The operation you need to use to perform global summation across all the threads is known as a "parallel reduction". While you could use atomic operations to do this, I would not recommend it. There is a reduction kernel and a very good paper discussing the technique in the CUDA SDK, it is worth reading.
If I were writ... |
5,657,528 | 5,657,789 | Putting class declaration in .cpp file | Is it possible to have class declaration and implementation in same .cpp file?
I want to do some unit-testing with help of mock object. Here is some example of my test:
// Some includes removed
#include "abstractconnection.h"
class ConnectionMockup : public AbstractConnection
{
Q_OBJECT
public:
explicit Conne... | Yes, it's entirely legitimate and allowable to define a class and its member functions in a single file. In fact, from the viewpoint of the compiler that's essentially always the case -- you have the class definition in a header, and include that header in the source file where you implement its member functions.
The e... |
5,657,825 | 5,657,830 | What's the equivalent of int32_t in Visual C++? | What's the equivalent of int32_t in Visual C++?
| Visual C++ 2010 include <cstdint>, which includes typedef std::int32_t (you can also include <stdint.h> which has the same typedef in the global namespace).
If you are using an older version of Visual C++, you can use Boost's <cstdint> implementation.
|
5,657,861 | 5,662,957 | generating poisson variables in c++ | I implemented this function to generate a poisson random variable
typedef long unsigned int luint;
luint poisson(luint lambda) {
double L = exp(-double(lambda));
luint k = 0;
double p = 1;
do {
k++;
p *= mrand.rand();
} while( p > L);
return (k-1);
}
where mrand is the MersenneT... | From another question I asked earlier, it seems you could also approximate poisson(750) as poisson(375) + poisson(375).
|
5,657,898 | 5,657,919 | Can I specify that template arguments ought to be subclasses of some base class? | I have a class that is designed to work with a certain type of parameter. Is there any way that I can enforce that the template parameter be a pointer to a subclass of some type?
| #include <type_traits>
#include <utility>
struct B { };
struct D : B { };
template <typename T>
struct S {
typedef typename std::enable_if<std::is_base_of<B, T>::value>::type check;
};
int main()
{
S<B> x; // Ok!
S<D> y; // Ok!
S<int> z; // Not ok!
}
The enable_if utility and the is_base_of type... |
5,657,973 | 5,658,150 | One of the QImage constructors gives me a linker error, but another constructor doesn't? | In my project I'm using QImage to save a generated picture, but when I call
QImage image(width, height, QImage::Format_RGB32);
the visual studio compiler is giving me linker errors:
error LNK2019: unresolved external symbol "__declspec(dllimport) public: virtual __thiscall QImage::~QImage(void)" (__imp_??1QImage@@UAE@... | I found a hint to this problem at this link.
I fixed the problem by including the GUI library module in Qt Project Settings->Qt Modules.
|
5,658,021 | 5,658,073 | What's the equivalent of int64_t, int_least16_t & uint8_t in Visual C++ 2008? |
Possible Duplicate:
What's the equivalent of int32_t in Visual C++?
What's the equivalent of int64_t , int_least16_t and uint8_t in Visual C++ 2008?
|
int64_t: __int64
uint8_t: unsigned __int8
int_least16_t: __int16
|
5,658,054 | 5,658,084 | Instantiated from here | I have a problem with "instantied from here".
template <typename E>
class tree
{
public:
tree(){root=0;}
void addAVL( const E &data) throw(bad_alloc);
private:
class Node
{
public:
E data;
Noeud * left;
Noeud * right;
int high;
... | Noeud * left;
Noeud * right;
Noeud( const E&d ): ...
I guess that should be Node not Noeud? Does it fix your errors if you correct those typos?
|
5,658,483 | 5,658,558 | Linker error when using templates | I'm trying a controlled, learning experiment with my project and it involves creating my own collections and iterators, essentially an array and a linked list. There is something that I'm missing since it compiles with linking errors. I've spent three days examining, coding and recoding this and I really need some he... | In the Container class, you should declare begin() and end() as:
virtual Iterator<T> begin() const = 0;
virtual Iterator<T> end() const = 0;
|
5,658,499 | 5,658,610 | What is the relationship between a static function of a class and the constructor of the class? | What happens every time a static function is called on the class? When is the constructor executed?
| There is no dependency relationship, that is, you can call the static method without constructing an instance with the syntax "Class::method()"
class someclass
{
public:
someclass()
{
std::cout << "someclass constructor" << std::endl;
}
static void staticmethod()
{
std::cout << "som... |
5,658,542 | 5,658,594 | System Caching vs No Caching | If i were to read in a large file, with multiple threads running concurrently would running with no buffer have a faster transfer speed or would running with an OS buffer would sufficiently better?
| You shouldn't have more than one thread reading the same file at the same time, read with one thread and then send the data somehow to the others. That said, reading with buffers will be faster, but the standard already use buffer (if you read with fread or ifstream, you won't have a buffer if you use the funcion read ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.