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,494,772 | 7,507,221 | Qt, Designer creates scrollAreaWidgetContents in scrollArea, and i cant resize my imagelabel | I have dragged a scroll area into the designer, then i dragged a label (imageLabel, for setPixmap). Then i have right clicked and set the layout to be grid.
scrollArea = new QS.....
scrollAreaWidgetContents = new QWidget();
gridlayout = new QGri..(scrollAreaWidgetContents);
imageLabel = new QLabel(scrollAreaWidgetConte... | resize is ignored most of the time when the widget is inside a layout.
You can use setFixedSize or setMinimumSize instead to force the size or a size smaller than the image.
You also need to set the QLabel scaledContents property to True (in the designer or with QLabel::setScaledContents) to scale the image to the lab... |
7,494,869 | 7,494,897 | interesting problem with map<char*, int> | char* a = "aaa";
map<char*, int> m;
m.insert(pair<char*, int>(a,5));
a[0] = 'c';
a[1] = 'c';
a[2] = 'c';
cout << a << endl; // a = `ccc`
cout << m["aaa"] << endl; // found the node by `aaa`,
cout << m.begin()->first << endl; // but the node's left is actually `ccc`?
So the node's left is ccc or aaa?
| Actually it does not found the node by "aaa" nor "ccc", it founds the node by the memory address a points to. Comparison between pointers does just that, it does not perform a string comparison. If you want to index by a string, then use an std::string.
|
7,494,954 | 7,495,018 | C/C++ custom allocator memory leak | I create a custom memory allocator like following:
class pool_allocator
{
// required methods
// ...
private:
boost::shared_ptr<MemoryChunks> m_t;
};
The purpose of this allocator is to share memory allocating by different container and only deallocate them when all container and deleted. therefore, I use ... | Are you aware that allocators are treated as stateless in C++03? Try using your allocator in conjuntion with Boost.Containers (It was just accepted, but I think they are already part of Boost.Interprocess), which respects allocators. Not easy to say anything else without the definition for MemoryChunks.
|
7,495,254 | 7,495,283 | How to replace access specifiers with its data in a strings? | HI I have following three strings,
char* string1, string2, string3;
printf("First string = %s", string1);
printf("Second string = %s", string2);
printf("Third string = %s", string3);
Output of above code is,
First string = My Content is : %s, My value is : %d
Second string = Open source OS
Thirf string = 100
Now i ne... | Use sprintf along with printf as:
char format[1024];
sprintf(format, "First string = %s", string1); //this makes the format string
printf(format, value1, value2); //this prints output with the formatted string
|
7,495,492 | 7,495,564 | calculate the sum of all element in a double array | i am a bit confused in using array in doing recursion, can anyone correct my mistake?
new update, based on question required some of the line cannot be edit
double sum_of_array(double x[],int size)
{
static double sum; <---can be edit
int index = 0; <--can be edit
if(index<size){
return sum + sum_o... | You never actually add the values in x[] and y[] to sum and in addition, index is always equal to 0. You should probably pass it as another parameter to the function:
double sum_of_array(double x[], int size, int index)
{
if(index<size){
return x[index] + sum_of_array(x, size, index+1);
}
else {
... |
7,495,891 | 7,495,912 | Will fseek function flush data in the buffer in C++? | We know that call to functions like fprintf or fwrite will not write data to the disk immediately, instead, the data will be buffered until a threshold is reached. My question is, if I call the fseek function, will these buffered data writen to disk before seeking to the new position? Or the data is still in the buffer... | I'm not aware if the buffer is guaranteed to be flushed, it may not if you seek to a position close enough. However there is no way that the buffered data will be written to the new position. The buffering is just an optimization, and as such it has to be transparent.
|
7,496,129 | 7,496,183 | Whether assigning smart pointer to _variant_t requires a manual AddRef()? | Here is an example snippet:
_variant_t var;
var.vt = VT_UNKNOWN;
var.punkVal = unknownInterfaceSmartPointer;
unknownInterfaceSmartPointer->AddRef(); // Question Statement
// Setting unknownInterfaceSmartPointer to some other container
Whether manual AddRef is really needed here? Following will is better way than t... | If you directly assign to punkVal member (as in your first snippet) then you need an AddRef() - noone will do it for you. A much better way would be to use operator=() member of _variant_t:
_variant_t var;
var = unknownInterfaceSmartPointer.GetInterfacePointer();
or do as you suggest - use a conversion constructor:
_v... |
7,496,224 | 7,496,313 | while loop in assembly language | There is such code in C++:
#include <iostream>
int main(){
int a = 4;
while(a--){
std::cout << (a + 1) << '\n';
}
return 0;
}
and corresponding code of main function in assembly code produced by g++:
.globl main
.type main, @function
main:
.LFB957:
.cfi_startproc
.cfi_personality 0x0,__gxx_p... | The while condition is formally the equivalent of:
while ( a -- != 0 )
(Omitting the comparison is a legal obfuscation.)
The compiler is generating code to compare a with 0, save the
results in register al, then decrement a, and then test the saved
results.
|
7,496,225 | 7,496,645 | boost signals connection management | I've been bashing my head for the last two nights trying to figure this out with no positive results. There is the thing, in boost signals, every time I want to connect, say, a member function of one class to another's class signal, I have to save the resulting connection in a variable if I want to disconnect later. If... | You shouldn't need to keep connection instances around, you should be able to disconnect from a signal by passing the original callable to signal::disconnect, as described in the Boost.Signals tutorial. With member functions the problem is rather the fact that you cannot pass them directly to signal, you either wrap th... |
7,496,280 | 7,496,320 | How to figure out if the first index in an array is a negative sign | I am trying to write a bool function that looks at the first index in an array which contains a positive or negative number and classifies if it is a negative sign (i.e. -). If it is a negative Sign it returns false everything else returns true. I am trying to figure out how to compare the negative sign. The following ... | char '-';
The compiler thinks you're trying to declare a char, but that's not a valid declaration.
Your entire function could be replaced with:
return (digits[0] != '-');
Of course, this is assuming that [0] is a valid index of digits. If not, bad things will happen. If you know the length of the array, you can do a ... |
7,496,431 | 7,496,479 | LoadLibrary for the calling program itself | I know that under Linux you can get a handle to the calling program with dlopen( NULL, RTLD_* ). Is there a way to do so in Windows using LoadLibrary? I've tried using LoadLibrary(NULL) which doesn't work, the handle variable is NULL, and I've tried by specifying the executable file as well and that doesn't seem to be ... | The handle to your own process is already open, you should not use LoadLibrary to open a new one. Use GetModuleHandle (specifically, GetModuleHandle(NULL)) or instance handle from WinMain instead.
|
7,496,516 | 7,496,707 | C-style casting confusion | I'm reading someone's (public) source code and I've come across this line and have no idea what it does. I've tried decomposing it but it always ends up confusing me in spite of what I try.
uintptr_t* pInterfaceVTable = (uintptr_t*)*(uintptr_t*)pd3dDevice;
pd3dDevice is a LPDIRECT3DDEVICE9, which is a IDirect3DDevice9... | uintptr_t is an integer type that can store a pointer.
The author assumes (knows?) that the first entry in IDirect3DDevice9 is a pointer, so he casts IDirect3DDevice9 to (uintptr_t*) and dereferences it to access that pointer. Then he casts that uintptr_t again to a pointer (to uintptr_t) to assign it to pInterfaceVTa... |
7,496,657 | 7,496,714 | When printing hex values using %x why is 'ffffff' printed after each value? | In a sample c++ code I will open a file and print each char in hexa
file has only 16 chars but why ffffff will print after each heax values?
char buff[256];
// buff filled with fread
for(i=0;i<16;i++)
printf("%x",buff[i]);
Output is:
4affffff67ffffffcdffffff
Why is this?
| Edit:
printf("%x", (int)(*(unsigned char*)(&buff[i])) );
This should make the trick. My first version was incorrect, sorry. The problem is in the sign bit: every value more than 127 was handled as negative. Casting to unsigned char should solve the problem.
|
7,496,848 | 7,497,460 | How do you make a method avaible to other dlls in a c++ dll in managed code? | The first piece of code is the example i am working on, after changing it to the second example, it works exept for the __declspec(dllexport) wich gives a __declspec(dllexport) cannot be applied to a function with the __clrcall calling convention. removing that piece of code does make the dll compile but the method is ... | The C++/CLI compiler does support exporting managed functions. It automatically generates a thunk that loads and initializes the CLR if necessary so that the managed code can be executed. Beware the overhead. You however can't use any managed types for the function arguments. IntPtr in your case. That doesn't make... |
7,496,870 | 7,497,036 | Passing parameters, pointer and adress problem | I have some problem with passing parameters to function. Example:
#include <iostream>
using namespace std;
struct VShop
{
bool index;
char *fName;
char *edName;
char *genre1;
char *genre2;
double rating;
double price;
};
void AddtoDB (VShop *Film, char *name, char *ed, char *genre1, char ... | There are several errors with your code. Firstly:
VShop *Film = new VShop[size];
size is 0 and which may fail and will not work when you try to access it.
Secondly:
*size++;
++ has higher precedence than * so it evaluates to:
*(size++);
while increments size and then dereferences the old value of size. You probably ... |
7,497,123 | 8,350,934 | QUICKFIX 64-bit Build for .NET on Visual Studio (.NET C++ DLL Wrapper) | I spent a sleepless night trying to build QUICKFIX to have the 64-bit version of quickfix_net.dll and quickfix_net_messages.dll
My C# Framework is 64-bit and the regular offered QUICKFIX dll's are 32-bit, so I have no other choice (Switching back my app to 32-bit is NOT an option)
I was expecting the VS_10 solution to... | You should check out QuickFIX/n, a FIX library built specifically for .NET (without the unmanaged C++ wrapper). QuickFIX/n keeps all the good conventions of QuickFIX.
|
7,497,167 | 7,497,437 | How do you call CMFCRibbonProgressBar methods from a different thread? | I have a simple CMFCRibbonProgressBar and a thread that calls SetPos(value, TRUE) on it when a lengthy operation progresses.
The problem is that in debug mode it asserts in wincore.cpp with this:
CHandleMap* pMap = afxMapHWND();
ASSERT(pMap != NULL);
I understand by the comments in that file that I shouldn't b... | Ok, someone commented very briefly on the question and they had the right answer. I don't know why they retracted their comment :/
I ended up storing a CWnd* pointer in the CMFCRibbonProgressBar derived class, and whenever I call the "SetAmountCompleted" method from the worker thread, I use the CWnd to send a custom me... |
7,497,192 | 7,497,237 | ENUM constants questions | It was posted on this site how you could generate unique enum constants by doing the following:
enum _EXAMPLE
{
LEFT = 'left',
RIGHT = 'right'
//etc
};
Ignoring the issue of validity, how are the numbers generated? More specifically, what technique is used? As I wish to try to build a function that emulate... | 'left' is a multicharacter literal (2.13.2/1 of C++03), it has type int.
It's implementation-defined what integer value it actually has. In particular, there's no guarantee that 'left' and 'right' aren't equal, so you're on to something of a loser using them in an enum.
For an example, though, GCC documents its behavio... |
7,497,630 | 7,498,764 | How to measure the time that a piece of code takes to execute? | Suppose I want to measure the time that a certain piece of code takes. For that I would normally do something like this
clock_t startTime = clock();
//do stuff
//do stuff
//do stuff
//do stuff
float secsElapsed = (float)(clock() - startTime)/CLOCKS_PER_SEC;
What if the program is multithreaded and context switches occ... | There are different ways to measure how long code takes to execute.
If you are interested in the relative performance of certain functions, a profiler is the only way to go. Note that this will de-emphasise the impact of blocking I/O due to the computation overheads it induces.
If you want the clock-based time of certa... |
7,497,637 | 7,497,708 | C++ - detect out-of-range access | I would like to analyse my C++ code to find bad access in vectors and arrays (out of range access), is there a tool for that ?
thanks in advance
| You can compile with _GLIBCXX_DEBUG and _GLIBXX_DEBUG_PEDANTIC defined if your are using gcc. This will enable glibc assertions to be raised if out of bounds access is requested.
Testing with valgrind::memcheck will also reveal bad memory reads
|
7,497,962 | 7,498,025 | Find and subsitute a portion of a const char array | My problem is the following:
a const char* is provided to the function in which I would like to perform the operation I am going to describe
what is provided is a filename (full absolute path included) of indeterminate length
I would like to locate the occurrence of the substring output and replace it with input
the o... | This will work, but you don't need the cast on name.c_str() (in fact, it's wrong: c_str() returns a const char *).
But the pointer you get from name.c_str() is invalidated as soon as you modify name, or when name goes out of scope. So don't try returning newfilename from a function, for instance.
If you need it to per... |
7,498,211 | 7,498,234 | memory management question |
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
i have following question related to memory managment,source from where i am reading this article says that,
When a variable goes out of scope, that memory is no longer guaranteed to store the
variable’s value
example code is given
in... | The key phrase "no longer guaranteed". The behaviour is undefined. It might work, or it might not, depending on what your compiler decides to do.
You cannot rely on this behaviour. So you should never write code like that.
|
7,498,371 | 7,498,468 | how to store an ip address in c++? | I am creating a p2p c++ library, where I intend to maintain a linked list of members (their Ip addresses and ports for communications), identical on every members. What C++ data type should I use to store IP addresses? string, long int? so that I can easily use them for UDP communications later on, possibly using send... | Define a new datatype. You may be able to get some inspiration from previous attempts at this:
Boost.Asio ip::address
Poco::Net IPAddress
.Net System.Net.IPAddress
Java java.net.InetAddress
And so on and so forth.
|
7,498,553 | 9,061,135 | Direct2D interface and blurry text issue | My new application will feature a rich interface which should be resizable on-the-fly uses transparent icons/images etc. For this application I'm trying to decide on using the new Direct2D API against the good old GDI. One of the downsides is of course it does not run on XP, although I've found a bit nastier issues to ... | The fix to your problem is very simple. Direct2D is highly configurable, and that includes text rendering and hinting. If you want to make it render text to match GDI's rendering (that is, very tight pixel alignment) just:
Call the SetTextRenderingParams function on the render target http://msdn.microsoft.com/en-us/li... |
7,498,589 | 7,498,741 | Good way to integrate C++ App Server with C# Web Service (Client+Server) | I have WSDL of remote web service and WSDL of server.
I have C++ application server too and i must integrate this Web Service
Client and Server with C++ POSIX server daemon.
I will implement web services in C#.
I integrate web service server with C++ server with XML protocol over TCP/IP
But what is good solution for in... | Look at "gSOAP Toolkit" (http://www.cs.fsu.edu/~engelen/soap.html)
|
7,498,835 | 7,499,080 | Beginning c++: OOP Methodologies and more |
Possible Duplicate:
OO Software Design Principles
My questions concern methodology that are built onto OOP (not sure about the terminology here...). I have learned some things about the Law of Demeter and MVC.
I am not a total beginner in programming, but I have never worked on a really tricky OOP development. So I ... | You should realise that although C++ was initially designed to enable OOP, it is very ill suited for that kind of programming (where I define OOP as the use of virtual functions, which imply dynamically allocated objects, etc...).
Modern C++ programming provides tools that are far better than traditional OOP for solvin... |
7,498,892 | 7,499,490 | About command line arguments of main function | It will look like int main(int argc, char *argv[]);. My questions are:
1 How many array items can I add in argv[]?
2 What is MAX size of every char *?
| You can try:
$ getconf ARG_MAX
2180000
http://pubs.opengroup.org/onlinepubs/007904975/basedefs/limits.h.html
ARG_MAX is maximum length of argument to the exec functions including environment data.
That is, there is no individual limit on the number of arguments or argument's length. Only the limit on total size requ... |
7,499,286 | 7,499,496 | C++ class: pointer to a non-static func | This is my last question. I try to improve my class Thread.
Constructor receives pointer to the function, that must run in a new thread.
class Thread {
public:
Thread(void (*p)()) {
pf=p;
}
~Thread () {}
void StartThread() {
hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadPro... | As the outhers pointed out, the problem is that a static method cannot access non-static members. The usual way to do something like this is to pass the object as parameter to the thread start routine, e.g.:
class Thread {
public:
Thread(void (*p)()) {
pf=p;
}
~Thread () {}
void StartThread() {... |
7,499,400 | 7,499,583 | Ternary conditional and assignment operator precedence | I'm confused about direct assignment and ternary conditional operators precedence:
#include<stdio.h>
int main(void)
{
int j, k;
j = k = 0;
(1 ? j : k) = 1; // first
printf("%d %d\n", j, k);
j = k = 0;
1 ? j : k = 1; // second
printf("%d %d\n", j, k);
return 0;
}
I would expect the out... | The operator precedence in the C/C++ language in not defined by a table or numbers, but by a grammar. Here is the grammar for conditional operator from C++0x draft chapter 5.16 Conditional operator [expr.cond]:
conditional-expression:
logical-or-expression
logical-or-expression ? expression : assignment-expres... |
7,499,423 | 7,499,452 | how are integers stored in memory? | I'm confused when I was reading an article about Big/Little Endian.
Code goes below:
#include <iostream>
using namespace std;
int i = 12345678;
int main()
{
char *p = (char*)&i; //line-1
if(*p == 78) //line-2
cout << "little endian" << endl;
if(*p == 12)
cout << "big endian" << endl;
}... |
I'd prefer a reinterpret_cast.
Little-endian and big-endian refer to the way bytes, i.e. 8-bit quantities, are stored in memory, not two-decimal quantities. If i had the value 0x12345678, then you could check for 0x78 and 0x12 to determine endianness, since two hex digits correspond to a single byte (on all the hardwa... |
7,499,796 | 7,500,245 | Error on cvApproxPoly function | I have the following fragment of code:
int count = (int)sizes.size();
CvPoint2D32f p;
CvSeq* seq = cvCreateSeq(CV_SEQ_KIND_GENERIC|CV_32FC2, sizeof(CvSeq), sizeof(CvPoint2D32f), memStorage1);
CvSeq* result;
for (int i=0;i<count;i++) {
p.x = sizes[i];
p.y = depths[i];
cvSeqPush(seq, &p);
}
result = cvAppro... | According to this post, cvApproxPoly gives an error when the CV_SEQ_POLYLINE flag isn't set for the sequence you pass in. Try adding that flag to your cvCreateSeq line.
|
7,499,839 | 7,499,860 | boost shared_ptr get owner count | I'm using boost::shared_ptr to store a pointer to texture. I'm loading new textures as i need and share them among the program using shared_ptr. If my app is using too much memory i want to remove unused textures to clear memory. Is there a way I can determine how many objects are having access to the texture via shar... | If it's unused then the shared_ptr will free it automatically. That's the point of shared_ptr. If you are holding a shared_ptr to a texture without actually using it, then you're violating the contract of shared_ptr and should not be using it.
|
7,499,846 | 7,500,643 | convert getch() response to ascii character | I am using ncurses on linux. I use getch() to get the next key pressed from the input stream but it returns a number not a letter.
After doing research on google I have found that getch() is not standard so I am at a loss of what to do.
I need the keys 0-9, tab, ctrl, p,v,m,l,a,b,c,d,e,f, and the arrow keys as well a... | MAJOR EDIT Get rid of previous examples, try this large one.
The return value from getch() is either an ASCII character, or the curses name for some special key.
Here is a program that might make the point clear:
#include <ncurses.h>
#include <cctype>
int main(int ac, char **av)
{
WINDOW* mainWin(initscr());
... |
7,499,902 | 7,499,926 | c++ inserting elements at the end of a vector | I am experiencing a problem with the vector container. I am trying to improve the performance of inserting a lot of elements into one vector.
Basically I am using vector::reserve to expand my vector _children if needed:
if (_children.capacity() == _children.size())
{
_children.reserve(_children.size() * 2);
}
and... | Increasing the capacity doesn't increase the number of elements in the vector. It simply ensures that the vector has capacity to grow up to the required size without having to reallocate memory. I.e., you still need to call push_back().
Mind you, calling reserve() to increase capacity geometrically is a waste of effort... |
7,500,021 | 7,500,158 | Preventation from starting a thread twice | Imagine you have a little calculation method, which is startet by a thread:
boost::mutex mMutex;
void MyClass::DoSomething {
boost::unique_lock<boost::mutex> tLock(mMutex);
if(tLock.owns_lock() {
// do some stuff...
}
}
And you want to start this in a thread, raised from different member functions. They can... | Make a variable and before you start the t1 thread, increase that variable in atomic way. When it finished, decrease that variable to null in atomic way. In Foo you should just check if this variable is null, or not.
Check this example.
|
7,500,024 | 7,500,105 | how do I define a member of the linked list? | LinkedList<T> Class:
I want each member to be a struct containing an
IPAddress object and an integer.
| struct Foo {
IPAddress a;
int dummy;
};
int main() {
LinkedList<Foo> list;
}
|
7,500,386 | 7,500,520 | Writing bits to COM port in Windows - equivalent to INPORTB function | I am writing a program to control a relay switch connected thru the serial (RS-232) COM1 port. The device I am using has contains two relay switches. These are either 'open' or 'closed'.
By default, both relays are open. The number 1 relay is closed by setting bit 1 in the modem control register. Number 2 relay is clos... | You need to understand how your device works. You cannot "set bits" directly in hSerial. Having COM port opened, you can send/receive bytes. Possibly you need to send something to device using WriteFile(hSerial, ...). Maybe you need to read information from device using ReadFile(hSerial, ...). COM port is not port as i... |
7,500,515 | 7,500,724 | WiX/MSI - Custom Action - Upgrade Logic | I have some sort of requirement that states that we have to set up scheduler tasks in the install phase and then, naturally, remove them in the uninstall phase.
However this scenario gets complicated when we introduce our upgrade mechanism (we just have major upgrades), where we have to preserve these scheduler tasks.
... | You can condition the custom action execution with "Not UPGRADINGPRODUCTCODE".
http://msdn.microsoft.com/en-us/library/windows/desktop/aa372380(v=vs.85).aspx
|
7,500,772 | 7,500,809 | Shared Pointer on a thread counts 1 after join? | Having a boost::condition_variable which waits for a thread to complete:
boost::condition_variable mContd;
boost::shared_ptr<boost::thread> mThread;
Imagine, the Thread was started some time before, and now wait:
if(!mContd.timed_wait(tLock, boost::posix_time::seconds(1))) {
// cancel thread if deadline is reached
... | use_count() simply tells you how many shared_ptr object points to the same boost::thread object. It has nothing to do with whether the thread has terminated.
The counter will automatically get decremented when mThread goes out of scope.
If you no longer need the thread object, you could call mThread.reset(). That'll al... |
7,500,890 | 7,501,018 | Good RNG for shuffling playing cards | Right now I'm using the Mersenne Twister RNG and performing Fisher-Yates shuffle algorithm 100 times:
std::vector<Card> shufCards;
for(int i = 0; i < 4; ++i)
{
for(int j = 0; j < 13; ++j)
{
shufCards.push_back(Card((Card::SuitEnum)i,(Card::RankEnum)j));
}
}
for(i... | Our perception of randomness is notoriously poor. If you suspect that your routine is skewed in some way, I'd recommend conducting a large number of random trials using your routine and then looking at the realized probabilities of various hand distributions, and comparing them with what is to be expected theoretically... |
7,500,901 | 7,787,689 | Malformed Archived TOC Entry on creating StaticLib | I'm currently working on a project which creates a static library and three executables that link to this library. On a clean build when I try to create the library on OSX 10.7.1 it will build correctly. However if it's not a clean build then I get this error.
ld: in ./libframework.a, malformed archive TOC entry for Ga... | The error here is that the table of contents of the static library need to be updated when recompiling. To fix this the -s flag can be added to ar or ranlib can be executed after compiling the library but before linking.
|
7,500,902 | 7,501,366 | Internal and external encoding vs. Unicode | Since there was a lot of missinformation spread by several posters in the comments for this question: C++ ABI issues list
I have created this one to clarify.
What are the encodings used for C style strings?
Is Linux using UTF-8 to encode strings?
How does external encoding relate to the encoding used by narrow and wid... |
Implementation defined. Or even application defined; the standard
doesn't really put any restrictions on what an application does with
them, and expects a lot of the behavior to depend on the locale. All
that is really implemenation defined is the encoding used in string
literals.
In what sense. Most of the OS igno... |
7,501,002 | 7,501,058 | Is it possible in C++ to declare an attibute in the body? | Is it possible in C++ to declare an attibute in the body, that is, the .cpp file ?
| If by attribute, you mean member variable of a class, then the answer is: "member variables must be defined in the class definition." They cannot be defined anywhere else, neither in the constructor, or in any member function.
Whether the class definition sits in the header file or in the source (.cpp) file is not rele... |
7,501,146 | 7,501,218 | what standard says about static casting to temporary inheritor? | sometimes (quite rarely) I need to get protected members from existing variables
like this:
struct S {
protected:
int i;
};
struct T : S {
using S::i;
};
int main() {
S s;
static_cast<T&>(s).i = 0;
}
I'm almost sure this ( static_cast(s) ) is UB, but is someone know what the C++ standard (2003) says about this... | This type of operation is actually the basis for implementing the constant reoccurring template pattern, where inside the base-class you actually static_cast the this pointer of the base-class to the derived-class template type. Since S is an unambiguous base class of T, and you are not accessing any members from the ... |
7,501,189 | 7,501,373 | How to redefine large amounts of data quickly | I'm currently writing an ASCII Command Prompt game engine and I am not sure how to redefine 256+ ASCII chars quickly. I am not up to the job of learning all 256 codes.
I was going about having a separate file with the variables to save space, but honestly I'm not upto the job of writing this:
char ascii_null = char(0);... | The standard methods are to use #define or const to provide a name to values. These will more efficient since you won't be changing the values after you define them.
#define ascii_null char(0)
#define ascii_bell char(7)
or
const char ascii_null = char(0);
const char ascii_bell = char(7);
The easiest way to write tho... |
7,501,211 | 7,501,423 | How to set the alignment in a platform independent way? | In the latest draft of the c++11 standard, chapter 3.11 talks about the alignment.
Later, the chapter 7.6.1 defines how to define an aligned structures (or variables?)
If I define a structure like this :
alignas(16) struct A
{
int n;
unsigned char[ 1020 ];
};
does it means that all instances of the class A are goi... | Alignment is first and foremost a property of types.
It can be overridden for a type with alignas; alignas can also be used to assign a new alignment value to a specific object.
So, both examples are valid, and will have the semantics that you've presumed.
[n3290: 3.11/1]: Object types have alignment requirements (3.9... |
7,501,235 | 7,513,912 | How to declare a template default value when using CRTP with several template parameters? | I want to do:
template <class Derived=BattleData>
class BattleData : public BattleCommandManager<Derived> {
};
But obviously BattleData isn't declared, so I tried a forward declaration:
template <class T> class BattleData;
template <class Derived=BattleData>
class BattleData : public BattleCommandManager<Derived> {
}... | Here is how I solved it:
template <class Derived> class BattleDataInh: public BaseClass<Derived> {
void foo1(){};
void foo2(){};
void foo3(){};
};
template class SubBattleData: public BattleDataInh<SubBattleData> {
void foo1(){};
};
class BattleData : public BattleDataInh<BattleData> {
};
And that wa... |
7,501,294 | 7,501,502 | UDP client multicast : join a group, what address to specify? | http://msdn.microsoft.com/en-us/library/ekd1t784.aspx
The JoinMulticastGroup method subscribes the UdpClient to a multicast group using the specified IPAddress.
What address should I specify?
context: I have many computers, which I want to exchange messages between each other by udp multicasting so that one computer ... | While echoing @Vlad's suggestion on general network background, there is sample code in MSDN for the scenario you want here.
The following code example demonstrates how to join a multicast group
by providing a multicast address.
Once you have members who have joined the group, any member can call Send to multicast ... |
7,501,322 | 7,501,855 | How can I show an dialog in which the permissions of a registry key can be set | I'm working on a registry editor for Windows.
I want to add an dialog which can be used to change the permissions for a specific registry key. This is the way it should look like:
This dialog is used by regedit and also by third party registry editing software such as
O&O Regeditor.
I'm looking for a windows function... | You want the Access Control Editor.
|
7,501,620 | 7,502,374 | Create color variations in cpp | I have a given color and want to create variations of it in terms of hue, saturation and lightness.
I found a webpage which creates variations the way I would like it (See http://coloreminder.com/). However, I do not entirely understand how these variations are created for an arbitrary color. From what I can tell from ... |
From what I can tell from considering created variations at this home page, it seems not to be enough to simply change the HSL values seperately to create variations.
Really? The interface seems to be clear enough about what modifications it makes. You can select "hue", "saturation" or "luminance" and it shows 9 va... |
7,501,839 | 7,501,859 | WinAPI - avoid redraw of window | I'm drawing into a WinAPI-Window by using the SetPixel()-Function.
If I scale the window or lose focus (another window is on top) I lose the whole content that I draw into the window.
I just used
RECT rc;
GetClientRect(hwnd, &rc);
RedrawWindow(hwnd, &rc, NULL, RDW_NOERASE | RDW_NOFRAME | RDW_VALIDATE);
which helped to... | Draw it to a buffer/bitmap and then draw that to your window.
|
7,501,996 | 7,510,982 | Accessing the indices of non-zero elements in a UBLAS sparse vector | How can I know the index of the first non-zero element in a sparse_vector in ublas and each subsequent nonzero element as well? The function begin() gives me an iterator that can be used to know the first non-zero value stored, not its index in the vector.
| Here is the answer, after Oswin Krause, from the ublas mainling list:
Iterators offer a method index() which returns the desired result. But
remember that only the const_iterator is really sparse!
for(SparseVector::const_iterator pos = sparseVec.begin(); pos !=
sparseVec.end();++pos){ std::cout << pos.index()<< "... |
7,502,291 | 7,502,347 | Drawing without flickering | I have a win32 application which was developed in c++. The application draws some stuff on the window using basic shapes (rectangles). The windows is repainted every 20ms (50hz) using InvalidateRect. All works well but the drawing is flickering. How can i prevent the flickering? In c# i normally use a double buffered c... | You can easily implement double buffering in Win32 as well. Assuming you are doing your painting directly on the Window using its device context, do this instead:
Create a "memory" device context and do all your drawing on that device context, then copy the invalidated portions of the window to the actual device conte... |
7,502,314 | 7,504,157 | Question about the explanation of data segment on Wikipedia? | Following yesterday's question, I did some research and I thought I had a more clear picture of linux process memory map.
I think one reason of my initial confusion is the incorrect explanation on Wikipedia, which claims heap is a part of data segment, which is obviously wrong. Also, it claims that data segment is not ... | "Segments" are a rather old-fashioned concept, dating back to when modern paged-memory architectures weren't widely used. Segmented architectures forced quite a rigid memory layout, whereas paged memory allows the process to have many separate regions of virtual memory, each with its own access restrictions.
A Linux pr... |
7,502,344 | 7,507,999 | Centering Pascal's Triangle Output in C++ | I have successfully written a code to output Pascal's Triangle in a somewhat triangular shape using cout.width(total_rows - current_row), but it looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
... | I figured it out. You have to use the stringstream library to convert the integer line from the Pascal function to a string. You can then just use string.length() to figure out how many characters are in the string. Then you do the math that I was explaining earlier to adjust the output.
Here's my code:
/*
* Pascal's... |
7,502,356 | 7,502,646 | Windows Mobile C++ - Application design-type question | i have my application skeleton working as expected - it might be that somebody has a good solution to what i am trying to achieve within Windows Mobile 6.5 enviroment.
Here's what i am actually trying to do:
Application running in background ( it sends periodically network packets to office server, packets are loaded ... | You'll have to move to a Windows Mobile paradigm for your app, as what you're trying to do isn't possible (as you're finding). A home screen plug in has problems if the user customizes it, and you are correct that there is no "tray". The icons in the corner (battery, signal strength, etc) are reserved for OEM use onl... |
7,502,476 | 7,502,560 | using getch() to hold command prompt open Visual C++ 2010 | Im currently learning c++ from a book called 'Ivor Hortons Beginning Visual c++ 2010'.
In all the examples i've attempted so far I've had to use getch() to hold open the command prompt, and sometimes remove the return 0 statement from the end of the main method.
Is this a vagary of windows 7 and will it cause problems ... | getch() is not operating system specific, but it is not directly portable. The preferred method for doing this in C++ is to use std::cin.get();.
The main function can return 0 implicitly (you don't need to actually have that code, see below).
int main()
{
// valid, return 0 implied.
}
See this question for more de... |
7,502,588 | 7,507,049 | CreateCompatibleBitmap and CreateDIBSection (Memory DC's) | from what I've read here it seems that most of the Windows GDI functions are accelerated. So for instance a call to BitBlt or AlphaBlend uses hardware acceleration if available. It also mentions that the contents of a window are kept only in video memory. Now this is all good and true for a window DC, but how can I use... | Memory DCs are not created on a device. They are designed to put GDI output into memory.
From Memory Device Contexts on MSDN:
To enable applications to place output in memory rather than sending
it to an actual device, use a special device context for bitmap
operations called a memory device context. A memory DC e... |
7,502,600 | 7,503,040 | How to use SIGNAL and SLOT without deriving from QObject? | OR other way to formulate my question (though it didn't solve my problem): 'QObject::QObject' cannot access private member declared in class 'QObject'
I need SIGNALs and SLOTS functionality in my class, but I assume it is not possible without to derive from QObject?
class MyClass
{
signals:
importantSignal();
public... | If you want a copyable object with QObject features you need membership (by pointer) rather than inheritence.
You can derive a class Handler from QObject where Handler's slots call SomeInterface virtual functions on its parent.
struct NonQObjectHandler {
virtual ~ NonQObjectHandler () {}
virtual void receive (i... |
7,502,671 | 7,502,937 | Tutorial for multi core CPU usage in c++ in unix | I would like to know if someone can point me any library or tutorial to work with measurements. In a first moment, CPU usage, but latter I will need network (I've already found libcap, is this good?) and memory usages also.
I believe that each of then will be a different library or project, so thanks in advance.
I am c... | Look into the /proc filesystem. It contains a bunch of plain-text files with system statistics. /proc/stat has cpu info, and /proc/net/* has network info.
Additionally, /proc/<pid>/* contains information about a specific process.
|
7,502,701 | 7,502,890 | In a multithreaded app, can 2+ threads access the same function if the function does not modify/read data or modifies/reads temporary data? | I can't seem to find an answer anywhere on Google. I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in undefined behavior or do I have to use a mutex?
void foo(void)
{
float x(133.7);
float y(10);
std::cout << std::endl << (x * y);
}
void foobar(... | I am pretty sure your code doesn't have undefined behaviour.
That said, you are using shared data, namely std::cout.
So if you expect std::cout << std::endl << (x * y) to be executed as a single operation (e.g. to prevent bits of output from different threads getting interleaved on stdout), you are going to have to use... |
7,502,750 | 7,503,295 | cannot compile c codes using microsoft visual studio c++ 2008 express edition | I have a c codes which can be compiled in Linux using gcc. But when I try to compile it using microsoft visual studio c++ 2008 express edition, using the ide, it shows the error
vec.obj : error LNK2005: _INIT_SETA already defined in a.obj
fatal error LNK1169: one or more multiply defined symbols found
I checked the he... | I checked the header files, and all of them have the preprocessor guard to prevent the header to be included multiple times
This only prevents the preprocessor from including a single header file multiple times in a single compilation unit (cpp file). So you still have that header included in both cpp files, and that ... |
7,502,926 | 7,502,978 | What is atoi equivalent for 64bit integer(uint64_t) in C that works on both Unix and Windows? | I'm trying to convert 64bit integer string to integer, but I don't know which one to use.
| Use strtoull if you have it or _strtoui64() with visual studio.
unsigned long long strtoull(const char *restrict str,
char **restrict endptr, int base);
/* I am sure MS had a good reason not to name it "strtoull" or
* "_strtoull" at least.
*/
unsigned __int64 _strtoui64(
const char *nptr,
char **endptr... |
7,502,934 | 7,502,994 | c++: initializing static string members | I'm having some problems initializing static string members in c++. I have several classes and each one is holding several static string members that represent an id. When I am initializing the variables by calling a static function everything is fine. However, when I'd like to assign one variable with the value of ano... | This is Static Initialization Fiasco.
As per the C++ Standard the initialization order of objects with static storage duration is unspecified if they are declared in different Translation units.
Hence any code that relies on the order of initialization of such objects is bound to fail, and this problem is famously... |
7,502,952 | 7,503,767 | What's the best way to distribute your SDK if the end user is required to link against the Debug CRT? | I work for a camera company and we provide an SDK for our customers. Historically we only provided a release build of our SDK that was built against the non-debug CRT. As part of our SDK package we provide a number of examples on how to use the SDK. The examples have Debug project configurations which use the debug ... | Yes, you'll need to distribute Debug and Release builds of your library. Built with respectively /MDd and /MD so the CRT can be shared. Different versions too, built against, say, the VS2005, VS2008 and VS2010 versions of the CRT.
This is of course painful. To narrow it down to a single library, you'll need to carefu... |
7,503,042 | 7,504,660 | How to start two instances of the same app with different static values? | Problem: I want to run my application with the different arguments, for example app.exe -param1 and a little bit later I need to start app.exe -param2. Parameters comes from arguments. Arguments I need to place to global static value, to be able to get it at any time from any where in code.
How to do that?
I have tried... | My guess is you have more than one definition of the variable. Do you have this line in a header file?
static QString gMyValues;
If so, each and every source file that includes it will have its own copy of gMyValues. And only the one in main.cpp will be filled with correct value.
You should declare it in the header fi... |
7,503,436 | 7,503,725 | Looking for pathing algorithms for maps without edges | I have 2D world maps that are basically Mercator-Like projections, (If you walk west long enough you end up east of where you started)
Question I have: Can you use A* for computing paths on these types of maps as well?
I can't think of any reason why you couldn't (I'm thinking that you would simply represent the edge... | Pathfinding algorithms don't really care about global topology of the map. The only tricky part is to get a good estimator for A* but using the 3D distance should be ok if your map is indeed a surface in a 3d space and step cost is step length.
Your map can have all sort of strange "connections" (including for example ... |
7,503,508 | 7,503,802 | Can you set a weak_ptr<> in a ctor? | The following code fails to compile in Visual C++ 11 with this error:
1>c:\users\tony\documents\visual studio 11\projects\cpp11_ex1\cpp11_ex1\main.cpp(52): error C2440: '' : cannot convert from 'Foo *const ' to 'std::weak_ptr<_Ty>'
#include <stdio.h>
#include <memory>
using namespace std;
class Foo;
class Bar
{
pu... | Since Foo will be pointed at by a shared_ptr, and Bar will always be owned by a shared_pointer of Bar, then if Bar exists, Foo exists. Ergo, you don't need a smart pointer in Bar. (If I understand the problem correctly)
#include <stdio.h>
#include <memory>
using namespace std;
class Foo;
class Bar
{
public:
Ba... |
7,503,631 | 7,503,680 | Reference to a temporary variable - why doesn't compiler detect it? | I hope this is not a duplicate, I've read a number of related questions but no one seemed to cover this case:
#include <iostream>
int* return_dangling_p()
{
int x = 1;
return &x; // warning: address of local variable 'x' returned
}
void some_func()
{
int x = 2;
}
int main(int argc, char** argv)... | I'm not sure why the compiler doesn't complain. I suppose it's not a very common use-case, so the compiler authors didn't think to add a warning for it.
You can't infer anything useful about behaviour you observe when you are invoking undefined behaviour. The final output could have been 3, it could have been 4, or i... |
7,503,642 | 7,619,873 | Help with a really strange COM+ callstack | We have a legacy COM+ dll that is called by an old ASP application. It is periodically crashing, and the call stack is very strange looking
It appears that a call to DllUnregisterServer and to CoInstall appear within the call stack (we don't dynamically install/uninstall anything within the code -- it's just querying ... |
ole32!CoInstall + 0x6ed
The +0x6ed offset is an important 'quality' indicator. What it tells you is that the return address is 1773 bytes from the known address of CoInstall. That's rather a lot. The stack trace builder just didn't have any other known address that was closer so it could only offer CoInstall as a ... |
7,503,917 | 7,503,962 | Attempting to write constructors for subclass inheriting from class, guessing at syntax, expected-primary-expression error? | I have a class Sphere that inherits from class Shape (for a homework project):
Within Shape I have three constructors. The declarations from Shape.h are as follows:
Shape();
Shape(Vector);
Shape(Vector, float[]);
Within Sphere my constructors inherit from these constructors. The declarations in my Sphere.h file are ... | You need to specify names, not just types, for the parameters, and pass the names, not the types. For example:
Sphere(Vector a, float b, float[] c): Shape(a, c) {}
|
7,504,030 | 7,504,056 | stdlib "Unique" method does not work | I'm trying to use the C++ Standard Library algorithm unique (with BinaryPredicate).
I've created a vector of pairs; each pair is like "(first=a vector of 4 doubles, second=an integer)". The second element serves as index so after using `unique, I can still tell the original index.
In the example below, I've created s... | You want to do:
ak.erase(unique(ak.begin(), ak.end(), uniquepred), ak.end());
The reason for this is that std::unique reorders the values. It doesn't delete them though and you are left with a new range, from begin() to the iterator that unique returns. The container itself is not altered, other than this reordering.
... |
7,504,086 | 7,504,173 | Thread memory changes while suspended | I suspended a thread in another process using SuspendThread and then I get its context using GetThreadContext. GetThreadContext succeeds.
Then I read parts of its stack with ReadProcessMemory.
I do some stuff (still when the thread is suspended) and then I read the same memory again.
I assumed that while the thread is ... |
What could cause this? Many things could cause this but the likely (p = .999999) cause is that some buggy code of yours is polluting the thread's memory by writing into it.
and how can I make the memory remain the same? There's only one answer here: fix the bug in your code.
|
7,504,139 | 7,504,164 | Malloc allocates memory more than RAM | I just executed a program that mallocs 13 MB in a 12 MB machine (QEMU Emulated!) . Not just that, i even browsed through the memory and filled junk in it...
void
large_mem(void)
{
#define LONGMEM 13631488
long long *ptr = (long long *)malloc(LONGMEM);
long long i;
if(!ptr) {
printf("%s(): array alloc... | It's called virtual memory which is allocated for your program. It's not real memory which you call RAM.
There is a max limit for virtual memory as well, but it's higher than RAM. It's implemented (and defined) by your operating system.
|
7,504,252 | 7,504,437 | memory deallocation problem of an object | I hava a class
class vlarray {
public:
double *p;
int size;
vlarray(int n) {
p = new double[n];
size = n;
for(int i = 0; i < n; i++)
p[i] = 0.01*i;
}
~vlarray() {
cout << "destruction" << endl;
delete [] p;
size = 0;
}
};
when I use ... | There seems to be some confusion amongst the existing answers on this question, so I am going to jump in.
Immediate issue
Your primary issue is that you have not defined your own copy assignment operator. Instead, the compiler generates a naive one for you, so that when you run a = b, the pointer inside b is copied in... |
7,504,300 | 7,504,375 | virtual function that is const in the base class and not const in the derived | Can anyone explain the output of the following code?
#include <iostream>
#include <string>
class Animal
{
public:
Animal(const std::string & name) : _name(name) { }
~Animal() { }
virtual void printMessage() const
{
std::cout << "Hello, I'm " << _name << std::endl;
}
private:
std::string... | Cow isn't overriding the virtual function from Animal because it has a different signature. What's actually happening is that Cow is hiding the function in Animal.
The result of this is that calling printMessage on an Animal will just use the version in Animal, regardless of the one in Cow (it isn't overriding it), but... |
7,504,396 | 7,504,700 | C++ vector containing pointers of user-defined types | I have a problem with this code:
struct document_type_content
{
long long m_ID;
QString m_type_name;
};
std::vector<QString> document_type::get_fields_by_name(e_doc_type) const
{
std::vector<QString> tmp;
std::vector<document_type_content*>::iterator it = m_table_data.begin(),
it_end = m_ta... | Because your function is constant, you only have constant access to the this pointer of your class. The results in a constant access to your vector. You need to get a const_iterator from the vector.
This should do the trick:
std::vector<QString> document_type::get_fields_by_name(e_doc_type) const
{
std::vector<QSt... |
7,504,572 | 7,504,790 | Strange same numbers | I use some random numbers as initial values for my 'metaheuristics optimization' calculations. I run my same optimization program on different computers using MPI. I surprisingly obtained a lot of same results. For example I use 40 host computers, the results have few different values. Almost 6-7 values are the same. A... | That's because some of your host computers are having the same time, so the srand() takes the same time and therefore the random sequence have same starting point, so of course your are getting the same random numbers. Try to to this:
srand(time(0)*my_computer_id);
|
7,504,695 | 7,504,750 | overloading resolution, cpp | I understand that if there are several function with the same name and same number of parameters the compiler is trying to find the best match (am I right so far?)
What I don't understand is the difference between type promotion and type conversion.
Say I have this function decleration: void foo (double x) and then ins... | Type promotion is special case of type conversion.
http://en.wikipedia.org/wiki/Type_conversion#Type_promotion
|
7,504,777 | 7,504,900 | Graph Template Class | I am working on Graph Template Class. Here is what I written till now.
#ifndef __GRAPH_H__
#define __GRAPH_H__
#include <map>
#include <list>
template <typename _Ty>
class Graph {
private:
template <typename _Ty>
class Vertex {
public:
Vertex(_Ty in) : m_Label(in) {
}
~Vertex() {
... | std::string test = "ABC"; does implicit casting, but it is not happening while calling the function. Try myGraph3.AddEdge(std::string("A"),std::string("B"));.
Function call overloading by defining another function as in
void AddEdge(_Ty vLevt, _Ty vRight) {
this->AddEdge((VertexType) vLevt, (VertexType) vRight)... |
7,504,921 | 7,505,034 | Is it defined to provide an inverted range to C++ standard algorithms? | Consider standard algorithms like, say, std::for_each.
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f);
As far as I can tell, there is actually no requirement placed on the relative states of the two InputIterator arguments.
Does that mean that the f... | The standard explicitly requires the last iterator to be reachable from the first iterator. That means that by incrementing first one should be able to eventually hit last.
24.1 Iterator requirements
...
6 An iterator j is called reachable from an iterator i if and only if
there is a finite sequence of applications ... |
7,505,151 | 7,505,298 | Sandboxed Plugin architecture | I was googling and searching SO for plugin architecture and I'm satisfied by general knowledge on how to implement it. Now I went further to look for a sandboxed architecture. Basically what I mean is an application with plugin whereby crashing in plugin won't crash the whole app and the plugin can be reloaded.
I canno... | The only way you can have a truly sandboxed architecture wherein a plug-in cannot directly crash the parent application's process or corrupt its memory is by placing it into a separate OS process, with a separate memory space. When doing this, you will need to rely on interprocess communication facilities of the OS (... |
7,505,228 | 7,506,447 | Non-POD datatypes allowed in firstprivate of OpenMP parallel section? | Can we specify a std::vector object in the firstprivate clause of a openmp task pragma?
Is is possible to make a vector object firstprivate?
It compiles and runs correctly... It is always threadsafe?
| Yes you can
The firstprivate variable is initialized once per thread
the firstprivate object is constructed by calling its copy constructor with the master thread's copy of the variable as its argument
So basically as long as
the copy constructor and assignment operator for the class are accessible
they provide deep... |
7,505,267 | 7,505,576 | Is it defined to provide an empty range to C++ standard algorithms? | Following on from my previous question, can we prove that the standard allows us to pass an empty range to a standard algorithm?
Paragraph 24.1/7 defines an "empty range" as the range [i,i) (where i is valid), and i would appear to be "reachable" from itself, but I'm not sure that this qualifies as a proof.
In particu... | I don't seem much room for question. In §24.1/6 we're told:
An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j.
and in $24.1/7:
Range [i, j) is valid if and only if j is reachable from i.
Since 0 is finite, [i, i) is... |
7,505,315 | 7,505,393 | "Invalid argument" when sending UDP packet, but which? | My C++ application is sending binary data as UDP packets. The sendto() call returns EINVAL (Invalid argument), but I don't see anything wrong with the parameters I'm passing.
I did an strace of the application and here are the revelant system calls:
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 33
setsockopt(33, SOL_IP, IP... | You bound your socket to the local address 127.1, but you are sending to a non-localhost address. I need to check, but perhaps the EINVAL means "you can't send 127.1 packets off-host."
|
7,505,388 | 7,505,526 | Inline ntohs() / ntohl() in C++ / Boost ASIO | Hi I'm using C++ / Boost ASIO and I have to inline ntohl() for performance reasons. Each data packet contains 256 int32s, hence a lot of calls to ntohl(). Has anyone done this?
Here is the compiled assembly output out of VC10++ with all optimizations turned on:
; int32_t d = boost::asio::detail::socket_ops::network_... | The x86-32 and x86-64 platforms have a 32-bit 'bswap' assembly instruction. I don't think you'll do better than one operation.
uint32_t asm_ntohl(uint32_t a)
{
__asm
{
mov eax, a;
bswap eax;
}
}
|
7,505,432 | 7,505,466 | C++ prime number generator is not working | #include <iostream>
using namespace std;
int checkIfPrime(int num) {
for (int i = 1; i < num; i++) {
int result = num / i;
if (num == result * i) {
return 0;
}
}
}
int main() {
int i = 3;
while(1) {
int c = checkIfPrime(i);
if (c != ... | After the question has completely changed its meaning:
Your CheckIfPrime is just wrong. You're checking divisibility in a very strange way. The general way to check whether a is divisible by b is if(a % b == 0)
That said, your error is that your loop starts with 1. Of course every number is divisible by 1, therefore b... |
7,505,654 | 7,505,674 | Shorter way to get an iterator for a std::vector | Lets say that I have got a vector like this.
std::vector<a_complicated_whatever_identifier *> *something
= new std::vector<a_complicated_whatever_identifier *>;
// by the way, is this the right way to do this?
Now I want to get an iterator for this... so I would do this like this.
std::vector<a_complicated_whateve... | Use a typedef.
typedef std::vector<complicated *>::iterator complicated_iter
Then set them like this:
complicated_iter begin, end;
|
7,505,890 | 7,505,940 | using unordered map find function | If I want the unordered map find function to return a bool value, how would I go about doing that?
Here's my code right now.
bool NS_SymbolTable::SymbolTable::Contains(std::string lexeme)
{
SymbolTable *tempSymbolTable = this;
std::unordered_map<std::string, Identifier*>::iterator it = tempSymbolTab... | For documentation look std::unordered_map::find. There it says:
Return value
iterator to an elements with key key. If no such element is found, past-the-end (see end()) iterator is returned.
To get boolean value indicating whether an element is present, use
bool contained = it != tempSymbolTable->hashtable.end();
... |
7,506,134 | 7,515,951 | Valgrind errors when linked with -static -- Why? | I have a test driver linked to a library I wrote. The library uses autotools so it produces both an archive (.a file) and a dynamic library (.so).
When I link my driver with 'g++ -static', presumably linking to the .a, valgrind lights up complaining repeatedly 'Conditional jump or move depends on uninitialised value(s)... |
Does valgrind just not work with -static?
It does. The problem is not in Valgrind, it's in glibc, which is not Valgrind clean. The glibc developers refused to fix these problems (because the problems are of a "don't care" nature, and fixing them costs (a few) cycles).
When you link dynamically, these errors come from... |
7,506,223 | 20,653,223 | QNetworkRequest with ssl local certificate | I need to exchange data with server which requires local certificate (.crt file).
I try this:
loginRequest = QNetworkRequest(QUrl("https://somesite.com/login"));
QSslConfiguration sslConf = loginRequest.sslConfiguration();
QList<QSslCertificate> certs = QSslCertificate::fromPath(Preferences::certificatePath());
qDebug... | SOLUTION, Part I:
I mostly solved this (the lack of connection), there were 2 reason:
1st - the apache server actually require private key (for some unknown reason, found it [here][1]), how to add private key:
QFile x(Preferences::certificateKeyPath());
x.open(QIODevice::ReadOnly);
pKey = QSslKey(x.readAll(),QSsl::Rs... |
7,506,329 | 7,506,378 | Embed Java into a C++ application? | I got an application written in C++ and I am able to extend the applications functionality by writing plugins in C++ for it.
What I basically want to do is to embed Java into this application. This has already been done with Python (not done by me).
I read something about JNI but there is always the speech from a full ... | You can embed a JVM within your application. Oracle's official reference book has some more details. The synopsis of it is:
#include <jni.h> /* where everything is defined */
int main() {
JavaVM *jvm; /* denotes a Java VM */
JNIEnv *env; /* pointer to native method interface */
JDK1_1InitArgs ... |
7,506,415 | 7,506,436 | Millisecond timing C++ | I want to time the real-time performance of some C++ functions I have written. How do I get the timing in milliseconds scale?
I know how to get time in seconds via
start=clock()
diff=(clock()-start)/(double) CLOCKS_PER_SEC
cout<<diff
I am using Ubuntu-Linux OS and g++ compiler.
| In Linux, take a look at clock_gettime(). It can essentially give you the time elapsed since an arbitrary point, in nanoseconds (which should be good enough for you).
Note that it is specified by the POSIX standard, so you should be fine using it on Unix-derived systems.
|
7,506,485 | 7,506,511 | Compiling C++ with cygwin doesn't search provided include paths | I am working within a tree that compiles fine on any Unix machine I throw it at, but Cygwin is being difficult and I'm not really sure where to start. I have the following directory structure:
buildwin/
|-- main.cpp
|-- other project files
|-- include/
|-- tclap
|-- CmdLine.h
|-- other files (includ... | You're specifying -Iinclude/tclap, then include tclap/CmdLine.h, so the compiler goes hunting for include/tclap/tclap/CmdLine.h.
Either use -Iinclude, or include CmdLine.h without the path.
|
7,506,704 | 7,506,801 | Difference between sequence points and operator precedence? 0_o | Let me present a example :
a = ++a;
The above statement is said to have undefined behaviors ( I already read the article on UB on SO)
but according precedence rule operator prefix ++ has higher precedence than assignment operator =
so a should be incremented first then assigned back to a. so every evaluation is known,... | The important thing to understand here is that operators can produce values and can also have side effects.
For example ++a produces (evaluates to) a + 1, but it also has the side effect of incrementing a. The same goes for a = 5 (evaluates to 5, also sets the value of a to 5).
So what you have here is two side effects... |
7,506,952 | 7,506,987 | Understanding the different clocks of clock_gettime() | Hi I wanted to use the clock_gettime() function for measuring the performance of my code.
I am unable to understand the difference between the different kinds of clocks used in the function from the man page descriptions. esp
CLOCK_REALTIME,
CLOCK_PROCESS_CPUTIME_ID
CLOCK_THREAD_CPUTIME_ID
Can someone explaing wha... | CLOCK_REALTIME reports the actual wall clock time.
CLOCK_MONOTONIC is for measuring relative real time. It advances at the same rate as the actual flow of time but it's not subject to discontinuities from manual or automatic (NTP) adjustments to the system clock.
CLOCK_PROCESS_CPUTIME_ID is for measuring the amount of ... |
7,506,995 | 7,507,152 | Cannot run C program compiled with MinGW Dev-C++ on 64bit Vista | A few days ago I started programming with C after programming with C++, however, my Windows Vista 64bit machine was unable to create a C project. I recompiled the code with the MinGW Dev-C++ compiler without issue.
However, when I ran the code I received the following error:
Unsupported 16-Bit Application
The program ... | The error you're seeing is from using an ancient (as in 16-bit Windows 3.1 era) software that Windows 64-bit does not provide backwards-compatibility for. This has nothing to do with C or C++, just a really old compiler.
You can either install windows 7 with XP-mode, which provides a virtual 32-bit XP machine running ... |
7,507,026 | 7,507,091 | Preferring non-member non-friend functions to member functions | This question title is taken from the title of item #23 in Effective C++ 3rd Edition by Scott Meyers. He uses the following code:
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
//This is the function in question.
void clearEverything();
};
//Alternative n... | Usually, you would put them in the associated namespace. This serves (somewhat) the same function as extension methods in C#.
The thing is that in C#, if you want to make some static functions, they have to be in a class, which is ridiculous because there's no OO going on at all- e.g., the Math class. In C++ you can ju... |
7,507,070 | 7,507,168 | Qt framework OK for this Windows and Mac GUI? | Some background. I'm writing a program that needs to monitor the default audio buffer and write to a virtual COM port. Both those operations are platform specific, and are driven via an GUI.
My question is, would the Qt framework suffice? I'm heard great things about it on my never ending google quest, but I am not su... | Yes Qt is definitely useful for the GUI. However depending on if Qt offers the ability to access the audio buffer and virtual COM port you may have to couple that with the use of Boost ASIO. Boost is also cross-platform like Qt.
|
7,507,117 | 7,507,140 | cannot convert to a pointer type : C error | I have a function that I need to call
int (*trytoprint_f)(int val, void *param);
but when I call this function, and put
str name = {"jack", 4};
int age = 2;
client->trytoprint(age, (void *)name));
it gives me an error of "cannot convert to a pointer type : C error"
I know the solution which is basically use a funct... | You have to convert a pointer to structure to void* not a structure itself. Try this way
client->trytoprint(age, (void *) &name));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.