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,284,456 | 7,284,855 | How to test connect timeout on RHEL c/cpp application | I have an application which talks to server over HTTP. I have written a code to control connect timeout (amount of time it will wait before server replies) . But I am finding it hard to generate a test case to test my connect timeout code. Could you please help me.
Basically, TCp handshake will contain
Host A sends a ... | Given you mentioned RHEL I think you're best off using iptables to help test this. For example you could call:
iptables -I INPUT -s hostb -d hosta -p tcp --dport $port --tcp-flags SYN,ACK SYN,ACK -j DROP
calling that before running the test (or even during it perhaps?) and an equivalent matched -X to delete it seems t... |
7,284,477 | 7,284,540 | Need to Release a com_ptr_t before reassigning with CreateInstance? | In a C++ class with _com_ptr_t members, will memory leak if CreateInstance() is repeatedly used on the same pointer to get fresh instances of COM objects, without first performing a Release()? It's well documented that ref count is decremented when one of these smart pointers goes out of scope, and that it is not when... | No leak will occur since _com_ptr_t calls Release() at the beginning of CreateInstance() which you can easily verify yourself by reading _com_ptr_t implementation.
|
7,285,325 | 7,345,587 | Error 411 (Length Required) in post request with header, but header has Content-Length. libCurl | I use this options:
curl_easy_setopt(curl, CURLOPT_URL, urlUpload);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
It must be post request with header. And in header variable there is length
***
ch... | This error was because in the authentication string that I receive from YouTube was in the end the new line symbol, I erase it and this error disappeared.
|
7,285,351 | 8,635,555 | Howto Debug CgiCC App | I develop a Win32 C++ cgi app for windows and linux and start from scratch.
I use CgiCC as lib and Visual Studio 2010 as IDE.
How can I debug that? When I instanziate my cgicc class the program holds and waits for CGI input I guess.
How can I set up an environment for my CGI input?
I set some environment variables like... | Solved it by myself:
Build cgicc with the same visual studio version that I compile my project with.
Build cgicc as a static library instead of a dynamic library.
Setting the preprocessor define CGICC_EXPORTS in my project which activated __declspec(dllexport).
Then it worked!
|
7,285,390 | 7,285,481 | Using Qt: Invalid conversion from const void* to void* while using QList<Type *const> | I've been messing around with Qt and C++ for a while, but I've run into this error and can't seem to figure out why it crops up. There are a lot of other questions that have been answered out there with the const void* conversion error message, but I can't really see how the explanations help in my case, so here goes:
... | From the documentation:
QList's value type must be an assignable data type.
Alas MyType *const is not assignable. You have several remedies:
1. Make T a mutable pointer
2. Make T a pointer to your const pointer:
typedef MyType *const Element
void MyTypeManager::addMyType(Element var)
{
Element* ptr2ptr = new Ele... |
7,285,583 | 7,285,817 | Where are the implementation of stack functions? | I am learning data structures and algorithms. My teacher told me the following:
push(): push inserts an element in the stack
pop(): pop deletes the last inserted element from the stack
size(): Returns the number of elements in the stack
isempty(): Returns a boolean indicating if the stack is empty
top(): returns the t... | Your teacher was explaining the functions available for the generic stack data structure. Those functions aren't implemented anywhere in particular because your teacher was not talking about any specific stack. Your teacher wasn't even talking about C++. Right now you're just learning about what a stack is: they're abs... |
7,285,645 | 7,285,748 | Advantages of typedef over derived class? | Simply put, what are the (or are there any) differences between doing say
class MyClassList : list<MyClass> { };
vs
typedef list<MyClass> MyClassList;
The only advantage that I can think of (and its what lead me to this question) is that with the derived class i can now easily forward declare MyClassList as
class MyC... | Well, a typedef can only do what its name suggests while a derived class can possibly be a full-blown makeover of its base(s). So while there may not be much of a difference if you limit yourself to "just" deriving (and not add any members, or override anything, etc) as far as the compiler is concerned, there might be ... |
7,285,663 | 7,589,328 | Optimal technique to parse a real-time char* data received from a buffer for text content in C++ | I have created a live continuous mjpeg stream. A crude illustration is like this
....[image (jpeg)]->[text "content-length"]->[image (jpeg)]->[text "content-length"]->....
As you can see I receive data from gstreamer media pipe line which contains image and my own injected text
(Note: Although I am using Gstreamer, m... | I ended up using ringbuffer class
In header file declare
//queue size
enum { rb_size = 5 }; // ---->element1 -> element2 -> .... -> elementN -> gap ->
// ^ |
// | ... |
7,285,952 | 7,286,020 | Efficiency of std::copy vs memcpy | How severe is the efficiency loss between using memcpy and std::copy?
I have a situation where the vector implementation on my system doesn't appear to use contiguous memory, which is making me have to std::copy its contents later on rather than doing memcpy(dest, &vec[0], size);. I'm not sure how badly this is likely... | A reasonably decent implementation will have std::copy compile to a call memmove in the situations where this is possible (i.e. the element type is a POD).
If your implementation doesn't have contiguous storage (the C++03 standard requires it), memmove might be faster than std::copy, but probably not too much. I would ... |
7,285,975 | 7,286,313 | match multiple types for template specialization resolution | Briefly dismiss the fact that normal function overloading will serve this example better. It is meant only as a way to learn about template programming. Having said that, you are welcome to comment on the benefits/differences you'll get from using function overload, compared to function template specialization (althoug... | Here's a standard solution idiom:
#include <type_traits>
#include <cstdio>
// Helper class
template <typename T>
struct Printer
{
static typename std::enable_if<std::is_floating_point<T>::value, int>::type
print(T x, char * out, std::size_t n)
{
return std::snprintf(out, n, "%f", x);
}
};
// Convenience... |
7,286,200 | 7,286,233 | ArrayDeque class of chars | I'm trying to move a paren balancer I wrote in C++ to Java.
I'm trying to implement the stack with an ArrayDeque class from the Deque interface by declaring an ArrayDeque of characters like so:
Deque<char> parens = new ArrayDeque<char>();
and the compiler chokes on it claiming
expected: reference
found: char
What a... | You can't use primitive types as generic parameters. You need the corresponding Object wrappers:
Deque<Character> parens = new ArrayDeque<Character>();
Let's update our Box class to use generics. We'll first create a
generic type declaration by changing the code public class Box to
public class Box<T>; this intro... |
7,286,394 | 7,286,469 | Is MeeGo Development Viable? | To start, I'll put this question into context:
Is it viable for an individual programmer. Possibly a small team for an artist, but think mostly a very small non-corporate team making commercial apps. I'm mostly asking this question as a mobile apps programmer who would be interested in deploying his apps to multiple ... | Symbian is dead because the companies that made it popular have abandoned it.
Meego never had any companies make it popular. Intel is still sort-of backing it, and eventually it is theoretically possible that it might one day end up being actively used in the market. But the thing about Intel is that they don't make a ... |
7,286,651 | 7,286,688 | c++: I want 2, 4, 6 to display... instead I think address numbers are displaying? | I want 2, 4, 6 to display... instead I think address numbers are displaying?
What do I need to do to correct and why?
Thanks
(purpose... to demonstrate ability to change array space and still keep the base of the array)
int *line;
line = new int;
line[0] = 2;
line = new int;
line[1] = 4;
lin... | Try this instead:
int *line;
line = new int[3];
line[0] = 2;
line[1] = 4;
line[2] = 6;
printf("%d %d %d", line[0], line[1], line[2]);
delete[] line;
Points to notice:
line = new int[3]; // here you are supposed to specify the size of your new array
...
delete[] line; // whenever you use new sometype[somevalue];
... |
7,286,755 | 7,287,071 | How can I iterate over two vectors simultaneously using BOOST_FOREACH? | I'd like to replicate the following with BOOST FOREACH
std::vector<int>::const_iterator i1;
std::vector<int>::const_iterator i2;
for( i1 = v1.begin(), i2 = v2.begin();
i1 < v1.end() && i2 < v2.end();
++i1, ++i2 )
{
doSomething( *i1, *i2 );
}
| Iterating over two things simultaneously is called a "zip" (from functional programming), and Boost has a zip iterator:
The zip iterator provides the ability to parallel-iterate over several
controlled sequences simultaneously. A zip iterator is constructed
from a tuple of iterators. Moving the zip iterator moves ... |
7,286,819 | 7,286,850 | Finding Geometric Mean of user input | I am working on a project for a class and I am having trouble with the output of the geometric mean, which always come out to be 1 and I'm sure that isn't right.
Here's my code:
#include<iostream>
#include<math.h>
using namespace std;
int main(int argc, char**argv)
{
float i, j, k;
float a, h, g;
cout<<"Enter 3 fl... | 1/3 is an integer equal to 0. You should write 1.0/3.0 (or 1./3) to get a floating point value.
|
7,286,985 | 7,287,034 | Need help understanding this article about templates | I was reading this article from this page, so let me present the code:
template <class T> class D: typename C<T>::Base { //#1 error
D(): typename C<T>::Base(typename C<T>::Base(0)) { } //#2 error, #3 correct
typename C<T> f() { //#4 error
typename C<T>::A* p; //#5 correct
A<T>::B * n;
}
};
c... | "Qualified" means that it is not in the same scope, but a subscope of the current one, which also depends on a template. For instance,
template <class T> struct C {
typedef int b;
}
b is a qualified id when referenced in another template e.g
template<typename T> struct M {
typename C<T>::b bb;
}
Relevant quo... |
7,287,065 | 7,287,093 | Calling a const function rather than its non-const version | I tried to wrap something similar to Qt's shared data pointers for my purposes, and upon testing I found out that when the const function should be called, its non-const version was chosen instead.
I'm compiling with C++0x options, and here is a minimal code:
struct Data {
int x() const {
return 1;
}
};... | If you have two overloads that differ only in their const-ness, then the compiler resolves the call based on whether *this is const or not. In your example code, test is not const, so the non-const overload is called.
If you did this:
testType test;
const testType &test2 = test;
test2->x();
you should see that the ot... |
7,287,086 | 7,287,197 | What's the best way to rewrite this generic function I wrote in C++ in C? | //Prints out a given array
template <typename T>
void print(T t)
{
for(int i = 0; i < t.size(); i++)
{
cout << t[i] << " ";
}
cout << endl;
}
I have an idea but it includes passing the size of the array. Is it possible to avoid this?
*Update
Thanks for all of the answers/ideas but this problem... | If you don't have ELEMENTS, it's
#define ELEMENTS(a) (sizeof(a)/sizeof(*a))
Then,
#define print_array(a, specifier) print_array_impl(a, specifier, ELEMENTS(a), sizeof(*a))
void print_array_impl(void* a, char* specifier, size_t asize, size_t elsize)
{
for(int i = 0; i < asize; i++)
{
// corrected base... |
7,287,188 | 7,309,541 | How to get the whole line where a given word is and store it in a variable? | i am a beginner in the C++ world, i need to get the whole line where a given word is and store it into a variable.
my TXt file has this structure :
clients.txt
085958485 Roland Spellman rolandl@gmail.com
090545874 KATHLEEN spellman kathleen1@hotmail.com
056688741 Gabrielle Solis desperate@aol.com
so the program req... | thank all of you for your answers, I finally figured it out , I used this function :
bool mostshow(int option, string id)
{
if (option== 2 && id== id1)
return true;
if (option== 3 && id== id1)
return true;
return false;
}
and this other one
void showline(string field1, string field2, string field3, string fie... |
7,287,224 | 7,287,568 | Why isn't std::find() using my operator==? | In the following snippet of code, I've overloaded the operator== to compare my pair type with string. But for some reason, the compiler isn't finding my operator as a match for the find function. Why not?
Edit: Thanks for all the suggestions for alternatives, but I'd still like to understand why. The code looks like... | The problem is that std::find is a function template and it uses argument-dependent lookup (ADL) to find the right operator== to use.
Both of the arguments are in the std namespace (std::pair<std::string, int> and std::string), so ADL starts by looking in the std namespace. There it finds some operator== (which one, i... |
7,287,400 | 7,287,473 | Exporting function from DLL syntax | In export.def file one can put such lines:
LIBRARY plug
EXPORTS
funcName
main=funcName
What is the effect of exporting function in such a way? Does it export two function names, which belong to the same function? Or does it just exports function, giving it another name?
| According to MSDN:
The EXPORTS keyword can be on the same line as the first definition or
on a preceding line. The .def file can contain one or more EXPORTS
statements.
The syntax for export definitions is:
entryname[=internalname] [@ordinal [NONAME]] [PRIVATE] [DATA]
entryname is the function or variable name th... |
7,287,434 | 7,287,734 | C++ GUI Development - Bitmap vs. Vector Graphics CPU Usage | I'm currently in the process of designing and developing GUI's for some audio applications made in C++ (using the Juce framework).
So far I've been playing with using bitmap graphics to create custom sliders and dials, by using 'film strip' style images to animate the components (meaning when the user interacts with a ... |
Or would CPU consumption be down to the particular methods/functions/libraries/frameworks being used?
Any of these things could influence it.
Pixel based images might take a while to read off of disk the bigger they are. Compressed types might take more time to uncompress. Vector might take more time to render when... |
7,287,663 | 7,288,763 | QueryPerformanceCounter Status? | I've read some about the problems and inaccuracy of the QPC implementation. But all those discussions and articles seem rather out of date.
Anyone know what the current status is of the QPC functionality on the latest Win7 OS and Intel/AMD cpus? Has there been any improvements? Is e.g. Turbo Boost still a big issue?
I'... | QPC was patched software side by microsoft ages ago (old kb article on the problem: http://support.microsoft.com/kb/895980 ). This fix can be installed on any target system for piece of mind (I've seen a few games doing this), however it shouldn't be needed. All newer processors have a hardware fix/compensation for thi... |
7,287,710 | 7,287,750 | C++ local variable changes value | I have the following c++ function, that is trying to find the maximum subarray sum, within an array of negative and positive integers
int MaxSubArray::find_max_subarray(void) {
int maxsofar =0 ;
int maxendinghere = 0;
for(int i = 0;i <= arr_size; i++) {
cout << "maxending here is: " << maxendinghere << endl;... | Shouldn't it be:
for(int i = 0; i < arr_size; i++)
?
Note that you modify maxsofar in the last loop iteration after you've printed it, which is why you see a difference - you're probably adding in a garbage value on that last iteration because of your off-by-one loop bounds.
Hope you're enjoying Programming Pearls.
|
7,288,042 | 7,288,190 | Check for every rugby score the recursive way without repetitions | Just for fun I created an algorithm that computes every possible combination from a given rugby score (3, 5 or 7 points). I found two methods : The first one is brute force, 3 imbricated for loops. The other one is recursion.
Problem is some combinations appear multiple times. How can I avoid that ?
My code :
#include ... | One way to think about this is to realize that any time you have a sum, you can put it into some "canonical" form by sorting all the values. For example, given
20 = 5 + 7 + 3 + 5
You could also write this as
20 = 7 + 5 + 5 + 3
This gives a few different options for how to solve your problem. First, you could alway... |
7,288,222 | 7,288,290 | C++ - catch all exceptions? | I want to inject a DLL into a process. Once this DLL is in there, it should catch & properly handle all access violation exceptions which occur in the process. Is there any way to accomplish this?
| How about SetUnhandledExceptionFilter( function )?
function's prototype is:
LONG __stdcall ExceptionHandler(EXCEPTION_POINTERS *ExceptionInfo);
I've used this function to create crash dumps, etc.
|
7,288,279 | 7,288,413 | How to embed a file into an executable? | I have a small demo executable wrote in C++ that depends only on one 5kb PNG image being loaded before it can run, which is used for a pixel text I made. Because of this one file, I would need to give out a ZIP archive instead of just one executable file, which creates enough friction between download and 'play' that ... | A portable way is to define a function like
typedef unsigned char Byte;
Byte const* pngFileData()
{
static Byte const data =
{
// Byte data generated by a helper program.
};
return data;
}
Then all you have to do is to write a little helper program that reads the PNG file as binary and generat... |
7,288,404 | 7,288,485 | Linking C++ to C in GCC | I have one function extern "C" int ping(void) in a C++ "static-library" project. Now, I would like to write a simple Hello-World C program that will call this function int x = ping();.
I use g++ / gcc but I cannot link the C executable with C++ shared library. Please, how can one do that? Could you please provide exact... | You may have to use g++ as the linker, not gcc. If the ping() function uses any STL, or exceptions, new, etc, it probably links against libstdc++, which is automatically linked in when you use g++ as the linker.
|
7,288,555 | 7,289,636 | Continuous Integration with Hudson and Automated Testing QWidgets | I was playing around with Hudson on my development computer and ran into an issue where one of my automated unit tests has to create a QApplication in order to test a subclass of QWidget. Since hudson is running without X, this fails. The error log reads unknown: cannot connect to X server.
Is there a way for me to per... | Try launching some X server. Remember that it doesn't have to physically display anything--a VNC server will be enough. Then, set $DISPLAY environment variable in your hudson instance to point to the VNC server.
|
7,288,734 | 7,290,494 | native c++ extension for Node.js : "cloning" a Local< Value > in the constructor | I've read the tutorial "Writing Node.js Native Extensions": https://www.cloudkick.com/blog/2010/aug/23/writing-nodejs-native-extensions
The code worked fine ( https://github.com/pquerna/node-extension-examples/blob/master/helloworld/helloworld.cc )
Now I want to change:
class HelloWorld: ObjectWrap
{
private:
int m_c... | 'Local' variables will be automatically cleaned up, so you can't just save a copy of them like that. You need to use a 'Persistent' Handle.
class HelloWorld: ObjectWrap
{
private:
Persistent< Value > myval;
public:
(...)
HelloWorld(const Local< Value >& v) :
myval(Persistent< Value >::New(v)) {
}
(...)
sta... |
7,288,752 | 7,294,477 | How to force all derived classes to implement a virtual method? | Say you have a base class Dep for a tree of classes. There is a virtual method Dep* Dep::create() that I want to be implemented by every single leaf class. Is there any way to enforce this?
Note: The problem here is that there could be intermediate classes (say class B : public A : public Dep) implementing this method ... | Using curiously recurring template fun, you can achieve something quite similar:
template<typename T>
class Cloneable : public T, public Dep
{
private:
Cloneable<T>() : T() { }
public:
static Cloneable<T>* Create() { return new Cloneable<T>(); }
Cloneable<T>* clone() { return new Cloneable<T>(*this); }
};
... |
7,288,892 | 7,288,940 | C++ Operator Overload - call function to get value inside overload | Is there a way I can call an operator overload in C++ and call the parameter's function during the comparison?
For example:
class MyClass{
private:
int x;
int y;
public:
MyClass(int x, int y);
int getX();
int getY();
bool operator < (const MyClass &other) const {
return (x < other.ge... | You can declare the operator as a friend of the class.
Edit: I seem to have tomatoes on my eyes, your operator is class member and already has private access. You could friend it however it was defined outside of class scope.
|
7,288,917 | 7,291,361 | Having different configurations on Pantheios | This question is regarding logging in C++ with Pantheios library.
In my application, I need to have these different loggers:
One that logs the critical messages to logFile1 and to Console
One that logs the warning messages to logFile2
One that logs the error messages to WindowsEventLog
I'm wondering if I can do... | What you may be after is Extended Severity Information. These two links might help:
* http://blog.pantheios.org/2009/05/use-of-extended-severity-information.html
* severity_information_2example_8cpp_8misc_8extended__sea251715135bb302f75cbc1fd50584869.html">http://www.pantheios.org/doc/html/cpp_2misc_2example_8cpp_8misc... |
7,289,453 | 7,289,470 | Reading Hard Disk Sectors in C++ on Linux | How do you read hard disk sectors in C++ with gcc/linux? Is there a standard library that I can use or must something be downloaded? In Windows I can use CreateFile(...) to access raw disk sectors, but I do not know how to do in in Linux.
I am using GCC on Ubuntu LTS 10.4. Thank you for your help.
| The hard disk is just another file (not a "regular file" but a "device file", but still, a file). Open it the normal way...
int fdes = open("/dev/sda1", O_RDONLY);
if (fdes < 0)
err(1, "/dev/sda1");
... do more ...
You will get permission errors unless you have the right permissions. Note that "/dev/sda1" is jus... |
7,289,554 | 7,289,692 | C++ Borland Builder 6 SQL Query | I'm building an app in CppBB6 that reads/writes data from/in a database. From a table called Students I want to extract the Name of a student using the given Index number (both Name and Index are fields in table Student) and afterwards I want to put that Name in a String or AnsiString variable.
I'm using this query to... | I'd guess something like
Edit1->Text = Query1->FieldByName("Name")->AsString;
or in case you really only have one field and/or know index of the field(s) then
Edit1->Text = Query1->Fields[0]->AsString;
And as Ken White suggest in comments - one should really use parameterized queries for safety and perfomance reasons... |
7,289,718 | 7,289,735 | Analyzing crash - translate disassembly instructions to C++ equivalent | I'm attempting to debug a crash. (ACCESS_VIOLATION)
Below is a disassembly snippet. I marked the line that the exception occurs on.
What instruction does it correspond to in the actual C++ code shown below it?
Disassembly:
420: for( Uint32 i = 0; i < m_children.size(); ++i){
06A923D3 8B 46 0C mov ... | Looks like cmp dword ptr [eax],edi corresponds to the < size() check - note that the dereference of the size member of m_children is inlined into the less-than check.
Most likely, your this pointer is invalid. You may have called ICategoryNode::iterate on a null pointer, or a deleted object or something (if eax has a v... |
7,289,819 | 7,289,911 | Bit setting question | In C or C++, it's apparently possible to restrict the number of bits a variable has, so for example:
unsigned char A:1;
unsigned char B:3;
I am unfamiliar however with how it works specifically, so a number of questions:
If I have a class with the following variables:
unsigned char A:1;
unsigned char B:3;
unsigned cha... |
What is the above technique actually called?
Bitfields. And you're only supposed to use int (signed, unsigned or otherwise) as the "type", not char.
Is above class four bytes in size, or one byte in size?
Neither. It is probably sizeof(int) because the compiler generates a word-sized object. The actual bitfields wi... |
7,289,896 | 7,290,849 | Should I Use Blocking or Asynchronous boost::asio::socket Read/Write to Implement a Protocol Handshake | I'm implementing an RTMP protocol using boost::asio::socket.
After the async_accept, the protocol requires a 3-step handshake. See the code below:
.
.
.
void RtmpServer::StartAsyncAccept()
{
// Create a new connection
nextConn = RtmpConnection::Create(this, ios);
// FIXME: shall we use async or blocking accept... | The typical two approaches are:
async. operations with a small number of threads
sync. operations with one thread per connection/client
I believe it's well established that in terms of scalability, (1) beats (2), but in terms of simplicity of the code (2) typically beats (1). If you don't expect to handle more than a... |
7,290,078 | 7,290,112 | C++: When is a class implicitly copied? | When is a class implicitly copied in C++?
I have a class that contains a unique_ptr, and therefore cannot be safely copied, and therefore, I disabled the copy constructor on the class by creating private versions of X(X&) and X& operator = X&.
I immediately ran into the problem that instances of this class cannot be r... | The situations that come to mind are: functions that receives the class by value, functions that returns then class by value, and any class or container that contains that class. Classes like std::vector will use move semantics whenever possible (you did overload that right)? but will be unable to use functions that r... |
7,290,130 | 7,290,160 | Using cin.get() in a tight loop | I'm not new to programming, but I am relatively new to C++. I would like to distribute simple console applications so I can help others as I learn. The vast majority of machines on the campus of my university are windows based, and have the Borland compiler installed by default. I prefer to do my development on a Linux... | You can add
cin.ignore(1);
or
cin.ignore(INT_MAX, '\n');
before you call cin.get(). This will ignore the newline left from the user entering the second number or all the characters in the buffer until a newline.
Also you neither need to compare the return value of get to '\n' nor put it in a loop. The user has to hit... |
7,290,462 | 7,290,600 | Sleep() doesn't work in winapi32? | I'm still a beginner in programming GUI using c++ winapi32, and I found something strange.
Here's a part of my code:
InvalidateRect(hwnd,&rect, true);
//Sleep(delay);
MessageBox(hwnd, "Blahblah!", "blahblah",MB_OK | MB_ICONINFORMATION);
InvalidateRect(hwnd,&rect, true);
//Sleep(d... | The important thing is, that InvalidateRect doesn't draw anything. It only schedules the window content to be drawn (enqueues a WM_PAINT message into the message queue). The actual drawing doesn't happen until you return to the message loop and the window actually gets to process the paint message. So after the last Sl... |
7,290,570 | 7,290,580 | Is a macro made to define constants? |
Possible Duplicate:
"static const" vs "#define" in c
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. (No memory required)
So, people use it as a method to define constants instead of the syntax: const int num = 1;
Is this a good habit... | Macros can be used for other reasons than just defining constants. Nowadays, macro usage is generally frowned upon unless there are absolutely no other options available.
Debugging complex code with macros littered throughout can cause you more than one headache.
From GCC docs:
A macro is a fragment of code which has ... |
7,290,797 | 7,291,035 | Smart Pointer for a template class? | I suspect I can't do this directly using a PIMPL pattern. Is it possible to have a smart pointer to a template class? I have not been able to compile by turning knobs on the shared_ptr declaration.
// ============Foo.h ============
// Forward declare the implementation
template <typename T> class FooImpl;
class Foo
{
... | I'm not entirely certain what you are trying to accomplish, but does this help?
Try 1:
// ============Foo.h ============
// Forward declare the implementation
template <typename T> class FooImpl;
template<class C>
class Foo
{
public:
Foo getInstance(const string& fooType);
...
private:
shared_ptr< Foo... |
7,291,058 | 7,291,241 | How to access private data private member through its offset? | I'm trying to access and modify the private data member of a class by offset.
AFAIK, first thing is to calculate the offset, then access the member through the offset.
Here is my code.
class Test {
public:
int a;
int b;
private:
int c;
};
Test test;
cout << *(&test + &Test::b + 1); // access c
I g... | This works:
#include <iostream>
using namespace std;
class test {
public:
int a;
int b;
test () : c(100) {}
void show () {cout << "c = " << c << endl;}
private:
int c;
};
int main (void)
{
test x;
test *ptr;
ptr = &x;
ptr++;
ptr = (test *) ((int *)ptr - 1);
cout << "c = "... |
7,291,077 | 7,291,265 | In memory Binary Search Vs. Disk based Binary Search | In this program, I am reading "key.pc.db" file and printing its mid value.
#include <fstream>
#include <conio.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
using namespace std;
int main( int argc, char *argv[] )
{
ifstream fp;
int mval;
int sizek;
... | You're seeking to the wrong point in the file in the first case. You should be seeking to mid*sizeof(int) rather than mid.
|
7,291,596 | 7,292,057 | When can the compiler statically bind a call to a virtual function? | I expected the compiler to be able to statically resolve a function call to a virtual function if the type of the class is known at compile time (e.g. if the class instance is not being used through a reference or a pointer as illustrated in Case 1) below).
However, I have observed a strange behavior with Visual Studi... | I don't know why MSVC doesn't compile your "Case 2" scenarios to direct calls - it's certainly possible. I think that only Microsoft would be able to answer.
Note that GCC does perform the optimization that you're looking for (tested with MinGW 4.5.1 and -O2).
Also, MSVC used vtable dispatch even for the following sequ... |
7,291,638 | 7,291,656 | Read number from text file without whitespace | I am trying to read a 12 digit number from a text file in to an array. I have been able to do this successfully if I place whitespace between each digit. for instance:
1 1 1 1 1 1 1 1 1 1 1 1
But when I remove the whitespace between the digits my program is no longer able to allocate the array from the text file. for... | To read an array of chars, supposing there are no spaces or other delimiters, you can read the whole of it from input stream at once:
in >> myarray;
To create an array of integers, you can read the input char by char and fill the array in place:
char c;
int i = 0;
while( !in.eof())
{
in >> c;
myarray[ i++ ] = c ... |
7,291,670 | 7,292,331 | How do I return from a function inside a lambda? | Consider the following toy code to determine whether a range contains an element:
template<typename Iter, typename T>
bool contains1(Iter begin, Iter end, const T& x)
{
for (; begin != end; ++begin)
{
if (*begin == x) return true;
}
return false;
}
(Yes I know, there are already perfectly fine ... |
How would I write the same thing with for_each and a lambda?
You can’t (leaving aside exceptions). Your function isn’t isomorphic to a for-each loop (= kind of a mapping), it’s as simple as that.
Instead, your function is described by a reduction so if you want to use higher-order functions to replace it, use a reduc... |
7,291,721 | 7,291,736 | Question about C++ syntax in V8's TYPE_CHECK macro | Once reading v8.h in V8 engine code, I could find the following macro.
#define TYPE_CHECK(T, S) \
while (false) { \
*(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
}
I know that this is to check the type S is compat... |
As a result, the macro is not always usable, is it?
The macro is always usable. The intent is to produce a compile-time error or warning (namely that one type is not compatible with another).
The purpose of wrapping it in while (false) is to prevent the code ever executing at runtime - and with modern compilers the c... |
7,291,800 | 7,292,044 | Change alpha of image cropped with SDL_Rect using C++ & SDL | I need to adjust the alpha of an image ( SDL_Surface* ) that's been cropped and blitted to the screen using SDL_Rect. I have one image file (.bmp) with 3 images on it, I've cropped each image using SDL_Rect but I need to adjust the alpha of each image individually.
Can this be done?
Failing that, can I store each crop... | You can adjust each surface's alpha individually, it won't affect any of the other surfaces. The only condition is, the surface should have an alpha channel. To check is has an alpha channel, do this:
SDL_Surface *surface; // Assume this has been allocated elsewhere.
if (surface->format->Amask != 0)
{
// You have a... |
7,291,815 | 7,291,832 | What are signals in netbeans C++ Debuggning | Hi guys i'm trying to debug this application in C++ using netbeans (running it gives me run failed after closing it) it gives me a signal error at this point
*c = (char)any number;
where any number is an integer from 1-7
it tells me signal caught SIGSEGV ? with signal error ?
what is it
the code writes some stuff to a ... | You haven't allocated memory to c. It's a pointer to some random location (or NULL, depending on how memory is being initialized). You then try to write to it.
Does it really need to be a pointer? Could you just use char c;, and then c = (char)1; etc. You'd then want to change your fwrite call to f.write(&c, 1); (or us... |
7,291,874 | 7,291,895 | Is strict aliasing is c or c++ thing? | In ISO/IEC 9899:TC2, the standard says following
6.3.2.3 Pointers
A pointer to an object or incomplete type may be converted to a pointer to a different
object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined. Otherwise, when converted back agai... | Strict aliasing rule is defined somewhere else. This is the wording:
C (ISO/IEC 9899:1999 6.5/7):
An object shall have its stored value accessed only by an lvalue
expression that has one of the following types:
a type compatible with the effective type of the object,
a qualified version of a type compatible with the... |
7,292,041 | 7,292,062 | how to tell Inline ASM the variable is in hex | I am trying to use the following code
__declspec(naked) void StubStart()
{
__asm{
MOV EAX, oep
JMP EAX
}
}
and I wanted to tell it that the "oep" variable is in hex, but I think I cannot put both (0x and h) to tell it, it is in hex.
what can I do?
| The oep variable is most likely just an int (or some other integral type).
Regardless if you did
oep = 0x55;
or
oep = 55;
it will ultimately be represented in binary in the computer... you can't say that a variable contains a hexadecimal value, decimal value or octal value... it contains an integer.
|
7,292,558 | 7,292,575 | expected unqualified-id before ‘;’ token | I seem to have a strange problem:
I coded an application in C++ (using Eclipse CDT) that uses Mozilla's Netword Security Services. This application is running fine, so I thought I can just move the appropriate classes/headers/sources to another project (can this generally be done?). The original project uses some addit... | i suspect you have included QT before secmodt.h. 'slots' is a QT moc keyword.
Update
i guessed this because QT is a popular library (and i knew of its usage of slots). plus, this type of error looked like typical preprocessor nonsense.
QT's #defined 'slots' to nothing for use with its Meta Object Compiler.
you can eith... |
7,292,595 | 7,293,647 | g++ Attach a library to application | Ok so I made a linux application with the help of Poco library.
I successfully compiled it with eclipse, but when someone attempts to run the application it requires for them to have Poco library installed.
Is it possible to somehow attach the library to my application so that other people wouldn't have to install the ... |
The current release is 1.4.2. The POCO C++ Libraries are open source software, released under the Boost Software License.
You can download the source from their site and compile it along with your project that way the user will not need the dynamic library on their machine.
|
7,292,757 | 7,292,773 | How to get screenshot of a window as bitmap object in C++? | How to get screenshot of a window as bitmap object in C++? Supposed that I already have the window handle. And I want to know also whether it's possible to get the screenshot of a window when it's in minimized state?
C++ here means VC++ with all the libraries associated with Windows XP+ (win32).
| you should call the PrintWindow API:
void CScreenShotDlg::OnPaint()
{
// device context for painting
CPaintDC dc(this);
// Get the window handle of calculator application.
HWND hWnd = ::FindWindow( 0, _T( "Calculator" ));
// Take screenshot.
PrintWindow( hWnd,
dc.GetSafeHdc(),... |
7,292,826 | 7,292,851 | Why isn't there a for_each member function for each collection type in stl? | For example:
v.for_each([](int i) { printf("%d\n", i); });
if far more elegant and readable than the commonly-used:
std::for_each(v.begin(), v.end(), [](int i) { printf("%d\n", i); });
Is there a legitimate reason such a member function is missing from the standard?
| This is the standard design rationale for the entire library: Separate containers from algorithms.
If you did it your way, you'd have to implement every feature X for every container Y, leading you to M * N implementations if you have M features and N containers.
By using iterators and make algorithms work on iterators... |
7,292,828 | 7,293,002 | Type deduction on parent class from nested class | I've got a problem with type deduction in Visual Studio 2010. I need to do something like this:
class Outer {
template<typename T> ... SomeTemplateFunction() { ... }
class NestedClass {
std::vector<decltype(SomeTemplateFunction<SomeOtherType>())> stuff;
};
};
However, even after adjusting for the n... | You can define the nested class later
class Outer {
static Outer* null() { return nullptr; }
template<typename T> ... SomeTemplateFunction() { ... }
class NestedClass;
};
class Outer::NestedClass {
std::vector<decltype(Outer::null()->SomeTemplateFunction<SomeOtherType>())> stuff;
};
The compiler is ri... |
7,292,948 | 7,292,959 | C++ STL Containers With Pointers: A few questions | Let's say you have a type T and subtypes TSub1, TSub2 etc.
Several of these subtypes are initialised with new TSub(...). The resulting pointers are then stored as elements in:
list<T*> tsList;
The same pointers are also used as keys in:
map<T*,V> tsMap;
Now consider an iteration over tsList, with iterator variable tI... |
Will tsMap[*tIter] and tsMap.find(*tIter) both successfully find the
correct associated value?
Yes, but tsMap[*tIter] will create a default value if it doesn't find the key.
Will delete *tIter successfully free the full memory block allocated
for the relevant TSub even though STL sees the type as T?
If and onl... |
7,292,990 | 7,293,017 | Template specification problem | I am trying to do the folllowing:
class definition h file:
template<int Size>
class Sculptor
{
public:
Sculptor();
~Sculptor(void) ;
void Sculp(SculptData* sculpData);
void ToShape(Shape* shape);
int CalculateMesh();
unsigned char sculpture[Size][Size][Size];
}
class definition cpp file to... | Remember that the implementation of a template class must be visible from the compilation unit that uses it. In particular, you may not place the implementation into a separate .cpp file (as is common practice with non-template classes) but instead should place it in the header file where the template was declared.
|
7,293,123 | 7,293,143 | A class-based state machine? | In C++ I'm trying to make a simple state machine for a game, based on classes.
stateMan.setState<mainMenuState>();
I have a class with the declaration as:
class stateManager
{
...
template <class T>
void setState(void);
}
And the test code as:
template <class T>
void stateManager::setState<T>(void)
{
T* blah ... | The definition of the member function template should be this:
template <class T>
void stateManager::setState(void)
{
//...
}
That is, it should be simply setState instead of setState<T>. The latter syntax is used in function template specialization. Since T is a type parameter, the specialization would be consider... |
7,293,131 | 7,294,536 | IE BHO c++ data sharing among tabs | I would like the BHO instances of my IE extension to be able to share common data. I just need them to share a couple of variables, so I am trying to find an easy solution for the problem.
The alternatives I can think of, from easier to more complex are:
1) Writing/reading data to/from the file system or to the regist... | Often, Memory Mapped Files are used for this purpose. It's a non-trivial amount of work, however, as you must ensure that they are ACL'd properly to allow cross-process access (each tab may be in a different process) and work across multiple integrity levels.
|
7,293,212 | 7,293,345 | GetWindowlong to check button style | I would like to use raw winapi32 to check button style whether it is a checkbox button or a pushbutton.
bool isPushBtn(HWND hBtn, DWORD dwStyle)
{
return (0!=dwStyle | GetWindowLong(hBtn,GWL_STYLE));
}
But this always returns false. Do you know a way to check this ? Thank you.
| In order to understand how button styles work we need to look at the values used by the style constants:
#define BS_PUSHBUTTON 0x00000000L
#define BS_DEFPUSHBUTTON 0x00000001L
#define BS_CHECKBOX 0x00000002L
#define BS_AUTOCHECKBOX 0x00000003L
#define BS_RADIOBUTTON 0x00000004L
#define BS_3STA... |
7,293,291 | 7,293,308 | Why is there an endianness problem here? | I was reading up on this thread on pointer aliasing rules, and one answer gives the following example, which mentions a potential problem with endianness, I wanted to know if anyone could give me what the endianness problem is in the following code?
struct Msg
{
unsigned int a;
unsigned int b;
};
int main()
{
... | There isn't any endianness problem. As long as StupidApi doesn't involve sending it over a network or serialization between platforms, then there's no endianness issue at all.
|
7,293,349 | 7,293,370 | Returning NaN or throwing an exception? | I have a function that gets a sample (an std::vector<double>) as input and computes the average of the sample: what is the best way to handle the empty input vector case?
My first idea is to throw an exception like in this snippet:
double average(const std::vector<double>& sample)
{
size_t sz = sample.size();
if ... | I DO think that mathematically the NaN would be more correct. In the end it's 0.0/0. Had it been a direct division, what would have happened?
Be aware that about C++ and exceptions there are holy wars. For example read this: To throw or not to throw exceptions?
|
7,293,434 | 7,293,447 | why am I getting an error when I pass an ifstream&? | I'm trying to code a simple program that uses an ifstream and scanner to read a text file. For some reason I'm getting this error: "In passing argument 1 of 'bool ReadVector(std::ifstream&, Vector<double>&)'". Any idea what I've done wrong?
#include <iostream>
#include <fstream>
#include <string>
#include "scanner.h"
#... | ReadVector accepts a reference, but you are giving a pointer. Just call
bool foo = ReadVector(infile, vec);
|
7,293,571 | 7,295,189 | How to get the aperture angle from a webcam with OpenCV? | I'm capturing the webcam images with OpenCV and C++ and tracking the persons face. So my problem is that I need the aperture angle to calculate the position of the person. How to get this angle?
Thanks
| You need to calibrate your camera using a standard calibration target like a chessboard. Look here for the OpenCV camera calibration API.
|
7,293,671 | 7,293,695 | API that handles boost ublas sparse OR dense matrices | I am a bit perplexed by the Boost ublas documentation. It does not seem clear to me that the sparse and dense matrix classes share a common parent class---which I believe is by design. But then how can I design an API that can accept either sparse or dense matrix, assuming that it need only operate on entries of the ... | Templates unfortunately. You can use a very generic type, or dig in and find something more concrete, but the general idea is:
template< typename MatrixType >
float doMatrixMath(MatrixType m)
{
return m(1,1)+m(2,2);
}
Of course this can be enhanced with a more concrete type and return value detection...
|
7,293,700 | 7,293,847 | Porting a C++ map with std::accumulate to PHP | I'm not terribly well versed with array manipulation in PHP, so I have a simple porting question. In C++ I have a map std::map<int, int>, for which the implicit ordering on the key is a crucial part of the structure. What I want to do is to sum up all the values for an initial range of keys, which I do like this:
// ac... | Unfortunately, the PHP array map/reduce functions only map over values, not keys. If your map is using PHP key => value arrays, you'll need some tricks to filter out the values whose keys have a certain value. The easiest is a straight forward loop:
$map = array(1 => 20, 2 => 30, 3 => -10, ...);
$n = 3;
$result = 0;
f... |
7,293,715 | 15,976,703 | Is there a tool to add the "override" identifier to existing C++ code | The task
I am trying to work out how best to add C++0x's override identifier to all existing methods that are already overrides in a large body of C++ code, without doing it manually.
(We have many, many hundreds of thousands of lines of code, and doing it manually would be a complete non-starter.)
Current idea
Our cod... | There is a tool under development by the LLVM project called "cpp11-migrate" which currently has the following features:
convert loops to range-based for loops
convert null pointer constants (like NULL or 0) to C++11 nullptr
replace the type specifier in variable declarations with the auto type specifier
add the overr... |
7,293,751 | 7,293,828 | Overhead of DLL function call | How big is a performance penalty when calling functions from DLL? Loading DLL is not an issue for us, number of calls to our highperf library will not be big.
Approximately, how many instructions/clock-cycles does one call take over a static library call?
| My answer is based on how the Linux/glibc/ELF dynamic linker works, but I would assume the overall answer is the same for other platforms:
There is a difference between the first call to a dynamically loaded symbol and the next calls. The first call is expensive, can involve many cycles. All other calls are more or les... |
7,293,859 | 7,293,955 | The application has failed to start because cv210.dll was not found" - problem with running application in other computers | I'm writing small application using OpenCV. Everything works great on my computer. I can compile and run my program without any problems.However if I copy Debug directory to another computer and try to run MyApplication.exe I get
The application has failed to start because cv210.dll was not found"
What is strange fo... | A .lib is not a DLL. A lib is like a collection of obj files. Compilers and linkers know about yout .lib file, but it is useless for the OS. You need a DLL for that
|
7,293,926 | 7,293,940 | Finding the smallest element in a Binary Search Tree - entering infinite loop | I am using recursive method to create a Binary Search Tree. My objective is to find the lowest element in the tree. Below is my code.
Insertion
node insert(node root, int value)
{
if ( root == NULL )
{
return ((newNode(value)));
}
if ( root->info == value )
{
... | You never modify curPtr in your loop.
|
7,294,032 | 7,294,133 | Calling a c++ virtual function from WndProc fails | I'm developing a program that displays graphical windows using the windows API. Below is function I provided as the WndProc when registering the window class - it is a static function inside the class WindowsWindow.
#define BTK_DLL_FUNC __dllspec(dllexport)
class AbstractBackend
{
protected:
bool FatalWarnings;
pub... | Since you have not posted full code that we can run to reproduce the problem we have to guess.
The only way that I can see for the call to QuitMainLoop() to fail is if WindowsBackend::instance is somehow corrupted. Have you destroyed it by mistake before calling QuitMainLoop()? Has there been a memory corruption perhap... |
7,294,062 | 7,294,091 | Using iconv while maintaining code correctness | I'm currently using iconv to convert documents with different encodings.
The iconv() function has the following prototype:
size_t iconv (
iconv_t cd,
const char* * inbuf,
size_t * inbytesleft,
char* * outbuf,
size_t * outbytesleft
);
So far, I only had to convert buffers of type char* but I also realized I c... | reinterpret_cast<char const*> is safe and not implementation defined, at least not on any real implementations.
The language explicitly allows any object to be reinterpreted as an array of characters and the way you get that array of characters is using reinterpret_cast.
|
7,294,261 | 7,294,488 | C++ with wxWidgets, Unicode vs. ASCII, what's the difference? | I have a Code::Blocks 10.05 rev 0 and gcc 4.5.2 Linux/unicode 64bit and
WxWidgets version 2.8.12.0-0
I have a simple problem:
#define _TT(x) wxT(x)
string file_procstatus;
file_procstatus.assign("/PATH/TO/FILE");
printf("%s",file_procstatus.c_str());
wxLogVerbose(_TT("%s"),file_procstatus.c_str());
Printf outputs "/PA... | This is to do with how the character data is stored in memory. Using the "string" you produce a string of type char using the ASCII character set whereas I would assume that the _TT macro expands to L"string" which create a string of type wchar_t using a Unicode character set (UTF-32 on Linux I believe).
the printf fun... |
7,294,294 | 7,294,588 | Debug stack corruption | Now I am debugging a large project, which has a stack corruption: the application fails.
I would like to know how to find (debug) such stack corruption code with Visual Studio 2010?
Here's an example of some code which causes stack problems, how would I find less obvious cases of this type of corruption?
void foo()
{
... | There's one technique that can be very effective with these kinds of bugs, but it'll only work on a subset of them that has a few characteristics:
the corrupting value must be stable (ie., as in your example, when the corruption occurs, it's always 100), or at least something that can be readily identified in a simple... |
7,294,391 | 7,294,438 | using sscanf for boost date | I am trying to use sscanf to separate a string that has a boost date. here's the code:
std::sscanf(ss.c_str(),"%ls\t%lf\t%lf",&date1_,&num1_,&num2_);
and I get the following error:
warning: format ‘%ls’ expects type ‘wchar_t*’, but argument 3 has type ‘boost::gregorian::date*’
can anyone suggest me a fix for this. ... | It cannot be done this way. sscanf is a C function and can only read primitive types, not class types.
In C++ the guns for reading/writing class types are "streams" and come in <iostream> and <sstream> headers. They will work if the authors of the Boost library you're using were kind enough to overload operator<< and o... |
7,294,574 | 7,294,726 | C++ or C#: Reading commands from a Human Interface Device(HID) | I have this game controller pad and I need to read it's commands for another project I'm working on.
Question is: Are there any sort of libraries for C++ or C# that can communicate with HIDs as there are for Serial Ports?
Any sample code would also be very much appreciated.
| Since you don't provide any details only some general pointers - perhaps these are helpful:
https://github.com/mikeobrien/HidLibrary
http://www.usbhidnetclass.org/ (commercial)
http://www.codeproject.com/KB/cs/USB_HID.aspx
http://code.google.com/p/csharp-usb-hid-driver/
http://www.lvr.com/hidpage.htm
http://www.codepr... |
7,294,870 | 7,295,037 | Why does SSL_pending return 0 after SSL_read reads 1,400 bytes? | while(1)
{
read_blocked_on_write=0;
const int buff_len = 1024;
char buff[buff_len];
iResult = SSL_read(ssl, buff, buff_len);
int ssl_err = SSL_get_error(ssl, iResult);
if(ssl_err == SSL_ERROR_NONE)
{
if(offset + iResult > recvbuflen - 1)
{
FD_ZERO(&fdread);
... | I'm no ssl expert but it's likely because there is nothing to read. You are reading and moving a buffer (which takes milliseconds at most) and then terminating if there is nothing more to read at that instant. Meanwhile you are dealing with the much slower network speeds and decryption at the lower layer. It's not a... |
7,295,155 | 7,295,890 | Concatenating strings into own protocol | I'm writing networking programming using socket.h to my studies. I have written server and client simple programs that can transfer files between them using buffer size given by user.
Server
void transfer(string name)
{
char *data_to_send;
ifstream myFile;
myFile.open(name.c_str(),ios::binary);
if(m... | You have some issues which may or may not be your problem.
(1) send/recv can return less than you requested. You may ask to receive 30 bytes but only get 10 on the recv call so all of these have to be coded in loops and buffered somewhere until you actually get the number you wanted. Your first set of programs was lu... |
7,295,175 | 7,295,294 | valueChanged of doubleSpinBox not working | //in my .h file i have:
void on_doubleSpinBox_test_valueChanged(double t);
//in my .cpp(mainwindow):
void MainWindow::on_doubleSpinBox_test_valueChanged(double t)
{
ui->lineEdit_test->setText(QString::number((double) t/2));
}
My problem is that when i set the value for lineEdit in SpinBox everything works, howeve... | The valueFromText and textFromValue methods might do what you want. They allow displaying the value of the spin box in a customized format, such as always displaying half the value of the spin box as in your code above.
http://doc.trolltech.com/4.7/qdoublespinbox.html#valueFromText
http://doc.trolltech.com/4.7/qdouble... |
7,295,252 | 7,295,268 | C++ Linker Error LNK2019 | I'm still kind of new to C++ and don't know why I'm getting these linker errors while trying trying to call these functions in another class.
The errors are:
error LNK2019: unresolved external symbol "public: float __thiscall Star::getMass(void)" (?getMass@Star@@QAEMXZ) referenced in function "public: void __thiscall P... | You have several functions declared in the Star class:
Star(float m, float r, float X, float Y, HTEXTURE);
float getMass();
float getRadius();
float getX();
float getY();
And you are trying to use some of them without providing a definition, that is to say, the body of the function, which is why you're getting those l... |
7,295,632 | 7,295,699 | Question about enums in C++ | I tried to use an enum in a for loop like this:
enum foo
{
foo_0,
foo_1,
foo_2,
foo_3,
...
foo_n,
foo_count
};
for(foo f = foo_0; f < foo_count; ++f)
and I had a compilation error. I understand that this is not valid because ++f might not be a valid foo enum - not in this case but in gen... |
I had a compilation error. I understand that this is not valid because ++f might not be a valid foo enum.
No. That is wrong interpretation of the error. It doesn't compile because there is no operator++ defined for foo type.
If you define operator++ as:
foo & operator++(foo & f)
{
return f = foo(f+1);
}
Then ... |
7,295,654 | 7,705,882 | Question About An Implementation Of Parallax Scrolling In C++/SDL/OpenGL | I been working in a project with a team for a Software Engineering class and we think that using the parallax scrolling will help our game to look really nice but we are not really sure if our idea for implementation it's the correct one, so I hope that someon will give us some guidance about our plan.
First, we have t... | Sorry for the late answer. I already find out the problem, I leave the new code so maybe someone will find this useful. The problem was handling the different offset in each row of the tilemap, but now it's solved.
void Tilemap::drawTilemap(int indexTileset)
{
GLfloat offsetXTemp = offset.x;
offsetXTemp = tran... |
7,295,664 | 7,295,689 | Segmentation fault i cant figure out | I have the following constructor:
Timing::Timing():
_numMes(INIT_NUMMES),_msgs(new allMSgs*[NUMBER_OF_MSGS])
{
cout<<"build timing OK\n";
}
allMSgs is a struct :
typedef struct AllMSgs
{
double msg;
Agent* dedicatedTo;
}allMSgs;
and the declaration of it is done l... | You've made an array of pointers, but not set them to point anywhere valid yet. You either need to change it to be simply:
allMSgs* _msgs;
and:
new allMSgs[NUMBER_OF_MSGS]
Or call new for each pointer in the allMSgs array.
Better yet though you could just use a std::vector or other container, with std::vector<allMSgs... |
7,295,922 | 7,297,251 | What platform can I compile binaries for, using LLVM (Low Level Virtual Machine)? | I am interested in using the LLVM's Clang compiler. LLVM claims to be cross-platform however it is not clear which platforms can be targeted. I have done quite a lot of Googling on this but there doesn't seem to be much information about LLVM's supported platforms. The only thing I did find was "this" which is kinda... | I'm only answering the edit's question here (it would probably be more appropriate to make a new question).
This is a good architectural overview of LLVM. This page also contains a ton of documentations on all aspects of LLVM.
The short version is that LLVM is the optimizer and backend of a traditionnal compiler. It op... |
7,295,957 | 7,295,982 | rename multiple file in a sequence c# or c++ | How can I rename multiple files like this:
file.txt , anotherfile.txt , log.txt
into something like this :
file1.txt , file2.txt , file3.txt
How can I do this in c# or in c++ ?
| Use File.Move Method as:
IEnumerable<FileInfo> files = GetFilesToBeRenamed();
int i = 1;
foreach(FileInfo f in files)
{
File.Move(f.FullName, string.Format("file{0}.txt", i));
i++;
}
And if f is a fullpath, then you can do this instead:
File.Move(f.FullName,
Path.Combine(f.Directory.ToString(), strin... |
7,296,058 | 7,296,081 | C code and C++ compiler | Does anyone know if there is any performance penalty if one compiles C code with C++ compiler?
I have a C like code and use MinGW C++ compiler. I'm using qmake to compile the project. If there is a performance gain if I switch the compiler to compile in C, I'll have to update the code, there are some incompatibility wi... | There should be very little, if any, performance difference, to the point that if there is a difference, it will be very nearly immeasurably small - assuming you're using a C and C++ compiler from the same vendor or collection. Using a C compiler from one vendor and a C++ compiler from another will likely show larger d... |
7,296,410 | 7,296,432 | Copy machine code from windows executable and run on linux | I copy the machine code of a function on Windows.
For example:
void func()
{
printf("hello");
}
In the above case, I would copy func()'s hex code segment data and printf()'s hex code data plus other dependencies and data and relinked it on a differnt machine running linux, would it be possible to run the code on a... | This is a pretty vague/unanswerable question, but this would be extremely difficult, if not impossible. You have a number of difficulties which would need addressed. Namely, the executable format (ELF on Linux, vs PE on windows), the calling conventions between systems/compilers, etc.
The biggest issue I can think of... |
7,296,708 | 7,296,727 | c++ vector of derived class calls constructor only once | If I make a size 2 std::vector of a derived class, the constructor is called only once. If I make a size 2 vector of a base class, the constructor is called twice.
I usually wouldn't post the complete code that duplicates an issue, but in this case it can be made quite short:
#include <iostream>
#include <vector>
clas... | You're deceiving yourself: A single default construction of the derived object calls both constructors.
Now, what you are not seeing is the copy constructor, which does in fact get called twice in both cases.
The constructor of vector that you're calling makes one default construction of its value type, and then copies... |
7,296,731 | 7,296,788 | How does one return a reference pair from a newly inserted pair (to a map)? | How do I correctly and efficiently return a pair from a newly inserted pair to a map?
inline pair<unsigned int, T> *createObj(unsigned int UID){
static pair<unsigned int, T> ret;
objList.insert(pair<unsigned int, T>(UID, T()));
if (UID_Counter <= UID)
UID_Counter = UID+1;
ret = make_pair(UID... | The particular overload of insert that you're using returns an std::pair<iterator, bool>. In particular the first member of that pair is an iterator to either the element that was newly inserted or the element that was already present. Thus:
pair<const unsigned int, T>&
createObj(unsigned int UID)
{
auto inserted =... |
7,296,915 | 7,308,553 | OpenCV - Object matching using SURF descriptors and BruteForceMatcher | I have a question about objects matching with OpenCV.
I'm useing SURF algorithm implemented in opencv 2.3 to first detect features on each image, and then extracting the descriptors of these features.
The problem in matching using Brute Force Matcher, I don't know how I judge that the two images are matched or not that... | The problem was in using Brute Force Matcher only, I found methods to obtain a set of good matches between two views at "OpenCV 2 Computer Vision Application Programming Cookbook"
Ch9: Matching images using random sample consensus
They are using K-Nearest Neighbor and RANSAC
And thanks
|
7,296,963 | 7,297,011 | _GNU_SOURCE and __USE_GNU | I want to use CPU_SET, which is a glibc linux-specific macro that should be defined in sched.h The manpage clearly states that _GNU_SOURCE must be defined so that the macro is defined. However, looking at the header, CPU_SET is defined only if __USE_GNU is defined (there is an #ifdef guard). I seem to remember a few... | _GNU_SOURCE is the only one you should ever define yourself. __USE_GNU is defined internally through a mechanism in features.h (which is included by all other glibc headers) when _GNU_SOURCE is defined, and possibly under other conditions. Defining or undefining __USE_GNU yourself will badly break the glibc headers.
|
7,297,024 | 7,297,784 | Call default copy constructor from within overloaded copy constructor | I need to write a copy constructor that deep copies the contents of a std::shared_ptr. However, there are a bunch of variable int a, b, c, d, e; also defined in the class. Is there a way to generate the default copy constructor code (or call the default copy constructor) inside my new overloaded one.
Here is a code sni... | Here’s the question code as I’m writing this:
class Foo {
public:
Foo() {}
Foo(Foo const & other);
...
private:
int a, b, c, d, e;
std::shared_ptr<Bla> p;
};
Foo::Foo(Foo const & other) {
p.reset(new Bla(other.p));
// Can I avoid having to write the default copy constructor code below... |
7,297,158 | 7,297,221 | C/C++ unused inline function undefined reference | Consider the following code (this is not pthread specific; other examples, such as those involving the realtime library, exhibit similar behavior):
#define _GNU_SOURCE
#include <pthread.h>
inline void foo() {
static cpu_set_t cpuset;
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
}
int ma... | Well, apparently your program contains an error: you declare and call function pthread_setaffinity_np, but you never define it. Apparently you forgot to supply the library that contains the definition. This is an error in both C and C++.
In other words, this is not a valid program in C and in C++. It violates the One D... |
7,297,470 | 7,297,517 | Renaming executable to game.exe causes 15 second delay when running -- STRANGE issue | This shakes my understanding of computers and operating systems on a level that makes me very uneasy. I have just spent about an hour entering different iterations of compile commands to g++ and in my exasperation I renamed the executable which kept having the delay from game.exe to gameg.exe and all of a sudden the pr... | I'm assuming you have either a AMD (ATI) or Nvidia graphics card with their official drivers.
Chances are, game.exe is the executable name for an actual game released and your drivers are running special optimizations for the "game" or loading the Crossfire or SLI profiles for this game. A quick Google search seems to ... |
7,297,623 | 7,297,631 | How to provide your own delimiter for cin? | In c, I can use newline delimeter ([^\n]) with scanf. Using which I can store the line. Similarly for cin, I can use getline.
If I have to store a paragraph, I can simulate the functionality using my own special char delimiter like [^#] or [^\t] with scanf function in c.
char a[30];
scanf("%[^\#]",a);
printf("%s",a);
... | istream.getline lets you specify a deliminator to use instead of the default '\n':
cin.getline (char* s, streamsize n, char delim );
or the safer and easier way is to use std::getline. With this method you don't have to worry about allocating a buffer large enough to fit your text.
string s;
getline(cin, s, '\t');
E... |
7,297,639 | 7,298,204 | cvsnakeimage in opencv2.2 | I want to use the cvsnakeimage function for active contours from opencv.
The problem is that i cannot find this function under opencv2.2, have the name been changed or what is the problem.
Thanks in advance!
| Function cvSnakeImage reside in legacy module. (opencv2/legacy/legacy.hpp at line 818)
/* Updates active contour in order to minimize its cummulative
(internal and external) energy. */
CVAPI(void) cvSnakeImage( const IplImage* image, CvPoint* points,
int length, float* alpha,
... |
7,297,682 | 7,400,954 | SVM (Support Vector Machine) opencv | I'm new to machine learning. I'm doing a project by using opencv open source library. My issue is that I don't have experience in Machine Learning. I have extracted features from different images and I have evaluated them, now I want to classify objects in those images by using SVM but I don't know what to do. BTW, I u... | With the information provided, all I can give you is the following list:
category-level classification tutorial from the CVML2011 summer school. It includes code (for you unfortunately in Matlab) which can help you to understand the concept behind it.
paper called "A Practical Guide to Support Vector Classification" w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.