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,158,518 | 7,158,547 | Reuse nested loops without copy and paste | Suppose I've this nested loop
for (int a=1; a<MAX_A; ++a)
for (int b=1; b<MAX_B; ++b)
for (int c=1; c<MAX_C; ++c)
{
do_something(a, b ,c);
}
and I reuse this loop in various part of my code, changing the function do_something. It's quite boring to rewrite every time the first three lines. In pytho... | Use templates:
template<typename Func>
inline void do_something_loop(Func f)
{
for (int a=1; a<MAX_A; ++a)
for (int b=1; b<MAX_B; ++b)
for (int c=1; c<MAX_C; ++c)
{
f(a, b ,c);
}
}
This can be called with any function pointer or function object that matches the signat... |
7,158,528 | 7,201,073 | is there any code for bitwise and ipv6 address and network mask (prefix)? | I want to ask about calculation of ipv6 network and host side.
For example, I have the IPv6 address 2001:470:1f15:1bcd:34::41 and prefix 96.
Do you know a easy way to do bitwise and between IPv6 address and prefix?
According to IPv4:
192.168.1.2 255.255.255.0 network : 192.168.1.0
So simple.
I want to do the same ... | guys i solved my problem the source code is below use it and go on coding :D : Warning the function assume the IPv6 address is valid.,
my type is:
typedef uint16_t ip6_addr[8];
void ipv6_app_mask(const char *ip6addr, unsigned int mask, ip6_addr ip6){
ip6_addr in_ip6;
inet_pton(PF_INET6, ip6addr, ip6);
... |
7,158,563 | 7,457,117 | CvNormalBayesClassifier train error | I'm using OpenCv to make a CvNormalBayesClassifier, but when I try to train it I get an error.
this is my code:
CvMat train=cvMat(1, 32, CV_32FC1, val);
CvMat res=cvMat(1, 1, CV_32FC1, type);
M1.train(&train, &res);
where val is an array of double and type is an array of just one int element. M1 is my CvNormalBayesCla... | First of all, the last argument cvMat function has a void* type so it does not know the real type of your arrays. As result no data conversion is possible. But you are using CV_32FC1 constant which assumes float type and train and res matrices just reinterpret bits of your int and doubles as floats. And your CvNormalBa... |
7,158,648 | 7,158,776 | Why do we need `class` in C++? | Using struct we can achieve all the functionalities of a class:
constructors, destructors
member functions, static functions.
overloaded functions, virtual functions
public / private / protected access specifiers.
operators
The only difference are the default access rights: private for class, public for struct.
Wh... | IIRC when C++ was created (as C with classes), a design goal was to only ever add functionality, so the initial idea was to have a class as in C++, and a struct as in C. But then things got blurred, and in the following 20 years struct "mutated" into some kind of class.
|
7,158,956 | 7,159,206 | "Proper C++ solution"-- is c-style logic 'bad' when using C++? | So recently I got into a debate about how to solve a problem, the problem specifically was: How do I find all the pallindromes between 1 and 1 million. I said, "Use atoi to make a string, use a for loop to reverse the string, the use strcmp to compare the string(s) in question.
A few minutes later someone asked "Wh... | Example C++ solution:
#include <algorithm>
#include <iterator>
#include <iostream>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/lexical_cast.hpp>
namespace {
bool is_palindrome(unsigned int i) {
const std::string& s = boost::lexical_cast<std::string>(i);
return std::equal(s.begin(), s.e... |
7,159,196 | 7,159,246 | Cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' | Having an issue with this particular method and not sure how to resolve it! The error I'm getting is the above:
"error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot
access private member declared in class
'std::basic_ios<_Elem,_Traits>' C:\Program Files\Microsoft Visual
Studio 10.0\VC\include\ostr... | The return type should be ostream & which is a reference to ostream.
ostream & operator<<( ostream & stream, ProcessClass const & rhs )
{ //^^^ note this!
stream << rhs.name_;
return stream;
}
When you return by value (instead of reference), then that requires copying of stream object, but copying of any stream... |
7,159,271 | 7,159,337 | "live C++ objects that live in memory mapped files"? | So I read this interview with John Carmack in Gamasutra, in which he talks about what he calls "live C++ objects that live in memory mapped files". Here are some quotes:
JC: Yeah. And I actually get multiple benefits out of it in that... The last iOS Rage project, we shipped with some new technology that's using some ... | The idea is that you have all or part of your program state serialized into a file at all times by accessing that file via memory mapping. This will require you not having usual pointers because pointers are only valid while your process lasts. Instead you have to store offsets from the mapping start so that when you r... |
7,159,348 | 7,159,392 | Disable single warning error | Is there a way to disable just a single warning line in a cpp file with visual studio?
For example, if I catch an exception and don't handle it, I get error 4101 (unreferenced local variable). Is there a way to ignore this just in that function, but otherwise report it in the compilation unit? At the moment, I put #pra... | #pragma warning( push )
#pragma warning( disable : 4101)
// Your function
#pragma warning( pop )
|
7,159,571 | 7,163,176 | what c++ for feedforward neural network do you suggest? | I want to do some classification problem (word sense disambiguation) in c++; and I need a a feedforward neural network (MLP). I know there are many libraries but I want the one that is not very large, I need just MLP and , and easy to learn and get work?
I'v read about OpenCV and FANN, but I have no idea which library ... | FANN looks fantastic, and has very helpful introduction/getting started sections on its website (here and a PDF here for example). The MLP is a fairly straightforward concept for neural networks so your work should be well within the capabilities of the library.
With regard to size, you only need to include the bits of... |
7,159,758 | 7,159,789 | why assignment operator returns ref not pointer? | I saw some q&a on SO about the Big-Three and copy-and-swap.
Indeed, I learned some new stuff, but there's one thing I don't quite understand.
Why does the operator= return a reference not a pointer?
| There's nothing preventing you from returning a pointer if you'd like (though, I don't see why), but if you want to mimick the behaviour of the integral types in c++ you return a reference.
|
7,159,952 | 7,160,060 | Read program output C++ | I have a TF2 server and if TF2 gets updated while I'm away, server will output:
Your server is out of date. Please update and restart.
How could I observer/read the output with C++?
The idea is:
1. if (output == "Your server is out of date. Please update and restart.")
2. kill the application
... | That's basically a watchdog.
A solution can be done using piping:
Pipe your server output to standard input from your C++ application (reading it with cin will do). For example, if your TF2 server is tf2.exe and your C++ app is cpp.exe:
tf2.exe | cpp.exe
You will need to execute this command again everytime you're re... |
7,160,146 | 7,160,286 | Easy way of calling function with unknown args count via pointer | I have the following code:
typedef void * (__stdcall * call_generic)(...);
typedef void * (__stdcall * call_push2)(unsigned long,unsigned long);
void * pfunc;
// assume pfunc is a valid pointer to external function
// this is a logically correct way of calling, however this includes:
// add esp, 8
// after the call, ... | ((call_generic)pfunc)(1,1); is only a logically correct way of calling if the function pointed to by pfunc actually has the signature you cast to, void *(...). Your code tells the compiler to make a varargs call, so it makes a varargs call. A varargs call to a function that isn't a varargs function doesn't work (in thi... |
7,160,232 | 7,160,698 | PIMPL, POD, visibility of the implementation class, will its destructor get called? | Wikipedia claims, in the article on opaque pointers, that
The d-pointer is the only private data member of the class and points to an instance of a struct (which must be a POD since its destructor is not visible)
This is not required in PIMPL and just Wikipedia being typically idiosyncratic isn't it?
I'm taking the l... | Yup, it's plain wrong. The destructor of the PIMPL struct must be visible at the point where it's called, which is from the definition of the destructor of the class itself. Put both destructors in the same .cpp file, PIMPL dtor first, and visibility is assured.
There is no reason for the PIMPL dtor to be visible at an... |
7,160,268 | 7,160,308 | Recycling an unused vector | I've defined a vector in my program as follows:
vector<bool> isPrime (limit + 1, false);
where limit is an int. Later on in the program, I want to recycle the vector, keeping the name but reducing the size and populating all elements with false.
I've tried using
vector<bool> isPrime (otherLimit + 1, false);
in the sa... | You could either
isPrime = vector<bool>(otherLimit + 1, false)
or use it's members clear and resize:
isPrime.clear();
isPrime.resize(otherLimit + 1, false);
|
7,160,563 | 7,160,616 | [c++]: problem about initiation list in constructor | I stumbled across a question that I never thought about before.
Here it is:
each object's (listed in the initialization list) "constructor" will be triggered.
class B
{
public:
B() { cout<<"B Con\n";}
B(const B &b) { cout<<"B Copy Con\n";}
};
class A
{
public:
A(B &b):_m(b) { cout<<"A C... | The reason is when you call
_m( whatever )
then the copy constructor
B(const B &b)
is the only one that could match the parameter list. You pass it one parameter and that parameter is of type class B.
Copy constructor is not something super special - it is just a parameterized constructor that will be invoked via the... |
7,160,600 | 7,203,321 | What is the easiest way to invoke a member function on an argument passed to a mocked function? | Given the interfaces
class IFooable {
virtual void Fooable() = 0;
};
class IFoo {
virtual void Foo(IFooable* pFooable) = 0;
};
and the goole mock mock
class TMockFoo : public IFoo {
MOCK_METHOD1(Foo, void (IFooable*));
};
what is the easiest way to specify an action which calls Fooable() on the argument to the... | I could not find an easy way and finally settled with
TMockFoo MockFoo;
ON_CALL(MockFoo, Foo(_))
.WillByDefault(Invoke(boost::mem_fn(&IFooable::Fooable)));
|
7,160,650 | 7,160,673 | Where should I put this .h file, or how can I properly set my path in TextMate? | I'm just getting my feet wet in C++ using the Stanford CS 106B lectures available online. The assignments have the students use some custom libraries which are available for download online, although the installation instructions are gone.
While I can do the assignments in Xcode using a pre-built blank project which in... | Just put the file in the same directory as your other source files.
#include "filename"
searches the source directory first, whereas
#include <filename>
only searches the include file path.
The reason why /previouspathinthelist:/Users/me/Desktop/C++\ libraries doesn't work probably has to do with the space in the fil... |
7,160,901 | 7,166,667 | Why is C++11's POD "standard layout" definition the way it is? | I'm looking into the new, relaxed POD definition in C++11 (section 9.7)
A standard-layout class is a class that:
has no non-static data members of type non-standard-layout class (or array of such types) or reference,
has no virtual functions (10.3) and no virtual base classes (10.1),
has the same access control (Clau... | You are allowed to cast a standard layout class object address to a pointer to its first member and back by one of the later paragraphs, which is also often done in C:
struct A { int x; };
A a;
// "px" is guaranteed to point to a.x
int *px = (int*) &a;
// guaranteed to point to a
A *pa = (A*)px;
For that to work, t... |
7,161,008 | 7,161,092 | RegExp to find a specific string not ending with a specific word | I am trying to figure out a RegExp to match the following strings...
MyClassSetupEngine
MyClassExecuteEngine
MyClassDatalog
but not the specific string
MyClassSetup
Notice the string #1 includes the string #4 but #1 should be found by the RegExp while #4 should not.
I tried the following (with no success so far):
M... | Try:
MyClass(?!(Setup$)).+
The dollar sign signifies the end of the string.
[Note, this works for Javascript - what language are you using?]
|
7,161,089 | 7,161,372 | Creating boost::local_time::custom_time_zone without daylight saving time | I want to convert a boost::posix_time::ptime to a boost::local_time::local_date_time using a timezone without daylight saving time only specified by it's offset to UTC. I am using boost 1.47.0.
Currently I'm trying to create a boost::local_time::custom_time_zone (a.k.a custom_time_zone_base<char>). The only constructor... | The example in the date time docs shows you how to create a custom time zone without DST. You can see it at http://www.boost.org/doc/libs/1_47_0/doc/html/date_time/examples.html#date_time.examples.simple_time_zone.
Look at the code for the phx_1 timezone. You basically pass in a dst_adjustment_offsets initialized to th... |
7,161,173 | 7,161,268 | C++ console window to take input from USB only | I am not profficient in C++ so answers explained well/in detail would be appreciated thank you.
I have made a small C++ program that takes the input from an RFID reader (Similar to a barcode scanner) I have tried searching all over the internet for a simple answer but have had some mixed results.
I have two options, th... | Does the RFID reader appear as an HID keyboard? The Win32 Raw Input API will allow you to subscribe to a particular keyboard and differentiate its input from the real keyboard.
Start by reading http://www.toymaker.info/Games/html/raw_input.html
To do this, your console application will need to create a normal window (... |
7,161,512 | 7,162,081 | how to work with pointers and references c++ and VALGRIND? | I have the following code:
[test.h]
class MyClass
{
public:
string Name;
MyClass();
void method(MyClass &obj);
}
[test.cpp]
void MyClass::method(MyClass &obj)
{
cout<<obj.Name<<endl;
}
[main.cpp]
#include "test.h"
void main()
{
MyClass *class = new MyClass();
class->Name="Foo";
class->met... |
Why can't I put int VALUE = 0; in the test.h file?
If VALUE is part of class variables, then it is not allowed to initialize as a part of class declaration. Instead, constructor initializer list should be used.
// Constructor
MyClass :: MyClass() : VALUE(0)
// ^^^^^^^^^^^ Initializer list
{ }
How... |
7,162,096 | 7,162,143 | Is the C++ * operator "already overloaded?" | My C++ teacher thinks that the * operator in standard C++ is "already overloaded," because it can mean indirection or multiplication depending on the context. He got this from C++ Primer Plus, which states:
Actually, many C++ (and C) operators already are overloaded. For example, the * operator, when applied to an add... | Both are right as the question depends on context and the meaning of the word overloading.
"Overloading" can take a common meaning of "same symbol, different meaning" and allow all uses of "*" including indirection and multiplication, and any user-defined behavior.
"Overloading" can be used to apply to C++'s official o... |
7,162,158 | 7,162,324 | How can I refactor my library to include templates? | I am trying to add template functionality to my vector class, after already having used it without templates throughout my project.
The old version used hardcoded float to save the values for x, y and z. What I am trying to do now is to make the class also be able to use double through a template.
My class definition l... | Referring to a class template without angle brackets is illegal, unfortunately.
The way the STL does this with std::string is like this, even though your request was "no mangling":
template <typename T> class basic_string { ... };
...
typedef basic_string<char> string;
In your case, you would have to write vector<> e... |
7,162,457 | 7,162,612 | How to convert boost::gregorian::date to mm/dd/yyyy format and vice versa? | Boost has several functions converting to other string formats described here, but there is no conversion into the necessary mm/dd/yyyy format. Currently I am doing it the following way:
std::string dateAsMMDDYYYY( const boost::gregorian::date& date )
{
std::string yyyymmdd = boost::gregorian::to_iso_string( date... | boost has fairly versatile date/time IO facilities
const std::locale fmt(std::locale::classic(),
new boost::gregorian::date_facet("%m/%d/%Y"));
std::string dateAsMMDDYYYY( const boost::gregorian::date& date )
{
std::ostringstream os;
os.imbue(fmt);
os << date;
return os.str();
}
I... |
7,162,589 | 7,162,825 | Weird 'undefined reference' error | I have run into a peculiar error in a C++ project at work.
I have found a fix, but I am now really satisfied, as I would like to understand what actually causes the error.
When building this snippet of code:
#include <iostream>
#include "snmp/snmp/SW_SNMP_Values.hpp"
#include "snmp/agent/SW_Agent.hpp"
#include "snmp/ag... | Linkers are complicated and this behaviour is by no means unusual. Here's one possible explanation:
You are linking with a static library libfoo.a.
libfoo.a contains foo.o that contains SW_Agent_PP::SW_Agent_PP() and a bunch of other functions.
Another library libbar.a, listed after libfoo.a in the link line, uses a b... |
7,162,626 | 7,164,541 | can a pointer be deleted several times c++? | If I have the following example:
test.h
class MyClass
{
public:
MyClass();
std::string name1;
std::string name2;
std::string type1;
std::string type2;
void method1(MyClass &obj1);
void method2(MyClass &obj2);
}
test.cpp
MyClass *mainObject = new MyClass();
MyClass::MyClass()
{
}
void MyClass::method1((MyClass &obj1)... | I think that I'd go a slightly different way.
Like this:
test.h
class MyClass
{
public:
MyClass();
std::string name1;
std::string name2;
std::string type1;
std::string type2;
void method1(MyClass &obj1);
void method2(MyClass &obj2);
}
test.cpp
MyClass mainObject; // default c-tor called automatically.
... |
7,162,899 | 7,163,251 | Are there any caveats about optimizing a DLL that wouldn't appear in a EXE? | I am generally familiar with the sorts of optimizations performed by the -O2 or -O3 switches.
I have been bitten a couple of times now by issues that are specific to building a DLL that don't appear in writing a flat executable, so before I start turning on optimizations are there any "gotcha"s that I should be aware o... | Dead code elimination in an EXE basically starts with main as the single root of reachability, but every exported function of a DLL is a separate root.
|
7,163,018 | 7,163,116 | return a vector vs use a parameter for the vector to return it | With the code below, the question is:
If you use the "returnIntVector()" function, is the vector copied from the local to the "outer" (global) scope? In other words is it a more time and memory consuming variation compared to the "getIntVector()"-function? (However providing the same functionality.)
#include <iostream... | In theory, yes it's copied. In reality, no, most modern compilers take advantage of return value optimization.
So you can write code that acts semantically correct. If you want a function that modifies or inspects a value, you take it in by reference. Your code does not do that, it creates a new value not dependent ... |
7,163,449 | 7,163,507 | Dependent template parameters | My templated function has two template parameters(int m and int n). The function returns a class Foo<int r>, where I want r=m+n.
In foo.h I have:
template<int m> class Foo {};
template<int m, int n>
Foo<m+n> myFunc(const Foo<m> &a, const Foo<n> &b);
In foo.cpp I have:
Foo<m+n> myFunc(const Foo<m> &a, const Foo<n> &b... | You are probably putting the function body code in the wrong place. With (non-specialised) template functions, you generally want to put the whole function body in the header file and not the source file, otherwise the compiler cannot generate the code for that function when it is called.
|
7,163,562 | 7,171,275 | Elegant (and typical) workaround for OpenMP reduction on complex variable in C++? | I realize that reduction is only usable for POD types in C++. What would you do to implement a reduction for a complex type accumulator?
complex<double> x(0.0,0.0), y(1.0,1.0);
#pragma omp parallel for reduction(+:x)
for(int i=0; i<5; i++)
{
x += y;
}
(noting that I may have left some syntax out). It seems an obvi... | The typical workaround in absence of user-defined reductions in OpenMP is even uglier than what you suggested. Usually, prior to the parallel region people create an array of (at least) as many elements as there will be threads in the region, accumulate partial results separately for each thread using omp_get_thread_nu... |
7,163,727 | 7,163,904 | Operator overloading in template in C++ | I read following code from somewhere:
template<class T> class A {
T a;
public:
A(T x):a(x) {}
operator T() const {return a;} // what is point here?
};
int _tmain(int argc, _TCHAR* argv[])
{
A<int> a = A<int>(5);
int n = a;
cout << n;
return 0;
}
What does below line mean?
operator T() ... |
operator T() const {return a;}
This is the typecast operator. It'll implicitly convert the class instance to T. In the example code you've posted this conversion is being performed at the line
int n = a;
|
7,164,019 | 7,164,046 | Does memcpy not throw exceptions? | Hopefully there is a simple answer to this as it seems a simple question, however I have not been able to find any information on this on the interwebs.
In the following code snippet, Visual Studio complains of unreachable code at the line "delete bytes;"
try
{
memcpy(bytes, other.bytes, count);
}
catch (...)
{
d... | No. memcpy is a C function. It doesn't know about C++ features such as exceptions. (Of course, it's perfectly legal to use it in C++, although arguably not the best idea).
In response to karlphillip: I must indeed clarify my thoughts: in C++, memcpy should be used only for low-level buffer copies inside object private ... |
7,164,110 | 7,164,175 | As related to maintainability are mapping tables a better design than a large switch statement? | I am translating text files from one set of definitions to another, and I solved the problem by writing a small parser. Once I've identified a symbol I end up at a case statement that decides which translation routine to call depending on what the user selected input option was (these are codes that mean different thi... | A hash-table type structure would definitely be easier to maintain but there is at least one tradeoff, namely that your giant switch statement would almost certainly be faster because any decent compiler would optimise it into a jump table. But it (depending on the implementation) it shouldn't be that noticably slower ... |
7,164,654 | 7,166,165 | C++ LibCurl - Converting CURLcode into a CString | What would be the easiest way to convert the "res" variable (CURLcode) into a CString?
Here's the standard example which compiles fine on my machine but I want to use this in a MFC app and display the result as a MessageBox. Any help is appreciated!
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;... | You can use curl_easy_strerror function.
CString str(curl_easy_strerror(res));
or
CString str;
str.Format("curl_easy_perform return %s [%d]",curl_easy_strerror(res),res);
|
7,164,689 | 7,164,841 | g++ warning on declaring multidimensional, double array | In my C++ program I am trying to initialize a 3*3*3 array of type double with all 0's.
In the class header file, I declared a member
double list[3][3][3];
When I printed out the content of this array, I found that not all entries are 0 as I expected. e.g. list[1][1][1] has value 4.03158e-321
Hence I manually initiali... | Am I missing something or can you not just do
class Class {
public:
double array[3][3][3];
Class() : array() { }
};
|
7,164,879 | 7,195,105 | BOOST ASIO: Why don't I get "bind: Address already in use" in Windows (but do get it in Linux)? | Trying to bind an already bound TCP port should raise exception ("bind: Address already in use" exception).
It does happen under Linux. But under Windows , no exception is raised..
Could it be because under windows it tries to bind to ANY interface? but in Linux it tries to bind to ALL of them and raise an exception if... | In windows, the option tcp::acceptor::reuse_address is equivalent to calling setsockopt and specifying SO_REUSEADDR. This specifically allows multiple sockets to be bound to an address even if it is in use. See the MSDN documentation here.
There's a corresponding option in Win32 (SO_EXCLUSIVEADDRUSE) which is documen... |
7,165,071 | 7,167,035 | openMPI data type portability | FAQ #20 says:
As of v1.1, Open MPI requires that the size of C, C++, and Fortran
datatypes be the same on all platforms within a single parallel
application with the exception of types represented by MPI_BOOL and
MPI_LOGICAL -- size differences in these types between processes are
properly handled. Endian diff... | It should be mentioned that MPI 1.1 is a bit old. If you have to use MPI 1.1 then I'm not sure, but if you can use MPI 2 then have a look at section 3.3 of the MPI 2.2 standard. From my understanding it is not required that for example a MPI_UNSIGNED_LONG be the same size (same number of bytes) on all hosts. For send/r... |
7,165,303 | 7,165,386 | Need help in C++ with allegro library....? | I installed CodeBlocks 10.5 with minGW compiler. After setting environment variables for minGW I cheked gcc -v on cmd and it is working fine.
The problem is that, I have made a small program in CodeBlocks project the code is below
#include <iostream>
#include <allegro5/allegro.h>
using namespace std;
int main()
{
co... | Do not try to "place" libraries in the "right place". Instead, tell the IDE where you put them explicitly. This is called setting the include path.
Code::Blocks should have some setting for include directories. You should point it to the place where Allegro lives.
|
7,165,319 | 7,165,340 | Can a private function of a class be called from a local function? | Simplification of the code to express the concept:
class classA
{
public:
private:
int a;
seta(int x);
};
//local prototype
void somefunction();
int main()
{
classA object; //create an object of the class
somefunction(object);
return 0;
}
void somefunction(classA &object)
{
object.seta(5);
}
}... | The function that is calling seta() is not part of classA, so this is an error; that's the very definition of private. If you were to make somefunction() a member of classA, or declare it to be a friend of classA, then this would work.
|
7,165,383 | 7,165,808 | Detecting keypresses when application has no focus | I have an application that lives in the tray, and I need to detect the user activity so that I can perform certain tasks. For windows, I know that I can use GetAsyncKeyState or SetWindowsHookEx, but I would like to have a cross-platform solution.
Does anyone have a solution for this? maybe a reimplementation of keyPres... | This is inherently platform specific.
I'd make sure to isolate whatever you do and separate the mechanism of capturing the event and recording the keystrokes from the consumption of those keystrokes. That way you only have to implement the capture/record mechanism on each platform and all of the other code should be pr... |
7,165,424 | 7,165,487 | Unable to poll for mouse click event in SDL | I have the code
int userinput()
{
while(hasquit == false)
{
while ( SDL_PollEvent(&event) )
{
if ( event.type == SDL_QUIT )
{
hasquit = true;
}
if ( event.type == SDL_KEYDOWN )
{
if ( event.key.keysym.sym... | You have the
if(event.type == SDL_MOUSEBUTTONDOWN)
inside the
if ( event.type == SDL_KEYDOWN )
block. It should be separate.
This should work:
int userinput()
{
while(hasquit == false)
{
while ( SDL_PollEvent(&event) )
{
if ( event.type == SDL_QUIT )
{
... |
7,165,491 | 7,170,231 | boost::mutex, pthread_mutex_destroy failed - debug suggestions? | We have several locks (boost::mutex) in static classes, but when the program exits, pthread_mutex_destroy fails in the destructor of the mutex (there is an assertion checking this in boost).
As far as I know, pthread_mutex_destroy will only fail in two cases.
[EBUSY] The implementation has detected an attempt to destr... | You typically get this error when you unlock your mutex without locking it first.
boost::mutex m;
m.unlock();
My guess is that somewhere you are using lock and unlock members rather than RAII,
and that you have lost a call to lock.
Note that most of the time you should not be calling the lock and unlock members. ... |
7,165,720 | 7,165,738 | Can I put a cast operator in an enumeration to convert it to a different type? | For example, if I have:
enum SomeEnum { One, Two, Three };
and I want to be able to directly get the enumeration as an unsigned integer or a string, can I write a casting operator that would be capable of looking at the enumerated value and returning a suitable representation for it?
I know you can do this with classe... | Enumerations can be converted to an integer, you don't even need a cast to do so. There's no way to automatically convert it to a string however.
If you're willing to do a string array in parallel you can easily index it with your enumeration; the only problem is that it can get out of sync if you're not careful to mod... |
7,165,780 | 17,345,045 | IDEs to organize #include's in C++? | I recently discovered the nice Ctrl+Shift+O command in Eclipse to organize import's.
Is there an IDE with that feature, for #include's in a C++ program?
| Eclipse CDT 8.2 (Kepler), which was just released, can do this now: http://wiki.eclipse.org/CDT/User/NewIn82#Organize_Includes_Command
|
7,165,930 | 7,165,966 | Do scoping operators change what happens under the covers? | I have a situation here - basically:
#include <iostream>
class A {
public:
virtual void foo()=0;
};
class B : A {
public:
void foo() { cout << "I hate this code." << endl; }
void DoSomething() { /* Code */ }
};
A and B are in different files in my case, and much more complex needless ... | The code looks correct. This strongly implies that the vptr or vtable have been corrupted by some out-of-bounds memory access, or that the this pointer is invalid.
The scoping operator changes the call by allowing it to bypass the virtual function lookup altogether.
|
7,165,987 | 7,166,024 | How to increment a 64 bit number when the OS only supports 32? | I have a number stored as a string up to 16 chars (0 to F) in length. This needs to be incremented and the result stored as a string.
Simplest thing would have been to convert the string to an int, increment by one, then convert back to a string. However the OS doesn't support 64 numbers. What's the alternative?
I pres... | You can increment one digit at a time. If the digit is between '0' and '8', just add one; likewise if it's between 'A' and 'E'. If it's '9', set it to 'A'. If it's 'F', set it to '0' and increment the next digit to the left.
|
7,166,201 | 7,167,482 | Working C# code for the Windows clipboard? | How do I convert the following C++ code (for taking a Bitmap from the Clipboard and copy it onto a form), into a WPF C# code that also uses APIs (not inbuilt Clipboard helpers from the .NET Framework) to copy it into a BitmapSource (or Bitmap for that matter)?
hdcMem = CreateCompatibleDC(hdc);
if (hdcMem != NULL)
{
... | Something like this
IntPtr hDstdc = CreateCompatibleDC(IntPtr.Zero);
IntPtr hDstBm = CreateCompatibleBitmap(hDstdc, 64, 64);
SelectObject(hDstdc, hDstBm);
IntPtr hSrcdc = CreateCompatibleDC(IntPtr.Zero);
...
IntPtr hSrcbm = GetClipboardData((uint)clipboardFormat);
SelectObject(hSrcDc, hSrcbm);
BitBlt(hDstdc, 0, 0, 64,... |
7,166,254 | 7,166,362 | What's the easiest way to print the address of a member function? | If I have a base class with a pure-virtual function, and a derived class that implements that function - what's the easiest way I can print out the address that the function actually gets called at?
class A { public: virtual void func()=0; }
class B:A {
public:
void func() { /*implementation*/ }
... | [Edited] As far as I know, there's no way to get the address of the function that actually will be called, regardless of virtualness. For virtual methods specifically, the method and destination of virtual dispatch is left to the implementation. However even for normal functions the function pointer may not be the actu... |
7,166,412 | 7,170,284 | double linked list and its deletion | i wrote the following code to delete the nodes at the beginning and at the end of a doubly linked list....but the execution of these functions stopped in between and the program was aborted......
struct nodeb
{
int value;
nodeb *next;
nodeb *pre; //pre of first node and next of last node point to null...
... | Now I can see all the code the problem is very simple. Your deletebeg function is deleting the beginning node with delete, but you didn't allocate the node with new. You should only delete memory if you created it using new.
Normally when people write linked list classes they allocate the nodes inside the list methods ... |
7,166,799 | 7,167,388 | specialize template function for template class | I have an indexer function, and was attempting to specialize it for the standard container types, but get errors. I'm sure it's either simple or impossible, but I can't recall which. I would prefer these as a function-object, but I wasn't able to make that work either. Is it possible to specialize a template functio... | Since functions cannot be partially specialized, I can replace the indexer functions with function objects. This seems to work fine, and solves all my problems.
namespace std { //declarations of predefined indexable types
template <class T, class A> class vector;
}
template <class T>
struct indexer {
double o... |
7,166,903 | 7,167,441 | Need to programmatically initialise class variable array, how best do I do it? | In C++ I have an array of doubles which need initialising programmatically, at run time, just once, for the whole class to share. They could be both static and constant. How best can I initialise them? I have gone off using static with the prodigious popularity of parrallel processors presently pervading. So must I set... | You can put a static bool flag in your constructor. The flag will only be initialized to false the first time it is called. After that it will remain true.
// foo.h
class Foo {
static const int MIDTRACE = 3; // static const, no definition needed
static const int NUMTRACES = 2 * MIDTRACE + 1; // static const, no de... |
7,167,116 | 7,167,145 | trouble getting c program to execute another program | I'm mainly interested in the simple goal of getting a C program to
I just want to get a C program to do
c:\windows\system32\cmd.exe /k dir
or
c:\windows\system32\cmd.exe /k c:\windows\system32\cmd.exe /k dir
I found a windows C compiler.. called lcc-win32
Here is the code i'm using, at the moment just aiming at launch... | You're opening the executable file, not executing it. Check out the "system" call.
|
7,167,300 | 7,208,735 | Discarding data with boost::asio | I'm using boost::asio in asynchronous mode and I'd like to skip/discard/drop a message that has been sent to me over TCP. I want to do this because I've already read the header for the message and I know that it is of no interest to me. The message may be large so it I would prefer not to allocate space for it and even... | As far as I know, the BSD socket interface doesn't give you this functionality. You always have to read into a buffer. Now, what you can do in order to not allocate a huge buffer is to read into a smaller buffer in a loop. Something like this:
void skip_impl(tcp::socket& s, int n, boost::function<void(error_code const&... |
7,167,320 | 7,167,381 | When is the vtable used? | Is the vtable only used for virtual function lookups, or does it get used for normal member function lookups as well?
| Technically, this is an implementation detail. The C++ standard says nothing about vtables or vptrs.
But typically, a compiler will only choose to use the vtable/vptr mechanism when a member function is being called in a polymorphic sense (i.e. via a pointer/referene to base class). If it knows at compile-time what t... |
7,167,434 | 7,167,674 | Are heap allocated member references a terrible idea? Why? | To best explain this problem, I have constructed a simple example. Say I have a class Blob as follows:
class Blob
{
string personalName;
string& familyName;
}
A Blob can be spawned by the Creator (aka Programmer), at which point it gets to pick a personalName and, since it has the privilege of being a 1st gen... | The only time it makes sense to store a reference as a class member is when:
The data is not owned by the class and the class is not responsible for freeing it;
The lifetime of the referred object is guaranteed to be longer than the lifetime of the containing object.
Your example violates rule 1.
|
7,167,558 | 7,167,649 | Implementing abstract class members in a parent class | Is it possible to implement an abstract base class with members inherited from another parent class in C++?
It works in C#, so I tried doing it in C++:
// Virtual destructors omitted for brevity
class ITalk
{
public:
virtual void SayHi() = 0;
};
class Parent
{
public:
void SayHi();
};
class Child : public Pa... | No because what you really have is two base classes without any knowledge of each other.
Italk Parent
/ \ / \
| |
+---------+
|
Child
If Parent and Italk had two variables named i, there'd be two instances of "i", ITalk::i and Parent::i. To access them you'd have to fully qualify wh... |
7,167,773 | 7,416,541 | Getting an Eclipse C++ environment running with Xalan | I have been working on getting a C++ IDE going on my 64-bit Windows 7 machine. It's been frustrating, mostly because of the incompatibilities of 32 and 64 bit programs using Eclipse IDE for C/C++ Developers
Well, I finally got HelloWorld compiling, now I want to add Xalan to my project. I've downloaded both the source ... | You can't link a C++ library built with Microsoft Visual C++ to objects or libs built with mingw. The ABI is not compatible.
My prefered search engine doesn't give any link to existing Xalan/Xerces mingw binaries, so you will probably have to build them yourself.
|
7,168,484 | 7,168,552 | 3D Line Segment and Plane Intersection | I'm trying to implement a line segment and plane intersection test that will return true or false depending on whether or not it intersects the plane. It also will return the contact point on the plane where the line intersects, if the line does not intersect, the function should still return the intersection point had... | I could be wrong about this, but there are a few spots in the code that seem very suspicious. To begin, consider this line:
// calculate plane
float d = Dot(normal, coord);
Here, your value d corresponds to the dot product between the plane normal (a vector) and a point in space (a point on the plane). This seems wr... |
7,168,551 | 7,168,871 | XML processing in C++ | All,
we currently use TinyXML for authoring XML files and expat for parsing them. Our XML files are ultra simple, no DTD, etc...Does anyone have any experience using TinyXML for parsing XML files? I hate to use 2 different packages for XML processing. Thoughts?
| My experience with TinyXML was remarkably good, too. I expected it to have trouble when we started using more complex XML, but it turns out that TinyXML is so simple that it's hard to mess it up too badly.
I think you can guess the things we had trouble with (missing tags, malformed tags, etc.), but these would be prob... |
7,168,562 | 7,168,587 | Is there a function in boost to find how many people are waiting on a mutex lock? | I am using boost 1.41.0. Is there a way to use boost to find how many people are waiting on the lock?
| No: there is no way to get a reliable answer as it could change before the function returns, and Boost's interface doesn't provide an unreliable method either.
If you want such a thing, you'll need to implement your own thread-safe counter alongside the mutex; off the top of my head I'm not sure that you could do that ... |
7,168,731 | 7,168,811 | Program Will Not Compile - What am I doing wrong? | This is just a simple header file used to parse XML with the Xerces Parser. I'm banging my head trying to figure this one out, but for whatever reason, the compiler is complaining about things which shouldn't be an issue. I need a second reference to look this over and tell me what's happening.
#include "xerces_string.... | I can't debug your filesystem issues. It would, however, be not difficult for me to do some translation of the errors.
Compiler says:
character.h:6: error: expected unqualified-id before ‘using’
character.h: In constructor ‘Character::Character(const XMLCh*)’:
character.h:18: error: no matching function for call to ‘Xe... |
7,168,799 | 7,169,957 | Parsing/debugging/porting C++ program with lots of macros | I'm just curious if anybody could help with finding good tool for the task.
I have large program in C/C++ which needs to be ported from Win32 to Linux. As "wrapping" (i.e. the most OS-sensitive) part was successfully isolated from insides of the program this task only involves going through its "internals". Some things... | Eclipse CDT will expand macros and even show you how many macro-evaluations were required to reach the final code that would be emitted by the preprocessor.
http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.cdt.doc.user/concepts/cdt_c_whatsnew.htm
Look at the "Macro Exploration" section.
|
7,168,933 | 7,169,041 | Get page contents in C++ | I've created a PHP and C# app that gets the users Xbox 360 Profile ID from their gamertag.
I was just wondering how I do a web request and put the page contents of the url into a string in C++.
Thanks.
| Here's a down-and-dirty C++ HTTP fetcher I wrote using libCURL some time back.
It takes a URL and returns a string with the contents of a get request. Modify and flavor to taste:
/*
* HttpFetcher.h
*/
#ifndef _http_fetcher_
#define _http_fetcher_
#include <stdlib.h>
#include <string>
class HttpFetcher {
public:
... |
7,169,131 | 7,169,153 | Is there a compile-time func/macro to determine if a C++0x struct is POD? | I'd like to have a C++0x static_assert that tests whether a given struct type is POD (to prevent other programmers from inadvertently breaking it with new members). ie,
struct A // is a POD type
{
int x,y,z;
}
struct B // is not a POD type (has a nondefault ctor)
{
int x,y,z;
B( int _x, int _y, int _z ) : x(... | C++0x introduces a type traits library in the header <type_traits> for this sort of introspection, and there is an is_pod type trait. I believe that you would use it in conjunction with static_assert as follows:
static_assert(std::is_pod<A>::value, "A must be a POD type.");
I'm using ISO draft N3092 for this, so ther... |
7,169,136 | 7,169,195 | Override c++ streams | In a C++ program, we have 3 streams: stdin, stdout, and stderr. Can I override these in a console application and use them in a application that uses forms?
For example, if in some base class, I have cout<< "...", can I "redirect" to something visual (like a Windows Form)?
| What I would recommend doing is having a class which wraps around an iostream like this :
#include <iostream>
#define LOG Log()
class Log
{
public:
Log(){}
~Log()
{
// Add an newline.
std::cout << std::endl;
}
template<typename T>
Log &operator << (const T &t... |
7,169,454 | 7,169,474 | c++ undefined reference | I am getting an undefined reference error:
/afs/ec.auckland.ac.nz/users/c/s/cshe079/unixhome/Desktop/306P1/ARToolKit/examples/simple/simpleTest.cc:161: undefined reference to `affine_transformation_range::~affine_transformation_range()'
collect2: ld returned 1 exit status
I am including the file which has the ~affine_t... | You're not linking in the translation unit containing:
affine_transformation_range::~affine_transformation_range
|
7,169,492 | 7,169,856 | Private set / get functions -- Why private and how to use? | I've read a lot of guides that explain why I should use "private" and the answer is always "Because we don't want anyone else setting this as something". So, let me ask the following questions:
Assuming that I want to have a variable that is set-once (perhaps something like a character name in a video game, ask once,... | The access specifiers mainly serve to denote the class interface, not to effectively limit the programmer's access or protect things. They serve to prevent accidental hacking.
If something is set once, then you should try to set it when it is created, and make it const.
If the interface doesn't need to be especially cl... |
7,169,542 | 7,169,594 | Why can't I declare a struct variable inside a lambda in c++0x? | Here's the code.
#include<struct.h>
#include<iostream>
#include<functional>
using namespace std;
void LambdaTest(const function <struct dummy (void)>& f)
{
struct dummy test = f();
cout<<test.a<<endl;
}
int main()
{
int val = 5;
struct dummy dum;
auto func = [val](void) -> struct dumm... | The problem is that GCC incorrectly thinks you're declaring a new struct type on the trailing return, and it declares a field of an incomplete type that is the same type GCC thinks you're declaring.
It also complains that
error: 'temp' does not name a type
on the line with the assignment, because it is expecting a me... |
7,169,592 | 7,169,613 | Error: missing type specifier - int assumed. C++ does not support default int | I wrote a sample class with template use. it's fairly simple:
template <class T>
class myClass
{
public:
// construction, destruction
myClass();
virtual ~myClass();
class Object
{
public:
Object() { m_pNext = NULL; m_pPrev = NULL; }
~Object() {}
T m_Value;
... | You need to change
template <class T>
inline myClass<T>::Object* myClass<T>::Beginning()
{ return m_pBegin; }
to
template <class T>
inline typename myClass<T>::Object* myClass<T>::Beginning()
{ return m_pBegin; }
because myClass<T>::Object is a dependent type.
|
7,169,658 | 7,169,675 | Is this struct POD in C++11? | Is this struct a POD in C++11?
struct B
{
int a;
B(int aa) : a(aa) {}
B() = default;
};
Note that this question is explicit about C++11. I know that this class is not a POD in C++98 nor C++03.
For an explanation of POD in C++11, see trivial vs. standard layout vs. POD
(Inspired by this question: Is there a compi... | Yes, it is a POD according to the new rules.
If you look up paragraph §8.4.2/4 of the new standard, you can see that if a constructor is defaulted on the first declaration, it is not user-provided:
Explicitly-defaulted functions and implicitly-declared functions are
collectively called defaulted functions, and the i... |
7,169,738 | 7,170,833 | Open MPI: how to run exactly 1 process per host | Actually I have 3 questions. Any input is appreciated. Thank you!
1) How to run exactly 1 process on each host? My application uses TBB for multi-threading. Does it mean that I should run exactly 1 process on each host for best performance?
2) My cluster has heterogeneous hosts. Some hosts have better CPUs and more mem... | 1) TBB splits loops into several threads of a thread pool to utilize all processors of one machine. So you should only run one process per machine. More processes would fight with each other for processor time. The number of processes per machine is given by options in your hostfile:
# my_hostfile
192.168.0.208 slots=... |
7,169,961 | 7,170,354 | Can anyone interpret this C++ code (from OpenJDK6) into plain English? | Here's a code snippet from OpenJDK6's hotspot/src/share/vm/prims/unsafe.cpp (starting on line 1082):
// JSR166 ------------------------------------------------------------------
UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h))
Unsaf... | It is a JNI wrapper for the CAS API, with memory barriers for IA64 architecture.
edit: for a description of CAS:
Compare dest with compare value and if they match assign exchange value to dest.
It is an atomic operation which means no other processor can change the value of dest whilst the operation executes.
Typical p... |
7,169,981 | 7,178,207 | Compiling SDL from source on a Mac running OS X 10.7 Lion | I've downloaded the SDL source SDL-1.2.14.zip from the libsdl website and gotten to the make step.
When I ./configure, I have no issues. However, when I make, it gets what seems like a long way through the compilation process and dies with this output:
/bin/sh ./libtool --mode=compile gcc -g -O2 -I./include -D_GNU_SO... | Try ./configure --disable-assembly.
|
7,170,214 | 7,170,244 | Possible to wrap or merge separate namespaces? | I seem to recall seeing notes somewhere on a way to combine multiple namespaces into one.
Now, looking for said notes I am not finding them -- even searching using search terms combing, grouping, merging and wrapping I'm not coming up with anything. Maybe I misunderstood what I saw before. I don't have a specific appl... | You can do this:
namespace c
{
using namespace a;
using namespace b;
}
But if a and b have elements with the same names, you won't be able to use them from namespace c.
|
7,170,232 | 7,170,589 | C++ One Header Multiple Sources | I have a large class Foo1:
class Foo {
public:
void apples1();
void apples2();
void apples3();
void oranges1();
void oranges2();
void oranges3();
}
Splitting the class is not an option2, but the foo.cpp file has grown rather large. Are there any major design flaws to keeping the definition of ... |
Are there any major design flaws to keeping the definition of the class in foo.h and splitting the implementation of the functions into foo_apples.cpp and foo_oranges.cpp.
to pick nits: Are there any major design flaws to keeping the declaration of the class in foo.h and splitting the definitions of the methods into ... |
7,170,269 | 7,170,312 | C++ Thread in member function | can I use thread in member function to call a member function for C++ in windows? If yes, how to implement it? Here is the sample
void Class::fun_1(void){
_beginthread(fun_2, 0, NULL); //This is the error line :: function call missing argument list; use '&Class::fun_2' to create a pointer to member
}
void Class::fun_... | There are actually multiple issues here:
You can't pass a pointer to a member function as the routine to the _beginthread() function. The function requires a pointer to a global or static function.
Standard C++ requires that you fully qualify the member function name (even within the class) and use an & to obtain a po... |
7,170,367 | 7,171,758 | Can I query the compiler about C++0x "alignas" support? | I'm writing a few classes and structs that could benefit from 16-byte alignment. Instead of using compiler-specific hacks, I'd rather use the new C++0x alignas functionality for future portability. However, using it outside of appropriate #ifdef or #ifndef guards will obviously cause errors on compilers without align... | There are no direct feature-support macros for the various C++0x (C++11) facilities. There only two ways I can think of to determine their presence.
Keep a list of which compilers support them, and use #ifdef directives based on the compiler-supplied version macros such as __GNUC__ and _MSC_VER, or
Use a feature-dete... |
7,170,380 | 7,170,617 | DLL Import (import dynamic dll library on windows) | I need to make Erlang <- C++ Bridge
I'm making win32 dynamic library :
#include "stdafx.h"
#include <Tlhelp32.h>
#ifdef _MANAGED
#pragma managed(push, off)
#endif
#define DLLExport __declspec(dllexport)
extern "C"
{
DLLExport int RunOPC(int);
DLLExport void Save();
}
And want to import and use this fu... | I think you should implement erlang linkedin driver or erlang port.
http://www.erlang.org/doc/tutorial/c_portdriver.html
|
7,170,394 | 7,170,548 | Calling member function of zero data struct which was cast from incompatible type - Undefined? | There is a forward C struct declared in an unmodifiable header. I would like to "virtually" add convenience member functions to it. Obviously my first choice would be to extend the struct and add the methods to the derived class. No-can-do, as the struct itself is declared as "forward" in the header, so I get the err... | I don't believe this works if you're using static_cast because you cannot static_cast between two completely unrelated class types. To be specific, if you have a pointer of type A* and try to convert it to a pointer of type B*, the static_cast only succeeds if this declaration is valid:
B* ptr(myAPtr);
or if B is non... |
7,170,710 | 7,170,737 | Inheritance Confusion | Alright so I've been working on a game engine, and I'm running into a problem... Currently I have a hierarchy of classes (image->animation->object) all of which have a method get_type() and I'm having this problem:
if I declare a derived class using the new keyword, or statically, I get the desired results:
object in... | This is because both the constructor and destructor have run in your code:
object* t = &object();
cout << t->get_type();
The &object() creates an (anonymous, temporary) object, immediately destructs it (because it's temporary), and then assigns the address of the now-destructed object to t. (Your compiler may warn yo... |
7,170,795 | 7,170,968 | Wrapping native C++ templated class with C++/CLI | Is it possible to wrap a templated native C++ class with C++/CLI? For example,
template <class T>
class TemplateTest
{
public:
TemplateTest(const T& x) { mX = x; }
~TemplateTest(void);
T getValue() { return mX; }
private:
T mX;
};
The usual way is to hold a pointer to class TemplateTest however with ... | There is no general strategy, other than pre-defining all such template specialisations you care about, and explicitly mapping each CLI generic to a custom wrapper for the template specialisation.
|
7,170,915 | 7,171,529 | C++ and STL: Constructor Factory | I have a big factory, and I'm trying to figure out how to make it look pretty.
There are about 40 possible object/constructor combinations:
if(algorithm == "SHA-1")
return new HashImpl<...>(algorithm, seed, size);
if(algorithm == "SHA-224")
return new HashImpl<...>(algorithm, seed, size);
if(algorithm == "SHA-2... | No need to use them fancy newfangled maps.
template <class Impl>
BaseImplementation* makeAlgo (const std::string& algo,
const byte* seed, size_t size)
{
return new Impl(algo, seed, size);
}
typedef BaseImplementation* makeAlgo_t (const std::string& algo,
... |
7,170,994 | 7,171,965 | Boost.Serialization: Error on Calling Class Method during serialization process | I have the following problem when I try to call method in "TestSerialize" class during serialization process.
Here is my code:
class TestSerialize
{
public:
std::string GetVal() { return Val + "abc"; }
void SetVal(std::string tVal) { Val = tVal.substr(0, 2); }
protected:
std::string Val;
friend class... | save is a const function and can only call other const functions. GetVal isn't. Change it:
std::string GetVal() const { ... }
|
7,171,079 | 7,171,187 | Moving from fixed-pipeline to modern OpenGL | I have done some simple OpenGL (old fixed pipeline ,without shaders ..etc) and want to start some serious "modern" OpenGL programming. (Should compile on Windows and Linux)
I have few questions.
1) In Windows , the "gl.h" doesnt have OpenGL2.0+ related API calls declared .(eg. glShaderSource() ) . How can I access thes... | There has been a long-held belief among some (due to the slowness of GL version updates in the late 90s/early 00s) that the way to get core OpenGL calls was to just include a header and a library. That loading function pointers manually was something you did for extensions, for "graphics-card specific" function. That i... |
7,171,257 | 7,171,290 | Does constant static member variables of a class or a struct in C++ need not be defined separately? | Does constant static member variables of a class or a struct in C++ need not be defined separately?
Is this correct?
struct test
{
const static int x;
};
int test::x;
| No that's not correct. The definition must match the declaration and x is const int, not int. As a const variable of POD type it also needs to be initialized. E.g.
const int test::x = 0;
As a const static member of integral type, it is also allowed to supply the initializer in the definition of the class instead.
|
7,171,309 | 7,171,357 | Shows an assertion error at runtime in vector c++ | I want to erase an element from a vector in c++, but it shows a runtime assertion error.
My code is:
int i=0;
for(socketIterator=vectClientSocket.begin();socketIterator!=vectClientSocket.end();){
SOCKET clientSocket=*socketIterator;
isTrue=getBufferData(strt,stp,rm,clientSocket);
... | You need to update your iterator after erasing an element:
socketIterator = vectClientSocket.erase(socketIterator);
see also std::vector<..>::erase(..) documentation
[EDIT]
Use the operator !=(..) to compare the iterators:
for(socketIterator=vectClientSocket.begin();socketIterator!=vectClientSocket.end();){
|
7,171,515 | 7,171,575 | Program Has Unexpectedly Finished | My execution program won't work properly, for whatever reason.
#include <QtCore/QCoreApplication>
#include <tinyxml/tinyxml.h>
#include "classowner.h"
#include "character.h"
int main(int argc, char *argv[])
{
Character * holland = new Character("Holland", HUMAN, MALE);
delete &holl... | First of all, you try to dereference a null pointer:
int * Character::char_count = 0;
Both constructors of class Character do this
this->char_id = *char_count;
and that's an attempt to dereference a null pointer. That code makes no sense to me, I guess you could just use int instead of pointer:
int Character::char_co... |
7,171,793 | 7,174,857 | gxThread - shed_yield equivalent | Is it possible to yield the processor using gxThread functions, like the POSIX call shed_yield does?
| I found nothing like that in the gxThread documentation, however their thread model diagram indicates that they use native threads underneath. So if you cannot replace gxThread with another threading library, I would recommend to just use platform-dependent calls such as sched_yield or SwitchToThread.
|
7,171,890 | 7,171,993 | how to clean a cluttered main()? | In order to keep the main() (in c++) as clean/small as possible, there a a few options you can choose but which of them is best? initialize all variables in main, init them outside of main as global, global in .h, init them in main BUT set there values elsewhere (by passing them over to a function). there may be other... | There are some common patterns, like encapsulating data and operations in classes that make sense. For example, if you process command line arguments or configuration from files, you can create a Config class that you initialize from argc and argv and/or possibly a file, and then use that as storage for the user contro... |
7,171,954 | 7,173,192 | text mining in sqlite | I have sqlite database and need to find the most frequent words in it.
Example,
text
table chair floor
table chair
table
Solution needed
word number
table 3
chair 2
floor 1
The database is big (several Gb). I am looking for solution in SQL. Also maybe using C++ or other approach.
| http://www.sqlite.org/fts3.html
Check out the Fts4aux - Direct Access to the Full-Text Index section.
|
7,172,145 | 7,175,123 | set_intersection for two different types of sets | Is there any way to do std::set_intersection on two different types of sets?
I have two sets:
std::set<X1> l_set1;
std::set<X2> l_set2;
I'm able to define some comparator for them that checks if X1 and X2 are equal.
struct sample_comparer
{
bool operator()(const &X1 p_left, const &X2 p_right)
{
return ... | The comment by PlasmaHH is likely the problem.
The way functions like set_intersection work is they first do: a < b and then b < a
As a result ample_comparer needs to be able to compare both ways:
struct sample_comparer
{
bool operator()(const &X1 p_left, const &X2 p_right)
{
return p_left == p_right;... |
7,172,315 | 7,172,496 | Gen code without runtime checks in VC++ | How do I generate pure code (without runtime checks) in VC++ 2010 Express ? For example I removed Buffer Security Check ( set compile opt /GS-), but in my code I again saw these calls
call __security_init_cookie
...
call _RTC_CheckEsp
...
call _RTC_CheckEsp
...
How do I remove these calls?
| The MSVC docs indicate that __security_init_cookie is called by the CRT runtime for "code compiled with /GS (Buffer Security Check) and in code that uses exception handling" (emphasis added). See http://msdn.microsoft.com/en-us/library/ms235362%28v=VS.100%29.aspx
I wouldn't be surprised if there's code in the runtime l... |
7,172,376 | 7,177,952 | Creating GUIs for application | This is a question I've been wondering about for a long time.
How do you create an Interface for your program ?
It seems to much of a pain to position form controls and buttons using just code.
I'm looking for something similar to Visual Basic where you can drag and drop controls onto the window. But, I want to do this... | If you don't want to go the Qt route you can use ResEdit which is freeware. It will produce Win32 friendly .rc files that can be built with the MinGW resource compiler and used in Win32 applications.
There are some C++ Win32 wrapper libraries available though I'm not aware of any that are nearly as mature as Qt. I beli... |
7,172,424 | 7,172,605 | Boost lambda with shared_ptr | If I have a polymorphic base class called Base as well as classes Derived1 and Derived2 which inherit from Base. I can then use boost::lambda to create a factory of sorts. Something like:
typedef boost::function<Base *()> Creator;
std::map<std::string,Creator> map1;
map1["Derived1"] = boost::lambda::new_ptr<Derived1>... | class Base {
public:
virtual ~Base() = 0;
};
Base::~Base() {}
class Derived1 : public Base {};
class Derived2 : public Base {};
typedef boost::shared_ptr<Base> BasePtr;
typedef boost::function<BasePtr()> Creator;
template <typename T>
Creator MakeFactory()
{
namespace la = boost::lambda;
return la::bind... |
7,172,726 | 7,173,697 | Editing frameless window in Qt | I've been created a frameless window in Qt that have widgets and background. but i have a problem in that form, when i resize form all widgets resize good but background not
See this pic for demonstration
When no resize occured:
http://0000.2.img98.net/out.php/i20624_no-resize.jpg
when resize occured:
http://0000.2.im... | Since your controls are centered in the window but don't look like they are, it might indicate that there is a transparent border around the non-transparent part of the image you are using as background.
You can remove the transparency from the brush in paintEvent to confirm that, with, for example:
painter.setBrush(QC... |
7,173,024 | 7,173,225 | Good C/C++ compiler for OpenSolaris for x86 | I am using OpenSolaris on x86. I tried the gcc compiler for Solaris for free, but found it to be quite old (gcc 3.4.6). I want to know if there is any latest C++ compiler for OpenSolaris, that is similar to gcc. What is the best compiler out there for x86 with Solaris?
| Nothing is more similar to GCC than GCC... The GNU people have some answers for you:
http://gcc.gnu.org/install/binaries.html
If none of those binaries are useful, Google found for me:
http://www.dev-eth0.de/compile-gcc-4-on-opensolaris
Why haven't you found a good guide like that and run with it? It's not all that dif... |
7,173,063 | 7,173,304 | Ascending probabilities with descending numbers | I would like to write code which gives cumulative probabilities (0-1) to each number which are descending in order. For example;
I have a set of number:
150
152
155
160
175
I will give those numbers a probability in this way:
for first one (150) probability is = 175/total Sum
Second one is = 1... | Your problem is that you aren't using the sorted index in all access of Sol_list. This one is wrong:
Sol_list[PopulationSize-1-minus]
It should say:
Sol_list[sortindex[PopulationSize-1-minus]]
|
7,173,494 | 7,173,643 | VBOs with std::vector | I've written a model loader in C++ an OpenGL. I've used std::vectors to store my vertex data, but now I want to pass it to glBufferData(), however the data types are wildly different. I want to know if there's a way to convert between std::vector to the documented const GLvoid * for glBufferData().
Vertex type
typedef ... | If you have a std::vector<T> v, you may obtain a T* pointing to the start of the contiguous data (which is what OpenGL is after) with the expression &v[0].
In your case, this means passing a Vertex* to glBufferData:
glBufferData(
GL_ARRAY_BUFFER,
vertices.size() * sizeof(Vertex),
&vertices[0],
GL_STATIC_DR... |
7,173,564 | 7,173,719 | Defining namespaced member vs free functions without qualification | I sometimes declare classes in nested namespaces and when it comes to defining their member functions, I prefer not to have to qualify each one with these nested namespace names, especially if they are long-ish.
Adding "using namespace " (or, for more precise targetting, "using ::SomeClass") before I define the memb... | When you define a member-function, the compiler realizes that it is a member-function that must belong to a previously declared class, so it looks that class up, as specified in Section 9.3.5 of the standard:
If the definition of a member function is lexically outside its class
definition, the member function name s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.