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 |
|---|---|---|---|---|
4,823,548 | 4,823,582 | Are Windows Memory Mapped File contents always zeroed by default? | I've determined empirically that, on my system, a memory mapped file created to be a certain size is always completely zeroed by default. For example, using the call
HANDLE hMM =
CreateFileMapping (h,
NULL,
PAGE_READWRITE,
0,
... | The CreateFileMapping documentation (Remarks section) explicitly states that
If the file is extended, the contents of the file between the old end of the file and the new end of the file are not guaranteed to be zero; the behavior is defined by the file system.
so, if your file on disk starts empty, it's not guarante... |
4,823,649 | 4,825,517 | Is my stdcall wrapper for usercall function correct? | I need to wrap the below __usercall function to _cdecl/_stdcall:
char __usercall sub_4017B0<al>(int a1<ebx>, int a2)
a1 is integer,
a2 is actually an arry of ints ('int args[10]')
Is this correct? What does the <al> mean behind sub_4017B0 ?
int __stdcall func_hook_payload(int callnum, int* args);
// Wrapper for
// c... | does the function take an actual int* or does it take va_args? in cases like this you need to provide the original calling code to.
from what I can gather, your wrapper should look like this(I don't use stack frames, but your frame is wrong as you don't pop ebp before returning):
__declspec(naked) void func_hook()
{
... |
4,823,668 | 4,823,674 | Should this use of nullptr produce a compiler error? | Is there a good reason why this code compiles without warning (and crashes when run) with Visual C++ 2010:
int a = *((int*)nullptr);
Static analysis should conclude that it will crash, right?
|
Should this use of nullptr produce a compiler error?
No.
Dereferencing a null pointer results in undefined behavior, but no diagnostic is required.
Static analysis should conclude that it will crash, right?
It might. It doesn't have to. It would certainly be nice if a warning was issued. A dedicated static analy... |
4,823,703 | 4,823,715 | Code inside nested If statements | is there be any performance effect on "Lines of code" running inside nested ifs?
if (condition_1)
{
if (condition_2)
{
if (condition_n)
{
/* Lines of code */
}
}
}
| No, there shouldn't be a performance effect. Any decent compiler should easily be able to cope with that and optimize it correctly. The biggest problem with your code is not the performance but the readability.
By the way, you could easily rewrite it to the following more readable code:
if (condition_1 &&
condition... |
4,823,761 | 4,823,787 | Minimal set of nested typedefs for a custom STL sequence? | What is the minimal set of nested typedefs that should be defined in a custom STL class meeting the Sequence concept? The custom sequence should be compatible with:
std::back_insert_iterator
BOOST_FOREACH
Boost range concept.
| The C++ Standard says all containers must have the following typedefs (C++03 23.1/Table 65):
value_type
reference
const_reference
iterator
const_iterator
difference_type
size_type
Reversible containers must have the following typedefs (C++03 23.1/Table 66):
reverse_iterator
const_reverse_iterator
|
4,823,866 | 4,823,885 | `this` operator in c++? | Sorry not sure if this has been asked before, I really dont know what to look up either. I'm new to C++ from Java. When we want to call a function on an object in Java, we say picture.rotateRight();
Then, in rotateRight(), we'd have something like int height=this.getHeight();. However, how do we do this in C++? I have ... | First of all, your invertcolors() function definition is a non-member function. Although you've declared it inside the Image class, you haven't linked the implementation to the class in any way so the compiler thinks its a non-member function. To make it a member of Image, you need to use Image::invertcolors like this:... |
4,823,884 | 4,824,036 | C++ generate next key | const int SIZE = 3;
const char val[SIZE] = {'3', 'z', '7'};
const string& next(){
static string ret = "0";
static unsigned i = 0;
static unsigned j = 0;
s[j] = val[i];
i++;
return ret;
//...
}
Everytime next is called, I want it to return the next string key, such as:
3
z
7
33
3z
37
z3
zz
z7
73
7z... | In terms of wrapping your head around it, you can think of it like you would incrementing a number. Increment the right-most value, but if that goes past the end then set it back to the first value and increment the next column, etc., then adding an extra value at the front if necessary.
#include <iostream>
#include <... |
4,823,927 | 4,823,956 | stream operator overloading problem | I have a class using operator overloading, but there are some warnings.
// base.h
class base {
public:
base();
base(int n);
virtual ~base();
virtual void printBase(std::ofstream & out);
virtual base & operator =(const base &);
friend std::ofstream & operator <<(std::ofstream & out, const base &... | The problem is actually with one of your class's constructors:
base(int n);
This constructor is what is called a converting constructor. It can be used to convert an int to a base, so this would be legal:
base x = 42;
If you don't want to allow this implicit conversion, you can make the constructor explicit:
explici... |
4,824,122 | 4,824,169 | Console/Command Prompt Full screen in Windows Vista/7 | Is there a way to get the console windows full screen in Windows Vista/7?
I'm looking for a distributable C/C++ solution, library, or emulator.
Microsoft's "solution" is to install a VM which is pretty ludicrous.
The relevant super user's question doesn't have good answers.
For those interested, the full screen console... | Take the Console2 source code, modify it to strip toolbars and other visual garbage you don't need and run it in full screen mode.
What it does is starts a command-line shell, redirects the output to its own internal buffers, and then draws the text from those buffers using GDI to a bitmap. Same thing the Virtual PC so... |
4,824,216 | 4,824,256 | Copy constructor error | I need someone to show me what is wrong with this code. I don't know what's wrong with it. I know the code doesn't do anything meaningful and it can't be used. I created it only to know how copy constructors work.
class test
{
public:
int* value;
public:
int getvalue()
{return *value;};
test(int... | You need to change the declaration of getvalue() to int getvalue() const, since you're trying to call getvalue() on a const reference in your copy constructor.
|
4,824,273 | 4,824,322 | How To Use C++ CGI Script? | I am currently enrolled in a web applications class at my college and we are learning about cgi scripts. I am having a hard time learning how to implement my CGI script. When I click on my link a window pops up asking me to download my helloworld.cgi file instead of just redirecting.
HTML:
<html>
<body>
<a... | /user/local/apache2/cgi-bin/helloworld.cgi is the physical path of the file on your hard disk. To run the script through Apache, you need to specify the path relative to your server's document root, for eg. http://localhost/cgi-bin/helloworld.cgi.
|
4,824,278 | 4,824,292 | C++ Defining a type cast | Is there a way to define a type cast from say a user defined class to a primitive type (int, short, etc.)? Also, would any such mechanism require an explicit cast, or would it work implicitly?
for example:
// simplified example class
class MyNumberClass
{
private:
int value;
public:
// allows for implicit type ... | Yes, you can define an operator type() to do the conversion, and yes, it will work implicitly whenever such a conversion is required:
operator int() {
return value;
}
|
4,824,596 | 4,824,620 | Minor image differences in image manipulation program | I've implemented a method that takes an input image and flips it around a vertical line through the center and saves it to an output image file. So whats on the left becomes on the right and vice versa. The image looks great and looks like it flipped perfectly. However, we are given the actual flipped image file that i... | What image format did you save as? If you used a lossy compression, such as JPEG, then the image colours will always be slightly different, as they have been re-compressed. You should use a non-lossy format such as PNG.
You should also not use 'diff' to look at images. I don't know what Kaleidoscope is, but the ImageMa... |
4,824,831 | 4,824,836 | What do "<, >" mean as syntax in this context?-- std::auto_ptr< sql::Statement > stmt(con->createStatement()); | std::auto_ptr< sql::Statement > stmt(con->createStatement());
I looked through my textbook but there is no mention of anything of this sort. Can someone tell me what it is called so I can look it up? The only use of "<" I know is as a binary less-then operator.
| Its a template. http://en.wikipedia.org/wiki/Template_%28programming%29
|
4,825,019 | 4,825,035 | linux makefile equivalence? important | I am a CS student but I CANNOT and please don't ask me why; I cannot use make and linux for my cs assignments. Is there anything in Windows 7 or Windows in general that is similar to make in linux? I want to do my assignments in windows instead of linux. What is the closest thing to make? I have eclipse but I wan't som... | You can easily get a free (as in cost and freedom) make for Windows, both CygWin and GnuWin32 provide them. In fact, I seem to recall that Microsoft compilers have their own make as well (nmake from memory, but I could be wrong).
If you can't use any make, then the next best thing is probablt cmd files to build your en... |
4,825,030 | 4,825,077 | C++ Add to linked list in sorted order | Hi I have a linked list using structs. Right now I got it to add every element at the end. However I'd like to add each element in sorted order based on the ID. The struct has two elements: string name, and long ID.
node* temp = new node;
temp->name = nameRead;
temp->id = idRead;
//check if first item, if so add as he... | node* temp = new node;
temp->name = nameRead;
temp->id = idRead;
node* temp2 = head;
node** temp3 = &head;
while(temp2 != null && temp2->id < temp->id)
{
temp3 = &temp2->next;
temp2 = temp2->next;
}
*temp3 = temp;
temp->next = temp2;
EDIT: Explanation: The 'temp3' pointer points to where 'temp' would need to go... |
4,825,169 | 5,083,508 | SPOJ Problem KPRIMES2 | I am new to this forum and not well aware of protocols of this forum so pardon me for my ignorance. My question is related to spoj problem https://www.spoj.pl/problems/KPRIMES2/. I am getting TIME LIMIT EXCEED for this problem.I think the bottleneck of this program is generating 10^9.Could some one suggest how to impro... | Consider compacting your prime storage even more. For example, in every block of 2*3*5*7*11=2310, there are exactly 1*2*4*6*10=480 numbers that have no prime factor of 11 or less, which you can pack into 15 array entries rather than (about) 36. That will eliminate a few hundred million bit operations sieving out those ... |
4,825,305 | 4,827,956 | How to demangle C++ in GCC 2.96 | When I compile the code with cxxabi.h, I got this error:
$g++ -g -o bt bt.cpp linux.cpp -rdynamic -fnew-abi
cc1plus: -fnew-abi not supported in gcc-2.96-RH
[PS: I need do this in the source code, not c++filt bin tool!]
Thanks in advance.
Dma
| The -fnew-abi flag was marked as experimental and subject to undocumented changes. Why are you using it? It's likely that (consistently!) removing it will allow you to rebuild everything.
|
4,825,313 | 4,825,388 | What does this code mean? | This is a part of a static assert trick. I can't understand how the unspecialized class works. Can someone explain it to me?
EDIT: Full code with macro: (taken from http://www.skynet.ie/~caolan/Fragments/C++StaticAssert.html)
#ifndef STATICASSERT_HXX
#define STATICASSERT_HXX
/*
Lifted direct from:
Modern C++ Design: ... | The macro calls this code in a way similar to this:
compile_time_check<static expression> temp(Error_Some_Struct_here);
So, for example, you could do this:
compile_time_check<sizeof(Foo) < sizeof(Bar)> temp(Error_Foo_must_be_smaller_than_Bar);
When sizeof(Foo) is less than sizeof(Bar), the template would instanciate ... |
4,825,470 | 4,825,606 | C++ Regex to match words without punctuation | I searched, couldn't find anything. In the interest of not wasting any more of my time on the chance that the answer is obvious to someone else, I'm asking here. Only site that has been useful so far is this one: http://softwareramblings.com/2008/07/regular-expressions-in-c.html but the samples are far too simplistic. ... | A few things here.
First, your regex string needs to have the \ escaped. Its still a C++ string, after all.
regex rgx("\\w");
Also, the regex \wmatches just one "word character". If you want to match an entire word, you need to use:
regex rgx("\\w+");
Finally, in order to iterate through all possible matches, then ... |
4,825,685 | 4,825,711 | Question with virtual functions | I have two classes:
class x {
public:
virtual void hello() {
std::cout << "x" << std::endl;
}
};
class y : public x {
public:
void hello() {
std::cout << "y" << std::endl;
}
};
Can someone explain why the following two calls to hello() print different messages? Why don't they both print "y"? Is it bec... | Yes, you are right
x b = a;
Invokes a copy constructor (b IS an 'x')
x& b = a;
Assigns a reference and will use the override (b is still actually a 'y')
|
4,825,705 | 4,828,645 | Calling QApplication::processEvents() inside an OpenMP loop? | Greetings all,
In my QT application, I use OpenMP to parallelize loops.In the loop , I want to update progressbar values of the current QMainWindow.
Following code snippet shows how I am trying to do this :
#ifdef OPENMP_ENABLE
#pragma omp parallel for
#endif
for (int i = 0; i < endIndex; i++) {
getMainWindow()->set... | Subclass QThread and put your business logic there and use OpenMP there. Use signals and slots to update the QProgressBar.
You can only call GUI methods in the main GUI thread. When you call QApplication::processEvents outside of it, inside a OpenMP thread, you break this rule.
|
4,825,821 | 4,834,746 | stringstream operator<< crash (malloc_consolidate ) | Program terminated with signal 11, Segmentation fault.
#0 0x0000003663c70485 in malloc_consolidate () from /lib64/libc.so.6
(gdb) bt
#0 0x0000003663c70485 in malloc_consolidate () from /lib64/libc.so.6
#1 0x0000003663c72a6c in _int_malloc () from /lib64/libc.so.6
#2 0x0000003663c74cde in malloc () from /lib64/libc.... | This should be because stringstream::operator<< is non-reentrant function.
|
4,825,851 | 4,846,927 | How to return an fstream (C++0x) | I think I'll get right into it and start with the code:
#include <iostream>
#include <fstream>
#include <string>
class test : public std::ofstream
{
public:
test(const std::string& filename) { this->open(gen_filename(filename)); };
test(const test&) = delete;
//test(test&& old) = default; /... | I'm going to answer my own question here:
In the GCC C++0x Library Features page, have a look at item 27.9, which reads:
27.9 - File-based streams - Partial - Missing move and swap operations
I guess that's probably the issue I'm having with gcc.
|
4,825,868 | 4,825,897 | What is the meaning of colon (:) operator in "uint isWidget : 1;" in Qt? | What is the meaning of colon (:) operator in "uint isWidget : 1;" in Qt? Is "uint isWidget : 1;" equivalent to "uint isWidget(1)"?
The code in Qt is
QObjectData
{
public:
virtual ~QObjectData() = 0;
QObject *q_ptr;
QObject *parent;
QObjectList children;
uint isWidget : 1;
uint pendTim... | This is part of C struct notation - you can specify the size of an integer field in bits by using a : numBits after the property name.
I must assume that the same syntax can be used in a C++ class (i'm a C guy, but i'm sure that this is doing the same thing in C++)
|
4,825,926 | 4,825,961 | C++ compile error messages not showing properly in PuTTY | If I compile a C++ program with errors in Linux connected through PuTTY, I see error messages like:
g++ a.cpp
a.cpp: In function âint main()â:
a.cpp:38: error: expected primary-expression before â)â token
a.cpp:38: error: âwaitpidâ was not declared in this scope
Any idea about why the character â is coming?
| Check to make sure command locale returns the same encoding which set in PuTTY configuration Translation->Received data assumed to be in which character set.
|
4,825,980 | 4,826,101 | What are the basic settings+tasks to get started debugging in WinDbg? | To quote myself, from the question Are there any books that “teach” WinDbg?:
With the Visual Studio debugger, I
know where I am at a given point, that
is it is very easy and convenient to
set it up so that the current
breakpoint(sourcecode)+disassembly+call
stack+local variables+... all make
sense together... | I have written on this in the past, here: How to use WinDbg to analyze the crash dump for VC++ application?
|
4,826,044 | 4,826,226 | OpenCV unresolved external errors with objdetect.hpp functions (C++) | I'm trying to compile a simple face detection program in C++ in VS2010 and have come across two LNK 2019 errors:
Error 2 error LNK2019: unresolved external symbol _cvReleaseHaarClassifierCascade referenced in function _main
Error 3 error LNK2019: unresolved external symbol _cvHaarDetectObjects referenced in function "... | Have you added the libraries to your link dependencies?
right-click on your project -> Properties -> Linker -> Input -> Additional Dependencies
|
4,826,379 | 4,826,464 | Size of UTF-8 string in bytes | I am using QString to store strings, and now I need to store these strings (converted to UTF-8 encoding) in POD structures, which looks like this :
template < int N >
struct StringWrapper
{
char theString[N];
};
To convert raw data from the QString, I do it like this :
QString str1( "abc" );
StringWrapper< 20 > str2... | The first question you need to answer is what is the encoding of your source files is? QString default constructor assumes it's Latin1 unless you change it with QTextStream::setCodecForCStrings(). So if your sources are in anything else than Latin1 (say, UTF-8), you get a wrong result at this point:
QString str( "Schön... |
4,826,404 | 4,826,416 | Getting first value from map in C++ | I'm using map in C++. Suppose I have 10 values in the map and I want only the first one. How do I get it?
Thanks.
| A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).
You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.
|
4,826,413 | 4,830,186 | Boost-Asio , multi-thread tcp server | I'm not able to succeed about boost-asio multithread program.
Since there is not any good example or documentation about this,
I want your help :)
Simply, I think this code do listen, but when I want to 'cout' buffer data,
it does not print anything or listening once and stopped.
My code is:
void Worker::startThread(... | You haven't looked at the documentation very long if you don't see the multi-threaded examples
HTTP Server 3
An HTTP server using a single
io_service and a thread pool calling
io_service::run().
HTTP Server 2
An HTTP server using an
io_service-per-CPU design.
Keep in mind these examples use asynchronous meth... |
4,826,662 | 4,834,366 | C++. How to know where a method/variable is defined? or how to ask the compiler about it? | In our very large framework, tracking down a bug in one package, I ended up on a call to a function.
This function is not defined in the package I'm working on, and a search over the package itself does not give me any clue about the place where that function is defined in the framework.
So apparently it's defined in ... | You can "ask" the compiler (and/or linker) where it is defined by creating a second definition of that function.
void foo();
void foo() // function you are looking for
{
}
void foo() // second definition to tease the compiler.
{
}
Now the compiler will complain and give you a hint
main.cpp: In function ‘void foo()’:... |
4,826,719 | 4,826,751 | C++ volatile member functions | class MyClass
{
int x, y;
void foo() volatile {
// do stuff with x
// do stuff with y
}
};
Do I need to declare x and y as volatile or will be all member variables treated as volatile automatically?
I want to make sure that "stuff with x" is not reordered with "stuff with y" by the compi... | Marking a member function volatile is like marking it const; it means that the receiver object is treated as though it were declared as a volatile T*. Consequentially, any reference to x or y will be treated as a volatile read in the member function. Moreover, a volatile object can only call volatile member functions... |
4,826,768 | 4,826,985 | Was the behavior of deleting pointers-to-const changed in the past? | I got the following test code from http://support.microsoft.com/kb/131322:
const int * pi = new int(1000);
const char * pch = new char(65);
void main(void)
{
delete pi ;// Error C2710:cannot delete a pointer to a const object
delete pch ;// Error C2710:cannot delete a pointer to a const object
}
On t... | You can indeed delete a pointer-to-const.
If Visual C++ says otherwise for a standard-conforming program, then that's a compiler bug and should be reported.
Your (or Microsoft's?) program is not standard C++, however, since you have void result type for main.
The KB article you link to says "Deleting a pointer to a con... |
4,826,833 | 4,826,931 | Problems when reading from a FILE and use strtok function | I have writen a code in C++ that must read information from a txt file and when it finds a "|" character it must jump to a new line. Its something quite easy but Im having problems when executing and Ive been trying to find the problem for hours and I havent suceed. :( I attached the code.
Thaaaanks in advance for yo... | You are using uninitialized pointer temp in read function. Trying to write to this memory location will invoke undefined behavior. Dont create a temp as a pointer. Instead you can do char temp; and pass the address of temp i.e. &temp to the read function. Then you need not use strtok, you can simply compare the charact... |
4,826,838 | 4,826,947 | Do Standard Library (STL) Containers support a form of nothrow allocation? | The new operator (or for PODs, malloc/calloc) support a simple and efficient form of failing when allocating large chunks of memory.
Say we have this:
const size_t sz = GetPotentiallyLargeBufferSize(); // 1M - 1000M
T* p = new (nothrow) T[sz];
if(!p) {
return sorry_not_enough_mem_would_you_like_to_try_again;
}
...
I... | By default, the standard STL container classes use the std::allocator class under the hood to do their allocation, which is why they can throw std::bad_alloc if there's no memory available. Interestingly, the C++ ISO specification on allocators states that the return value of any allocator type must be a pointer to a ... |
4,826,899 | 4,827,906 | Equality Test Operator in String Classes | I noticed that many string classes in C++ doesn't implement the == operator to compare to strings. What is the reason behind that? As far as I can see, implementing a class for a string is supposed to make the string an entity by itself, rather than a pointer to a set of characters. So we should definitely expect the =... | Often, when a class doesn't implement operator==, it's because there's a free function outside the class. The advatnage of a free function operator== is that it supports implicit conversions on both sides. This is especially important for strings, because there you often use const char[] literals and want that implicit... |
4,827,301 | 4,842,297 | How to read integer value from file in C++ | How can read integer value from file? For example, these value present in a file:
5 6 7
If I open the file using fstream then how I can get integer value?
How can read that number and avoid blank space?
| It's really rare that anyone reads a file Byte by Byte ! ( one char has the size of one Byte).
One of the reason is that I/O operation are slowest. So do your IO once (reading or writing on/to the disk), then parse your data in memory as often and fastly as you want.
ifstream inoutfile;
inoutfile.open(filename)
std::s... |
4,827,422 | 4,827,527 | Core dump in libc exit call | I am seeing a core dump in solaris at the exit procedure of my program.. How to debug and fix this kind of core dump?
(gdb) where
#0 0xff2cc0c0 in kill () from /usr/lib/libc.so.1
#1 0x0004dac0 in run_before_killed_handler (sig=11) at NdmpServer.cpp:1186
#2 signal handler called
#3 0xfee0ad50 in ?? ()
#4 0x00060a6... | Your program apparently uses atexit(3C) to register an exit handler. The problem is occuring in that handler.
|
4,827,503 | 4,827,705 | Quick 64bit integer ID Lookup/Search | I'm working on a game, and to be on the safe side any user (programmer) is only allowed to store IDs to objects instead of pointers, and must use this ID to get the pointer to the object in order to have to some quality alone-time with it.
Let's use the worst case scenario: Every single ID is in use. It is 64 bit so th... | This is a classical case for a hash map. First, realize how many IDs you can actually have active at any one time. 2^64 is nonsense since then even the data structure just to hold these IDs and the pointers to the objects would already be at least 268'435'456 TB. Now, there's nothing wrong with using 64bit IDs, but fig... |
4,827,531 | 4,828,467 | Ill-formed C++0x code or compiler bug? | In the following C++0x code I tried to clone an object by using a
clone member function (if it exists) and falling back on a copy
constructor:
struct use_copy_ctor {};
struct prefer_clone_func : use_copy_ctor {};
template<class T>
auto clone(T const* ptr, prefer_clone_func)
-> decltype(ptr->clone())
{ return ptr->clon... | I think I convinced myself that this is actually a compiler bug and filed a report. Let's see what happens. As a workaround decltype(new T(*ptr)) can be replaced with T*. The only difference is that the function template will stay part of the overload resolution set which is not a big issue in this case.
Edit: Btw, I w... |
4,827,596 | 4,827,659 | multiple definition and namespace | Is that the right way to have functions in namespace that i will #include in multiple files?
test.h
#pragma once
#ifndef TEST
#define TEST
namespace test{
namespace {
bool test(){
return true;
}
}
}
#endif //TEST
| The include guard name TEST is likely to conflict with some other macro, use something more elaborate, like HEADERNAME_H.
Note: names that start with underscore followed by uppercase, and names that contain two successive underscores, are reserved for the implementation.
Secondly, if you're going to put that in a heade... |
4,827,641 | 4,827,668 | Changing the contents of a pointer variable | In this code:
#include <iostream>
int main()
{
const char* name = "Abc";
std::cout<<*name<<std::endl;
return 0;
}
How can I change the contents of the pointer variable, not to what it is pointing at?
And, why am I just getting A as output from this program?
Thanks.
| You get a char because you are de-referencing a char* pointer.
You could change the contents by doing:
*a = 'B'; // your char* would contain "Bbc"
a[0] = 'B'; // your char* would contain "Bbc"
a[1] = 'B'; // your char* would contain "ABc"
a[2] = 'B'; // your char* would contain "AbB"
But, changing the contents of a st... |
4,827,674 | 4,827,997 | new[] expression does not respect alignment in Microsoft VC++ | If new[] expression is used to create an array of objects having destructors,
the objects in the array may not be properly alligned
#include <stdint.h>
#include <stdio.h>
#pragma pack(8)
struct A{
int64_t i;
char dummy;
~A(){}
};
int main(){
A* pa= new A[2];
printf("sizeof(A)= %d, pointer= %p", sizeof(A), ... | You should use __declspec for this purpose. Your code generated misaligned objects on my computer too (using VS2010) but when I changed to __declspec(align(8)), the pointers were correctly aligned.
I believe that pragma pack only changes the size of the struct and doesn't make any guarantees about it's location.
|
4,828,167 | 4,828,226 | Purpose of a ".f" appended to a number? | I saw 1/3.f in a program and wondered what the .f was for. So tried my own program:
#include <iostream>
int main()
{
std::cout << (float) 1/3 << std::endl;
std::cout << 1/3.f << std::endl;
std::cout << 1/3 << std::endl;
}
Is the .f used like a cast? Is there a place where I can read more about this intere... | Without the .f the number gets interpreted as an integer, hence 1/3 is (int)1/(int)3 => (int)0 instead of the desired (float)0.333333. The .f tells the compiler to interpret the literal as a floating point number of type float. There are other such constructs such as for example 0UL which means a (unsigned long)0, wher... |
4,828,331 | 6,669,255 | How to create a remote viewer for a games LAN party? | In my LAN I have 11 computers for multiplayer games LAN parties.
I need to create a remote viewer for all 10 computers in my LAN.
So this program only needs to captures and sends the desktop to my computer.
What API, functions or library do I have to use ?
.
P.s. I want create my own program, so I don't want to use oth... | I can give you some advice for Windows platform and Borland Builder C++. You'll need two applications, one installed at client side and one in your side.
Client side
A TCP server listening for your command request.
An UDP client to send screenshot to your side.
Screenshot grabber, you can do it by sending a print-scr... |
4,828,388 | 4,828,533 | Cygwin Make bash command not found | I installed cygwin with all the packages on windows 7 64 bit. For some reason the make command is giving me an error: bash make: command not found. I checked and in my bin folder, there is no make.exe. Can anyone help me on this? I really need make to work in CYGWIN. I dont wanna have to go to windows xp.
| You probably have not installed make. Restart the cygwin installer, search for make, select it and it should be installed. By default the cygwin installer does not install everything for what I remember.
|
4,828,436 | 4,828,738 | Outputting a string variable into a text file in HEX format | I'm stuck with a problem that I cannot solve.
So what i need is following: I need to make a program that receives one string input and converts it to hex and after that it saves it into a file.
If the file isn't created, it should, but if there is one already it should continue writing to the same (i guess "a+" parame... | You are learning C++ so why not use file streams?
#include <fstream>
#include <iomanip>
using namespace std;
int main () {
// Read your string as before
fstream fs;
fs.open ("hex.txt", fstream::out | fstream::app); // app = append to file
for(int i=0; i<a.size(); ++i)
{
fs << hex << static_cast<int>(... |
4,828,438 | 4,841,043 | checking for webcam camera device gnome library | How can i detect camera device(s) using gnome libraries.
Please get me some sample codes regarding this.
I have followed Cheese source code, but when i call detect camera api, it returns NULL.
Thanks and Regards,
iSight
| from my understanding, you don't really need to use gnome\gtk if what you need is webcam device information. Pls, try the code below, it should query and output video driver capabilities:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
int main()
{
stru... |
4,828,580 | 4,828,648 | Optimize File Read and Write | I have this code to read 64MB of binary data into memory:
#define SIZE 8192
char* readFromFile(FILE* fp)
{
char* memBlk = new char[SIZE*SIZE];
fread(memBlk, 1, SIZE*SIZE, fp);
return memBlk;
}
int main()
{
FILE* fp = fopen("/some_path/file.bin", "rb+");
char* read_data = readFromFile(fp);
// do something... | It looks like the additional memory you need for your code induces thrashing in the application which probably is already running at the limit.
If you want to "do something" with the file you can either:
Process the file blockwise
Using mmap() or some similar memory mapping technique on your operating system to map t... |
4,828,992 | 4,829,036 | Is there an easy way to tell if a class/struct has no data members? | Hallo,
is there some easy way in C++ to tell (in compile-time) if a class/struct has no data members?
E.g. struct T{};
My first thought was to compare sizeof(T)==0, but this always seems to be at least 1.
The obvious answer would be to just look at the code, but I would like to switch on this.
| Since C++11, you can use standard std::is_empty trait: https://en.cppreference.com/w/cpp/types/is_empty
If you are on paleo-compiler diet, there is a trick: you can derive from this class in another empty and check whether sizeof(OtherClass) == 1. Boost does this in its is_empty type trait.
Untested:
template <typenam... |
4,829,104 | 4,829,274 | Why won't this C array initialization compile under g++? | HI all
I have this code taken from a C project. I am not able to compile it in any way under g++.
What can I do with this?
enum EnumIndexID{
ID_VALUE_A=2,
ID_VALUE_B=2
}
struct newtype {
enum MyEnumID eid;
const char *name;
} table[] = {
[ID_VALUE_A] = { MyEnumA, "ID_MSG_HeartbeatReq"},... | The following compiles fine as C99 (note: it's not valid as C89):
enum MyEnumID {
MyEnumA, MyEnumB
};
enum EnumIndexID{
ID_VALUE_A=2,
ID_VALUE_B=2
};
struct newtype {
enum MyEnumID eid;
const char *name;
} table[] = {
[ID_VALUE_A] = { MyEnumA, "ID_MSG_HeartbeatReq"},
[ID_VALUE_B] = { MyEnu... |
4,829,341 | 4,830,206 | internal address space reuse with vectors created inside a loop | The contrived example below shows the duplicate addresses seen inside of a loop. The same phenomenon manifests when I build both with and without optimization on MinGW GCC 4.5.0. The problem I'm seeing is that when I create a vector inside a loop, the internal array sometimes appears to occupy the same memory addresses... | The problem I see is in this loop:
cout<<"other vector addresses"<<endl;
for (size_t i = 0;i<stacked_vector.size();i++){
other_stacked_vector.push_back(vector<int>());
other_stacked_vector.back().reserve(9);
other_stacked_vector.back().resize(5,0);
write_container_addresses<int>(other_stacked_vector[i])... |
4,829,428 | 4,837,893 | OpenMP code executed in thread pool | I'm thinking about a design were a thread pool will execute code blocks, which may contain OpenMP statements (parallel for mostly).
(Similar to: How to deal with OpenMP thread pool contention I guess).
My question is if it will cause problems or lead to bad performance if an OpenMP parallel region is executed by a diff... | Vitor's comment is correct. It is hard to tell whether or not this will cause problems, because the answer depends on many factors (i.e., the data layout, how you are accessing the data, the cache size, the type of processor you are running on, and the list goes on).
What I can say, is that you may or may not be able ... |
4,829,437 | 4,830,303 | Convert int64_t to time_duration | I would like to transfer a boost::posix_time::ptime over the network as a boost::int64_t. According to A way to turn boost::posix_time::ptime into an __int64, I can easily define my own epoch and only transfer the time_duration from that reference epoch as a 64 bits integer. But how to convert back to a ptime?
#include... | Working solution with millisecond resolution:
int main(int argc, char ** argv){
ptime t = boost::posix_time::microsec_clock::local_time();
// convert to int64_t
ptime myEpoch(date(1970,boost::gregorian::Jan,1));
time_duration myTimeFromEpoch = t - myEpoch;
boost::int64_t myTimeAsInt = myTimeFromEpo... |
4,829,518 | 4,830,259 | Accessing parent's protected variables | I couldn't think of a better wording for the title, so it is a little misleading, however, I am not talking about a child accessing its variables inherited from its parent, which is easy enough.
What I am talking about is this:
class Parent {
protected:
Parent *target;
int hp;
}
class Child : public Parent... | Member functions of a particular class only have access to protected members of base classes that actually are base class subobjects of objects of their own class type (or more derived types).
Members of one class do not have access to protected members of other instances of that base class and so are also forbidden fr... |
4,829,547 | 4,830,238 | What to use instead of static variables | in a C++ program I need some helper constant objects that would be instantiated once, preferably when the program starts. Those objects would mostly be used within the same translation unit, so the simplest way to do this would be to make them static:
static const Helper h(params);
But then there is this static initia... | There are several possibilities for global state (whether mutable or not).
If you fear that you'll have an initialization issue, then you should use the local static approach to create your instance.
Note that the clunky singleton design you present is not mandatory design:
class Singleton
{
public:
static void DoSom... |
4,829,696 | 4,829,740 | why does boost::noncopyable require inheritance | Adding any noncopyable member to a class would prevent the automatic generation of copy construction and assignment operator. Why does boost require inheritance to use noncopyable?
I think I am not alone in my stylistic preference for
class MyUtility : public MyBase
{
noncopyable guard;
...
};
as opposed to
cl... | Because sizeof(boost::noncopyable)!=0. So in this case your class size will be bigger.
Here you can read about the empty base optimization. (look at section "4.7: The Empty Member Optimization").
Edit: The fact, that noncopyable doesn't have public constructors makes it useless for any other use, while classes with pub... |
4,829,720 | 4,830,194 | debug cgi c++ application | I am new to cgi and have an cgi C++ application to debug.
How can I set up the environment on my developer PC in order to debug in visual studio?
My app supports GET and POST method but I have no idea what to do to make it start up correctly.
The app is started through a link with some arguments like:
myApp.exe?m... | If your parameters are usually sent as part of the URL, then they should be found in the QUERY_STRING environment variable. You normally get this by calling get_env("QUERY_STRING").
Before running, try setting the environment variable QUERY_STRING to contain mode=create&name=jack
|
4,829,962 | 4,830,098 | Use C++ DLL with VB6 | I just created a DLL for my boss in MSVC++2010. I selected "New Win32 DLL" with option "Export symbols", so, everything is completely standard. There are some predefined exports in the new project files, a class, its constructor, a global function and variable with bogus values and a file dllmain.cpp with an APIENTRY f... | Yeah, VB6 doesn't work like that. You need to declare the DLL functions in your VB code somewhat like this:
Private Declare Function WinHelp Lib "user32" Alias "WinHelpA" _
(ByVal hwnd As Long, ByVal lpHelpFile As String, _
ByVal wCommand As Long, ByVal dwData As Long) As Long
You would replace "user32" with "MyC... |
4,830,279 | 4,830,536 | Why does the print command in gdb return \035 for C++ std::strings? | Say I have the code:
std::string str = "random";
function(str);
void function (std::string str)
{
std::cout << str << std::endl;
}
If I step through this code in gdb and then go into the function and do p str it would print out something like this \362\241 but the cout will print to the screen the correct string r... | You have a broken version of GCC, or GDB, or you are trying to print the string at the wrong place. Here is what it should look like (using g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3 and GNU gdb (GDB) 7.2.50.20110127-cvs with STL pretty printers enabled):
#include <string>
#include <iostream>
void function (std::string str)
{
... |
4,830,334 | 4,880,115 | How to get the source and target points from Edge_iterator in CGAL | I have a Delaunay triangulation over some points and want to iterate over all of the edges in it in length-ascending order in order to build a minimum spanning thread.
I've tried with the following approach but cannot get it to compile:
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Delaun... | The edge_iterator is a std::pair of a face and a vertex index. The edge's source and target vertices can be accessed over this face reference. The vertex index in the edge_iterator conforms to the opposite vertex. So, the other two have id's (i+2)%3 and (i+1)%3.
Some other solution is getting to the segment via triangu... |
4,830,654 | 4,830,745 | How to generate a 64 bit COM Proxy | I have a 32 bit COM server (and the source code for it)
The source generates the server and a 32 bit proxy stub. (The MIDL compiler generates the proxy stub code.)
I would like to make a 64 bit proxy as well, so that 64 bit programs can talk to my 32 bit COM server.
How do I go about converting a 32 bit proxy into a 64... | The proxy code generated by the MIDL compiler should work. You just need to build a 64-bit dll from that code.
Make sure your types are defined properly. Make sure you avoid types like UINT_PTR which will not work when a 64-bit caller calls a 32-bit server.
|
4,830,671 | 4,830,697 | How can I best improve the execution time of a bicubic interpolation algorithm? | I'm developing some image processing software in C++ on Intel which has to run a bicubic interpolation algorithm on small (about 1kpx) images over and over again. This takes a lot of time, and I'm aiming to speed it up. What I have now is a basic implementation based on the literature, a somewhat-improved (with regard ... | I think GPU is the way to go. It's probably the most natural task for this type of hardware. I would start by looking into CUDA or OpenCL. Older techniques like simple DirectX/OpenGL pixel/fragment shaders should work just fine as well.
Some links I found, maybe they could help you:
Efficient GPU-Based Texture Int... |
4,830,678 | 4,830,784 | proper factory pattern in C++ | in C# you have to declare everything in a class so an example factory pattern could look like:
namespace MySpace {
public class CFactory
{
public static CFactory Current()
{
static CFactory singleton;
return singleton;
}
public CBase Create() { return null; }
}
}
in C++ you dont have this limitation.... | You can presume from its usage in the standard library that a namespaced global factory is not implicitly wrong. Nothing prevents it from being correct.
Your approach of wrapping the factory in a class is an organizational change. Organization itself is neither good nor bad. It can be done well or poorly.
You shoul... |
4,830,976 | 4,831,148 | are STL Containers .push_back() naughty | This might seem daft for which I'm sorry, I've been writing a bit some code for the Playstation 2 for uni. I am writing a sort of API for the Graphic Synthesizer. I am using a similar syntax to that of openGL which is a state machine.
So the input would something like
gsBegin(GS_TRIANGLE);
gsColor(...);
gsVert... | Vector's push_back has amortized constant time complexity because it exponentially increases the capacity of the vector. (I'm assuming you're using vector, because it's ideal for this situation.) However, in practice, rendering code is very performance sensitive, so if the push_back causes a vector reallocation, perf... |
4,831,074 | 4,831,118 | Get most accurate image using OpenCV | I wonder if someone give me a solution to this. How can I get most clear iplimage among rest ,
using OpenCV.?
As a example there is a web cam input which move a hand. But when I stream this video ,I get 10 iplimages. But only 5th one is more clear. I want to filter that 5th one using openCV.
I hope kindness support fro... | You could probably use some kind of edge detection. Out-of-focus or motion-blurred images will have fewer detectable edges than "sharper" images. Look at Canny et al.
|
4,831,081 | 4,831,111 | trouble with creating two dimensional array from file | I have some troubles with parsing matrix file. It looks sth like this:
# Matrix made by matblas from blosum62.iij
# * column uses minimum score
# BLOSUM Clustered Scoring Matrix in 1/2 Bit Units
# Blocks Database = /data/blocks_5.0/blocks.dat
# Cluster Percentage: >= 62
# Entropy = 0.6979, Expected = -0.52... | Your code has a fundamental problem in it: as soon as it reaches that return statement, the function will end, and the rest of your file won't be parsed.
This is why you're not seeing anything; it's printing out the first character in the first line of your file ONLY, and that happens to be the blank space before the f... |
4,831,216 | 4,831,365 | Set of efficient 3D intersection algorithms | Anyone knows a source, website where I can get some good implementations of 3D intersection algorithms, like
intersection of sphere and sphere
sphere/ellipsoid
sphere/cuboid
ellipsoid/ellipsoid
ellipsoid/cuboid
cuboid/cuboid
sphere/ray
ellipsoid/ray
cuboid/ray
triangle/ray
quad/ray
triangle/triangle
quad/quad
| http://www.realtimerendering.com/intersections.html.
It's a huge matrix of algorithms that calculate intersections between various types of objects. Excellent resource.
|
4,831,523 | 4,831,578 | What type should I catch if I throw a string literal? | I am writing a pretty simple application in C++ using g++ under Linux and I am trying to throw some raw strings as exceptions (yes, I know, its not a good practise).
I have the following code (simplified):
int main()
{
try
{
throw "not implemented";
}
catch(std::string &error)
{
cerr<<"Error: "<<erro... | You need to catch it with char const* instead of char*. Neither anything like std::string nor char* will catch it.
Catching has restricted rules with regard to what types it match. The spec says (where "cv" means "const/volatile combination" or neither of them).
A handler is a match for an exception object of type E ... |
4,831,569 | 4,831,581 | How to create split screen console output? | I would like to be able to channel two text streams to a single console window with a vertical split view. The ideal solution would be if I could simply write to two different std::ostream objects.
The reason I need it is to compare the output of two different versions of a program. I know there are simple workaro... | This cannot be done using "pure c++" alone. You will need additional, potentially platform specific, libraries to implement the behavior you desire. For example, look at the ncurses library.
|
4,831,571 | 4,831,595 | Create a copy or use reference for parameter? | My problem is that I want to return a common substring of two strings s1, s2. Apparently, s1 and s2 are symmetric.
string shortest_common( const string& s1, const string& s2 ) {
}
There are three possible solutions to this problem that I came up with:
Either make a copy of s1 and s2
Or swap them, which means I ha... | I would opt to go with the signature that you've displayed. If you're finding a common substring then you don't want to have side-effects. That's not what people think of when they would call your function. I don't expect a function called "add_two_numbers" to modify one of the numbers and return a value.
|
4,831,759 | 4,831,896 | Ambiguous definition of operator() with multiple inheritance | I compile this code with GCC (4.2.1 Apple build 5664)
#include <cstddef>
using std::size_t;
template <char I> struct index { };
struct a
{
void operator()(size_t const &) { }
};
struct b
{
template <char I>
void operator()(index<I> const &) { }
};
struct c: public a, public b { };
int main (int argc, ... | Modify c this way:
struct c: public a, public b
{
using a::operator();
using b::operator();
};
C++ (prior to C++0x) is kind of awkward in inheriting functions: if you provide a function with the same name of a base class' function it hides base class ones.
It looks like also inheriting from two classes has the... |
4,831,775 | 4,833,619 | Documenting callback typedefs in Doxygen | I have the following typedef:
typedef void( __cdecl *tCallback )( const char* Message );
How would I document that correctly using Doxygen?
I would like to to have the tCallback documented and the parameters expected documented.
A simple example:
/// \typedef test
typedef test bool
produces correct output in doxygen... | Add the following to your Doxyfile:
PREDEFINED = __cdecl=
This will cause Doxygen to ignore this identifier for purposes of documentation.
|
4,831,858 | 4,832,019 | C++: Our installer refuses to load our application's resources DLL (module not found) [XP only] | Basically, when our software runs under Windows 7, it works: the call to LoadLibrary() succeeds, and life is good.
But when the same software is run on an XP box (latest patches), the call to LoadLibrary fails, returning NULL, with an error code that specifies module not found.
I have tried forcing it to use the UN... | I would examine differences between your toolset and platform combinations.
For example the VS2008 vs VS2010 distinction is less important than what SDK you're using. Different SDKs could be targeting different msvc runtime libraries.
Is it possible you have the VS2010 runtime library installed on your XP VM and not t... |
4,832,275 | 4,835,911 | C++ typedef member function signature syntax | I want to declare type definition for a member function signature. Global function typedefs look like this:
typedef int (function_signature)(int, int);
typedef int (*function_pointer) (int, int);
But I'm not able to the same thing for a member function:
typedef int (foo::memberf_signature)(int, int); // memberf_poin... | For questions regarding the awkward function pointer syntax, I personally use a cheat-sheet: The Function Pointers Tutorial (downloadable here, thanks to Vector for pointing it out).
The signature of a member function, however, is a bit different from the signature of a regular function, as you experienced.
As you prob... |
4,832,280 | 4,832,364 | Where to Start With Contributing to Ubuntu (and other distros) | The learning days of my development started with C++, but the days since then have been many. I would like to look into contributing to Ubuntu (or Chromium), but I'm not sure where to start. I am extremely rusty when it comes to C++ and especially in such a large project. Is there a good place for me to start?
I'm m... | Ubuntu is a distribution, that means it's a bunch of programs packed together in a nice way. You can contribute in many ways to distributions: maintaining package repositories, checking for bugs, artwork... If you're interested in the programming side, I'm sure you'll enjoy fixing bugs for the many packages that Ubuntu... |
4,832,331 | 4,832,412 | C++ Macro text manipulation | I would like to write a C++ macro taking arbitrary argument like:
#define MANIP(...) \
//Implementation
Such that writing
MANIP(m_a, m_b, m_c);
expands to
f(a, b, c);
g("a", "b", "c");
Is this possible?
Thank you in advance for helping me with this seemingly extravagant question :)
| I don't believe there will be an easy way to go from m_a to a. However, the stringize operator # is part of standard C and C++.
for example, given
#define STRING(x) #x
then STRING(m_a) will be transformed to "m_a".
|
4,832,368 | 4,832,410 | Explicit override of virtual function | I just discovered that C++/CLI has a keyword that is not present (AFAIK) on standard C++: override.
I don't know much about C++/CLI, so, can someone explain for which purpose is it included there, and if is it a desirable feature to be added to C++?
| override is a special keyword extension from Microsoft that can be used in C++/CLI and Visual C++ implementations. It is similar to the @Override annotation in Java or override in C#, and provides better compile time checks just in case you didn't override something you meant to.
From the first link:
override indicate... |
4,832,688 | 4,838,320 | xgettext - extract translatable strings and update .pot | I have inherited a sample.pot file. Now, I have added new messages in a1.c and a2.cpp. Is it possible for me to use xgettext and output the contents to same sample.pot instead of creating a new one? Eg:-
xgettext -d sample -s -o sample.pot a1.c
xgettext -d sample -s -o sample.pot a2.cpp
Is this preferred way to go in ... | Does the -j, --join-existing option ("join messages with existing file") not do what you need?
Note that you can specify more than one input file on the command line.
xgettext -d sample -s -j -o sample.pot a1.c a2.cpp
|
4,832,692 | 4,832,780 | STL containers: iterating between two iterators | I am storing values in a std::map
I am finding two values in the map, and I want to iterate between the first through to the last item - however the <= operator is not implemented, so I can't do somethimng like this:
void foobar(const DatedRecordset& recs, const double startstamp, const double endtstamp)
{
... | Use != instead of <= and it will do what you want it to do.
void foobar(const DatedRecordset& recs, const double startstamp, const double endtstamp)
{
DatedRecordsetConstIter start_iter = recs.lower_bound(startstamp),
end_iter = recs.upper_bound(endtstamp);
for (DatedRecordsetConstI... |
4,832,745 | 4,832,819 | Accelerated C++problem - functions which call functions | I am having trouble with an exercise in Accelerated C++.
The main function is as follows:
int main()
{
// students who did and didn't do all their homework
vector<Student_info> did, didnt;
// read the student records and partition them
Student_info student;
while (read(cin, student)) {
if (did_all_hw(student))
... | First, you need to use the appropriate name for the analysis function. That would be optimistic_median_analysis. Next, you have to take in a reference to the vector, iterate over each item and apply the optimistic_median function to it.
double optimistic_median_analysis(const vector<Student_info> &v)
{
return std::... |
4,832,801 | 4,832,863 | Performance question on nested if's | is there be any performance effect on "Lines of code - (C)" running inside nested ifs?
if (condition_1)
{
/* Lines of code */ - (A)
if (condition_2)
{
/* Lines of code */ - (B)
if (condition_n)
{
/* Lines of code */ - (C)
}
}
}
Does that mean you can nest any number of i... | Remember C and C++ are translated to their assembly equivalents. In most cases, this is likely to be via some form of compare (e.g. cmp) and some form of jmp instruction.
As such, whatever code is generated from (C) will still be the same. The if nesting has no bearing on the output. If the resultant code is to generat... |
4,832,900 | 4,832,987 | How can I specialize a typedef and its implicit type differently? | I have something like this:
typedef int AnotherType;
template <typename T> Func( T Value );
// And I want to specialize these two cases separately:
template <> bool Func<int>( int Value ) {...}
template <> bool Func<AnotherType>( AnotherType Value ) {...}
I don't really need to specialize for int, what I really need... | You could use BOOST_STRONG_TYPEDEF.
|
4,832,949 | 4,839,057 | C++ - Iterating over a tuple & resolution of type vs constant parameters | I'm currently in the process of writing arithmetic operator overloads for tuples. The operator iterates over the tuple to perform the operation on each of its individual element. Here is the definition for operator +=:
template< typename... Ts, std::size_t I = 0 >
inline typename std::enable_if< I == sizeof... (Ts), st... | Using explicitly specified template arguments to a function or class template requires that any template parameter packs appear at the end of the overall template parameter list. Moving Ts... to the end of the template parameter lists and changing the calls appropriately makes the code work. Section 14.8.2.1 of the c... |
4,832,968 | 4,835,067 | Project files in KDevelop | I am trying to use KDevelop to write a cmake based simple application. KDevelop created two myProject.kdev4 project files: one in the project folder and one in .kdev4 hidden subfolder. Both are non-empty. Which ones should I check in? How can I make kdevelop use just one project file (and preferably not use hidden fol... | The .kdev4 file is used for kdevelop specific information (It mainly only tells KDevelop to use the CMake project manager). The folder includes user specific configuration (If you are familiar with Visual Studio, it is like the .user files).
Usually only the CMakeLists.txt files are needed as they should have all the r... |
4,833,080 | 4,833,160 | Trying to compile simple c++ program in make | I am having trouble with make. I installed all of the features that come with cygwin. When I type in make command it says:
make:***No targets specified and no
makefile found. Stop.
This is really annoying as it's a very simple program.
My make file (Makefile):
# This is a sample file.
all: lab1
lab1: lab1.o
g+... | The issue (fixed in the comments) was that there was a Makefile.mak in the directory but not an actual Makefile without an extension. Changing the name worked for the submitter.
|
4,833,747 | 4,833,786 | Unable to nail memory leak detected by valgrind | Below is the pattern of new/delete operators in my program. Valgrind says that memory is "definitely lost". I couldn't quite get where the leak is. Is there something wrong with my usage of new/delete operators.
class Generic
{
GenericInterface *gInterface; //GenericInterface is abstract class
pub... | You are not following the rule of three. If your class manages resources that need to be cleaned up, you must declare a destructor, copy constructor, and copy assignment operator. Neither of your classes has a copy constructor or a copy assignment operator.
Really, you should almost certainly just be using a smart po... |
4,833,915 | 4,833,942 | Passing NSArray to a cpp function | I need to call a cpp function like
void myFunc(float **array2D, int rows, int cols)
{
}
within an objective-c object. Basically, the array is created in my objective-c code as I create an NSArray object. Now, the problem is how to pass this array to my cpp function.
I am a bit new to these mixed c++/objective-c stuffs... | I guess you have to convert the NSArray to a plain C array.
Something like:
NSArray *myNSArray; // your NSArray
int count = [myNSArray count];
float *array = new float[count];
for(int i=0; i<count; i++) {
array[i] = [[myNSArray objectAtIndex:i] floatValue];
}
or, as a commenter suggested (assuming your NSArray co... |
4,833,972 | 4,834,010 | How does SysInternal's ProcessMonitor work? | Could someone please give me a high level explanation how they are able to monitor every single registry access?
http://technet.microsoft.com/en-us/sysinternals/bb896645
Enough detail so that i could google around the various sub-topics and try to write my own one? I know they've used some sort of dll injection/API hoo... | It loads a virtual driver on startup which does the monitoring on a low-level. So it doesn't have to inject anything in other processes.
On http://www.decuslib.com/decus/vmslt00a/nt/filemon.htm there's a short explanation about how FileMon, one of ProcMon's predecessors, works.
How Filemon Works
For the Windows 9x dri... |
4,834,076 | 4,870,968 | Link Error 'target machine "THUMB" requires "/WINDOWSCE"' on static library | I am moving a Embedded Visual C++ project to VS2005. When I compile the project I get this error: fatal error CVT1109: target machine "THUMB" requires "/WINDOWSCE" CVTRES. Goggling this just left me more confused. Most stated I needed to add the linker option /WINDOWSCE. My issue is there is no linker options in ... | Finally Resolved I opened
Project Properties --> Configuration Properties --> Librarian --> Command Line
Than I added the following line:
/subsystem:$(CESubsystem) /MACHINE:THUMB
I would of sworn I tried that from the start, thank the heavens I found the solution hope it helps someone else.
|
4,834,427 | 5,578,078 | Thrust graph; Native CUDA compilation problem... Linux | I'm trying to compile a simple example from thrust graph.
At the moment I have everything commented out in main(void)
I'm looking for ANY direction someone is willing to give!
My compilation error is this:
mseil@cuda:~/mseil_CUDA/test$ nvcc Example.cu
/usr/local/cuda/bin/../include/thrust/detail/device/cuda/reduce_by_... | I am thrust graph lib developer, drkkojima.
I updated to 0.2RC03 and solved the problems.
|
4,834,444 | 4,834,456 | Creating Random Number Using Vectors in C++ | I'm building a program in which a user types in a number (n) and a set of random numbers is created. So for example, if a user inputs 8, then eight random numbers should be created and they should range from 0-999,999. The program seems to be compiling, the only problem is, only one random number is being generated.
... | What's wrong with the obvious:
for (int i=0; i<n; i++)
v.push_back(rand()%1000000);
It looks like you're generating the right quantity of random numbers, but when you're done, you're printing r instead of v, which is what contains the random numbers.
Edit: std::vector doesn't support operator<< directly, so you ca... |
4,834,838 | 4,834,933 | Is there any online compiler with executer that would compile apps that use GPU-specific C/C++ code? | Generally I need some online compiler that can compile and execute provided program and output execution speed and other statistics. All program can be in one C file and it would use any GPU C/C++ lib provided. I want to compile at least C code. Does any GPU vendor provide any such compiler? Actually my problem is next... | Amazon EC2 recently added support for "GPU instances", which are normal HPC instances which come with two NVIDIA Tesla “Fermi” M2050 GPUs. You can SSH into these instances, install a compiler, and go to town with them.
It'll cost $2.10/hour (or $0.74/hour if you get a Reserved Instance for a longer block of time)
|
4,834,889 | 4,834,920 | Confused about the Linker in C++ | I am new to C++ and trying to understand everything. I know the Linker links the object file to any external files. Correct? Does the linker link the preprocessors? or just additional files?
For instance in a simple Hello World program. Would the linker link with my Hello World Program?
| This is a good explanation.
Wikipedia on linkers
|
4,834,895 | 4,838,610 | C++ STL optimization warning: problem with the code or something more sinister? | I have a program that I'm working on where I'm switching from using arrays to vectors, but I get a problem. I've reduced it down to this:
#include <vector>
class A {
public:
A(void);
~A(void);
private:
std::vector< std::vector<int> > a;
};
A::A(void) : a() {}
A::~A(void) {}
This gives the following warning from g+... | I think I finally got what the compiler was hinting at.
The loop is not executed on an integer, so I think what the compiler is trying to tell is that it cannot actually compute how many runs the loop will perform.
The warning you used should actually is usually coupled with -funsafe-loop-optimizations, from gcc optimi... |
4,835,022 | 4,835,030 | What type of exception is thrown when dividing by zero? | What kind of exception is thrown when there's a divide by zero error? I tried using the "catch-all" catch(...), but Visual Studio still complains that there's an unhandled exception.
int a = 0;
try
{
a /= a;
}
catch (/* what should I catch?*/)
{
cout << "divide by zero error" << endl;
}
Note: I'm not a... | This is not a C++ question, because there is no way to do so in standard C++.
In Windows, this generates a Structured Exception Handling exception.
See this example from MSDN:
__try
{
*pResult = dividend / divisor;
}
__except(GetExceptionCode() == EXCEPTION_INT_DIVIDE_BY_ZERO ?
EXCEPTION_EXECUTE_HANDL... |
4,835,177 | 4,878,941 | How to train/use the HOGDescriptor class in OpenCV | I have been looking into training/using OpenCV to attempt to detect human figures. I want to try training a HOG for my specific purposes and not use the provided getDefaultPeopleDetector function. I have been unable to find any usable documentation on the HOGDescriptor class.
How do I train my own classifier for my own... | HOG descriptor is very easy to implement. You can write your own code to do it. Look at http://smsoftdev-solutions.blogspot.com/2009/08/integral-histogram-for-fast-calculation.html.
It is fast implementation of HOG. Once you get HOG features of all the training images.You can train an SVM in OpenCV. Training with Gauss... |
4,835,192 | 4,835,234 | Threaded for loop in c++ | I am trying to figure out the best way to essentially thread a for loop. For example, if I have the following loop:
for(int i = 0; i < n; i++)
doSomethingThreadSafe(i);
This will be on a Windows platform. I have played around with creating a thread for each processor, and then attempting to divide n up as evenly as ... | Easiest way is openMP - visual studio supports it as standard, you just add a couple of magic #pragma to the loop and use all the cores you have !
Best way to learn is how not to do it - 32 OpenMP Traps For C++ Developers
An alternative - but slightly more complex method Intel TBB
|
4,835,243 | 4,836,284 | STL container with generic/templated variables | I would simply like to do something of the following:
template <typename T>
class gvar {
private:
T var;
public:
gvar(T var) : var(var) {}
};
std::stack<gvar> some_stack;
g++ spits out all kinds of errors about how gvar is not a type. Is this achievable in some relatively easy way? I prefer not to use boost::... | In general, if you want polymorphism, you'd use a base class:
class GVarBase
{
public:
virtual ~GVarBase() {}
};
template <typename T>
class GVar: public GVarBase
{
public:
private:
T mVar;
};
std::stack< std::unique_ptr<GVarBase> > stack;
Note that with the current code you have, even std::stack< GVar<int> > wo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.