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,201,503 | 7,201,546 | Reverse Template Alias | I need some way to achieve a "reverse template alias". So I'd use a template typedef to select the correct class to use at compile time. I'd like to do the following:
typedef ClassA Temp<int>;
typedef ClassB Temp<char>;
ClassA and ClassB are not template classes, but I'd like to select the right class through the use ... | No, typedef can't define type templates, only types. The two closest things you can do are:
template <typename T>
struct Temp;
template <>
struct Temp<int> : ClassA {}
template <>
struct Temp<char> : ClassB {}
so you write just Temp<int>, but it's a derived class, not the class itself, or
template <typename T>
struc... |
7,201,522 | 7,206,304 | short circuiting and parenthesis | Does it matter how I group subexpressions when dealing with a single short-circuiting operator?
a && b && c && d
a && (b && (c && d))
(a && b) && (c && d)
((a && b) && c) && d
Are the above expressions equivalent?
| It is relatively easy to prove the equivalence for two simplified cases of three subexpressions:
a && (b && c) --> a && bc // bc is a shorthand for b && c
Here, a will be evaluated first. If it is false, short circuiting will prevent the evaluation of bc. If it is true, bc will be evaluated, that is, b && c will b... |
7,201,621 | 7,201,803 | faster way to sort on value while retaining original index | I'm hoping to get some help coming up with a faster way to do a sort on value while retaining a key on the original order. I would prefer to avoid using boost and it does not need to be a stable sort. This is the code I came up with, it works but is slow and inefficent. I have no need to keep the map after the sort ... | Assuming it's fine to return the array of column_record objects, I don't think your solution is particularly inefficient. You could make it cleaner perhaps and eliminate the need for std::multimap by using STL algorithms:
bool compare_column_records(const column_record& lhs, const column_record& rhs)
{
return lhs.v... |
7,201,667 | 7,202,917 | Ld magically overrides statically linked symbols | For a few days we are dealing with very strange problem.
I can't understand how it even happens - when a third-party (MATLAB) program uses our shared library, it somehow overrides some of our symbols (boost, to be precise) with it's own. Those symbols are statically linked and (!!) local.
Here is the deal - we use boos... | Check out the -Bsymbolic option for ld.
If -Bsymbolic is specified, then at the time of creating a shared
object ld will attempt to bind references to global symbols to definitions
within the shared library. The default is to defer binding to runtime.
This may be clearer with an example.
Say example.o contains a refer... |
7,201,904 | 7,201,986 | How to use stdafx.h properly? | What is the proper way to use stdafx.h, in terms of separating dependencies?
If I put everything in there, then my compiles are blazing fast, and all I need to say in any file is
#include "stdafx.h"
with the caveats that:
I no longer know which files depend on which headers.
It reduces modularity, making my code less... | You shouldn't put your own header files in stdafx.h since your code is likely to change and will cause your whole program to recompile.
I usually put standard headers and other libraries in there, such as all boost includes.
|
7,202,041 | 7,202,149 | Eclipse gives an error 'Function 'MessageBoxA' could not be resolved' but still compiles successfully? | While compile Win32 applications on eclipse using the MinGW toolchain (and Internal Builder), eclipse compiles the following code:
#include <windows.h>
int WinMain (HINSTANCE p1, HINSTANCE p2, LPSTR p3, int p4)
{
MessageBox(0, "Hello.", "MyProg", MB_OK);
return 0;
}
But MessageBox is underlined in red, with th... | Eclipse can't resolve WinAPI functions. You need to add folders with WinAPI headers (windows.h) in to Include paths.
|
7,202,147 | 7,205,580 | increase buffer for cout | Citing Does setbuf() affect cout?
I want to increase the buffer size to improve the performance of cout (it is
usually redirected to disk)
Can I do:
std::cout.rdbuf()->pubsetbuf(some_buffer, buffer_size);
And also
ios::sync_with_stdio(false);
Does this make sense?
EDIT: Also I am using multiple threads, so I was hopi... | I would first check on the number of flushes that will make any larger buffer size irrelevant.
Especially look, if you have a lot of cout << endl in your code and try replacing them by cout << '\n' instead, if you do not need the flushing effect of endl.
As a last resort, before you try "optimizing" look for the root... |
7,202,215 | 7,202,279 | Why were C# generics designed to behave so differently from C++ templates? | I've already noticed that C# generics are quite different from C++ templates. I've read this question and answers to it and got a basic understanding of what the difference is.
However I don't get the reason for that design difference. I mean C++ was already quite developed when C# was being designed. What was suboptim... | The reason is that one ARE TEMPLATES the other are not. Sounds redundant? Partially because you ask a question oalong "why is a car different from a plane".
Templates are a very complex mechanism and most of the compelxity is rarely used. I think you don't really know what templates can do - only the 25% of C++ templat... |
7,202,311 | 7,202,688 | Boost: how deal time dependent thread operations? | For example having an array or reader threads and one writer thread we can sinc tham like this via shared_mutex and shared_lock this works if we are not dependent on time. But if we want to get all writing operations done inside of certan time frame and if thay are not done stop waiting and start doing something else ... | Use a timed lock.
boost::shared_mutex m
Reader()
shared_lock lock(m, timeout);
if(!lock) {
//I don't have the lock. Don't touch the resource and do something else.
}
else {
//I have the lock. Read now.
}
Writer()
upgrade_lock lck(m);
upgrade_to_unique_lock uniqueLock(lck);
Just pick a timeout value. ... |
7,202,317 | 7,202,358 | Accessing std::vector data members of a class from its member functions | I have a class which defines the following members in a header file (.hpp):
public :
int loadData(char* filename);
private :
std::vector<vertex> vertices;
std::vector<triangle> triangles;
std::vector<frame> frames;
The vertex, triangle and frame are structures defined in another header file included in this h... | A blind shot: because you forget to put the class-name before the loadData-method in your .cpp:
int className::loadData(char* filename)
But to be sure you need to show more code.
|
7,202,391 | 7,202,463 | What is the best way to include a "help" message in a console application? | I am writing a console application which is rapidly gaining many command line arguments and flags. For this reason I want the user to be able to access a description of these flags and what purpose they serve.
There are several possible solutions I can think of
I could write a README file and just stick it in the same... | Consider using the boost program options library.
|
7,202,511 | 7,202,529 | allocate memory and before delete the allocation define NULL | I would like to ask if I's correct the following :
MyClass *obj = new MyClass();//allocate memory
obj.Variab="HELLO";
obj=NULL;
delete obj; //free memory
Is the memory allocated for obj deleted after the last two sentences? Appreciate.THX
I would like to mention that I am working in c++ /Ubuntu. G++ is the compiler
... | no, you should use delete before assigning to NULL
delete obj; //free memory
obj=NULL;
this is becasue the actual parameter to delete is the address of the allocated memory, but if you assign NULL before delete is used, you are actually passing NULL to delete, and nothing will happen, and you will get yourself a memo... |
7,202,732 | 7,202,813 | Does abort run in ring 0? | These days i found a blog the mentioned abort function in C.
The following is the source code of abort function:
http://cristi.indefero.net/p/uClibc-cristi/source/tree/0_9_14/libc/stdlib/abort.c
I found that it use the hlt instruction (My PC is x86).
But seems that hlt must run in ring 0.
(refer to wiki http://en.wikip... | The abort function only uses the hlt instruction after sending SIGABRT fails. If you read the source code, the function first tries to:
raise(SIGABRT);
And then calls the invalid instruction :
/* Still here? Try to suicide with an illegal instruction */
if (been_there_done_that == 2) {
been_there_done_that++;
... |
7,202,754 | 7,202,770 | error C2228: left of '.draw' must have class/struct/union | ok, I think that the problem is that I haven't initialized the vector
but I dont know... anyway, I am getting an error saying that this is wrong:
drawable.at(i).draw();
with the vector being declared in the header file as:
vector<render*> drawable;
its a vector of render pointers as I have a whole bunch of classes th... | drawable.at(i)->draw(); because drawable.at(i) is a render pointer
|
7,202,817 | 7,202,885 | error writing to file with ofstream | I have a problem with writing number to a file with ofstream. When i write numbers there are characters like this █ instead of numbers. The method i write to the file is:
byte _b = 20;
ofstream p_file;
p_file.open("txt.txt", std::ios::app);
p_file << _b;
Is there any way to be right, or just use another filewriter... | I bet that byte is char or some variant thereof. In that case you are setting _b to the character with code 20, which in ASCII is a control character. The stream output will try to output the character not the number.
You can cast it to another integral type if you want to obtain the number:
p_file << static_cast<int>(... |
7,203,055 | 7,223,206 | Applying Boost UBLAS blas-1 to Matrices | How do I apply level 1 blas on a boost::numeric::ublas matrix?
For example I want to compute the maximum entry or the sum of all entries.
Using norm_1 or norm_inf on a matrix gives no compiler error but returns (as it seems to me) arbitrary results.
I am using boost 1.42
| norm_inf on a matrix computes the matrix norm induced by the infinity-norm on the underlying vector space. This happens to be the maximum absolute row sum of the matrix.
If you look at hannes's example, the last row of the matrix (i=99, j=0...99) contains:
9900, 9901, 9902, ... , 9999
If you sum those entries, you ge... |
7,203,231 | 7,215,281 | NEON vs Intel SSE - equivalence of certain operations | I'm having some trouble figuring out the NEON equivalence of a couple of Intel SSE operations. It seems that NEON is not capable to handle an entire Q register at once(128 bit value data type). I haven't found anything in the arm_neon.h header or in the NEON intrinsics reference.
What I want to do is the following:
// ... | You want the VEXT instruction. Your example would look something like:
int16x8_t val = vextq_s16(vector_of_8_s16, another_vector_s16, 1);
After this, bits 0-111 of val will contain bits 16-127 of vector_of_8_s16, and bits 112-127 of val will contain bits 0-15 of another_vector_s16.
|
7,203,278 | 9,205,909 | C++ algorithms that create their output-storage instead of being applied to existing storage? | The C++ std algorithms define a number of algorithms that take an input and an output sequence, and create the elements of the output sequence from the elements of the input sequence. (Best example being std::transform.)
The std algorithms obviously take iterators, so there's no question that the container for the Outp... | The Boost.Range.Adaptors can be kind of seen as container-returning algorithms. Why not use them?
The only thing that needs to be done is to define a new range adaptor create<T> that can be piped into the adapted ranges and produces the desired result container:
template<class T> struct converted{}; // dummy tag class
... |
7,203,590 | 7,203,646 | Array of polymorphic base class objects initialized with child class objects | Sorry for the complicated title. I have something like this:
class Base
{
public:
int SomeMember;
Base() : SomeMember(42) {}
virtual int Get() { return SomeMember; }
};
class ChildA : public Base
{
public:
virtual int Get() { return SomeMember*2; }
};
class ChildB : public Base
{
public:
virtual int Get() {... | Yes, this is correct behavior. The reason is
Base ar[] = { ChildA(), ChildB(), ChildC() };
initializes array elements by copying objects of three different classes onto objects of class Base and that yields objects of class Base and therefore you observe behavior of class Base from each element of the array.
If you wa... |
7,203,607 | 7,754,135 | Which is better for performance - using php-qt or writing custom php extensions for c++ using swig? | I'm writing a php web application using Yii and need to use C++ (will use Qt-Core) for some performance critical parts. I have two options:
i) Using php-qt and write those parts using qt bindings for php.
ii) Write those parts in C++/Qt and using swig to generate php extensions to use in my php app.
Which one would you... | Even though I like Qt quite a bit, but if performance is your concern I would take the swig path.
|
7,203,953 | 7,203,990 | Array allocation problem | This is probably a very easy question, but for some reason I don'd understand what I'm doing wrong here.
Anyways, I got a function that takes in function(size_type m, size_type n) and I have to build an array which is pointed to by a private variable in the class called int *value. I am trying to create an integer arra... | You may consider:
value = new int[m*n];
because you need to create a dynamic array. You will need to remember to delete [] this at the correct times.
You will probably find it easier to work with a std::vector, because the memory management is handled for you.
|
7,204,168 | 7,204,858 | C++: Clear bits of a single precision float | I'm currently converting a program that was originally intended for OpenCL to C++ and I'm having a bit of trouble with one particular part of it.
One of the expressions commonly used in said program involves taking a 32 bit float, converting it to an integer (i.e. not actually rounding it to an int, but interpreting th... | Use the union hack instead:
float ClearFloatBits(float Value, int NumberOfBits) {
union { unsigned int int_val; float flt_val; } union_hack;
union_hack.flt_val = Value;
(union_hack.int_val >>= NumberOfBits) <<= NumberOfBits;
return union_hack.flt_val;
}
Strictly speaking, this is undefined behavior. Per bo... |
7,204,173 | 7,204,783 | C++ Load function from DLL into Boost function | I want to load a particular function from DLL and store it inside the Boost function. Is this possible?
typedef void (*ProcFunc) (void);
typedef boost::function<void (void)> ProcFuncObj;
ACE_SHLIB_HANDLE file_handle = ACE_OS::dlopen("test.dll", 1);
ProcFunc func = (ProcFunc) ACE_OS::dlsym(file_handle, "func1");
ProcFun... | You need to take care about names mangling and calling convention:
So, in your DLL:
// mydll.h
#pragma comment(linker, "/EXPORT:fnmydll=_fnmydll@4")
extern "C" int WINAPI fnmydll(int value);
// mydll.cpp
#include "mydll.h"
extern "C" int WINAPI fnmydll(int value)
{
return value;
}
Then, in your DLL client applic... |
7,204,283 | 7,204,314 | How can I use a struct as key in a std::map? | I have the following code, but I get an error on on the last line:
struct coord {
int x, y;
bool operator=(const coord &o) {
return x == o.x && y == o.y;
}
bool operator<(const coord &o) {
return x < o.x || (x == o.x && y < o.y);
}
};
map<coord, int> m;
pair<coord, int> p((coord... | Try and make operator < const:
bool operator<(const coord &o) const {
(Your = operator should probably be == operator and const as well)
|
7,204,664 | 7,605,484 | pass callback from python to c++ using boost::python | I want to pass callback from my python code to c++
I want my code look something like this:
In C++ :
typedef void (*MyCallback_t) (CallbackInfo);
class MyClass
{...
void setcallback(MyCallback_t cb);
...
}
And to use it in python :
import mylib
def myCallback(mylib_CallbackInfo):
...
t = mylib.MyClass()
t.setca... | Ok, I'm still trying to figure this out too, but here's whats working for me so far:
#this is the variable that will hold a reference to the python function
PyObject *py_callback;
#the following function will invoked from python to populate the call back reference
PyObject *set_py_callback(PyObject *callable)
{
py... |
7,205,021 | 9,567,488 | Aliasing of NEON vector data types | Does NEON support aliasing of the vector data types with their scalar components?
E.g.(Intel SSE)
typedef long long __m128i __attribute__ ((__vector_size__ (16), __may_alias__));
The above will allow me to do:
__m128i* somePtr;
somePtr++;//advance to the next block
Aliasing a la Intel it will allow to advance my poin... | NEON intrinsics implementation does NOT support aliasing of the vector data types with their scalar components.
|
7,205,380 | 7,205,534 | How can i resize QVBoxLayout to fill Form without space? | How can i resize QVBoxLayout to fill Form without space?
with space:
http://0000.2.img98.net/out.php/i25106_with-space.png
without space:
http://0000.2.img98.net/out.php/i25107_without-space.png
| You have to set margins for layout
example:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QVBoxLayout* l = new QVBoxLayout();
l->setMargin(0); ///m
QWidget w; w.setFixedSize(300,300);
w.setLayout(l);
l->addWidget(new QPushButton("fd"));
w.show();
return app.exec... |
7,205,408 | 7,205,495 | Algorithm for finding a prime with the least amount of computations | Assuming you were going to write a function / method to find a prime number, what would be the most efficient way to do this? I'm thinking that it would be a test that is something like this:
Code Below in semi-c++
bool primeTest (int x) { //X is the number we're testing
int testUpTo = (int)((sqrt(x))+1);
for... | I would use the Miller Rabin test, which can easily be made deterministic for numbers smaller than 341,550,071,728,321 (and 2^31 is much smaller than that).
Pseudocode: there are a number of different cases.
x smaller than 9: Return (x & 1) != 0 || x == 2
x smaller than about 200 (tweakable): use trial division (what ... |
7,205,529 | 7,205,725 | Using std::wcin to read wchar_t always gives LF (10, 0xA) | I use this code in MSVC++2010 to implement a user input loop:
int wmain(int argc, wchar_t* argv[])
{
vector<wstring> arguments;
wstring userinput;
wchar_t userabort;
do
{
wcout << L"Please type param #" << argc++ << L":" << endl;
wcin >> userinput;
arguments.push_back(userin... | This behavior appears to occur when the "Treat wchar_t as a built-in type" (/Zc:wchar_t) option is not specified.
Go to the project's properties, under Configuration Properties, C/C++, Language, and make sure that "Treat WChar_t As Built in Type" is set to yes.
This is because when the option is set to no, wchar_t beco... |
7,205,557 | 7,205,646 | Global constants in .h file, linking problems with gcc, works with g++ | I have two .c files and one .h file included from them both. In the .h file, I have declared global constants. When building with gcc, I get linking problems, telling me that the constants are defined twice, even though I have
#ifndef __FOO
#define __FOO
const struct foo bar = ...
#endif
I get
/tmp/ccql6KF1.o:(.roda... | You should declare the constant in a .h file and define it in a single .c file:
bar.h:
extern const struct foo bar;
bar.c:
#include "bar.h"
/* do this in a single file */
const struct foo bar = ...;
Then include bar.h everywhere you want to access bar:
something.c:
#include "bar.h"
void doSomethingWithBar() {
s... |
7,205,774 | 7,205,850 | C++ : initialize static member large array | In order to use static data members in C++, I have currently something like that :
// HEADER FILE .h
class MyClass {
private :
static double myvariable;
};
// CPP FILE .cpp
double MyClass::myvariable = 0;
But if now I have :
// HEADER FILE .h
class MyClass {
private :
static double myarray[1000];
};
How can... | The same as you initialize ordinary arrays:
double MyClass::myarray[1000] = { 1.1, 2.2, 3.3 };
Missing elements will be set to zero.
|
7,205,957 | 7,206,219 | Recvfrom() is hanging -- how to deal this when Server is OFF | I have client code which gets a response from the server using UDP and recvfrom(). This is working fine when the server is ON, but once I stop the server my client program is hanging; I suspect recvfrom() is waiting for the response from the server.
If the server and client are both are installed on same system them I... | Your call is blocking, because there is no data for this socket right now. When the server was on, it was fast enough to send data so the recvfrom call got it and returned quickly. When the server is off, nobody's sending data and recvfrom waits forever. It does not matter whether server is on or off, recvfrom is doing... |
7,206,037 | 7,206,433 | C++ - When function inlining is not possible? | Folks,
I was reading "Thinking in C++" (Chap - Inline functions), where I encountered this statement.
"The compiler also cannot perform inlining if the address of the
function is taken implicitly or explicitly".
What does that mean by "taking address of function implicitly or explicitly" ?
Why it is not possible t... | Actually, the quote may mislead.
If a function address is taken, then it is necessary to generate the function in the library/executable, because the execution of a function by its address consist in jumping the instruction pointer to the block of code describing the function.
However, it certainly does not prevent the... |
7,206,062 | 7,206,220 | Pointer array question | int test[3] = {1,2,3};
cout<<test[3]<<endl;
// this will get a error
but
int test[3] = {1,2,3};
int (*A)[3];
A = &test;
cout<<test[3]<<(*A)[3]<<endl;
// this will print -858993460 withiout any errors
So could anyone tell me why? i am really confused by that.
in the first case why it is not outofboundary error ... | Undefined behaviour seems a very tricky concept for newbies to understand. But it's very simple, if you break the rules of C++ (as both your examples do) then, very often, the behaviour of your program is undefined. It means exactly what it says and it's pointless asking 'why does it do that' as there are no longer any... |
7,206,116 | 7,206,277 | Instantiate a template class <erroneous-expression>? | Here is my code :
template<typename T, template<typename = T,typename =std::allocator<typename = T> > class Container= std::vector>
class stack
{
public:
Container<T> cont;
stack()
{
}
};
If i replace the very first line of code to below code then it works :
template<typename T, template<t... | When a template parameter is itself a template, then its own template parameters are not used or relevant in the context of the outer template other than to define the "template signature" of the template-template parameter. Therefore, you don't need neither parameter names, as they are not usable or necessary. You can... |
7,206,298 | 7,206,926 | Is printing an empty string observable behavior in C++? | In C++03 Standard observable behavior (1.9/6) includes calls to library I/O functions. Now I have this code:
printf( "" );
which is formally a call to a library I/O function but has no effect.
Is it observable behavior? Is the compiler allowed to eliminate it?
| It's certainly observable if sync_with_stdio is true. When that's true, printf("") forces synchronization with std::cout output, flushing previously buffered output.
|
7,206,633 | 7,206,742 | Undefined Reference To Member function | I'm trying to solve a compiling problem regarding outside defined constructor.
Here's 2 of the classes that have this problem:
//Username.h
#ifndef USERNAME_H
#define USERNAME_H
#include <string>
using namespace std;
class Username{
private:
string Name;
public:
Username(string = "");
string getName() co... |
g++ User.cpp
This compiles User.cpp and attempts to create an executable from it (ie the linker is invoked). Since User.cpp has a symbol not fully defined in User.cpp (the Username constructor here:
User::User(string s):UserUsername(new Username(s)){}
the symbol is expected to be defined at the link stage. Linking i... |
7,206,771 | 7,207,275 | Dealing with hex values in C/C++ | I receive values using winsock from another computer on the network. It is a TCP socket, with the 4 first bytes of the message carrying its size. The rest of the message is formatted by the server using protobuf (protocol buffers from google).
The problemn, I think, is that it seems that the values sent by the server a... | not sure if this will be of any use, but I've used a similar protocol before (first 4 bytes holds an int with the length, rest is encoded using protobuf) and to decode it I did something like this (probably not the most efficient solution due to appending to strings):
// Once I've got the first 4 bytes, cast it to an i... |
7,207,103 | 7,207,176 | Is it better to define global (extern) variables in a single header, or in their respective header files? | I'm working on a small software project which I hope to release in the future as open-source, so I was hoping to gather opinions on what the best currently accepted practices are in regards to this issue.
The application itself is procedural, not object oriented (there is no need for me to encapsulate the rendering fun... | To me it is way better to have a header file corresponding to each implementation (c or cpp) file. You must think your classes, structures and functions as modules, and if you split your implementation, it is logical that you split your delarations too.
Another thing is that when you modify a header file, it leads all ... |
7,207,135 | 7,207,989 | Fixing big system font on some machines that is warping font in C++ program? | I have written a program (using Borland C++ builder) that works fine with normal default windows settings. But certain users have changed their systems to have a bigger font than normal (as in, they changed the windows theme or changed system settings to have the font bigger for bad eyesight, etc). This makes a lot of ... | Set each form's Scaled property to true. Each form will be resized according to the font scaling prevailing on the machine which shows the form.
|
7,207,211 | 7,207,387 | Which C language and Graphic library should be use to write OS independent program? | I am trying to write a program which I want to run just before booting up the system like the Setup program of Windows XP. The problem is that I cannot figure out which version of C/C++ programming language should be use. Because as far as I know about the many versions of C language they only works in DOS, Windows and... | You want to write a program that runs directly off boot, with no OS loaded? Sorry, but if you need to ask which language to use, you have a learning curve ahead of you that's so steep that you ought to consider lowering your ambitions considerably for a first effort.
In the bad old days when space was at a premium, boo... |
7,207,239 | 7,207,305 | What's the difference between putting std::string and std::string::c_str() into a stringstream? | We're seeing a strange scenario that basically boils down to the following:
std::string something = "someval";
std::stringstream s;
s << something;
std::cout << s.str();
is not equal to:
std::string something = "someval";
std::stringstream s;
s << something.c_str();
std::cout << s.str();
Taking that a step farther ... | It is different if the string contains nul characters, '\0'.
The .c_str() version will compute the length up to the nul, while the std::string output will know its length and output all its characters.
|
7,207,391 | 7,207,406 | The tilde operator in C | I've seen the tilde operator used in the ELF hashing algorithm, and I'm curious what it does. (The code is from Eternally Confused.)
unsigned elf_hash ( void *key, int len )
{
unsigned char *p = key;
unsigned h = 0, g;
int i;
for ( i = 0; i < len; i++ ) {
h = ( h << 4 ) + p[i];
g = h & 0xf0000000L;
... | The ~ operator is bitwise NOT, it inverts the bits in a binary number:
NOT 011100
= 100011
|
7,207,431 | 7,207,520 | Initialize templated type to "zero" | If I have a template function, say one that calculates an average by summing up the elements in a container of type T holding things of T::value_type, how do I elegantly initialize the sum with a zero?
Suppose the underlying type is not a plain old data type. It could be a complex variable, or some other as yet uncode... | maybe you would like better
T::value_type sum = T::value_type();
|
7,207,884 | 7,207,934 | Class construction with initial values | I'm new to C++, and the whole idea of classes - I'm still reading a book to try and learn. The book I'm reading says that when I construct a class, I can assign default values by doing this:
class foo {
public:
foo(char c, int i);
private:
char exampleChar;
int exampleInt;
};
foo::foo(char c, int i):
exampleC... | The first way, by doing : exampleChar(c), exampleInt(i) is called an initializer list.
If you do it the second way, the two variables are default constructed first1, then you assign them a value. (When the actual body of the constructor is entered, anything that hasn't been initialized by the initializer list is defaul... |
7,207,992 | 7,208,844 | XCode and expat XML parser | Expat has a .la file for the lib. I am trying to link against it with XCode.
What I have done is to set the target's "Other link flags" to libexpat.la and the "library search path to where the .la file exists.
I get a link error.
Is this an expat installation error or my usage of XCode?
| You also need to add the library to the "Link Binary with Libraries" build phase under your target. Here's what it looks like in Xcode 3:
|
7,208,048 | 7,208,105 | Is the order of the virtual table important? | I'm new so go easy on me :)
From what my lecturer had told some time ago, the order of the virtual table is important.
But I do not understand the reason for that!!?
Given the next code :
class A
{
public:
A() {cout <<"1" << endl;};
A (const A& s) {cout << "2" << endl;}
~A () {cout << "3" << endl;}
voi... | The order of the vtable is important for things to work properly, but only to the compiler (i.e. you don't need to care because it takes care of it).
If the compiler put it out of order for itself, then yeah, things would break, because functions are looked up by offset (so an offset would yield a random function which... |
7,208,070 | 7,208,119 | GoogleTest: How to skip a test? | Using Google Test 1.6 (Windows 7, Visual Studio C++). How can I turn off a given test? (aka how can I prevent a test from running). Is there anything I can do besides commenting out the whole test?
| The docs for Google Test 1.7 suggest:
If you have a broken test that you cannot fix right away, you can add the DISABLED_ prefix to its name. This will exclude it from execution. This is better than commenting out the code or using #if 0, as disabled tests are still compiled (and thus won't rot).
Example from the abo... |
7,208,253 | 7,209,857 | QSettings - Sync issue between two process | I am using Qsettings for non gui products to store its settings into xml files. This is written as a library which gets used in C, C++ programs. There will be 1 xml file file for each product. Each product might have more than one sub products and they are written into xml by subproduct grouping as follows -
File: "pr... | This is kind of an odd thing that you're doing, but one thing to note is that the sync() call is what actually writes the file to disk. In this case if you want your second process to actually see the changes you've made, then you'll need to call sync() before your second process accesses the file in order to guarantee... |
7,208,309 | 7,208,954 | Private inheritance hides base class with "inaccessible within this context" error | I'm having a problem similar to that described in Private inheritance renders class inaccessible where a privately inherited base class gives an "inaccessible within this context" error when I try to declare a member of the base class inside the derived class.
Explicitly referencing X with ::X works in the above case, ... | The problem that you are facing is that there is an injected identifier X in Y (and all derived types) that refers to X, which is not accessible below Y.
In the common case of user-defined types that are declared at namespace level, you could use the namespace to qualify the type and gain access:
class X {};
class Y : ... |
7,208,535 | 7,208,592 | Binary Tree search returns no results (C++) | I am working on some binary tree algorithms and need a "find node with searchindex..." function. The design for treenodes is basically
class TreeNode {
int index; // some identifier
TreeNode *left;
TreeNode *right;
}
and a tree is defined by a pointer to the root-node.
My implementation for the search function i... | Because you pass resultNode into the function as a pointer by value, its original value never changes. Think of TreeNode* as literally nothing more than a number representing a memory address; when you reassign it:
resultNode = root;
This modifies the copy that searchNode has, but not the original pointer in the code ... |
7,208,822 | 7,211,199 | Implementing T9 text prediction | I have a T9 dictionary in memory (trie/hash_map). The dictionary contains word-rating pairs, so when a word is picked from dictionary, its rating increments, and the word-rating pair goes up in the word list.
Let's say that there is a method to pick a word from the dictionary. That method also does some word rating r... | One option that I think would be particularly efficient would be to preprocess the trie into a modified structure specifically optimized for predicting words based on keystrokes.
Intuitively, the new structure is a trie created out of the possible digits that could be pressed at any point. Each trie node then stores a... |
7,208,828 | 7,344,635 | Should I use CString, basic_string<TCHAR>, or something else with ATL/WTL? | I've only learned a little bit of ATL in the last couple of days (after realizing how much pain pure Win32 is) and also learned about WTL and MFC, and from what I see, there are quite a few different string classes available for me.
I used to do something like this:
#include <tchar.h>
#include <string>
namespace std { ... | Something that I just read is that CString does not support null characters.
I guess I'll keep with STL, then.
|
7,208,829 | 7,209,350 | How to use Boost.MSM is_flag_active inside on_entry? | I would like to use is_flag_active() function inside one of my state's on_entry template function:
struct StBladeDown : public msm::front::state<> {
template<class Event, class FSM>
void on_entry(Event const& event, FSM& fsm) {
if(fsm.is_flag_active<FlagMaster>()) { // ERROR
// doSomeThing()... | Try this:
struct StBladeDown : public msm::front::state<> {
template<class Event, class FSM>
void on_entry(Event const& event, FSM& fsm) {
if (fsm.template is_flag_active<FlagMaster>()) {
// doSomeThing();
}
}
};
Note the addition of the template keyword. See this FAQ for inform... |
7,209,028 | 7,209,102 | How to remove borders of the window created by GLUT? | The question is quite clear, GLUT provides us functions to create a windowed application. But presently I need to re-design the title bar, and also the border styles. Anyway to remove the borders and title bar? (certainly I'm talking about C++ or Visual C++ 'cause this is an OpenGL related question)
| You have at least three options:
Modify your GLUT implementation to add this feature. If you're using FreeGLUT look into the implementation of fgOpenWindow() in freeglut_window.c.
Use a different framework that supports this feature. It looks like SFML should.
Manage the OS interface yourself.
|
7,209,591 | 7,209,712 | How to check for changes to the program code while I am running it | Hello fellow developers,
assume I had a program that required authorization granted to him by a server over the network. Obviously, at some point within my code there would be something along the lines of:
if (serverResponse == expectedResponse){
//Continue as the authorized user
}
This system has a very, very unl... | The trick here is not to rely on a simple if statement. As you say that is easily circumvented by someone who can reverse engineer your code. Instead you should use the value returned from the server for some vital function of your program. For instance the response from the server could be used as a key to decrypt som... |
7,209,654 | 7,746,657 | FindWindow by class name not working? | To preface we have a strange requirement that all dialogs must be modeless for an MFC application. There is a particular dialog using region drawing and some custom controls to select dates and times for viewing past and future data per view. I need to be able to close this window when it loses focus, the main app gets... | Below is the simplest and cleanest solution I could come up with:
BOOL CTransactionDialog::OnNcActivate(BOOL bActive)
{
if (!bActive)
PostMessage(WM_CLOSE);
return CDialog::OnNcActivate(bActive);
}
|
7,209,738 | 7,209,776 | Why won't the C++ compiler disambiguate between an inherited public and an inherited private method with the same name? | I'm confused as to why the C++ compiler won't accept this:
class Foo {
private: void Baz() { }
};
class Bar {
public: void Baz() {
};
class FooBar : public Foo, public Bar { };
void main() {
FooBar fb;
fb.Baz();
}
The error gcc gives is:
request for member ‘Baz’ is ambiguous
candid... | Name resolution works in two stages. First the name is looked up then the name is checked for access. If the name look up is ambiguous then the access is never considered.
As to why, maybe it's a deliberate language design, but I think more likely it's just to simplify the process of resolving names. The rules are fien... |
7,209,832 | 7,210,404 | Qt: best way to delegate a drag and drop to children | I'm using drag and drop on QWidget, I have reimplemented dragEnterEvent, dragLeaveEvent, dragMoveEvent and dropEvent, and that works well.
In my QWidget, I have other QWidget children, and I want them to manage drag and drop too. The issue is my parent QWidget catch the dnd events, so my children don't get it. What is ... | From the drag-and-drop documentation:
To be able to receive media dropped on a widget, call setAcceptDrops(true) for the widget, and reimplement the dragEnterEvent() and dropEvent() event handler functions.
Here's the quick summary:
The child should call setAcceptDrops(true).
The child should reimplement the dragEnt... |
7,210,075 | 7,210,302 | C++ code for right triangle using WHILE loop | I need to print this triangle:
*
**
***
****
*****
******
*******
********
using a FOR and WHILE loop. I need help, I have already figured out the for loop version I just have to convert it to while loop but everything I try is not giving me the correct output! Any help is appreciated!
My code so far:
#include <iostre... | What are the rules?
while (1)
{
cout << "*" << '\n';
cout << "**" << '\n';
cout << "***" << '\n';
cout << "****" << '\n';
cout << "*****" << '\n';
cout << "******" << '\n';
cout << "*******" << '\n';
cout << "********" << '\n';
break;
}
|
7,210,143 | 7,210,205 | Where are stored structs and classes written in C++? | In C# classes are stored in heap, and structs are stored in stack.
Does in C++ classes and strucs are stored in the same way (assuming I create my classes and structs statically, and every member of class or struct is not allocated by new) ?
Please explain this using snippet of code below:
class B
{
int b;
}
class C
... | There is no (necessary) difference in how structs are stored vs. how classes are stored. In fact, the only difference between structs and classes in C++ is that struct members are public by default, and class members are private by default.
Like any other kind of object, an object of class or struct type has a storage... |
7,210,286 | 7,901,567 | Incomplete class usage in template | I am very surprised that on various sampled versions of g++, the following compiles without error or warning:
// Adapted from boost::checked_delete()
template <class T> inline void assert_complete()
{
typedef char type_must_be_complete[ sizeof(T) ? 1 : -1 ];
(void) sizeof(type_must_be_complete);
}
class X;
void f... | (I was waiting to Alf Steinbach to post an answer, but since he is not doing it, I will post the reference that he mentioned in the Lounge C++ chat):
The standard indicates that template instantiations are performed after the translation unit has already been translated, so that in time, template instantiations happen ... |
7,210,321 | 7,210,718 | dynamic_cast doubt from C++/Stroustrup : converting to protected base class | I know that following code gives compilation error :
class A{ public : virtual void name(){cout<<typeid(this).name()<<endl;}; };
class B:protected A{public : virtual void name(){cout<<typeid(this).name()<<endl;};};
void foo(B* b)
{
A * a = dynamic_cast<A*>(b); //Error : 'A' is an inaccessible base of 'B'
r... | The actual quote from 15.4.1 is:
class BB_ival_slider : public Ival_slider, protected BBslider {
// ...
};
void f(BB_ival_slider* p)
{
Ival_slider* pi1 = p; // ok
Ival_slider* pi2 = dynamic_cast<Ival_slider*>(p); // ok
BBslider* pbb1 = p; // error: BBslider is a protected base
BBslider* pbb2 = dyn... |
7,210,324 | 7,210,460 | Affect depth, or stencil buffer from inside fragment shader? | I know it is possible to control what is written to the depth buffer in GLSL by writing to gl_FragDepth, but is it possible to write to the stencil buffer?
Also, can I cancel a pixel write completely from within the fragment-shader, as if the pixel had failed a stencil or depth test?
Thanks
| If you are using the right hardware, you can write to the stencil buffer. All Radeon HD hardware can use AMD_stencil_shader_export. There is an ARB_stencil_shader_export, but I can't verify if it is particularly widespread.
If you want to stop a fragment from writing anything, you can use discard. It's sort of like thr... |
7,210,331 | 7,210,365 | Capture/redirect cout to a function | Is it possible to capture cout in a way so that every standard output (cout << "example";) automatically calls a function (myfunc("example");)?
| One way would be to create a class which had the appropriate operator<< overloads and create a global instance called cout and to using std::whatever instead of using namespace std;. It would then be easy enough to switch back and forth from your custom cout to std::cout.
That's just one solution though (which may requ... |
7,210,389 | 7,622,917 | How to make my `std::string url_encode_wstring(const std::wstring &input)` work on Linux? | So we have such function:
std::string url_encode_wstring(const std::wstring &input)
{
std::string output;
int cbNeeded = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, NULL, 0, NULL, NULL);
if (cbNeeded > 0) {
char *utf8 = new char[cbNeeded];
if (WideCharToM... | IMHO you should use a portable character codec library.
Here's an example of minimal portable code using iconv, which should be more than enough.
It's supposed to work on Windows (if it does, you can get rid of your windows-specific code altogether).
I follow the GNU guidelines not to use the wcstombs & co functions ( ... |
7,210,412 | 7,210,431 | What is the cost of inheritance? | This is a pretty basic question but I'm still unsure:
If I have a class that will be instantiated millions of times -- is it advisable not to derive it from some other class? In other words, does inheritance carry some cost (in terms of memory or runtime to construct or destroy an object) that I should be worrying abo... | Inheriting from a class costs nothing at runtime.
The class instances will of course take up more memory if you have variables in the base class, but no more than if they were in the derived class directly and you didn't inherit from anything.
This does not take into account virtual methods, which do incur a small runt... |
7,210,417 | 7,211,924 | Symbolic Math Library in C/C++/Obj-C | I am trying to implement a graphing calculator on the iPhone. I am looking for a library that can take strings of expressions or functions and let me manipulate them (find derivatives, intercepts, zeros, etc). Does anything like this exist?
| There's GiNaC for C++. GPL-licensed and actively maintained, last update only a month ago. I found old links to many others that don't seem to exist anymore; perhaps people simply found it easier to use GiNaC?
|
7,210,905 | 7,212,124 | Using Qt where worker thread creates new GUI elements | I will keep the code simple so that you guys can see what I'm trying to do ;)
I am aware of all of the locking issues, etc. I'm trying to figure out how signals and slots play with threads.
In main.cpp:
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MyConsole c; // Subclasses QThread an... | The "Qt way" to emit a signal from one thread and receive it in a different thread is to use a Queued connection
connect( obj, SIGNAL(foo()), other_obj, SLOT(bar()), Qt::QueuedConnection )
From the Qt documentation for Qt::QueuedConnection:
The slot is invoked when control returns to the event loop of the receiver's ... |
7,210,944 | 7,210,968 | Can T in template <typename T> use inheritance? | I want to do something like this:
template <typename T:public Vertex> addTri( T v1, T v2, T v3 )
{
// Take v1.pos, v2.pos, v3.pos and create a geometric repn..
Triangle tri( v1.pos, v2.pos, v3.pos ) ; // all vertices will
// have to have a .pos member.
// Create the vertex buffer..
VertexBuffer<T>... | You cannot specify a type restriction in the template type argument. However, generally, you don't have to.
If you simply do:
template <typename T> addTri( T v1, T v2, T v3 )
{
Vertex &v1r = v1;
// ....
}
This will work if the function is instantiated with a derivative of Vertex. It will create an (obscure) er... |
7,211,019 | 7,211,173 | Binding modifiable rvalue reference to modifiable lvalue | I have 3 questions:
Can I bind a lvalue directly to a rvalue reference?
What happens to the object that being std::move()?
What's the difference between std::move and std::forward?
struct myStr{
int m_i;
};
void foo(myStr&& rs) { }
myStr rValueGene()
{
return myStr();
}
int main()
{
myStr mS= {1};
... |
1>Can I bind a lvalue directly to a rvalue reference ?
Not without an explicit cast (ie: std::move).
2>What happens to the object that being std::move() ?
Nothing until it is actually moved. All std::move does is return an r-value reference to what you gave it. The actual moving happens in the move constructor/assi... |
7,211,193 | 7,211,283 | nested overloaded operators? | Is nesting overloaded operators possible ? I would like to nest << inside a ()
template<class T>
struct UnknownName
{
T g;
T&operator<<(std::ostream&os, const T&v){return os<<v;}
bool operator()(const T&v)
{
if(v==g)
//do the streaming << then return true
else return false;
}
};
Woul... | The best I can think of would be to have operator<< return a specific type, and then overload operator() to accept that type:
#include <cstdio>
namespace {
struct Foo {
struct Bar {
int i;
};
Foo& operator()(const Bar& b)
{
std::printf("bar, %d\n", b.i);
... |
7,211,365 | 7,215,594 | QT C++ - Class problem wait until signal is processed and return data back | I've this code here in a program I'm making but I've a problem, How can I keep the program waiting for data on http2 before returning to the tcpserver class? And how can I get the data in the tcpserver class?
This is like a checkpoint were I need to get the data from the server and then keep running the tcpserver and u... | Qt makes use of signals and slots and the event loop. If you have no QEventLoop running which is normally provided by QApplication your events will not be handled.
Take a peek at this question to see how to create an event loop to simulate a blocking (synchronous) using the asynchronous programming model.
In addition I... |
7,211,422 | 7,211,484 | GLUT and C++ Classes | I've started using OpenGL a while ago, using GLUT. You can't pass member functions to GLUT functions. (or pointers to members for that matter, though I did not explore that option really far).
I was wondering if there is a "decent" way, or what is the "most decent" way to solve this? I know you can use static member f... | First, GLUT is not for serious application work. It's for simple graphics demos. And for that purpose, it is fine. If you find yourself trying to do serious work in GLUT, you will find yourself spending lots of time working around its limitations. This limitation is only one of many that you will eventually encounter. ... |
7,211,572 | 7,212,547 | Vectorizing (SIMD) Tree operations | What are some general tips/pointers on vectorizing tree operations? Memory layout wise, algorithm wise, etc.
Some domain specific stuff:
Each parent node will have quite a few (20 - 200) child nodes.
Each node has a low probability of having child nodes.
Operations on the tree is mostly conditional walks.
The performa... | Beware, this is very hard to implement. Last year a team of Intel, Oracle and UCSC presented an amazing solution "FAST: Fast Architecture Sensitive Tree Search
on Modern CPUs and GPUs". They won the "Best Paper Award 2010" by ACM SIGMOD.
|
7,211,594 | 7,211,713 | gluCylinder() and texture coordinates offset / multiplier? | How can i set the texture coordinate offset and multiplier for the gluCylinder() and gluDisk() etc. functions?
So if normally the texture would start at point 0, i would like to set it start at point 0.6 or 3.2 etc. by multiplier i mean the texture would either get bigger or smaller.
The solution cant be glScalef() bec... | Try using the texture matrix stack:
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glTranslatef(0.6f, 3.2f, 0.0f);
glScalef(2.0f, 2.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
drawObject();
|
7,211,642 | 7,211,670 | Enum argument based on template parameter? | Is it possible to generate arguments based on int type of a template ?
I would like to generate something like
template<int num>
void func(int g,...){}
if num=10 then I would like my function becomes void func(int g, int gg, ....., int gggggggggg);
I would love to know if this is feasible. Thank you.
| Variadic function arguments a la <cstdarg> are not typesafe, and they're not a good idea in C++. If you have C++11, you can use variadic templates for much better results.
Be that as it may, if you want to go with variadic function arguments, you have to tell the function which arguments there are and how big they are.... |
7,211,806 | 7,211,832 | How to implement insertion for AVL tree without parent pointer? | I saw some articles about the implementation of AVL's rebalance() function.
After each insertion, we should check the insertion Node's ancestors for balance.
So I think, in order to check ancestors' balance, I got to know the insertion Node's parent.
But, I wonder is there any other way to do that without having to use... | You can maintain a stack to the current node while you are traversing the tree
stack<Node*> nodeStack;
When you traverse to a new node, add it to the stack, and then you have your ancestry.
When you finish processing a node, pop it from the stack.
** Edit **
Elaboration for the alignment comment:
struct Node {
int... |
7,211,858 | 7,211,891 | passing arguments as array of integers | struct G{
G&operator()(const int**a)
{
v<<a;
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " "));
return *this;
}
friend std::vector<int>&operator<<(std::vector<int>&v,const int** n);
std::vector<int>v;
};
std::vector<int>&operator<<(std::vector<int>&v,cons... |
&v is giving you the address of the array, when you want the address of a pointer. Try doing const int* x = v then g(&x).
In C++0x, you can do this:
G& operator()(std::initializer_list<const int>);
g({1,2,3,4,5,6,5,4});
|
7,211,923 | 7,211,937 | Adding an offset to a pointer | If I have a pointer to an object and I want to get a pointer to an object that is say 16 bytes after the pointer how do I add the 16 byte offset to the pointer?
Also, memory addresses in 32bit systems look like this 0x00000000. If I change an address like 0x00000001 to 0x00000002 how many bytes are skipped?
| Pointers count bytes, so to point at the next byte you would need to change a pointer's value by 1. Pointer arithmetic, however, counts the objects pointed to by the pointer, and incrementing a pointer increases its value by the size of its pointee type. If you want to point at bytes, use a char pointer, since char has... |
7,211,934 | 7,211,954 | C++ Memory addresses? | How do memory addresses work?
In 32-bit a memory address is an hexadecimal value like 0x0F032010, right? But do those values point to bytes or to bits?
And what lies between two memory addresses like 0x0F032010 and 0x0F032011
|
In 32-bit a memory address is an hexadecimal value like 0x0F032010, right?
Its a number. A location in memory. It is bounded by the start and end of memory, which is starting at some value and ending at some value.
But do those values point to bytes or to bits?
It is generally accepted that addresses point to the... |
7,211,959 | 7,211,982 | Dividing points into subregions using hashmaps | I have a 2D raster of say 200pixels x 200pixels I want to subdivide this into 400 "buckets" of each 10x10 pixels.
Then I have a list of points ( about 200k ) that I want to map in the aforementioned structure. So if the point falls into the 10x10 area, add it to the bucket.
Now this seems to me something a hashtable co... | I think that you're confusing two pieces of terminology. There are "buckets" in the hash table sense, which are some internal implementation detail used to distribute elements evenly so that lookups tend not to scan over too many useless elements. There are also "buckets" in the spatial sense, which are partitions of... |
7,212,069 | 7,212,126 | C++, most efficient way to modulate sign (+/-) in an expression | I have an expression
x += y;
and, based on a boolean, I want to be able to change it to
x -= y;
Of course I could do
if(i){x+=y;} else{x-=y;}
//or
x+=(y*sign); //where sign is either 1 or -1
But if I have to do this iteratively, I want to avoid the extra computation. Is there a more efficient way? Is it possible to... | The most efficient way to do this iteratively is to precompute the data you need.
So, precomputation:
const YourNumberType increment = (i? y : -y);
Then in your loop:
x += increment;
EDIT: re question in commentary about how to generate code, like this:
#include <stdio.h>
void display( int x ) { printf( "%d\n", x... |
7,212,127 | 7,212,133 | How to overcome Memory error when reading large file (over 1GB) -- C/C++ | I am trying to read a file of over 1GB (which has 1,157,421,364 bytes), it gives memory error when using fread() function, but works well when I use fgets() function.
Note: I have intermixed C and C++..
Can someone help me to overcome this memory error, am I doing something wrong?
Thanks in advance...
Error is "Memory ... | You can read the file in chunks, instead of reading it as a whole, reading all of the file to one allocated buffer means a huge memory allocation of your application, do you really want that?. That's being said assuming you don't need to process it all in once (which is true in most cases).
|
7,212,212 | 7,212,264 | conversion for void* as a method argument | For a method with an argument of void* is C++ employing static/reinterpret_cast to make the conversion or is there a different mechanism in play here?
void foo(void* p)
{
// ... use p by casting it back to Base first, using static/reinterpret cast
}
Base* base(new Derived);
foo(base); // at this exact line, i... | The language specification does not express the behavior in terms of static_cast or reinterpret_cast in this case. It just says that the pointer base is implicitly converted to void * type. Conversions that can be performed implicitly are called standard conversions in C++. Conversion of any object pointer type to void... |
7,212,375 | 7,212,380 | Create my own operator in c++ | I know it is possible to overload operators that already exist in c++ to define desired behavior, but is it possible to create your own operator?
Just for example, making an operator # that returns the size of containers:
template<typename T>
size_t operator#(const T& obj) { return obj.size(); }
vector<int> v(1024);
c... | No. You need to stick with the operators the parser already knows how to handle. Overloading can extend the meaning of expressions, but the syntax is fixed.
|
7,212,554 | 7,212,587 | What base would be more appropriate for my BigInteger library? | I have developed my own BigInteger library in C++, for didactic purpose, initially I have used base 10 and it works fine for add, subtract and multiply, but for some algorithms such as exponentiation, modular exponentiation and division it appears to be more appropriate use base 2.
I am thinking restart my project from... | If you look at most BigNum type libraries you will see that they are built on top of the existing "SmallNum" data types. These "SmallNum" data types (short, int, long, float, double, ...) are in binary for too many reasons to count. Rather than a vector of base 10 digits, your code will be much faster (much, much, much... |
7,212,563 | 7,212,581 | Parsing a string by a delimeter in C++ | Ok, so I need some info parsed and I would like to know what would be the best way to do it.
Ok so here is the string that I need to parse. The delimeter is the "^"
John Doe^Male^20
I need to parse the string into name, gender, and age variables. What would be the best way to do it in C++? I was thinking about looping... | You can use getline in C++ stream.
istream& getline(istream& is,string& str,char delimiter=’\n’)
change delimiter to '^'
|
7,212,585 | 7,212,600 | Why is my union's size bigger than I expected? | When I print the size of a union like this:
union u {
char c[5];
int i;
} un;
using this:
int _tmain(int argc, _TCHAR* argv[])
{
printf("size of union = %d ",sizeof(un));
return 0;
}
I get an answer of 8 using Visual C++, but I expected 5. Why?
Well, for the same example,
i did something like this:
int i1... | The sizeof operator produces the size of a variable or type, including any padding necessary to separate elements in an array of that type such that everything is still correctly aligned. Since your union has an int member, it needs to be 4-byte aligned, so its "natural" size gets rounded upwards to the next multiple o... |
7,212,776 | 7,212,794 | External headers include in C++ | I have two projects, and they have some headers in common, so they both include those headers. Now my question is: Can I implement these headers in outside cpp files. For example when the header is inside the project you just declare the functions and implement them in .cpp file, and because the .cpp file is in the pro... | It depends on what you are trying to accomplish. I valid solution is to create a "header only" file where the implementation is in the declaration. A large portion of the boost library does this.
Another option would be to put your common code in another project, and link to it.
|
7,212,790 | 7,212,812 | complex template parameter type for C++ STL set | I'm implementing an STL set with a complex template parameter type. When inserting in to the set, I want the set to use the less-than operator I've defined for my type. I also want to minimize the quantity of object instantiations of my type. It seems I can't have both.
I've got two minimal examples below, each uses... | You are getting a copy from this: *new Foo(1).
Create this struct:
template<typename T>
struct PtrLess
{
bool operator()(const T *a, const T *b) const
{
return *a < *b;
}
};
Make the map look like set<Foo*, PtrLess<Foo>> s; and then add Foo's like s.insert(new Foo(1));
Note the *
Otherwise, when th... |
7,212,814 | 7,212,879 | How do I prevent continuation of the program if player inputs invalid selection? | I created a text-based game to help improve my C++ skills since I am very new to it. I'm trying to learn the basics n' all.
Here is the program. In the switch statement, if a person were to select "3" it would broadcast an Error saying you can only select "1" or "2".
** The issue is the program continues and doesn't m... | Use a do ... while loop, like this
int pickRace;
do
{
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
cout << "Pick your race: ";
cin >> pickRace;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "Yo... |
7,212,870 | 7,212,901 | Loading a dylib from a different architecture | I currently have a program I have compiled in x86_64, it relies on quite a few libraries also compiled in x86_64 (so recompiling them all would be a big project). I am looking to run a i386 dylib, however whenever I load it using dlopen I get an error saying it was not built for my architecture. Is there any way to eit... | You cannot load an i386 library in an x86_64 executable.
There only way to get an x86_64 library out of an i386 one is to recompile it for the right target. If you don't have the source code, this cannot be done.
You can recompile all your code for i386 and use the library though.
|
7,212,995 | 7,213,047 | What is .NET and how do I know if my project uses it? | I have a C++ assignment and it specifies that I may not use .NET technology in my project. What is .NET and how do I know if my Visual C++ project uses .NET or not?
I am using Visual Studio 2008.
| .NET is a Microsoft development framework. Its Common Language Runtime (CLR) is the basis for languages like C#, and it includes a lot of prewritten code libraries for simplifying common tasks.
Long story short, if you're coding in C++, you aren't going to be using any .NET functionality unless you accidentally set up... |
7,213,062 | 7,213,137 | Bit counting in a contiguous memory chunk | I was asked in an interview the following question.
int countSetBits(void *ptr, int start, int end);
Synopsis:
Assume that ptr points to a big chunk of memory. Viewing this memory as contiguous sequence of bits, start and end are bit positions. Assume start and end
have proper values and ptr is pointing to an initi... | The most quick and efficient way to my opinion is to use a table of 256 entries, where every element represents number of bits in the index. Index is a next byte from the memory location.
something like this:
int bit_table[256] = {0, 1, 1, 2, 1, ...};
char* p = ptr + start;
int count = 0;
for (p; p != ptr + end; p++)
... |
7,213,159 | 7,213,208 | Microsoft C++ compiler is too annoying! Is there an alternative for compiling for Windows 32/64bit? | I am so frustrated with the Microsoft C++ compiler (not Visual). I am really annoyed at how it uses
int _tmain(
and
_TCHAR* argv[]
as well as many other things. I just want to use straight C++ like you would in GCC. Is there an alternative?
Thanks to all the responses. I was really just looking for a way of not usin... | You don't have to use _tmain() and TCHAR if you do not want to. Just create an empty project, add an empty source file to it and start writing
int main(int argc, char* argv[])
{
}
On VC++ 2010 Express you can just compile and execute it straight away. I don't remember if previous versions require that you set the proj... |
7,213,211 | 7,213,220 | C++ boost unordered_map - determine if key exists in container | In boost::unordered_map how do I determine if a key exists in it or not?
boost::unordered_map<vector<int>, MyValueType> my_hash_map;
if (my_hash_map[non-existent key] == NULL)
The above gets compiler error "no match for operator '=='..."
Is the problem that I am using a custom value type or something else?
| You can use the find method:
if (my_hash_map.find(non-existent key) == my_hash_map.end())
|
7,213,284 | 7,213,562 | customizing unittest++ | I'm asking this with hopes that somebody has been in my shoes and has some ideas. Trying to avoid reinventing the wheel, so to speak.
I'm using UnitTest++: http://unittest-cpp.sourceforge.net/UnitTest++.html
I've got quite a few tests written by now, and they all execute every time I run the test build, which of cours... | Here's my solution:
namespace UnitTest {
class ListFilter {
char **list;
int n;
public:
ListFilter(char **list_, int count) {
list = list_; n = count;
}
bool operator()(const Test* const t) const {
for (int i=0;i<n;++i) {
std::stri... |
7,213,362 | 7,213,390 | compile-error when trying to inherit from std::runtime_error | I'm trying to compile this with g++ under Ubuntu:
#ifndef PARSEEXCEPTION_H
#define PARSEEXCEPTION_H
#include<exception>
#include<string>
#include<iostream>
struct ParseException : public std::runtime_error
{
explicit ParseException(const std::string& msg):std::runtime_error(msg){};
explicit ParseException(con... | The compiler through its error messages tells you important things. If we take just the first message (it is always a good thing to take care of compilation problems one by one, starting by the first that occurred):
parseexception.h:9: error: expected class-name before ‘{’ token
It tells you to look at line 9. There i... |
7,213,366 | 7,213,408 | What happens during initialization of a class? | Here is the code which confuses me:
#include <iostream>
using namespace std;
class B {
public:
B() {
cout << "constructor\n";
}
B(const B& rhs) {
cout << "copy ctor\n";
}
B & operator=(const B & rhs) {
cout << "assignment\n";
}
~B() {
cout << "destructed\n";
... | First Case:
B t1;
t1 = play(5);
Creates a object t1 by calling default constructor of B.
In order to call play(), A temporary object of B is created by using B(int i). 5 is passed as an and object of B is created, and play() is called.
return b; inside play() causes the copy constructor to be called for returning... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.