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 |
|---|---|---|---|---|
3,283,901 | 3,283,957 | Why am I getting error LNK2001 when linking to zlib.lib? | I'm working on a project that already contains the gzip library as follows:
zlib\zlib.h
zlib\zlib.lib
zlib\zconf.h
I would like to use the gzip functions from this .lib but am getting the following errors:
Compress.cpp
Linking...
Compress.obj : error LNK2001: unresolved external symbol _gzclose
Compress.obj : er... | I grabbed the one off here to get zlib to build in windows. If you did the same, you may have forgotten to #define ZLIB_WINAPI before including zlib.h
|
3,284,061 | 3,284,166 | WebBrowser Control from MFC — How to Inject Javascript? | This is like the question
How to inject Javascript in WebBrowser control?
But i don't know how to transform this code into good old MFC C++ code.
For example what is the InvokeScript method, i can't find it anywhere.
Isn't .NET webbrowser the same as IWebBrowser2 ?
| You can find a CodeGuru article describing how to accomplish this here.
|
3,284,103 | 3,284,294 | Heavy computations analysis/optimization | First of all, I don't have multiplication, division operations so i could use shifting/adding, overflow-multiplication, precalculations etc. I'm just comparing one n-bit binary number to another, but according to algorithm the quantity of such operations seems to be huge. Here it is :
There is given a sequence of 0's ... | It seems like what you want is a count of how many times each specific block occurred in your sequence; if that's the case, comparing every block to all possible blocks and then tallying is a horrible way to go about it. You're much better off making a dictionary that maps blocks to counts; something like this:
var dic... |
3,284,283 | 3,284,329 | Calculate high and low value of array | struct WeatherStation {
string Name;
double Temperature;
};
void Initialize(WeatherStation[]);
void HL(WeatherStation List[]);
int main()
{
string Command;
WeatherStation Stations[5];
//some commands
}
void Initialize(WeatherStation StationList[])
{
StationList[0].Name = "A";
StationList[0].T... | It cannot convert WeatherStation to int because WeatherStation is a structure. If you want to get a member of a structure you should write, for instance, List[0].Temperature.
|
3,284,641 | 3,284,662 | Private variable needs to be initialized only in constructor. How? | I have a class called Foo with a constructor that needs arguments, and a other class Bar with a Foo private variable
class Foo
{
public:
Foo(string);
}
class Bar
{
public:
Bar() { this->foo = Foo("test") }
private:
Foo foo;
}
However, when I try to compile this, I get a com... | You need to use an initializer list. If you don't, your code will call the default constructor for that object.
Bar::Bar() : foo("test") {
// stuff
}
|
3,284,646 | 3,284,768 | About pointer downcasts/inheritance | So I'm about finishing up prata's C++ primer and I'm u to RTTI. He showed a line of downcasting and just said it's wrong but I want to see a better example.
class Grand
{
private:
int hold;
public:
Grand(int h=0) : hold(h) {}
virtual void Speak() const { cout << "I am a grand class\n";}
virtual int Val... | Do not use C style casts.
They are not safe. C++ has introduced 4 new casts the one you are looking for is dynamic_cast<>
Magnificent * ps2 = dynamic_cast<Magnificent*>(pg); // If pg is a Magnificent
// (or is a super class of
... |
3,284,720 | 3,284,770 | Non-owning holder with assignment semantics | I have a class that should hold a reference to some data, without owning that data (i.e. the actual data is guaranteed not to go out of scope). In particular, the class cannot make a copy – the data is easily several gigabytes in size.
Now, the usual implementation (I assume) is to have a reference to the data:
struct ... | I don't see anything wrong with using a holder_ptr. It can be implemented something like so:
struct bad_holder : std::exception { };
struct holder_ptr {
holder_ptr() : value(0) { }
holder_ptr(type const& value) : value(&value) { }
type const& get() {
if (value == 0) throw bad_holder();
r... |
3,284,784 | 3,284,801 | C++ removing from list while iterating over list | I have a std::list of Bananas, and I want to get rid of the bad ones. Is there any relatively simple way to perform the following pseudocode?
foreach(Banana banana in bananaList)
{
if(banana.isBad()) bananaList.remove(banana);
}
(Making a transition from C# and Java to C++ has been a rocky road.)
| bananaList.remove_if(std::mem_fun_ref(&Banana::isBad));
Note that you should probably be using std::vector instead of std::list though -- vector performs better in 99.9% of cases, and it's easier to work with.
EDIT: If you were using vectors, vectors don't have a remove_if member function, so you'd have to use the pla... |
3,285,019 | 3,285,050 | can I specialize operator<<? | I want to specialize operator<< but this code is not compiling;
template<>
std::ostream& operator<< < my_type >( std::ostream& strm, my_type obj);
| To specialize a template, first you have to have a template declared.
In the case of a free operator<< you don't need a template; you can just overload it for your my_type class:
std::ostream& operator<<( std::ostream& strm, my_type obj );
If your object isn't trivial in size, you may want to consider passing via a co... |
3,285,038 | 3,285,962 | XMLRPCPP asynchronously handling multiple calls? | I have a remote server which handles various different commands, one of which is an event fetching method.
The event fetch returns right away if there is 1 or more events listed in the queue ready for processing. If the event queue is empty, this method does not return until a timeout of a few seconds. This way I don't... | I had some problems with XMLRPC also, and investigated many solutions like GSoap and XMLRPC++, but in the end I gave up and wrote the whole HTTP+XMLRPC from scratch using Boost.ASIO and TinyXML++ (later I swaped TinyXML to expat). It wasn't really that much work; I did it myself in about a week, starting from scratch ... |
3,285,057 | 3,285,071 | c++ constructor with new | I'm making a very dumb mistake just wrapping a pointer to some new'ed memory in a simple class.
class Matrix
{
public:
Matrix(int w,int h) : width(w),height(h)
{
data = new unsigned char[width*height];
}
~Matrix() { delete data; }
Matrix& Matrix::operator=(const Matrix&p)
... | 1. You're missing the copy constructor.
2. Your assignment operator should not just copy the pointer because that leaves multiple Matrix objects with the same data pointer, which means that pointer will be deleted multiple times. Instead, you should create a deep copy of the matrix. See this question about the copy-and... |
3,285,130 | 3,285,182 | standards compliant way to typedef my enums | How can I get rid of the warning, without explicitly scoping the enum properly? The standards-compliant code would be to compare against foo::bar::mUpload (see here), but the explicit scopes are really long and make the darn thing unreadable.
maybe there's another way that doesn't use typedef? i don't want to modify th... | If the enum is defined within a class, the best that you can do is bring the class into your own scope and just use class_name::value or define a typedef of the class. In C++03 the values of an enum are part of the enclosing scope (which in your case is the class). In C++0x/11 you will be able to qualify the values wit... |
3,285,351 | 3,285,401 | Differences between a `typename` parameterized template and and integral type one | I've been trying to work with templates for a while now and the more I do the less I realise I understand. This latest problem feels like it has unearthed a rather fundamental misunderstanding on my part and I'm starting to think more than ever that, "Right, tomorrow I shouldn't write any code but instead find a librar... | On gcc 4.4.3 your second example fails to compile with the message "error: no matching function for call to 'Foo<1>::Foo(Foo<0>::Bar&)'", which is exactly what you expected to happen.
So you did not misunderstand anything. If this compiles for you, that's non-standard behavior by your compiler.
|
3,285,429 | 3,286,325 | Profiling embedded application | I have an application that runs on an embedded processor (ARM), and I'd like to profile the application to get an idea of where it's using system resources, like CPU, memory, IO, etc. The application is running on top of Linux, so I'm assuming there's a number of profiling applications available. Does anyone have any... | As bobah said, gprof and valgrind are useful. You might also want to try OProfile. If your application is in C++ (as indicated by the tags), you might want to consider disabling exceptions (if your compiler lets you) and avoiding dynamic casts, as mentioned above by sashang. See also Embedded C++.
|
3,285,519 | 3,285,622 | Some final questions about inheritance/casting | I asked a question an hour or two ago that is similar but this is fundamentally different to me. After this I should be good.
class base
{
private:
string tame;
public:
void kaz(){}
virtual ~base() {}
void print() const
{
cout << tame << endl;
}
};
class derived: public base
{
private:
... | The derived class inherits all the members of the base class, so kaz() exists also for derived objects. If you call kaz() on a derived object, simply the method that was inherited from base is called. If you access the inherited members from within a method or directly doesn't matter.
The problem with e is that it is r... |
3,285,558 | 3,285,626 | Simple MIPS Instructions and Compilers | Is it common for compilers (gcc for instance) to generate an instruction that loads some empty memory element into a register? Like... lw at,0(sp) where memory[sp + 0] = 0. This basically just places 0 into $at ($R1.) I ask because I'm looking through an executable file's hex dump (executable file is the result of t... | Perhaps it's being placed after a jump statement? If so, that statement is run before the jump occurs and could be a do nothing instruction (nop). Beyond that, it could just be the compiler on a lower optimization setting. Another possibility is that the compiler is preserving the CPU flags field. Shift and Add pla... |
3,285,707 | 3,285,775 | How do I use less CPU with loops? | I've got a loop that looks like this:
while (elapsedTime < refreshRate)
{
timer.stopTimer();
elapsedTime=timer.getElapsedTime();
}
I read something similar to this elsewhere (C Main Loop without 100% cpu), but this loop is running a high resolution timer that must be accurate. So how am I supposed to not tak... | You shouldn't busy-wait but rather have the OS tell you when the time has passed.
http://msdn.microsoft.com/en-us/library/ms712704(VS.85).aspx
High resolution timers (Higher than 10 ms)
http://msdn.microsoft.com/en-us/magazine/cc163996.aspx
|
3,285,970 | 3,285,986 | C++ and returning a null - what worked in Java doesn't work in C++ | So I'm having a rather tumultuous conversion to C++ from Java/C#. Even though I feel like I understand most of the basics, there are some big fat gaping holes in my understanding.
For instance, consider the following function:
Fruit&
FruitBasket::getFruitByName(std::string fruitName)
{
std::map<std::string,Fruit... | There is no such thing in C++ as a null reference, so if the function returns a reference, you can't return null. You have several options:
Change the return type so that the function returns a pointer; return null if the element is not found.
Keep the reference return type but have some sort of "sentinel" fruit ob... |
3,286,129 | 3,290,190 | What is the preferred STL collection when that's all you need? | I just need a "bag of things". It doesn't need to be a set, a map or even have any particular order. I just need to be able to add things and iterate over it, nothing more. I don't expect it to be very large but it can't get really bad perf if it does.
What container should I use?
| The standard recommends using vector as your default container. But Herb Sutter actually makes a case for using deque as your first choice.
|
3,286,236 | 3,286,382 | Executing member function of class through pointer to abstract parent of said class | I have created an abstract base class Animal which has public virtual abstract method makeSound(). I created a subclass Cow which implements Animal.makeSound() as you would expect (you know... "moo"). And I have a Farm class which holds a private member variable std::vector<Animal*> animals. In one of the Farm metho... | ok, let me take a guess:
"Unhandled exception at 0x65766974 in TestBed.exe: 0xC0000005: Access violation reading location 0x65766974."
it seems that the code pointer is being sent to 0x65766974 ("exception at 0x65766974") but this is not a valid place to be reading, let alone code: ("Access violation reading location ... |
3,286,363 | 3,286,403 | What does C++ add to C? | What does C++ add to C?
What features of the language are the Clang/LLVM projects, the parts of GCC that are being written in C++, chromium, and any others all taking advantage of? What features are they avoiding?
| Because despite academic efforts such as Singularity, there's not a single mainstream OS where drivers can be written in a high-level language.
Note that anything that can be done in C++ can also be done in C, but some things are a lot easier in C++.
|
3,286,422 | 3,313,510 | Eclipse CDT Build Configs - Testing a DLL with CPP Unit | I'm making a DLL (and probably a Linux port at some later date) in C++ using eclipse. The situation is as follows: I am trying to make two separate build configurations, one that will build a DLL and one that will build an executable CppUnit test. Currently I have all of the DLL build working, and I can make a separate... | Well, I found out how to do it, so if anyone else stumbles across this...
If you go into "Project->Properties->C/C++ Build->Settings", then select a debug configuration (or create a new one). Go to the "Build Artifact" tab, and change the "Artifact Type" to executable.
Now to avoid having all of your source code compil... |
3,286,448 | 3,310,608 | Calling a python method from C/C++, and extracting its return value | I'd like to call a custom function that is defined in a Python module from C. I have some preliminary code to do that, but it just prints the output to stdout.
mytest.py
import math
def myabs(x):
return math.fabs(x)
test.cpp
#include <Python.h>
int main() {
Py_Initialize();
PyRun_SimpleString("import sys... | As explained before, using PyRun_SimpleString seems to be a bad idea.
You should definitely use the methods provided by the C-API (http://docs.python.org/c-api/).
Reading the introduction is the first thing to do to understand the way it works.
First, you have to learn about PyObject that is the basic object for the C ... |
3,286,524 | 3,286,553 | Help understanding class example code for C++, templates, operator() | I'm not sure exactly what the following class does that we have for a class example. In the following code, what does the operator() do in this case? I don't quite get the *(begin + first) and pretty much the whole return expression as what is being evaluated. Any help would be great. Thanks!
// IndexCompare.h - in... | If you're asking what operator () does, it allows you to call the object like a function. See this article for an example.
If you're asking what the function in your example is doing, it's comparing the values of two elements specified by the indices passed to the function. begin + first refers to the element at index ... |
3,286,572 | 3,287,207 | Which features of C++ are particularly resource intensive at compile time? | I believe C is generally faster to compile than C++, because it lacks features like late binding and operator overloading. I'm interested in knowing which features of C++ tend to slow the compilation process the most?
| This is a difficult question to answer in a meaningful way. If you look purely at lines of code per second (or something on that order), there's no question that a C compiler should be faster than a C++ compiler. By itself, that doesn't mean much though.
The mention of late-binding in the question is an excellent case ... |
3,286,669 | 3,287,393 | Zooming into the mouse, factoring in a camera translation? (OpenGL) | Here is my issue, I have a scale point, which is the unprojected mouse position. I also have a "camera which basically translates all objects by X and Y. What I want to do is achieve zooming into mouse position.
I'v tried this:
1. Find the mouse's x and y coordinates
2. Translate by (x,y,0) to put the origin at ... | Instead of using glTranslate to move all the objects, you should try glOrtho. It takes as parameters the wanted left coords, right coords, bottom coords, top coords, and min/max depth.
For example if you call glOrtho(-5, 5, -2, 2, ...); your screen will show all the points whose coords are inside a rectangle going from... |
3,286,822 | 3,286,860 | Reading a file to a string in C++ | As somebody who is new to C++ and coming from a python background, I am trying to translate the code below to C++
f = open('transit_test.py')
s = f.read()
What is the shortest C++ idiom to do something like this?
| The C++ STL way to do this is this:
#include <string>
#include <iterator>
#include <fstream>
using namespace std;
wifstream f(L"transit_test.py");
wstring s(istreambuf_iterator<wchar_t>(f), (istreambuf_iterator<wchar_t>()) );
|
3,286,882 | 3,286,914 | Why does this code result in 0? | I have the following code
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <stdint.h>
using namespace std;
int main(){
int x;
cin>>x;
uint32_t Ex;
Ex=(x<<1)>>24;
cout<<Ex<<endl;
return 0;
}
but it gives 0 for any value of x?
My task is the following:
Computation of the biased... | It is not so much that you get zero for 'any value of x' but that you get zero for any positive value of x smaller than 0x01000000 (which is 16777216).
None of this helps much with explaining a 'biassed exponent of a binary32 datum'. That sounds like the exponent of a 32-bit floating point (IEEE) number. You probably... |
3,286,901 | 3,286,927 | How is the memory use in a queue? | In my project I use the std::queue class. I would like to know what happen if I do the following.
Get a a pointer of a element inside the queue (note: a pointer and not a iterator).
I make modification in the queue like push and pop in the queue (pop element which is not the pointed by the previous pointer)
Does my p... | std::queue uses a sequence container for its implementation. By default, std::deque is used. With a std::deque, so long as all the insertions and erasures are at the beginning or the end of the container, references and pointers to elements in the container are not invalidated.
However, I don't know how you are going... |
3,287,052 | 3,287,086 | Famous design patterns that a C++ programmer should know |
Possible Duplicate:
What C++ idioms should C++ programmers use?
After reading books like C++ Primer, Effective C++ and TC++PL I want to learn some important design patterns.
So, what are the famous design patterns that every C++ programmer should know?
| The obvious answer is the Gang-Of-Four patterns from the famous book. These are the same patterns that get listed all over the place.
http://en.wikipedia.org/wiki/Design_Patterns
Beyond that, have a look around Martin Fowlers web site...
http://martinfowler.com/
There's a fair bit on there - the "famous" one is probabl... |
3,287,079 | 3,287,238 | Verify the structure of a database? (SQLite in C++ / Qt) | I was wondering what the "best" way to verify the structure of my database is with SQLite in Qt / C++. I'm using SQLite so there is a file which contains my database, and I want to make sure that, when launching the program, the database is structured the way it should be- i.e., it has X tables each with their own Y co... | You can get a list of all the tables in the database with this query:
select tbl_name from sqlite_master;
And then for each table returned, run this query to get column information
pragma table_info(my_table);
For the pragma, each row of the result set will contain: a column index, the column name, the column's type ... |
3,287,087 | 3,287,206 | Attach a video stream onto an existing application | Is it possible to show a video that is playing onto an existing application?
Application A is running.
Get Video A and place it on top of Application A and then play it.
Thanks! Cheers!
| If you mean to load a video and play it, you can use the DirectShow API, which will use the installed Windows codecs to attempt playback. You can also use ffmpeg for a selection of codecs that may not be installed on the computer.
|
3,287,096 | 3,287,116 | What is the simplest way to "cast" a member function pointer to a function pointer in C++? | I want to provide a member function for the "comp" parameter of an STL algorithm like lower_bound( ..., Compare comp ). The comp() function accesses a non-static member field so it must itself be a non-static member but the type of a non-static member function pointer is different from that of an ordinary function poi... | This is the most common use of std::mem_fun and std::mem_fun_ref. They're templates that create functors that invoke the specified member function. TR1 adds an std::tr1::bind that's also useful and more versatile (and if you don't have TR1 available, that's based on Boost::bind). C++0x will include std::bind in the sta... |
3,287,102 | 3,297,600 | C++ inheritance pattern + CRTP | am trying to understand pattern used in ublas.
pattern is such:
struct vector : vector_expression<vector>
where vector_expression is like this:
template<class E>
class vector_expression {
...
// no constructor or E pointer/reference in class
//
const E &operator () () const {
return *static_cast<const E*>(this);... | This is a trick to constrain function templates -- to restrict the class of types. There are lots of concepts like vector expression, scalar expression, matrix expression etc. If you want to write a function template that multiplies a vector with a scalar you could try to write
template<typename V, typename S>
some_typ... |
3,287,472 | 3,287,493 | Why is my .cpp file not being processed? | I'm trying to compile (make) a game source and it seems that my gRace.cpp file is being excluded or something because it keeps returning undefined reference errors for all my gRace class methods.
libtron.a(libtron_a-gGame.o): In function `gGame::StateUpdate()':
gGame.cpp:(.text+0x99e9): undefined reference to `gRace::R... | Not including the header file would cause undefined function compiler errors. These are linker errors, which means the actual source file isn't being linked with the other files (that is, it has nothing to do with whether or not you included gRace.h in the right places). Check your build script to ensure gRace.cpp is b... |
3,287,540 | 3,365,018 | How do i view source code in totalview? | I just fired up totalview on my "hello world" application (c++) and i only get to view the assembly code.
Is there any settings/flags i need to set to view the source code? Menubar->View->Source As->Source does not work for me.
the application im trying to debug is just a cout << "Hello World" application, just to get ... | Lets start with the simple stuff.
Did you compile your application with the '-g' debugging flag? The debugger relies on the compiler to provide it with a symbol table and line number table to map what happens in the executable back to your source code. Without that -g flag (or if you subsequently strip your applicatio... |
3,287,664 | 3,287,693 | C++ Classes and Overloaded Operators | I have been trying to make a StringTable class that holds a simple unordered_map<string, string>, and has the array index operator '[]' overloaded to work for accessing the map; however, the compiler will tell me that I have yet to define the overloaded operator when I try to use it. My code is as follows:
CStringTable... | Regarding the inline keyword, the compiler needs to be able to see the body of that method as well in the .h file. So either move the implementation of the operator from the .cpp file to the .h file, or include the body of the operator in the class declaration.
|
3,287,716 | 3,287,786 | Problems understanding iterators and operator overload in c++ | We have a class example and I just don't get it. I don't quite understand how the operator() works in this case, and everything starting with sort. I looked at the output after running the program, and I don't see how those values are obtained.
sort indices array: 2 8 10 4 1 7 5 3 0 9 6 11
replay numbers array: 37 ... | I am not sure I will be able to explain this correctly. Here is my try:
(1). vector<int> indices( vecNum.size() );
You are creating a vector to hold the indexes for the elements in vector vecNum. Obviously the number of elements in this vector is same as number of elements in vecNum.
(2). iota( indices.begin(), indices... |
3,287,801 | 3,287,828 | Pointers to elements of std::vector and std::list | I'm having a std::vector with elements of some class ClassA. Additionally I want to create an index using a std::map<key,ClassA*> which maps some key value to pointers to elements contained in the vector.
Is there any guarantee that these pointers remain valid (and point to the same object) when elements are added at t... | Vectors - No. Because the capacity of vectors never shrinks, it is guaranteed that references, pointers, and iterators remain valid even when elements are deleted or changed, provided they refer to a position before the manipulated elements. However, insertions may invalidate references, pointers, and iterators.
Lists ... |
3,287,834 | 3,287,841 | What is this at the end of function ,...) in c++ |
Possible Duplicate:
In a C function declaration, what does “…” as the last parameter do?
What does this mean ,...); it is written at the end of a function in a code i am debuging.
like this void abc( int a, int b, ...);
| It means the function can take any number of extra arguments. For example, consider printf; the first argument is the format string, and then there can be any number of arguments after that for all of the modifiers. This would be represented by using ... after the first argument when defining the function.
|
3,287,933 | 3,287,984 | Convert LPTSTR to string or char * to be written to a file | I want to convert LPTSTR to string or char * to be able to write it to file using ofstream.
Any Ideas?
| Most solutions presented in the other threads unnecessarily convert to an obsolete encoding instead of an Unicode encoding. Simply use reinterpret_cast<const char*> to write UTF-16 files, or convert to UTF-8 using WideCharToMultiByte.
To depart a bit from the question, using LPTSTR instead of LPWSTR doesn't make much s... |
3,288,037 | 3,288,054 | Why was the array type of formal parameter of a function converted to pointer? | The output of the following function is "int *", which means the formal parameter is converted to a integer pointer. Is there any necessary reason for this design? Why can't we reserve the array type?
// the output is "int *"
#include<typeinfo>
void Func(int ar[5])
{
printf("%s\n", typeid(ar).name();
}
int main()
{
... |
Is there any necessary reason for this design?
This is historical baggage from C. Supposedly 1 this was convenience as you can't pass arrays by-value anyway.
If you want to preserve the type, you can use a references or pointers:
void Func(int (&ar)[5]);
Or using template functions to accept an arbitrarily sized arr... |
3,288,422 | 3,288,481 | How to calculate the cumulative sum for a vector of doubles in C++? | I have a vector of doubles and I need to create another array which is a cumulative sum of the elements of the first. For example;
vector<double> Array(10,1);
vector<double> Sum(10);
Sum[0] = Array[0];
for(unsigned int i=1; i<Array.size(); i++)
Sum[i] = Sum[i-1] + Array[i];
Is there an in-built function... | Without having tested it, something like
std::partial_sum(Array.begin(), Array.end(), Sum.begin(), plus<double>());
should do the trick, if it's C++. (Actually, the plus<double>() can be defaulted out, it seems.)
|
3,288,551 | 3,288,571 | Cannot convert from const Point to const D2D1_POINT_2F | class ADot :
public Shape
{
private:
Point me_;
operator D2D1_POINT_2F() const;//HERE I HAVE CONVERSION OPERATOR BUT IT DOES NOT WORK
public:
ADot(signed, signed);
~ADot(void);
void draw()const;
Point center() const;
Point north() const;
Point south() const;
Point east() const;
... | The operator is declared PRIVATE. Make it public
You are also trying to convert a Point to D2D1_POINT_2F, but the operator is declared in ADot class
|
3,288,848 | 3,288,884 | Initialization of object static members | Static members confuse me sometimes. I understand how to initialize a simple built in type such as int with something along the lines of int myClass::statVar = 10;, which you place in a .cpp file, but I have something of the following sort:
class myClass
{
public:
// Some methods...
protected:
static RandomGenerator... | You could create wrapper class which will hold RandomGenerator instance in it and will call RandomGenerator::Randomize in its constructor.
|
3,289,028 | 3,289,062 | Any ideas for a dissertation? | I was wondering whether anyone had some ideas for a dissertation i have to do for university. It will be a 12 month project and I will probably be looking to do something in c++ but I'm open to anything. I was thinking about looking in AI but not sure.
Thank in adv.
| I would suggest you to look for people who work in this field at your university and ask them for project suggestions. You will eventually end up with someone from yor Uni as a supervisor anyway, so why not get in touch with them right away?
On the other hand, if you really want some suggestions, look at the numerous A... |
3,289,106 | 3,289,155 | How to write console data into a text file in C++? | I'm working on a file sharing application in C++. I want to write console output into a separate file and at the same time I want to see the output in console also. Can anybody help me...Thanks in advance.
| i don't program in c++ but here is my advice: create new class, that takes InputStream (istream in c++ or smth), and than every incoming byte it will transfer in std.out and in file.
I am sure there is a way to change standard output stream with forementioned class. As i remember, std.out is some kind of property of co... |
3,289,149 | 3,289,879 | Tracking - and correctly ending - native and managed threads in a C# - C++/CLI - C++ Windows forms application prior to exit | This is a follow-on from:
Debugging a Multithreaded C# - C++/CLI - C++ Solution in Visual Studio 2008: What are these threads?
Please excuse the format, I've just repeated some of the description of the application here:
I've inherited a project consisting of three levels of code. The lowest layer is native C++ that in... |
What I'd like to be able to do is identify what threads are doing what
You cannot make this work. There are ways to enumerate the threads in a process, like the managed Process.Threads property or the native Thread32First/Next but you don't get nearly enough info about the threads to know what they do. And most cer... |
3,289,290 | 3,289,933 | Qt - How to specify and make constant an element size in a layout? | Say there is a QHBoxLayout and some widgets in it. How to specify a widget width and hight in the layout, so that while resizing the widget which containes the layout the given width and hight stay constant?
| You can use
void QWidget::setFixedSize ( int w, int h )
which Sets the width of the widget to w and the height to h. This will make the size of the particular widget fixed when the window is re-sized.
Also you can use the combination of these functions,
void QWidget::setFixedHeight ( int h )
and also
void QWidget::se... |
3,289,321 | 3,291,311 | C# - Capturing Windows Messages from a specific application | I'm writing a C# application which needs to intercept Window Messages that another applications is sending out. The company who wrote the application I'm monitoring sent me some example code, however it's in C++ which I don't really know.
In the C++ example code I've got they use the following code:
UINT uMsg = Regist... | Turns out I also needed to send the other application a PostMessage asking it to send my application the Window Messages.
PostMessage((int)_hWnd, _windowsMessages[0], SHOCK_REQUEST_ACTIVE_CALLINFO, (int)_thisHandle);
PostMessage((int)_hWnd, _windowsMessages[0], SHOCK_REQUEST_ALL_REGISTRATIONINFO, (int)_thisHandle);
Pos... |
3,289,354 | 3,289,439 | Output difference in gcc and turbo C | Why is there a difference in the output produced when the code is compiled using the two compilers gcc and turbo c.
#include <stdio.h>
int main()
{
char *p = "I am a string";
char *q = "I am a string";
if(p==q)
{
printf("Optimized");
}
else{
printf("Change your compiler");
... | Your questions has been tagged C as well as C++. So I'd answer for both the languages.
[C]
From ISO C99 (Section 6.4.5/6)
It is unspecified whether these arrays are distinct provided their elements have the appropriate values.
That means it is unspecified whether p and q are pointing to the same string literal or not. I... |
3,289,726 | 3,289,913 | In C++, any general guidelines for handling memory allocation/deletion? | Probably all that I'm asking for is a link to a website that I have yet to find. But coming from a Java background, what are the general guidelines for handling memory allocation and deletion in C++? I feel like I may be adding all sorts of memory leaks to my application. I realize that there are several variants of... | My usual policy is this
Use smart pointers where usage is at all complex.
All raw pointers are owned by a specific object that is responsible for deleting it.
The constructor always either allocates the pointer or initializes it to null if it's to be set later.
The destructor always deletes any contained pointers
Tho... |
3,289,818 | 3,289,887 | Hybrid Inheritance Example | Can anyone suggest any real life example of Hybrid inheritance?
| Hybrid Inheritance is a method where one or more types of inheritance are combined together. I use Multilevel inheritance + Single Inheritance almost at all time when I need to implement an interface.
struct ExtraBase { void some_func(); };
struct Base : public ExtraBase {};
struct Derived : public Base, public IUnknow... |
3,290,134 | 5,570,956 | vtune - no symbols available | I have used vtune several times in the past, usually without too much trouble. Unfortunately the gaps between each use are often so long that I forget some aspects of how to use it each time. I know that the line number and symbols information needs to be stored somehow. I thought that all that was required was to comp... | The problem has been solved: It turned out that it was a mistake in setting the working directory; "/Zi" appears to be all that is required after all. I don't need to switch off optimization.
|
3,290,282 | 3,290,591 | typedef and non-simple type specifiers | Why is this code invalid?
typedef int INT;
unsigned INT a=6;
whereas the following code is valid
typedef int INT;
static INT a=1;
?
As per my understanding unsigned int is not a "simple type specifier" and so the code is ill-formed. I am not sure though.
Can anyone point to the relevant section of the Standard which... | typedefs are not like macros. They are not just text substitution. A Typedef creates a new typename.
Now when you say unsigned int, the unsigned isn't a modifier which is tacked onto the int. unsigned int is the complete typename; it just happens to have a space in it.
So, when you say typedef int INT; then INT is t... |
3,290,332 | 3,293,032 | var arg list to tempfile, why is it needed? | I have this code inside a constructor of a class (not written by me) and it writes a variable arg list to a tmp file.
I wondered why this would be needed? The tmpfile is removed after this ctor goes out of scope and the var arg list sits inside the m_str vector.
Can someone suggest a better way of doing this without... | This is C++ code: I think you may be trying to solve the wrong problem here.
The need for a temp file would go away completely if you consider using a C++-esque design instead of continuing to use the varargs. It may seem like a lot of work to convert all the calling sites to use a new mechanism, but varargs provide a ... |
3,290,389 | 3,291,200 | Is there an alternative for boost::phoenix::at_c in combination with boost::spirit::qi::grammar | I have created a test application to illustrate my problem. It parses a list of integers preceded by "a=" or "b=" and is separated by "\r\n". The list contains multiple occurrences of those fields in any order.
#include <string>
#include <vector>
#include <iostream>
#include <boost/spirit/include/qi.hpp>
#include <b... | Phoenix allows you to bind data members as well, so you can write:
Parser =
*( aParser [push_back(bind(&MyStruct::m_aList, _val), _1)]
| bParser [push_back(bind(&MyStruct::m_bList, _val), _1)]
);
Moreover, in this case you don't need the FUSION_ADAPT magic for your structure anymore.
|
3,290,408 | 3,290,530 | How to list threads opened by every application in Linux? | Is there a way to know, at a real time, what threads are opened and what application opened them?
| You can look in /proc/<PID>/task/ (where <PID> is a process-ID) which will have a number of subdirectories, each with the name equal to the thread-ID of one of the threads in that task.
Note that this is only sort-of real-time though -- unless you were to "freeze" the entire system for the duration, the information you... |
3,290,561 | 3,358,035 | Problems accessing uccapi.dll COM interface C++ | I'm working on a project involving the Microsoft Unified Communications Client API; uccapi.dll. I'm also using Codegear C++Builder 2010, not Visual Studio. After registering the dll with regsvr32 and importing it as type library into C++Builder 2010, uccapi_tlb- and uccapi_ocx-files were generated. When having imported... | This issue is already being discussed in detail in the Embarcadero forums.
|
3,290,729 | 3,306,698 | CodeSourcery giving compilation error: missing bits/c++config.h | in my project I'm making use of Eigen C++ library for linear algebra. ONLY when I turn on the vectorization flags (-mfpu=neon -mfloat-abi=softfp) for ARM NEON, I get a compiler error - c++config.h no such file or directory.
I'm not able to understand whats going wrong, what is this bits/c++config.h? What should I do to... | I got a response from the Codesourcery team. This problem was caused because I had not installed all the add-ons. The installation of the add-ons is a very simple step, if you are running in CodeSourcery's Eclipse environment then you have to just go to Help > Install New Software and after that its pretty straight for... |
3,290,780 | 3,290,814 | Does myVector.erase(myObject) call delete on myObject? | Similar to this question but with objects instead of pointers.
If I have the following code
Foo f;
vector<Foo> vect;
vect.push_back(f);
vect.erase(vect.begin());
Where does my object go? Is delete called on it? What if someone else holds a pointer to it? Is this a memory leak?
| push_back stores a copy of f in the vector, and erase destroys it. f itself is not affected by that.
All pointers, references and iterators to an element in a vector are invalidated when you erase it. Using them to access the element after erase yields undefined behavior.
|
3,290,874 | 3,290,933 | Consequences of this buffer overflow? | So here I believe I have a small buffer overflow problem I found when reviewing someone else's code. It immediately struck me as incorrect, and potentially dangerous, but admittedly I couldn't explain the ACTUAL consequences of this "mistake", if any.
I had written up a test app to demonstrate the error, but found (to ... | Your assessment is correct.
[edit] with the addition of the correction mentioned by James Curran.[/edit]
Likely, your test app didn't show the problem because the allocation is rounded up to the next multiple of 4, 8 or 16 (which are common allocation granularities).
This means you should be able to demonstrate with a ... |
3,291,047 | 3,291,315 | How do I print the string which __FILE__ expands to correctly? | Consider this program:
#include <stdio.h>
int main() {
printf("%s\n", __FILE__);
return 0;
}
Depending on the name of the file, this program works - or not. The issue I'm facing is that I'd like to print the name of the current file in an encoding-safe way. However, in case the file has funny characters which ... | Use can use the token pasting operator, like this:
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define WFILE WIDEN(__FILE__)
int main() {
wprintf("%s\n", WFILE);
return 0;
}
|
3,291,167 | 3,291,411 | How can I take a screenshot in a windows application? | How can I take a screenshot of the current screen using Win32?
| HDC hScreenDC = GetDC(nullptr); // CreateDC("DISPLAY",nullptr,nullptr,nullptr);
HDC hMemoryDC = CreateCompatibleDC(hScreenDC);
int width = GetDeviceCaps(hScreenDC,HORZRES);
int height = GetDeviceCaps(hScreenDC,VERTRES);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC,width,height);
HBITMAP hOldBitmap = static_cast<H... |
3,291,218 | 3,291,854 | Convert Mouse Points to Quadratic BSplines | I'm writing a drawing program. I'm trying to take an ordered list mouse positions, and approximate a smooth Quadratic BSpline Curve. Does anyone know how to accomplish this?
Thanks!
| "B-spline curve fitting based on adaptive curve refinement using dominant points" by Park & Lee and "Fair interpolation and approximation of B-splines by energy minimization and points insertion" by Vassilev seem to be solving this problem. Also there look like a few references on the first link that should help you.
C... |
3,291,258 | 3,291,319 | square-root and square of vector doubles in C++ | I'd like to calculate the square and square-root of a vector of doubles. For example given:
vector<double> Array1(10,2.0);
vector<double> Array2(10,2.0);
for(unsigned int i=0; i<Array1.size(); i++)
Array1[i] = sqrt(Array1[i]);
for(unsigned int i=0; i<Array2.size(); i++)
Array2[i] = Array2[i] * Array2[... | Same answer as your previous question...
static inline double computeSquare (double x) { return x*x; }
...
std::transform(Array1.begin(), Array1.end(), Array1.begin(), (double(*)(double)) sqrt);
std::transform(Array2.begin(), Array2.end(), Array2.begin(), computeSquare);
(The (double(*)(double)) cast is to force the... |
3,291,440 | 3,291,697 | How to write only regularly spaced items from a char buffer to disk in C++ | How can I write only every third item in a char buffer to file quickly in C++?
I get a three-channel image from my camera, but each channel contains the same info (the image is grayscale). I'd like to write only one channel to disk to save space and make the writes faster, since this is part of a real-time, data collec... | Let's say your buffer is 24-bit RGB, and you're using a 32-bit processor (so that operations on 32-bit entities are the most efficient).
For the most speed, let's work with a 12-byte chunk at a time. In twelve bytes, we'll have 4 pixels, like so:
AAABBBCCCDDD
Which is 3 32-bit values:
AAAB
BBCC
CDDD
We want to turn ... |
3,291,507 | 3,291,787 | Does explicitly calling destructor result in Undefined Behavior here? | In my opinion, the following code (from some C++ question) should lead to UB, but the it seems it is not. Here is the code:
#include <iostream>
using namespace std;
class some{ public: ~some() { cout<<"some's destructor"<<endl; } };
int main() { some s; s.~some(); }
and the answer is:
some's destructor
some's destruct... | The behavior is undefined because the destructor is invoked twice for the same object:
Once when you invoke it explicitly
Once when the scope ends and the automatic variable is destroyed
Invoking the destructor on an object whose lifetime has ended results in undefined behavior per C++03 §12.4/6:
the behavior is und... |
3,291,519 | 3,548,766 | Weird behavior of UuidCreateSequential | I have a software that runs over 2 000 computers on my company, without any issues.
This software, at some time, generate a GUID (or UUID) using UuidCreateSequential() (MSDN link).
The call usually returns RPC_S_OK on every computer. But on one of them, it always returns RPC_S_UUID_LOCAL_ONLY.
The documentation states ... | I contacted Microsoft and it seems that bug occurs only on Windows XP, when the first byte of the MAC address is superior or equal to 0x80.
This has been fixed for Windows Vista and Windows Seven. It won't be fixed for Windows XP.
|
3,291,521 | 3,324,173 | How are the Poco C++ events handled? | Lets say i have a Poco::Thread:
Thread Parent has an eventhandler method within it.
The parent then spawns two children threads, who are given events that are the parent subscribes the eventhandler to.
So two events both have the same event handler attached.
If Child A triggers their event, and Parent starts to execute... | Event delegates are called within the thread of the caller (unless you're using notifyAsync()), so in the case of multiple threads triggering the same event you'll have to take care of synchronization in your event handlers yourself.
|
3,291,568 | 3,291,620 | "import" a definition of a function from a base class to implement abstract interface (multiple inheritance in C++) | Say we have a class inheriting from two base classes (multiple inheritance). Base class A is abstract, declaring a pure virtual function foo, the other base class B declares and implements a function foo of the very same signature.
struct A
{
virtual void foo(int i) = 0;
};
struct B
{
virtual void foo(int i) {}
};... | In java, your sample code works. In C++ it doesn't. A subtle difference between those languages.
Your best option in C++ is to define C::foo() by forwarding to B::foo():
struct C : public A, public B
{
virtual void foo(int i) { B::foo(i); }
};
|
3,291,644 | 3,291,788 | C++: Creating an uninitialized placeholder variable rather than a default object | I'm moving from Java to C++ right now and I'm having some difficulties whenever a commonly used concept in Java doesn't map directly into C++. For instance, in Java I would do something like:
Fruit GetFruit(String fruitName) {
Fruit fruit;
if(fruitName == "apple") fruit = new Fruit("apple");
else if(fruitN... | C++ gives you much more headache when it comes to creating fruits. Depending on your needs, you can choose one of the following options:
1) create a Fruit on a stack and return a copy (you need a copy constructor) then and must provide some default fruit in case the name does not match:
Fruit GetFruit(const std::string... |
3,291,923 | 3,292,143 | How to get rgb value by cimg? | CImg<unsigned char> src("image.jpg");
int width = src.width();
int height = src.height();
unsigned char* ptr = src.data(10,10);
How can I get rgb from ptr?
| From the CImg documentation -- section 6.13 on page 34, and section 8.1.4.16 on page 120 -- it looks like the data method can take four arguments: x, y, z, and c:
T* data(const unsigned int x, const unsigned int y = 0,
const unsigned int z = 0, const unsigned int c = 0)
...where c refers to the color channel.... |
3,291,992 | 3,292,104 | Shunting-yard: missing argument to operator | I'm implementing the shunting-yard algorithm. I'm having trouble detecting when there are missing arguments to operators. The wikipedia entry is very bad on this topic, and their code also crashes for the example below.
For instance 3 - (5 + ) is incorrect because the + is missing an argument.
Just before the algorithm... | For binary operator only expressions, the postfix expression has the invariant that in any prefix of the expression, numbers of operands > numbers of operators and in the end, that difference is exactly one.
So you can verify the RPN expression for validity at each stage of the shunting yard by maintaining a running co... |
3,292,103 | 3,380,768 | How do I use a class wstringstream variable? | I have a std::wstringstream that I'm using as sort of a buffer in my class and it is used by a good portion of the methods in this class. However, when I try to do something like this:
#include <sstream>
class foo
{
public:
void methodA(int x, int y); // Uses mBufferStream
void methodB(int x, int y); // Uses... | This is because the compiler is implicitly declaring a copy constructor for class foo. std::wstringstream is noncopyable, because it inherits from ios_base.
Change your class to this:
#include <sstream>
class foo
{
public:
void methodA(int x, int y); // Uses mBufferStream
void methodB(int x, int y); // Uses ... |
3,292,107 | 3,292,157 | What's the difference between istringstream, ostringstream and stringstream? / Why not use stringstream in every case? | When would I use std::istringstream, std::ostringstream and std::stringstream and why shouldn't I just use std::stringstream in every scenario (are there any runtime performance issues?).
Lastly, is there anything bad about this (instead of using a stream at all):
std::string stHehe("Hello ");
stHehe += "stackoverflow... | Personally, I find it very rare that I want to perform streaming into and out of the same string stream.
Usually I want to either initialize a stream from a string and then parse it; or stream things to a string stream and then extract the result and store it.
If you're streaming to and from the same stream, you have t... |
3,292,145 | 3,292,273 | C++ Template Specialization Compilation | I'm going to outline my problem in detail to explain what I'm trying to achieve, the question is in the last paragraph if you wish to ignore the details of my problem.
I have a problem with a class design in which I wish to pass a value of any type into push() and pop() functions which will convert the value passed int... | First of all, you can't just have specialized templates without a base template to specialize. It's just not allowed. You have to start with a template, then you can provide specializations of it.
You can explicitly instantiate a template over an arbitrary set of types, and have all those instantiations compiled into y... |
3,292,259 | 3,292,304 | Can I make Visual Studio create the Debug DLL as XXXd.DLL instead of XXX.DLL? | I have found a solution for this, but it only works if you use .DEF files (I don't).
I wonder if this can be done without .DEF files.
| Project > Properties. Then Configuration Properties > Linker > General > Output file. Here you should have something like: $(OutDir)\$(ProjectName).dll just put $(OutDir)\$(ProjectName)d.dll
|
3,292,537 | 3,292,623 | How to make a function call bulletproof? | I need to call a function (an LLVM JIT to be specific) from a C++ application. This call might fail or even signal abort() or exit(). How can I avoid or at least reduce effects on my host application? Someone suggested using fork(), however I need a solution for both windows and posix. Even if I would use fork() ... wo... | You basically have to isolate the call that might fail spectacularly, so yes, you probably have to create a separate process for it. I'd actually be tempted to create a small executable just containing this particular call and the necessary supporting functionality and call that from your main executable. This gets you... |
3,292,683 | 3,292,870 | Where is a reference to regex header on MSDN? | I can include this file directly now without tr1 in VS 2010 but can't find description of this file anywhere on MSDN. Where is a reference to regex header on MSDN?
| The regex description on MSDN:
http://msdn.microsoft.com/en-us/library/bb982382.aspx
Basically, you create "basic_regex" objects, then call the "regex_match" or "regex_replace" functions
|
3,292,700 | 3,292,729 | uint64 flag or uint32 flag[2] for function argument to 32bit compiler? | I have a uint32 variable for some bit field flag state and an enum for these flags. This variable is passed as argument to some functions by value.
I need to add about 20 more flags to it. What are my best options? Extend it to 64 bits or treat it as an array of 2 32bits?
Extending to 64 bits will lead me to use compi... | I would use an STL bitset. Then my enum wouldn't have to be a power of 2. With normal enumeration, it would just be the index into the bitset. You could also use a vector<bool>.
The chief benefit would be portability since your flag set would now fit in any platform's normal enum range.
example:
enum errorFlags { pa... |
3,292,795 | 3,292,852 | How to declare a templated struct/class as a friend? | I'd like to do the following:
template <typename T>
struct foo
{
template <typename S>
friend struct foo<S>;
private:
// ...
};
but my compiler (VC8) chokes on it:
error C3857: 'foo<T>': multiple template parameter lists are not allowed
I'd like to have all possible instantiations of template struct foo ... | template<typename> friend class foo
this will however make all templates friends to each other.
But I think this is what you want?
|
3,292,811 | 3,292,828 | C# - DLLImport and function default values | I'm interfacing with a native 3rd party C++ DLL via C# and the provided interop layer looks like below:
C#:
[DllImport("csvcomm.dll")]
public static extern int CSVC_ValidateCertificate(byte[] certDER, int length);
C++:
CSVC_Status_t CSVCOMM_API CSVC_ValidateCertificate(BYTE* certDER, DWORD length,
DWORD context =... | The optional parameter in C++ is resolved at compile time. When you call into this via P/Invoke, you need to always specify all three parameters.
If you want to have an optional parameter, you'll need to make a C# wrapper around this method with an overload that provides the optional support (or a C# 4 optional parame... |
3,292,862 | 3,294,786 | Floating Point Div/Mul > 30 times slower than Add/Sub? | I recently read this post: Floating point vs integer calculations on modern hardware and was curious as to the performance of my own processor on this quasi-benchmark, so I put together two versions of the code, one in C# and one in C++ (Visual Studio 2010 Express) and compiled them both with optimizations to see what ... | For the float div/mul tests, you're probably getting denormalized values, which are much slower to process that normal floating point values. This isn't an issue for the int tests and would crop up much later for the double tests.
You should be able to add this to the start of the C++ to flush denormals to zero:
_contr... |
3,293,013 | 3,293,167 | C++ Base class destrutor order problem | Does anyone know any trick I could use to keep the Derived class until the base class destructor have been called?
i.e:
#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
... | You definitely don't want to change destruction order, which is good, because you can't.
What you really want to do is to dispose/disconnect/shutdown the Observer.
What I would do is add this to your Event::Observer class:
void Event::Observer::Shutdown()
{
if(!isShutdown)
{
//Shut down any links to th... |
3,293,062 | 3,293,145 | How do I fix this lvalue warning? | My code is:
void main() {
person student[10];
student[0].names[0] = 'C';
student[0].names[1] = 'a';
student[0].names[2] = 'm';
student[0].names[3] = 'i';
student[0].ages = 16;
student[0].sex[0] = 'F';
student[0].sex[1] = 'e';
student[0].sex[2] = 'm';
student[0].sex[3] = 'a';
student[0].sex[4] = 'l';
stude... | Array usage
You say you have:
typedef struct person {
char names[20][10];
char sex[6][10];
int ages[10];
int month[10];
int day[10];
int year[10];
} person;
There's no need for the [10]'s. You already have that in the person student[10] declaration, which is the proper place for the [10]. Remov... |
3,293,248 | 3,293,272 | how to write a cast-to-reference-to-array operator for a class? | I have following class:
template <size_t size>
class Araye{
public:
Araye(int input[]){
for (int i=0;i<size;i++)
araye[i]=input[i];
}
int araye[size];
};
How should I write a cast-to-reference-to-array operator for this class so that following works:
int adad[3]={1,2,3};
Araye<3> araye(adad);
int (&refer... | template <size_t size> class Araye {
public:
typedef int (&array_ref)[size];
operator array_ref () { return araye; }
// ...
Or with identity (thanks Johannes):
operator typename identity<int[size]>::type &() { return araye; }
With that your example works, but i'd prefer the following declaration inste... |
3,293,279 | 3,293,461 | How do you import an enum into a different namespace in C++? | I have an enum in a namespace and I'd like to use it as if it were in a different namespace. Intuitively, I figured I could use 'using' or 'typedef' to accomplish this, but neither actually work. Code snippet to prove it, tested on GCC and Sun CC:
namespace foo
{
enum bar {
A
};
}
namespace buzz
{
// Which of th... | Wrap the existing namespace in a nested namespace which you then "use" in the original namespace.
namespace foo
{
namespace bar_wrapper {
enum bar {
A
};
}
using namespace bar_wrapper;
}
namespace buzz
{
using namespace foo::bar_wrapper;
}
|
3,293,471 | 3,295,141 | Accessing negative pixel values OpenCV | I am attempting to perform a zero-crossing edge detection on an image in OpenCV. I blur and use the cvLaplace() then scale it from (0, max). My question is: How can I access the pixel values in that image in such a way as to correctly identify negative values? Using the function provided by OpenCV (cvPtr2D) returns uns... | Pixels are stored internally as IPL_DEPTH_8U, which means 8-bit unsigned char, ranging from 0 to 255. But you could also pack them as IPL_DEPTH_16S (signed integer) and even IPL_DEPTH_32F (single precision floating point number).
cvConvertScale() probably will do the job! But if you want to convert it manually:
OpenCV ... |
3,293,534 | 3,293,624 | C++ append one vector to another | I fully understand this question has been asked a lot, but I'm asking for a specific variation and my search-foo has given up, as I've only found algorithms that append one existing vector to another, but not one returned to from a function.
I have this function that lists all files in a directory:
vector<string> scanD... | If you're in the position to change scanDir, make it a (template) function accepting an output iterator:
template <class OutIt>
void scanDir(const std::string& dirname, OutIt it) {
// ...
// Scan subdir
scanDir(subdir, it);
// ...
}
You'll have the additional benefit to be able to fill all sort of data structu... |
3,293,796 | 3,293,992 | typedef declaration of template class | is there a difference, from prospective of meta-programming for example, between the two
declarations?
template<typename T>
struct matrix {
typedef matrix self_type; // or
typedef matrix<T> self_type;
};
thank you
| In this particular situation (inside a class template), matrix is a shorthand for matrix<T>. When you write lots of hairy templates all day long while trying to fit everything in 80 columns, the shorthand is welcome.
Note that you can also abbreviate method arguments:
template <typename T>
struct matrix
{
typedef m... |
3,293,883 | 3,293,917 | Call class constructor from new operator on GNU - use invalid class | The closest thread to my question is here. I am trying to compile the following code with gcc:
#include <malloc.h>
class A
{
public:
A(){};
~A(){};
};//class A
int main()
{
A* obj = (A*) malloc( sizeof(A) );
if(obj==0) return 1 ;
obj->A::A(); /*error: invalid use of 'class A' */
obj->A::~A();
free(obj... | You can't call a constructor on an object; a constructor can only be called in the creation of an object so by definition the object can't exist yet.
The way to do this is with placement new. There's no need to cast your malloc return. It should be void * as it doesn't return a pointer to an A; only a pointer to raw me... |
3,294,972 | 3,295,024 | setting max frames per second in openGL | Is there any way to calculate how much updates should be made to reach desired frame rate, NOT system specific? I found that for windows, but I would like to know if something like this exists in openGL itself. It should be some sort of timer.
Or how else can I prevent FPS to drop or raise dramatically? For this time ... | You have two different ways to solve this problem:
Suppose that you have a variable called maximum_fps, which contains for the maximum number of frames you want to display.
Then You measure the amount of time spent on the last frame (a timer will do)
Now suppose that you said that you wanted a maximum of 60FPS on you... |
3,295,053 | 3,296,077 | (C/C++/C#) DirectX 9 Overlay, preferably the same way xfire or Steam does it | I wonder what techniques xfire and/or Steam uses to overlay into games.
I'm trying to do something similar and I really would like to know what is the least intrusive way, I.e. won't alert any anti-cheat systems. I don't need any kind of information from the game (no wall-hack BS). I would basically just like to displa... | A few days back, I had asked this question. This might help you too. Read Alan's reply and the links he's mentioned : How to overlay graphics on Windows games?
|
3,295,337 | 3,296,434 | Template specialization with struct and bool | I have a template class in which I am specializing a couple of methods. For some reason, when I added a specialization for a struct, it seems to be conflicting with the specialization for bool. I am getting a type conversion error because it is trying to set the struct = bool (resolving to the wrong specialization). ... | (EDITED)
You may try the following, which delegates the method implementation to a templated helper class.
.h:
typedef struct Foo {
...
}
template<class T_Bar, class T2> struct BarMethod1;
template <class T> class Bar
{
template<class T2> void method1(...)
{
BarMethod1<Bar, T2>(...)(...);
}
}
templa... |
3,295,628 | 3,295,716 | Can I compile using VS2008's C++ compiler using VS2010 and only the Server 2008 Platform SDK? | I'd rather not install the entire VS 2008 installation given that I'm not going to be using anything other than the compiler. Will VS 2010's multitargeting work correctly using only the Platform SDK instead of the full VS2008 install?
| The custom setup options are not nearly fine-grained enough to allow you to leave the big chunks like the IDE out. It isn't just the SDK that's used, at least the VC subdirectory needs to be there. And bits of Common7, also the folder that contains the IDE. Rename the folders, delete them later if it works out.
|
3,295,690 | 3,295,761 | What is the end of line character when reading a file in using C++ get(char& c);? | My issue is I am trying my first attempt at writing a very basic lexical analyzer for ascii text files. so far, it reads and compares to my token list properly, however I am unable to grab the final token without a space or pressing enter. I've tried using the delimiter ^Z ASCII 26 as another selection before comparing... | Why don't you just delete:
if(f->eof())
break;
and use
if(f->eof() || c == '\n' || c == ' ' || c == '^Z' || c == '\r'){
then break afterwards? That way, when you hit EOF, you will add whatever remaining token you have.
Alternately, you could just check if the token is nonempty after you break out of the loop, and ... |
3,295,742 | 3,295,778 | Implementing a stack based virtual machine for a subset of C | Hello everyone I'm currently implementing a simple programming language for learning experience but I'm in need of some advice. Currently I'm designing my Interpreter and I've come into a problem.
My language is a subset of C and I'm having a problem regarding the stack interpreter implementation. In the language the f... | Great question! One of my hobbies is writing compilers for toy languages, so kudos for your excellent programming taste.
An expression statement is one where the code in the statement is simply an expression. This means anything of the form <expression> ;, which includes things like assignments and function calls, but ... |
3,295,817 | 3,295,853 | Any good recursive tutorials? Python? | Wondering if anyone could point me towards a good recursion tutorial. I am a bit rusty on it as I learned about it in my Data Structures class first semester. Would like to brush up on my recursion...any help?
| Consider this.
More seriously…
Recursion is a way of solving problems that have a clearly defined base case (or cases, btu I'm keeping it simple here.)
For examples, the commonly cited factorial problem is a great one.
What does factorial do? Let's see some examples:
factorial(0) = 1
factorial(1) = 1
factorial(2) = 2... |
3,295,979 | 3,295,987 | Is it valid to compare iterators which are got from the container separately? | For example, it this expression valid in semantic?
container.begin() == container.begin();
| Yes, so long as neither iterator has been invalidated.
For example, the following would not be valid:
std::deque<int> d;
std::deque<int> begin1 = d.begin();
d.push_front(42); // invalidates begin1!
std::deque<int> begin2 = d.begin();
assert(begin1 == begin2); // wrong; you can't use begin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.