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 |
|---|---|---|---|---|
6,293,531 | 6,293,600 | Defining a map with a structure inside it | I have a structure like
struct category {
int id,newID;
std::string name;
};
and a map like
std::map<std::string, category> categories;
is it safe to insert details into the map like
category x = {1,2,"Name"};
category y = {2,3,"Mike"};
categories["FIRST"]=x;
categories["SECOND"]=y;
or should i declare the... | What do you mean by safer? Both methods are just fine. When using the second way you must make sure to delete your category objects. On the first one they are deleted automatically when you delete your map.
The first one is slower if you need to pass the objects a lot around since you will be making copies. The second ... |
6,293,625 | 6,293,646 | one c++ syntax question (a structure method) | In the following code,
what's the meaning of :next(next_par),info(info_par)?
struct list_node : public memory::SqlAlloc
{
list_node *next;
void *info;
list_node(void *info_par,list_node *next_par)
:next(next_par),info(info_par) /* what's the meaning of :next(next_par),info(info_par)?*/
{}
lis... | :next(next_par),info(info_par) is an initialization list for member variables. Instead of having:
list_node(void *info_par,list_node *next_par){
next = next_par;
info = info_par;
}
EDIT: Just as a note, initialization lists can be important if you have member object variables that need to be constructed with... |
6,293,715 | 6,293,855 | php preg_match's equivalent in C++ with Boost? | I have the following working php code:
preg_match('/^(\d+):/', $string, $matches)
However, When I try to do it in C++ using Boost's regex library, it's not working.
regex expression1("^(\\d+):");
std::string filename = "C:\\Users\\root\\Desktop\\something.bin";
std::ifstream ifs(filename.c_str(), std::ios::in | std:... | | Single quotes | Double quotes |
-----+---------------+----------------+
PHP | string | string |
| (verbatim) | |
-----+---------------+----------------+
C++ | char | string |
-----+---------------+----------------+
Your use of single quotes in PHP... |
6,294,036 | 6,294,141 | Using the <algorithm> library on arbitrary data types | Earlier I asked this question which was on how to make my own set operations class e.g. intersection, union etc.
The answer I chose as my solution recommended the algorithm library which have these operations already implemented. I want to get these operations working on my data types like this:
struct my_data_type {
... | The compiler provides a suitable implementation of all three in this case - there is no need to write anything extra, and doing so would be bad style, IMHO. However, what you probably do need is a constructor that takes parameters, to construct a properly initialised object, and an implementation of operator<() so that... |
6,294,057 | 6,315,173 | std::fstream with multiple buffers? | You can specify one buffer for your file stream like that:
char buf[BUFFER_SIZE];
std::ofstream file("file", std::ios_base::binary | std::ios_base::out);
if (file.is_open())
{
file.rdbuf()->pubsetbuf(buf, BUFFER_SIZE);
file << "abcd";
}
What I want to do now, is using more than just one buffer:
char* buf[] = ... | I will take a look at boost::iostreams::mapped_file, but I think my requirement is much simpler. I've created a custom class derived from basic_filebuf.
template<typename char_type>
class basic_filemultibuf : public std::basic_filebuf<char_type/*, std::char_traits<char_type>*/>
{
private:
char_type** m_buffers;... |
6,294,060 | 6,294,695 | Why does this tiny RSA implementation give wrong results? | I'm trying to implement a simple RSA encryption/decryption process, and I'm pretty sure I've got the equations around the right way. Although it doesn't seem to be printing out the correct decrypted value after the encryption. Any ideas?.
//test program
#include <iostream>
#include <string.h>
#include <math.h>
using na... | The encrypted message m must be less than n. You can't use values larger than n, because the calculations are done modulo n. In your case m=65 and n=35. So you are actually getting the correct answer modulo n, because 65 % 35 == 30.
|
6,294,340 | 6,294,899 | Professionalise this code | I have been programming for about 3 years now and feel confident in my skills. But recently I began working alongside embedded systems and working on other peoples code and have begun to question how good my code is.
I see all these complex answers on SO and think I would have done that with a vector and if statements... | ahem since nobody mentioned it, let me point this one out:
int FindTarget(Player &player);
{
int aimPoint[5] = 0;
...
return 0
}
to roughly
void FindTarget(const Player &player)
{
std::vector<int> aimPoint(5, 0);
...
}
Also, since there is no knowing what the code should do (and how 'aimPoint' is re... |
6,294,533 | 6,294,672 | How can I have two classes linked each other by a vector (map, multimap..) in C++? | I have two class with a vector that holds instances of a third class.
Basically I have three classes:
Corporation
Market
Equities
Corporation and market can have 0..* equities and equities must be linked to 1 market and 1 corporation (to print values, etc...)
I don't know how to do that properly. For me the problem i... | The simplest way is to forward declare or prototype all the classes and types in a common header, place guards on that, and include the header from all your code files. For example:
header.hpp:
#ifndef COMMON_HPP
#define COMMON_HPP
class Corporation;
class Market;
class Equities;
typedef std::shared_ptr<Corporation> ... |
6,294,578 | 6,294,955 | C++ Container of Non-Interleaved Stored Tuples | I'm looking for a variant of std::vector or std::array of tuples, where the tuple elements are placed non-interleaved into separate memory areas instead of interleaved as would be the case for, for example, a std::vector<std::tuple<...>>.
The motivations for this is
Better control over alignment and in turn better per... | Boost.Iterator has exactly what you describe: boost::zip_iterator
|
6,294,833 | 6,295,063 | Boost vectors versus STL vectors | How do boost::numeric::ublas::vector and std::vector compare in runtime efficiency?
Is it safe to assume that I can convert an entire program from using std::vector to use boost::numeric::ublas::vector just by writing:
#include <boost/numeric/ublas/vector.hpp>
using namespace boost::numeric::ublas;
instead of #include... | You should only use ublas::vector if you want to do linear algebra operations, such as matrix vector multiplication etc.
They do not provide the same functionality nor the same interface as std::vector.
In terms of run-time efficiency, there is nothing, that I know of, that beats std::vector.
|
6,295,114 | 6,295,223 | More information on "cannot instantiate abstract class" | Sometimes I am working with relatively complex (and sometimes confusing - with the way they are laid out by whoever wrote it originally) abstract classes. When inheriting from it, I sometimes encounter cannot instantiate abstract class and most of the time it is because I forgot to declare & implement a pure virtual fu... | Are you using Visual Studio? If so, then switch from Error List tab to Output tab. There will be something like:
main.cpp(8): error C2259: 'foo' : cannot instantiate abstract class
due to following members:
'void Foo::method(char)' : is abstract
|
6,295,196 | 6,295,269 | Is it possible to efficiently check whether STL std::deque erase succeded? | We are trying to use the std::deque erase member function. The return value of the std::deque erase(iterator) member function is a A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the container end if the operation erased the last ... | Check if the size of dequeue decreases by the number of elements you erased.
With regards to the concern about performance, Time Complexity for dequeue::size is O(1)
#include <iostream>
#include <deque>
using namespace std;
int main ()
{
unsigned int i;
deque<unsigned int> mydeque;
// set some values (from 1 to... |
6,295,248 | 6,295,344 | C++ factory method pattern for abstract class | I have to implement a factory method pattern in C++. The class (C) that is to be "assembled" by the factory is abstract and is inherited by some other class (D). So I don't want C to have a constructor. But to create an instance of D, C has to have at least a protected constructor. But then someone might derive from C ... | It's probably a better option to give C a private constructor and make D a friend class of C.
|
6,295,253 | 6,295,275 | C++ - can execute function in diffrent way? | In this code:
void Window::oops() { printf("Window oops\n"); }
void TextWindow::oops() {
printf("TextWindow oops %d\n", cursorLocation);
}
TextWindow x;
Window a;
Window *b;
TextWindow *c;
a = x; a.oops(); // executes Window version
b = &x; b->oops(); // executes TextWindow or Window version
c = &x;... | If oops() is virtual, the b->oops() call will use the TextWindow version. If it is not, it will use the Window version.
|
6,295,462 | 6,389,057 | How to connect a wxWidgets timer to an event using wxEvtHandler::Connect | I have been trying to connect my timer to an a function.
In my derived class
What i am doing is
Timer->SetOwner(this,wxID_Timer);
Timer->Connect(wxID_Timer,wxTimerEventHandler( Window::OnUpdate ), NULL, this );
Where my declaration of OnUpdate is
void OnUpdate( wxTimerEvent& event );
Can any one tell me what is wro... | After a bit of searching i actually found the answer, no one is answering so i am posting it here.
There were a few things that i was doing wrong.
i. I actually had to connect the class to my timer . That meant i had to do something like
this->Connect(Timer.GetId(),wxEVT_TIMER,wxTimerEventHandler( Window::OnUpdate ), N... |
6,295,465 | 10,376,095 | C/C++ standard library wrapper with exceptions | I'm looking for classes like "File, Socket, String" wrapping the C (or C++) standard library functions and throwing exceptions in case of errors.
| Maybe the question wasn't clear,
btw i've found this library is exactly what i was looking for:
commonc++.
Edit: Better alternative still maintained.
|
6,295,505 | 6,295,734 | Optimize Algorithm Required- Arrays | We have an array A of integers of size N. Given another array B which contains indices, where size of B <= N and 0<=B[i]<=N-1.
Now we have to remove all elements from array A at position B[i].
So with deletion we mean we are also shifting elements in array A.
Can someone help me in reaching to O(n) solution for this ... | Similar to iliaden's solution except you could do the removing of deleted elements in place.
int[] a =
int[] b =
int nullValue =
for(int i: b) a[i] = nullValue;
int j=0;
for(int i=0; i < a.length; i++) {
if(a[i] != nullValue)
a[j++] = a[i];
}
// to clear the rest of the array, if required.
for(;j<a.length... |
6,295,575 | 6,295,989 | resolution of c++template specification and overload | I've read the Why Not Specialize Function Templates and after experiment a little bit,
I found an interesting thing. Here go the main.cxx:
// main.cxx
#include <iostream>
// Declarations
/*
template<class T>
void foo(T);
template<>
void foo(int*);
template<class T>
void foo(T*);
*/
// Definition and specification
... | Distributing the source into three files just confuse the matter: the preprocessing makes one compilation unit and the behavior just depend on the content of the CU and not in how many files it was distributed.
I think that you are surprised that in this case
#include <iostream>
template<class T> void foo(T); // A
tem... |
6,295,720 | 6,295,873 | How to create a Flat Button in WinAPI with visual style | I wanted to create a flat image push button like the Windows 7 mute button.
Here's the picture: flat button
When mouse hover it(display border): flat button hover
I tried to use BS_FLAT style, but nothing changed. My code is using visual style. When I try BS_FLAT without visual style, it does look flat, but still has... | Create toolbar with one button. When creating use TBSTYLE_FLAT style. I think also you will need CCS_NOPARENTALIGN | CSS_NORESIZE | CCS_NODIVIDER style bits.
|
6,295,991 | 6,296,063 | Creating objects of a Class in a dll in Java | There is a third part dll with definitions of a class in C++ which I've to use in Java. I've the complete knowledge of the public methods in the dll. Now to use these I'm kind of using a wrapper C++ program, which creates the object and calls the functions in the dll when required. And I interface this C++ code with th... | In order to call native(C/C++) code from Java, You will have to do Marshalling of the objects between native world and Java, JNI justs does that and your approach just looks right to me.
|
6,296,162 | 6,298,113 | Obtaining indices and elements - vector problem | I want to do following thing; I tried, but not succeeded. So I am expecting some way to solve this.
I have two vectors. One is vector<int> myvector and the other one is vector of Plane (where Plane is a created class which stores plane parameters and other properties of planes)
For example I will give you some example ... | I'm not sure what is wrong with your code, but there appears to be an easier way to code your algorithm:
// determine appropriate size of result
vector<int>::size_type newsize = myvector.back()+1;
// or, if not sorted:
// vector<int>::size_type newsize = std::max_element(myvector.begin(), myvector.end());
// Create ne... |
6,296,194 | 6,296,535 | Qt Creator Project deletes Makefile in between builds | I somehow seem to have jacked up a setting in my QtCreator project. I have a modified makefile in my projects build folder, and I am using that makefile to link in some external libraries, and point to other include files, etc. It seems like in between builds, or during cleans, or something, Qt Is deleting that file, ... | Qt mostly works with project files (*.pro) which it uses to generate Makefiles or Visual-Studio project files. Look for a file with the extension .pro in your project folder. You either have to lean how to handle project files or find ways to enter this information in QtCreator via the project tab.
|
6,296,206 | 6,296,388 | Getting std::map allocator to work | I've got an extremely basic allocator:
template<typename T>
struct Allocator : public std::allocator<T> {
inline typename std::allocator<T>::pointer allocate(typename std::allocator<T>::size_type n, typename std::allocator<void>::const_pointer = 0) {
std::cout << "Allocating: " << n << " itens." << std::endl;
... | Because allocator is 4th template parameter, whereas 3rd parameter is comparator like std::less?
so std::map<int, int, std::less<int>, Allocator< std::pair<const int, int> > > should work.
Also I think you should add default ctor and copy ctor:
Allocator() {}
template<class Other>
Allocator( const Allocator<Othe... |
6,296,328 | 6,296,390 | while (_index != string::npos) doesn't seem to be stopping the loop | My code counts spaces in string temp, which works fine. Later in the code I have a similar loop that does not end as expected.
Based on my debugging and some research, I’ve determined that the while loop isn’t stopping when it is supposed to the second time around, so an exception is thrown (std::out_of_range)… Why? Bo... | Within the second loop you reference a variable input instead of temp.
_index = input.find( " ", _index + 1 );`
Therefore the loop does never terminate. This you don't do within the first while-loop.
|
6,296,369 | 6,296,413 | Comparing Bitfields of Different Sizes | What happens if you use a bitwise operator (&, |, etc.) to compare two bitfields of different sizes?
For example, comparing 0 1 1 0 with 0 0 1 0 0 0 0 1:
0 1 1 0 0 0 0 0 The smaller one is extended with zeros and pushed to the
0 0 1 0 0 0 0 1 most-significant side.
Or...
0 0 0 0 0 1 1 0 The smaller one is extended wit... | The bitwise operators always work on promoted operands. So exactly what might happen can depend on whether one (or both) bitfields are signed (as that may result in sign extension).
So, for your example values, the bit-field with the binary value 0 1 1 0 will be promoted to the int 6, and the bit-field with the binary... |
6,296,412 | 6,299,931 | How to associate Boost Spirit parsed entities with their location in input stream? | Boost Spirit library permits to Track the Input Position While Parsing. This mechanism allows informing about location of a parser error during parsing.
I'd like to preserve original location for all parsed entities together with them for future use. (For example, AST semantic verification.) What would be the recommend... | If you need the position of all entities you might be better off using a lexer, which produces tokens optionally carrying positional information about the matched input (see here). If a lexer is not an option you might utilize the new on_success() construct (available in SVN or starting with Boost V1.47), which works s... |
6,296,505 | 6,296,545 | Why is Linux msync is returning "Cannot Allocate memory"? Is it possible to fix this error code? | Good afternoon, We are building a prototype deduper for Centos Linux Release x86_32 and Microsoft Windows. One part of the prototype is a MemoryMappedFile program which uses a 1800 element cache. For Centos Linux 5.5 we call msync to synchronize the file with the memory map. For the last several weeks, msync has been f... | The msync man page states:
ENOMEM The indicated memory (or part of it) was not mapped.
That's the errno value perror() prints for you. So you're somehow trying to msync() memory that you've not mmap()'ed from a file.
|
6,296,579 | 6,296,612 | Copy constructor called many times when data is inserted in vector | #include <iostream>
#include <vector>
using namespace std;
class base
{
int x;
public:
base(int k){x =k; }
void display()
{
cout<<x<<endl;
}
base(const base&)
{
cout<<"base copy constructor:"<<endl;
}
};
int main()
{
vector<base> v;
base obase[5]={4,14,19,24,29};... | If v needs to resize its internal buffer, it will usually allocate a totally fresh memory area, so it needs to copy all the objects that were previously in the vector to the new location. This is done using regular copying, so the copy constructor is invoked.
You should call reserve() on the vector to reserve storage u... |
6,296,746 | 6,297,510 | Function pointer to an instance member | I need to map some state to a particular member function of a class, for (a very cut down) example:
class Z {
_a_ptr_to_some_member _p;
void UpdateGuiForStopState(State s) {
// do something with state
}
Z() {
// setup _p to point to UpdateGuiForStopState
}
void StateComesInHere(State s)... | Using STL's bind1st and mem_fun:
class Z3 {
typedef std::mem_fun1_t<void,Z3,State> _a_ptr_to_some_member_raw;
typedef std::binder1st<_a_ptr_to_some_member_raw> _a_ptr_to_some_member;
_a_ptr_to_some_member _p;
void UpdateGuiForStopState(State s) {
// do something with state
}
Z3() : _p(std::bin... |
6,296,757 | 6,297,196 | Qdir's function exists() always returns true, even when the directory doesn't exist | I'm trying to error-proof the first part of a project, in which a folder is created in a specified base directory. The base directory is selected by the user either manually in QLineEdit, or by browsing through the computer's directories using QFileDialog. I'm trying to check if the base directory exists before I make ... | Your second if statement will not be executed if you type in anything in the text field. Your logic in the first if states that if the input is empty or a predefine string, then test for the existence of the dir. Which means you are always testing with an empty string or the canned message.
The correct logic should be:... |
6,296,945 | 6,296,980 | size vs capacity of a vector? | I am a bit confused about this both of these look same to me.
Although it may happen that capacity and size may differ on different compilers. how it may differ.
Its also said that if we are out of memory the capacity changes.
All these things are bit unclear to me.
Can somebody give an explanation.(if possible with an... | Size is not allowed to differ between multiple compilers. The size of a vector is the number of elements that it contains, which is directly controlled by how many elements you put into the vector.
Capacity is the amount of total space that the vector has. Under the hood, a vector just uses an array. The capacity of th... |
6,297,006 | 6,297,076 | c++ dynamic library segfault | I'm writing network application in c++ and I want to enable making plugins, but I don't know what to do, to protect my application from errors like segfault. For example:
I have interface:
class IPlugin{
public:
IPlugin();
virtual ~IPlugin();
virtual void callPlugin() = 0;
}
And someone will write dynamic librar... | It's a losing battle trying to protect you from bad code loaded into your address space. Those plugins could do real damage that you can never recover from.
Either accept the fact that a buggy plugin will bring your application down, or you have to isolate the plugin in a separate process as you suggest. But you only n... |
6,297,245 | 6,298,077 | How to directly map a Lua variable to a C++ variable? | I am working on a game engine in C++ using Lua to define NPCs.
I can define a prototypic NPC like this:
orc =
{
name = "Generic Orc",
health = 100
}
function orc:onIdle()
print("Orc idles...")
end
and then spawn an instance of "Orc" with entitySpawn(orc). This is a C++ function that reads values like heal... | This is possible. I'm assuming that entitySpawn returns the table that C++ created for the entity. I'll also assume that you can expose a function from C++ that takes an entity's table and returns the current health, and similarly for setting. (You can use a light userdata pointer to the C++ object as a member of this ... |
6,297,289 | 6,297,443 | Overloading operator-> in C++ | I have a smart pointer class and I want to overload operator->; it's provided for convenience so I can access the members of the class contained inside the smart pointer directly.
I was looking at the way Boost implements this operator in its shared_ptr template. I noticed they added an assert checking if the pointer i... | It's up to you. You could simply document that using it with a null pointer is undefined and do nothing, you could assert, you could throw an exception. There isn't a right answer. Personally, I would probably throw an exception.
|
6,297,331 | 6,297,418 | When to use C++ private inheritance over composition? | Can you give me a concrete example when is preferable to use private inheritance over composition? Personally, I will use composition over private inheritance, but there might be the case that using private inheritance is the best solution for a particular problem. Reading the C++ faq, gives you an example on using pri... | private inheritance is typically used to represent "implemented-in-terms-of". The main use I have seen is for mixins using private multiple inheritance to build up a child object with the proper functionality from the various mixin parents. This can also be done with composition (which I slightly prefer) but the inheri... |
6,297,345 | 6,297,415 | alternative to mutex lock/unlock when accessing class data | I am trying to make my_class thread-safe like so.
class my_class
{
const std::vector<double>&
get_data() const
{ //lock so that cannot get_data() while setting data
lock l(m_mutex);
return m_data;
}
void
run()
{
vector<double> tmp;
//some calculations on tmp.
{ //lock so that canno... | First step would be to look into read-write locks: this way multiple readers will not block each other.
The next step would be using lock-free or wait-free operations. There are plenty of resources online describing them better than I would be able to. Just one note: lock-free approaches deal with atomic (interlocked... |
6,297,485 | 6,297,931 | C++ Project hangs at Compiling | My boss has a C++ project that just began hanging today when he hits either the "Build Solution", "Rebuild Solution", or "Compile" buttons. The Build window says compiling and hangs there. He has tried reverting back to the project state from a week ago using Subversion but no dice.
We also have a solution that uses th... | Just in case. If you have any add-ons installed in MS VS 2008 then disable all of them to make sure that they do not cause that.
|
6,297,671 | 6,297,700 | special case of base class of Inner class | In c++, is it possible to declare inner class (CInner) such that it has outer class (COuter) as its base class ?
This question is about c++ technicalities. Not question of programming style or personal preferences.
| Yes. This compiles:
class COuter
{
class CInner;
};
class COuter::CInner : public COuter
{
};
The reason this is required is that a derived class requires that the entire definition be present for its own definition. So you just need to make sure that the outer class is completely defined before the inner class's... |
6,297,738 | 6,297,934 | How to build a full path string (safely) from separate strings? | Does C++ have any equivalent to python's function os.path.join? Basically, I'm looking for something that combines two (or more) parts of a file path so that you don't have to worry about making sure the two parts fit together perfectly. If it's in Qt, that would be cool too.
Basically I spent an hour debugging some co... | Check out QDir for that:
QString path = QDir(dirPath).filePath(fileName);
|
6,297,845 | 6,298,808 | QPainter error in GUI application | I'm trying to write a GUI that paints a graph onto it in C++. I am getting a list of errors, all of which say:
"QPainter::begin: Widget painting can onnly begin as a result of a paintEvent"
Nothing appears to be painting.
main.cpp
#include <QApplication>
#include <QFont>
#include <QPushButton>
#include <iostream>
usin... | From the Qt documentation:
Warning: When the paintdevice is a
widget, QPainter can only be used
inside a paintEvent() function or in a
function called by paintEvent(); that
is unless the
Qt::WA_PaintOutsidePaintEvent widget
attribute is set. On Mac OS X and
Windows, you can only paint in a
paintEvent()... |
6,298,001 | 6,298,050 | Value-initializing an automatic object? | I'm writing a template class and at one point in my code would like to be able to value-initialize an object of the parameterized type on the stack. Right now, I'm accomplishing this by writing something to this effect:
template <typename T> void MyClass<T>::doSomething() {
T valueInitialized = T();
/* ... */
... | The following uses copy-initialization, which is 'probably fine' 95% of the time in C++03:
T var = T();
But for generic (C++03) code, you should always prefer direct-initialization to account for that other 5%:
T var((T())); // extra parentheses avoid the most vexing parse – the extra parentheses
// forc... |
6,298,297 | 6,300,908 | Mingw build - depends on DLL not native to windows | I'm compiling my library for export as a shared library using MinGW (GCC 4.5.0). I do this by compiling all the source files using MAKE commands similar to:
gcc -shared -c mysource.cpp -o mysource.o
And then finally:
gcc -shared -lstdc++ -lm -lws2_32 mysource.o -o mylib.dll
When I do a dependency walk of my output fi... | The -static flag may be what you're looking for. (It still looks funny to me to use both -static and -shared on the same line, but they are not opposites.)
If you would use g++ as a driver instead of gcc, you could instead use the -static-libstdc++ flag.
|
6,298,333 | 6,298,369 | set_union on arbitrary structs - where have I gone wrong? | This is a continuation of my previous post that told me what to do nicely but implementing it didn't work :S. All I want is set_union (and the other set operations) in the C++ algorithm class to work on my structs. Here's what I have so far.
My struct:
struct player {
int lbl;
int lbl1;
bool operator<(co... | You should implement Strict weak ordering, because associative containers such as std::set, std::multiset, std::map, std::multimap require that the ordering of elements must be Strict Weak Ordering. And in your case, set_union operates on the data according to the std::set rules, which requires strict weak ordering b... |
6,298,389 | 6,299,205 | C++ Namespace 'using' declarative for a class' enum | I have a good understanding of how the C++ 'using' declaration and directive work. However, I'm stumped on this... Maybe it's not possible? I want to avoid having to quality my enum variables:
namespace Foo {
class MyClass {
public:
enum MyEnum { X, Y, Z };
}
}
And now, from outside that namespa... | C++03 does not support fully qualifying enum types, but it's an MSVC extension. C++0x will make this Standard, and I believe that you can using an enum in C++0x. However, in C++03, I don't believe that your problem can be solved.
|
6,298,458 | 6,298,506 | C++ template partial specialization question | I'm having compile time trouble with the following code:
template <typename T,
template <class T, class Allocator = std::allocator<T> > class C>
bool is_in(const C<T>& a, const C<T>& b);
template <typename T, std::vector> // HERE
bool is_in(const std::vector<T>& a, const std::vector<T>& b)
{
... | The partial specialization of a function template is not allowed by the Standard.
A simple solution is : use overload.
template <typename T>
bool is_in(const std::vector<T>& a, const std::vector<T>& b)
{
return false; // implementation tbd
}
This is overloaded function template. Its NOT partial specialization.
O... |
6,298,896 | 6,299,525 | When I send and convert std string with win32 SendMessage I'm getting weird characters | I need to append text to win32 edit control i have working function to do this , but the text that printed in the edit control is gibrish why ?
the sample code taken from microsoft example from here
void settext(HWND hDlg,std::string s)
{
//std::wstring ws;
//ws.assign( s.begin(), s.end() );
//LPWSTR pwst ... | My guess is that your app is compiled for Unicode and so the window is interpreting your ANSI C string as a Unicode C string, hence the characters from another language.
|
6,299,145 | 6,299,335 | Accessing Java byte[] in C++ | I have a Java application that persists byte[] structures to a DB (using Hibernate). I'm writing a C++ application that reads these structures at a later time.
As you might expect, I'm having problems.... The byte[] structure written to the DB is longer than the original number of bytes - 27 bytes, by the looks of th... | The object is probably being serialized using the Java Object Serialization Protocol. You can verify this by looking for the magic number 0xACED at the beginning. If this is the case, it's just wrapped with some meta information about the class and length, and you can easily parse the actual byte values off the end.
... |
6,299,266 | 6,299,463 | dynamic_cast of "this" inside constructor | This question is very similar to this one Why can't I dynamic_cast "sideways" during multiple inheritence?, except that the cast does work - just not inside in the constructor.
Header:
class A
{
public:
virtual ~A() {}
void printA();
};
class B
{
public:
... | Basically the standard says it will not work (dynamic_cast) during construction of an object.
<quote>
Edit: Added based on VJo comment below.
Note: The cast from a 'B' to an 'A' using dynamic cast should work because we are casting an object of type 'C'. If we added the following code to main:
B bObj;
B& bRef = c;
B*... |
6,299,468 | 6,299,510 | STL Container of Custom Classes Doesn't Hold Member's Values | I am having trouble using a container with my custom class. Every time I try to make an object and push it, the member variables in the pushed object show up as zero. So, myConnection.value appears 0 instead of its value. I suspect there is something wrong with my copy constructor.
Global Definition
vector<connection> ... | Your copy-constructor creates a temporary connection instance with the specified values and immediately destroys it, leaving the newly copy-constructed object completely uninitialized. A correct, idiomatic copy-constructor would be:
connection::connection(const connection& c)
: k(c.k),
order(c.order),
from(c.... |
6,299,572 | 6,299,634 | copying pointer to member functions from a structure | I have my code organized as following
class MyClass
{
public:
typedef void (MyClass::Ptr2func)();
}
struct abc
{
MyClass::Ptr2func ptr;
bool result;
}
void main()
{
MyClass myCls;
abc var;
//here is a lot of decision making code and pointer initializations
//I want to copy the pointer to ... | I believe that the problem is that your typedef
typedef void (MyClass::Ptr2func)();
Is not defining a typedef for a pointer to member function, but for a member function type. The typedef for a member function pointer would be
typedef void (MyClass::* Ptr2func)();
Notice the explicit pointer involved here. The type... |
6,299,701 | 6,300,589 | Overloading -> operator with temporary object | I'm writing a wrapper for a mesh class, trying to implement a more intuitive interface. The mesh uses somewhat dumb iterators that can be incremented and compared but not dereferenced; instead you must get their associated feature handle from the mesh. Similarly feature handles are dumb, so to get a position / color / ... | A custom operator-> has the particularity that it behaves as if operator-> is recursively called on the returned value. So given T some_type::operator->() const, this behaves as:
some_type()->some_member;
// moral equivalent:
some_type()::operator->()->some_member;
Usually it's not noticed because a plain pointer is r... |
6,299,786 | 6,415,147 | Problems with Bounding Box Frustum Culling | I am having trouble getting correct frustum culling to work. I got a great suggestion from someone about AABB point testing and it works great but I have gotten to the point where a max and a min point testing do not always work because often they won't be in the frustum but a plane from one of the sides will be. So I ... | You need to have the planes of the frustrum looking inside (their normals must point to the center). Then the rendering discard can be done by checking if the object is completelly outside of one of any of the six planes of the frustrum. You can do that with a sphere or with a AABB, or any other container where you can... |
6,299,967 | 6,300,005 | What are the use cases for having a function return by const value for non-builtin type? | Recently I have read that it makes sense when returning by value from a function to qualify the return type const for non-builtin types, e.g.:
const Result operation() {
//..do something..
return Result(..);
}
I am struggling to understand the benefits of this, once the object has been returned surely it's the... | Basically, there's a slight language problem here.
std::string func() {
return "hai";
}
func().push_back('c'); // Perfectly valid, yet non-sensical
Returning const rvalues is an attempt to prevent such behaviour. However, in reality, it does way more harm than good, because now that rvalue references are here, yo... |
6,300,083 | 6,308,093 | Tiling a large QGraphicsItem in a QGraphicsView | I am currently using a QGraphicsItem that I am loading a pixmap into to display some raster data. I am currently not doing any tiling or anything of the sort, but I have overriden my QGraphicsItem so that I can implement features like zooming under mouse, tracking whick pixel I am hovering over, etc etc.
My files that ... | It's not too surprising that there would be difficulty handling images that size. Qt just isn't designed for it and there are possibly other contributing factors due to the particular OS and perhaps the way memory is managed.
You very clearly need (or at least, should use) a tiling mechanism. Your main issue is that yo... |
6,300,203 | 6,300,327 | Can't use SFINAE, type traits and static_assert in MSVC10 | I've been investigating the use of some judicious static assertions to improve error messages. Here's an example:
#include <type_traits>
template<typename T> struct is_less_than_comparable {
template<typename Test> static char test(decltype(*static_cast<Test*>(nullptr) < *static_cast<Test*>(nullptr)));
template... | The problem is with VC++ 2010 handling of the metafunction is_less_than_comparable, not with static_assert.
If you change the code to:
static const bool value = std::is_same<double, decltype(test<T>(true))>::value;
Then it will be false regardless of which overload is picked. The assertion then fires.
Evidently the w... |
6,300,331 | 6,300,369 | An Extra Character At the End of Char Array (char *Result = new char) 8OI | I have a C++ function that splits LPSTR type variable an attact it into an char array (char*)
Example:
this->XMeshTexturePath = FindTexturePath(XMeshTexturePath,d3dxMaterials[i].pTextureFilename);
//the value of XMeshTexturePath is: Models\\Textures\\
//the value of d3dxMaterials[i].pTextureFilename is: BlaBlaBl... | char *Result = new char[PathLength+FileLength];
Result pointed data should end with the termination character \0. Or you will run into problems when returned such a string pointed by Result. So,
Result[PathLength+FileLength-1] = '\0' ;
Make sure you never overrun the buffer or even a better option is to use std::stri... |
6,300,676 | 6,301,090 | C++ OpenCV mat.at gives access violation when using data | I'm using openCV 2.1 in a visual studio 2010 C++ dll to do matrix operations. The dll recieves arrays from a VB.NET program and loads them into matrices for some manipulation. However I cannot use the .at member on any cv::mat object without throwing an access violation exception. I thought it was because I was passing... | The problem is that your created a matrix of float (32FC1) and you are trying to access it using double which causes an out of bound access.
You can either use float everywhere:
Mat Rhat(2,1,CV_32FC1);
Rhat.at<float>(0,0) = 10;
Rhat.release();
or double:
Mat Rhat(2,1,CV_64FC1);
Rhat.at<double>(0,0) = 10;
Rhat.release(... |
6,301,252 | 6,301,362 | What is the default allocator GCC uses for STL? | According to this link, gcc provides lots of interesting memory allocators to be used with STL containers, but which is used by default if I don't specify one when creating a std::list?
| As it says on that page you link to,
The current default choice for allocator is __gnu_cxx::new_allocator.
I.e, the default allocator is basically just operator new.
|
6,301,569 | 6,301,624 | Template program keeps crashing | My program will compile and run fine but it crashes when im in the program.
Any idea why?
template<class T>
T findFeq (T arr1[], T target, T arrSize);
template<class T>
T findFreq (T arr1[], T target, T arrSize){
int count = 0;
for(int i = 0; i < arrSize; i++){
if (target == arr1[i])
co... | There are several problems. But the problem which will cause a crash is,
for (int i = 0; i < maxSize; i++)
Just imagine what if you enter maxSize greater than arrSize ? The buffer will overflow and it causes either an Undefined behavior or crash. Same is applicable for while loop meant for filling double array.
On th... |
6,301,575 | 6,301,619 | How to access unnamed "enum class" encapsulated inside a class? | class A {
public: enum class { HELLO, WORLD };
};
Having known that, inside a class, declaring a simple enum (rather than enum class) is a better idea, because it's already typed with the class identification. But still above statement is a valid C++0x signature. Now how to access an unnamed enum class outside ?
int... | Actually, that is not valid. The C++0x FDIS says (9.2p1)
Except when used to declare friends (11.3) or to introduce the name of a member of a base class into a derived class (7.3.3), member-declarations declare members of the class, and each such member-declaration shall declare at least one member name of the class. ... |
6,301,578 | 6,304,436 | Down arrow key of my laptop? | The down arrow key of my laptop is very loose and it does not seems to last very long.
Is it possible to write any programm(in any language but especially C++) hat simulates the down arrow key.say I made a programm such that when I press A,B,C on the key board it simulates down arrow key.
If not then,
Is there any soft... | If you want to simulate input, use the SendInput API. This injects input at a fairly low level, windows automatically routes it to the appropriate thread based on who has focus. Call it twice, once to send the key down, and again to send the key up.
Perhaps the easiest thing to do is to write a simple app that calls Re... |
6,301,704 | 6,303,224 | Loading and using an HLSL shader? | I've been looking everywhere and all I can find are tutorials on writing the shaders. None of them showed me how to incorporate them into my scene.
So essentially:
Given an hlsl shader, if I were to have a function called drawTexturedQuad() and I wanted the shader to be applied to the result, how exactly could I do thi... | ID3DXEffect provides Begin() and BeginPass() methods. Simply call drawQuad() during that time. Any basic tutorial on shaders should show such a sample.
Just an additional note- if in doubt, ask MSDN.
|
6,302,195 | 6,302,328 | Where can I find a free or open source C++ library to do BCD math? | Where can I find a free or open source C++ library to do Binary Coded Decimal math?
| Here you go. I just wrote this, and am making it public domain.
It converts an unsigned bcd to an unsigned int and vice-versa. Use bcd2i() to convert your BCDs to unsigned ints, do whatever math you need, then use i2bcd() to bring the numbers back to BCD.
unsigned int bcd2i(unsigned int bcd) {
unsigned int deci... |
6,302,282 | 6,302,322 | How do I link libcurl to my c++ program in linux? | I need to use libcurl in a piece of software I am writing on my ubuntu machine. I am using Eclipse to write and compile all of the software. When I put the libcurl files in the same folder as the .cpp file, and include the curl.h file in the header, When I attempt to compile the program, It comes up with these errors:
... | Your header file inclusions are just fine; your problem is occurring at the linking step. In order to link against libcurl, you need to add the -lcurl command line option, assuming it's installed in a standard directory:
g++ -o sms ./src/sms.o -lcurl
If it's not installed in a standard directory, you also need to add... |
6,302,630 | 6,302,698 | small unit tests , msvc | When I do small unit tests (small exe that calls my function from my library, or calls a piece of code literally embedded before main(), it seems it takes 50 times quicker in Linux than in msvc:
1) In Linux:
vi test1.c; cut-and-paste includes.
cut-and-pase code. add int main(int
argc, char **argv) { declare_dat... | Nothing is stopping you from compiling and running your MSVC code from the command line. The actual compiler is a command-line tool, so if the IDE is getting in your way, just bypass it. You could even find a Windows port of Vi, and you'd have pretty much exactly the same workflow as on Linux.
But if you choose to use ... |
6,302,706 | 6,303,180 | Check whether iterator belongs to a list | Is there any way to check whether a given iterator belongs to a given list in C++?
| The obvious but invalid approach
You can't simply iterate through the list, comparing each iterator value to your "candidate".
The C++03 Standard is vague about the validity of == applied to iterators from different containers (Mankarse's comment on Nawaz's answer links http://www.open-std.org/jtc1/sc22/wg21/docs/paper... |
6,302,810 | 6,302,934 | How to auto link classes when compiling c++ in eclipse? | I am writing software in eclipse and i am using libcurl. In order for me to compile it, i have to go to the terminal(ubuntu) and after cd-ing to the directory wiht the .cpp file, i have to run this:
g++ -g -Wall -o myapp myapp.cpp -L/usr/local/lib -lcurl
How do I configure the eclipse compiler to run this when comilin... | project -> properties -> c/c++ build -> settings -> gcc c++ linker -> libraries
click on green + icon
add your library name (without -l)
|
6,302,850 | 6,303,093 | how to set win32 api c++ button background color and text color? | im using simple button in win32 application and i like to change its color and text
but i can't find from all searching in google how to do it.
i have this code that represent a button:
this is in the rc file :
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
IDD_DIALOG1 DIALOG 0, 0, 273, 209
STYLE DS_3DLOOK | DS_CENTER | DS_MO... | You can't, or at least you can't do so simply. If you want a coloured button then you need to set the owner-draw style and draw it yourself. Plain old buttons don't have customisable colours.
|
6,302,899 | 6,303,005 | Using std::copy - error C2679: can't find correct binary '=' operator | I am trying to use a solution from this question:
How do I iterate over cin line by line in C++?
The error message
c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(2144): error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const Line' (or there is no acceptabl... | Here is correct version that compiles fine :
class Line
{
std::string data;
public:
friend std::istream& operator>>(std::istream& inputStream, Line& line)
{
std::getline(inputStream, line.data);
return inputStream;
}
operator std::string() const
... |
6,303,011 | 6,303,030 | A c++ syntax question: class for method | in the code below, it has the following line
base_list(const base_list &tmp) :memory::SqlAlloc()
base_list is a method, memory is a namespace, SqlAlloc is a class, so what does it mean when combine them together?
class base_list :public memory::SqlAlloc
{
public:
base_list(const base_list &tmp) :memory::SqlAlloc... | base_list(const base_list &tmp) :memory::SqlAlloc()
Uses Initializer list to call constructor of class SqlAlloc inside namespace memory.
For more information on advantages of using Initializer List in C++, See this.
|
6,303,267 | 6,303,399 | Xcode 4 C++ header file with relative path to another header | I'm using a library with an include structure where the .h files are all in a single directory. These .h files contains a single line, a #include directive which points to the 'real' header file in specific source folder locations. The #include path in these files is relative.
So, here's an example. The directory struc... | From your directory structure it seems that the directories platformA and platformB are placed outside the include folder. There are two possible solutions to this:
Solution A
Move these
to include folder.
Solution B
Add project/platformA and
project/platformB to the
directories where include files
should b... |
6,303,269 | 6,303,331 | how to find the middle element of the map?? STL | Hi I am stuck in between the concept of Map in STL Library/C++.
int arr[] = {10,15,14,13,17,15,16,12,18,10,29,24,35,36};
int n = sizeof arr / sizeof *arr;
map<int, bool> bst;
map<int, bool>::iterator it;
vector<int> median_output;
const int k = 5;
for (int i = 0; i < k; ++i) {
bst.insert(make_pair(arr[i], true));... | map is a balanced search tree. To find it's middle - find it's size, and iterate from the begin() for half it's size - that will be the middle. Something like this:
for (it = bst.begin(), int middle = 0; middle < bst.size()/2; it++, middle++) {
cout << (*it).first << " ";
}
// now after the loop it is the median.
... |
6,303,435 | 6,303,496 | a private copy constructor: disallow | I'm programming in an open source library which has very little comments in the code, and absolutely no code related documentation, or such comments which show absolutely nothing or are completely confusing. An example class of the library is sometimes defined as follows (this is an abstracted short example):
class A
{... | It means pretty much what you said. Normally, the compiler would generate a copy constructor. To prevent this, you can define your own, and make it private. Then any attempt at copy-constructing the class will fail at compile-time, rather than silently doing the wrong thing.
|
6,303,513 | 6,303,595 | Why string==string comparison failing? | Following is the code snippet of what I did, can some body help me where I have wrongly coded it:
#include<iostream>
using namespace std;
void modifyName(string &name)
{
size_t sep = string::npos;
sep = name.find_first_of(".");
if(sep != string::npos) { name[sep] = '\0'; }
}
int main()
{
string name(... | As others have said, the strings don't match, as one is "test\0rtl" and the other is "test". It's fine to use == for std::string comparison, as the operator is overloaded for string equality. To do what you want, you should try replacing
if(sep != string::npos) { name[sep] = '\0'; }
with
if(sep != string::npos) { name... |
6,303,568 | 6,303,612 | Getting a value of a textfield from another application in Qt C++ | I am just wondering is there a way to get
the value of a textfield from another
application?
Windows OS
For example in window a textbox2 has a value of 1.
How would i get the value of textbox2 from another application then?
| Read up on IPC. You should be able to find a solution on that webpage that suits your needs.
|
6,304,071 | 6,304,184 | Which version of GCC introduced support for atomic builtins? | I see it's available in 4.1.0 but was it available earlier than this? I'm interested specifically in 3.4.3 but can't find a definitive answer.
| Looking at the online documentation, it seems the atomic builtins were added in the 4.1 release.
|
6,304,086 | 6,305,576 | How to compile a simple program with OpenSSL? | I am trying to compile a simple ssl program (it was taken from the openssl book source code).
The program has the following files: common.h common.c client.c server.c
I have installed openssl 0.9.7 so I have the same version with the book.
I have downloaded the source and ./Configure, make, make test, make install in t... | In some code versions of openssl book, the thread related functions are stored in reentrant.c, (in fact the declaration of TRHEAD_setup, in the version i've seen is there), so try with:
gcc -Wall common.c client.c reentrant.c -o client -lcrypto -lssl
|
6,304,259 | 6,415,754 | Can a class template explicit specialization also declare something else? | It would be nice if this code were invalid. But it's conceptually sound, and GCC accepts it although Comeau doesn't:
template< typename > struct t;
template<> struct t< int > {} r; // Bad declarator! Don't pee on the carpet!
(Edit: the above compiles but r seems no to be declared into any scope, so it is essentially ... | Explicit specialization and explicit instantiation do not declare a template. They declare a template-id which refers to a specialization, which is a class.
However, this doesn't validate my example. The problem is that everything declared following template or template<> is part of the explicit instantiation or specia... |
6,304,357 | 6,304,439 | Access violation on unusual program termination (C++) | The following minimum code examples runs fine when it is terminated normally (by pressing enter):
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
class SingletonLogClass
{
private:
SingletonLogClass() {}
public:
~SingletonLogClass()
{
LogMessage("~SingletonLogClas... | cout is a global object. Your singleton instance (defined as static in the getInstance static member function) is also a global object.
In C++, you cannot have control over the order of construction, neither destruction of global objects. As such, it is possible that the cout object is destructed before your SingletonL... |
6,304,721 | 6,304,758 | Is it possible to step through the members of a C++ struct? | I want to step through the members of a C++ struct and print out their values. I can easily code this explicitly, but is there any way of doing it without actually knowing what's in the struct?
I suppose I'm looking for a C++ equivalent of C#'s foreach command.
Thanks for any help.
ADD: I'm doing something like this in... | You could overload operator<< for your struct, then you only have to write the code once.
|
6,304,981 | 6,305,025 | C++0x initializer list passed by reference | I have tried to use C++0x initializer list as argument to a constructor call in this way:
Foo<float> foo("Foo 1", std::vector<const char *>({ "foo A", "foo B" }) );
with the constructor
Foo(const char *name, std::vector<const char *> &foos)
With this constructor the compiler complained:
error: no matching function fo... | You cannot bind a temporary to a T&.
You can bind a temporary to T const&:
Foo(const char* name, std::vector<const char*> const& foos)
But I'd question the sanity of a vector of char pointers. What's wrong with std::string?
|
6,305,296 | 6,305,368 | How do I know what standard formats the compiler supports? | I know one format is "IEEE 754 floating point standard"
To check if a C++ compiler uses the IEEE 754 floating point standard or not
std::numeric_limits<float>::is_iec559;
What other standard formats are there?
How do I check that the C++ compiler is following that format or not?
EDIT : how many Types of Format are... | You don't, numeric_limits is clearly designed with IEEE 754 in mind. You only get to know if the implementation is IEEE 754 compliant, or not.
But keep in mind that you should use has_infinity, has_quiet_NaN etc. to check for individual features - basically, you check for certain features, not for specific floating poi... |
6,305,396 | 6,305,429 | What's this C++ syntax that puts a brace-surrounded block where an expression is expected? | I came across this weird C++ program.
#include <iostream>
using namespace std;
int main()
{
int a = ({int x; cin >> x; x;});
cout << a;
}
Can anyone explain what is going on? What is this construct called?
| It assigns user input value to a and prints it out. it is done by using a Statement Expression.
Statement Expressions are a gnu gcc compiler extension and are not supported by the C/C++ standards. Hence, any code which uses statement expression is not standard conforming and non-portable.
The IBM XL C/C++ v7.0 also sup... |
6,305,488 | 6,305,903 | GCC - how to compile FFMpeg with FLV1 (aka H.263), MP3 (format and codec) and FLV (container format) only? | So I want to compile FFMpeg C libraries (as static) not in its full default glory but for my purposes only - so that it would contain:
2 codec formats MP3 and FLV1 (H.263)
2 file (container) formats MP3 and FLV
Of course I only want to limit only range of formats and codecs. Not functions of FFmpeg.
How to do such t... | The configure script has a list of options. Run ./configure --help to see them. I'm not sure how options stack, but you could try --disable-everything followed by --enable-demuxer=flv etc.
|
6,305,516 | 10,576,525 | Problem with hooking ntdll.dll calls | I'm currently working on hooking ntdll.dll calls via dll injection.
At first, I create thread in existing process via CreateRemoteThread() then I load my dll via LoadLibrary and finally hook calls on PROCESS_ATTACH.
Injection works fine, but then I want to log all registry and file system queries. And the problem is th... | If you use OllyDbg, ZwOpenKey starts with 5 bytes MOV EAX, 77.
You can overwrite these bytes like so JMP _myZwOpenKey then from there you can do whatever with the values on the stack, restore all registers then do a JMP 7C90D5B5 which is address of ZwOpenKey + 5 bytes.
CPU Disasm
Address Hex dump Command ... |
6,305,554 | 6,307,142 | c++ dynamic library dlopen error | I have two files:
RollDice.cpp
#include "RollDice.h"
#include "./IPlugins.cpp"
#include "./IPluginFunctions.cpp"
#include <iostream>
RollDice::RollDice(IPluginFunctions &iPluginFunctions) :
IPlugins(iPluginFunctions) {
//srand(time(NULL));
}
RollDice::~RollDice() {
}
void RollDice::callPlugin(std::string p... | One thing to check that doesn't seem to have been mentioned yet is that the exact name 'create' must be exported from your shared library.
Try
nm --dynamic --defined-only RollDice.so | grep create
If you get no matches, or get some mangled symbol for 'create', then your dlsym(..., "create") call is bound to fail.
Also... |
6,305,590 | 6,305,653 | Regular expression in sed to replace C++ includes | I'm trying to play with sed, to change all;
#include "X"
to:
#include <X>
However I can't seem to find a way to do this! - This is what I've done so far:
sed -i 's/#include ".*"/#include <.*>/g' filename
I think I'm in need of a variable to save the contains of ".*", i'm just unaware of how!
| Yes, you do. Regexps use () to save the contents of a match and a \1 to retrieve it. If you use more than one set of (), then the 2nd match is in \2 , and so on.
sed -e 's/#include "\(.*\)"/#include <\1>/g' < filename
will do what you need.
|
6,305,613 | 6,305,879 | C++ How to catch Mouse wheel up and down? | Is there any ascii value for mouse wheel up and down.
I found this for mouse wheel, but this one does not care if I'm scrolling down or up 8) and acting in boot states.
case 0x020A: //MOUSE Whell
{
g_fDistance += 0.5f;
}break;
Thanks for any help and suggestions.
| No ascii for this, ascii is for characters, not hardware inputs.
I always use a device inputs library like OIS to do this : http://sourceforge.net/projects/wgois/
It does all the translation work for you to get clear transformed input informations about keyboards, joysticks, mouses, wiimote...
That way I avoid OS-speci... |
6,305,749 | 6,312,024 | DataExchange for many variables | I'm new to MFC and creating basically a "preferences" tool. This of course means that there is a lot of input from the user. I have several "pages", each filled with a combination of text boxes and combo boxes, and I'm trying to figure out the best way to execute the DoDataExchange methods for each dialog class.
Of cou... | Just use the wizard, it will automatically map the variable name to the dialog: right click on the dialog and Add variable, no need to write them manually.
|
6,305,906 | 6,306,106 | Why does operator ++ return a non-const value? | I have read Effective C++ 3rd Edition written by Scott Meyers.
Item 3 of the book, "Use const whenever possible", says if we want to prevent rvalues from being assigned to function's return value accidentally, the return type should be const.
For example, the increment function for iterator:
const iterator iterator::op... | I'm pretty sure that this is because it would play havoc with rvalue references and any sort of decltype. Even though these features were not in C++03, they have been known to be coming.
More importantly, I don't believe that any Standard function returns const rvalues, it's probably something that wasn't considered un... |
6,305,977 | 6,306,771 | A question about exporting a C++ class to C | I've been reading about exporting a C++ class so that C can use it. I've followed this good example from Parashift, and a question came out.
To hold the memory allocated to the C++ class, we define the following structure
typedef struct A A;
So that A* can point to the address of the class A. My question is: does it m... | No, you shouldn't use void* by this. A pointer to an incomplete type struct A is a much better technique. This avoids that you mix pointers to different opaque types by accident. If you'd typedef it to void you could assign a pointer of your opaque type to any other data pointer. Probably not what you want.
Using an in... |
6,306,045 | 6,306,769 | Installing LibCurl on Visual Studio 2010 | I've been having a bit of trouble using LibCurl with Visual Studio 2010. Keep in mind I'm pretty new to C++.
I built the library according to the instructions on the libcurl website and tried to point my project to the include directory, libcurl.lib, etc but when I try to build the project I get a bunch of LNK2019 erro... |
error LNK2001: unresolved external symbol __imp__send@16
Hurray, we have an error message. Add ws2_32.lib to the Additional Dependencies setting. The MSDN Library lists the required import library at the bottom of the article for each API function.
Interpreting the linker error is important to diagnose these errors... |
6,306,231 | 6,306,443 | Write C++ container that fits neatly into STL | I would like to write a container class in a style which fits very neatly into STL. It should look and behave as if it where a standard STL container.
Is there a manual, report, Q&A, etc., out there that describes how to write code with these set of features? Such a text should compromise design principles of the STL, ... | It is not very difficult (for simple data stuctures). You should read the chapter about containers in the C++ standard. You can download the draft of the upcoming C++1x standard here :
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/#mailing2011-04
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.p... |
6,306,250 | 6,306,357 | C++ equivalent of C#'s Func<T, TResult> | The following code computes the average of a particular property of T in the items collection:
public double Average<T>(IList<T> items, Func<T, double> selector)
{
double average = 0.0;
for (int i = 0; i < items.Count; i++)
{
average += selector(items[i])
}
return average / items.Count;
}
... | The equivalent thing would be a std::function<double(T)>. This is a polymorphic function object which may accept any function object that has the correct operator(), including lambdas, hand-written functors, bound member functions, and function pointers, and enforces the correct signature.
Do not forget that in C#, the... |
6,306,261 | 6,306,349 | What exception guarantees do gcc atomic builtins offer? | I cannot find documentation which states what exception guarantees (none, basic, strong, nothrow) the gcc atomic builtins (e.g. __sync_synchronize()) offer. Can anyone provide details on this?
| Since they are usable in C, which does not have exceptions, none of them will throw.
|
6,306,317 | 6,306,370 | Virtual Template Workarounds | I have a template container class that I derive from called MyContainer. MyContainer defines methods like Get(), Set(), etc. to access individual elements. I'd like to make a bitfield class implemented as a MyContainer<char>, where each char element holds CHAR_BIT number of bits. However, to allow the user to operat... | It is not illegal, only template virtual member functions are.
// valid
template<typename T> class MyContainer {
virtual void set(const T &) = 0;
}
// not valid
class MyContainer {
template <typename T> virtual void set (const T &) = 0;
}
If I got you wrong, please consider placing a code-sample.
edit after y... |
6,307,070 | 6,307,090 | A question about class definition in C++ " : 1" |
Possible Duplicate:
What does 'unsigned temp:3' means
I encountered a problem when I'm reading the code of Clang.
class LangOptions {
public:
unsigned Trigraphs : 1; // Trigraphs in source files.
unsigned BCPLComment : 1; // BCPL-style '//' comments.
...
};
This is the first time I saw t... | It's a bitfield, which means that the value will only use one bit, instead of 32 (or whatever sizeof(unsigned) * <bits-per-byte> is on your platform).
Bitfields are useful for writing compact binary data structures, although they come with some performance cost as the compiler/CPU cannot update a single bit, but needs ... |
6,307,230 | 6,307,249 | 2-dimensional vector | When I create a 2-dimensional vector in c++ such as
vector < vector<int> > matrix(3, vector<int>(4));
would matrix[2][3] be accessible or would matrix[3][2] be accessible?
| You created the first dimension as 3 and the second as 4. That means that matrix[3] is out of bounds. The other way around, though, would be fine- and would be fine regardless of which is which.
|
6,307,321 | 6,307,367 | Does it make sense to make std::map key const? | When defining a std::map, does it make sense to make the key type const?
| The key is already const, actually, because a key cannot change once an element was inserted in the map.
|
6,307,352 | 6,307,474 | Bignum divison and value assignment in c++ | I'm writing my own bignum class for operating on large numbers. So far I've overloaded the operator= and operator+. How do I perform long division?
Also, right now I can only assign values within the range of integers to the bignum object. How do I assign values that fall outside the int range? Is it possible to do thi... | For assigning big numbers the usual way is strings. This usually only happens at the interface to your calculations and so is not a problem. Another way would be to have a template constructor that takes a range of chars that you interpret as a Two's Compliment number (I prefer this method, but I havent seen it used ve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.