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 |
|---|---|---|---|---|
2,705,141 | 2,705,165 | how to back to the first of text file | i have a txt file which have some lines ...and my code is :
string line;
ifstream myfile("c:\\main.txt");
bool passport = true;
while(passport==true){
int pos1=0;
cout<<setw(20)<<"PassPort_Number : ";
cin>>add.Id ;
if (myfile.is_open())
{
while(!myfile.eof()){
getline(myfile,line);
pos1+=line.find(add.Id);
cout<<pos1;
}
}
if(pos1<0)
passport=false;
else {
cout<<"PassPort Number tekrariye :d"<<endl;
}
}
first time everything is ok but at the second time of running it doesn't enter to second while (while(!myfile.eof() ) ...
what's wrong with my code?
when it goes to the end of text file it doesn't back to the first of file at the next loop ... how can i back to the first of text file ?
| Call:
myfile.seekg(0, ios::beg);
to set the file read pointer back to the beginning.
|
2,705,173 | 2,705,316 | Designing a state machine in C++ | I have a little problem that involves modeling a state machine.
I have managed to do a little bit of knowledge engineering and 'reverse engineer' a set of primitive deterministic rules that determine state as well as state transitions.
I would like to know what the best practices are regarding:
How to rigorously test my states and state transitions to make sure that the system cannot end up in an undetermined state.
How to enforce state transition requirements (for example, it should be impossible to go directly from stateFoo to StateFooBar, i.e. to imbue each state with 'knowledge' about the states it can transition to.
Ideally, I would like to use clean, pattern based design, with templates wherever possible.
I do need somewhere to start though and I would be grateful for any pointers (no pun intended), that are sent my way.
| Be sure to take a look at the Boost Statechart Library.
|
2,705,181 | 2,705,453 | Compile/use unrar C++ source for iphone app? | Writing an app that will include the ability to decompress zip and rar files. I think I'm OK on how to handle the .zips but .rars seem a little more trouble. I noticed that rarlabs has source available but it's C++. Is there a way to compile, wrap or otherwise use this code within an iPhone app?
Reference: http://www.rarlab.com/rar_add.htm
Open to alternate suggestions on how to handle .rar files as well.
I'm still pretty much a newbie so please explain in small words :)
| If all you need is to decompress RAR files, this library may be much easier for you to compile since it's a single C source file:
http://www.unrarlib.org/features.html
I had looked at compiling the library you mentioned, but there were a lot of errors and it was not initially apparent just how to resolve some of them (file type was not the issue).
|
2,705,183 | 2,705,209 | struct constructor + function parameter | I am a C++ beginner. I have the following code, the reult is not what I expect. The question is why, resp. what is wrong. For sure, the most of you see it at the first glance.
struct Complex {
float imag;
float real;
Complex( float i, float r) {
imag = i;
real = r;
}
Complex( float r) {
Complex(0, r);
}
std::string str() {
std::ostringstream s;
s << "imag: " << imag << " | real: " << real << std::endl;
return s.str();
}
};
class Complexes {
std::vector<Complex> * _complexes;
public:
Complexes(){
_complexes = new std::vector<Complex>;
}
void Add( Complex elem ) {
_complexes->push_back( elem );
}
std::string str( int index ) {
std::ostringstream oss;
Complex c = _complexes->at(index);
oss << c.str();
return oss.str();
}
};
int main(){
Complexes * cs = new Complexes();
//cs->Add(123.4f);
cs->Add(Complex(123.4f));
std::cout << cs->str(0); return 0; }
for now I am interested in the basics of c++ not in the complexnumber theory ;-)
it would be nice if the "Add" function does also accept one real (without an extra overloading) instead of only a Complex-object is this possible?
many thanks in advance
Oops
| You can't call one constructor in the body of another one like that:
Complex( float r) {
Complex(0, r);
}
In C++ it creates a temporary object of class Complex which immediately gets destroyed.
You could use default parameters in the constructor or some private method that would be called by constructors
|
2,705,269 | 2,705,276 | Why size_t arguments in template declaration need to be const? | I can have
std::bitset< 10 > bitsetA;
or
const size_t LengthB = 20;
std::bitset< LengthB > bitsetB;
without any problem.
But, if the length is not const
size_t LengthC = 30;
std::bitset< LengthC > bitsetC; // Line 30, say
I face the following compilation error
'LengthC' cannot appear in a constant-expression
template argument 1 is invalid
What is the reason for that?
What would be the problem, for compiler and for user code, if line 30 was to be accepted? Is it because LengthC might have some alias?
| Template arguments have to be declared const at compile time so that the template can be instantiated at compile time.
In the example you give, it does indeed appear that LengthC isn't going to change from the point where it is initialized to the point where the template has to be instantiated, so it could be treated as constant, but the compiler is not obligated to figure that out. The spec says the arguments have to be declared const, so that no compile-time flow control analysis needs to be done.
|
2,705,439 | 2,705,448 | Where does abort() and terminate() "live"? | Regarding the terminate handler,
As i understand it, when something bad happens in code, for example when we dont catch an exception,
terminate() is called, which in turn calls abort()
set_terminate(my_function) allows us to get terminate() to call a user specified function my_terminate.
my question is: where do these functions "live" they don't seem to be a part of the language, but work as if they are present in every single cpp file, without having to include any header file.
| If there are default handler functions for terminate and abort that you did not install yourself, they'd have to be in the runtime library provided by your compiler.
Normally, every program is linked against the runtime library (e.g. glibc under Linux). Among other reasons, this is because the runtime library contains "hidden" code for essential things, e.g. code that calls your main function at startup.
|
2,705,442 | 2,705,525 | Debugging MinGW program with gdb on Windows, not terminating at assert failure | How do I set up gdb on window so that it does not allow a program with assertion failure to terminate? I intend to check the stack trace and variables in the program.
For example, running this test.cpp program compiled with MinGW 'g++ -g test.cpp -o test' in gdb:
#include <cassert>
int main(int argc, char ** argv) { assert(1==2); return 0; }
Gives:
$ gdb test.exe
GNU gdb 6.8
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-pc-mingw32"...
(gdb) r
Starting program: f:\code/test.exe
[New thread 4616.0x1200]
Error: dll starting at 0x77030000 not found.
Error: dll starting at 0x75f80000 not found.
Error: dll starting at 0x77030000 not found.
Error: dll starting at 0x76f30000 not found.
Assertion failed: 1==2, file test.cpp, line 2
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Program exited with code 03.
(gdb)
I would like to be able to stop the program from terminating immediately, like how Visual Studio's debugger and gdb on Linux does it. I have done a search and found some stuff on trapping signals but I can't seem to find a good post on how to set up gdb to do this.
| Just set a breakpoint on exit:
(gdb) b exit
|
2,705,459 | 2,705,572 | 1>Project : error PRJ0003 : Error spawning 'rc.exe' | 1>Project : error PRJ0003 : Error spawning 'rc.exe'.. this is the error i get when i try to run this small practice program of reading and writing files which i cant do because of the reason of me not being able to get the files to open correctly. i use microsoft visual c++ 2008 and i have used the file path to try to open the file as well and i cant can someone help?
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ifstream infile;
ofstream myfile;
int num;
infile.open("example.txt");
if(infile.fail())
{
cout << "error" << endl;
}
myfile.open ("example.txt");
if(infile.fail())
{
cout << "error" << endl;
}
while(!infile.eof())
{
example >> num;
}
while(!myfile.eof())
{
example << num;
}
infile.close();
myfile.close();
return 0;
}
| There's something wrong with your setup of Visual Studio, it should never have any trouble finding and running rc.exe. First thing to check if the file is there. It should be located in c:\program files\microsoft sdks\windows\v6.0a\bin\rc.exe.
Next thing to check is that the paths are set properly. Tools + Options, Projects and Solutions, C++ Directories. Upper right: Show directories for = Executable files. Verify that $(WindowsSdkDirs)\bin is listed there. Try adding the folder name explicitly. If the latter step works then your registry is messed up. Despair a bit, rerun Setup.exe and choose Repair.
|
2,705,554 | 2,705,898 | runtime library and global namespace | Does the runtime library pollute the global namespace?
| The runtime library is required to use reserved identifiers. Without namespace qualification, these must begin with two underscores: __start, etc.
You are not allowed to use reserved names. The library is not allowed to use your names. If either crosses over to the other, it is "pollution" which is illegal.
Essentially, the situation is the same for C and C++ except, as the other answers point out, in C++ most standard library names have namespace qualification.
|
2,705,701 | 2,705,710 | My First Go With Function Templates | Thought it was pretty straight forward.
But I get a "iterator not dereferencable" errro when running the below code.
What's wrong?
template<typename T>
struct SumsTo : public std::binary_function<T, T, bool>
{
int myInt;
SumsTo(int a)
{
myInt = a;
}
bool operator()(const T& l, const T& r)
{
cout << l << " + " << r;
if ((l + r) == myInt)
{
cout << " does add to " << myInt;
}
else
{
cout << " DOES NOT add to " << myInt;
}
return true;
}
};
void main()
{
list<int> l1;
l1.push_back(1);
l1.push_back(2);
l1.push_back(3);
l1.push_back(4);
list<int> l2;
l2.push_back(9);
l2.push_back(8);
l2.push_back(7);
l2.push_back(6);
transform(l1.begin(), l1.end(), l2.begin(), l2.end(), SumsTo<int>(10) );
}
| Your functor is fine. The problem is in the call to transform.
Transform has the prototype
transform(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _OutputIterator __result,
_BinaryOperation __binary_op)
your call is
transform(l1.begin(), l1.end(), l2.begin(), l2.end(), SumsTo<int>(10) );
instead of l2.end(), the fourth iterator argument needs to be the beginning of the result sequence. It should reference a sequence of objects that you can construct from bool.
If you want to save the results into l2, then you want
transform(l1.begin(), l1.end(), l2.begin(), l2.begin(), SumsTo<int>(10) );
As GMan suggests, another approach is std::back_inserter from <iterator>:
vector<bool> sums10; // vector<bool> is Good Enough for Me
transform(l1.begin(), l1.end(), l2.begin(), back_inserter(sums10), SumsTo<int>(10) );
|
2,705,780 | 2,705,830 | How to use length indicator in a C++ program | I want to make a program in C++ that reads a file where each field will have a number before it that indicates how long it is.
The problem is I read every record in object of a class; how do I make the attributes of the class dynamic?
For example if the field is "john" it will read it in a 4 char array.
I don't want to make an array of 1000 elements as minimum memory usage is very important.
| In order to do this, you need to use dynamic allocation (either directly or indirectly).
If directly, you need new[] and delete[]:
char *buffer = new char[length + 1]; // +1 if you want a terminating NUL byte
// and later
delete[] buffer;
If you are allowed to use boost, you can simplify that a bit by using boost::shared_array<>. With a shared_array, you don't have to manually delete the memory as the array wrapper will take care of that for you:
boost::shared_array<char> buffer(new char[length + 1]);
Finally, you can do dynamic allocation indirectly via classes like std::string or std::vector<char>.
|
2,705,927 | 2,706,223 | Get specific process memory space | I have a pointer (void *) to a function and I want to know which process this function belongs to. I have no idea which way to go about it, but I think it's possible by using some form of VirtualQuery trickery. Any help would be appreciated.
Thanks in advance,
CLARIFICATION: By "belong to process" I mean what process the function is in. For example:
say there was an executable (test.exe) loaded in memory. This executable contains a function named SayHello, which is located at 0xDEADBEEF in memory. In an entirely different process, how would I know 0xDEADBEEF is in test.exe's memory space.
Hope that clears things up.
CLARIFICATION 2: I'm sure you're familiar with "VTable hooking", where an external module changes a VTable pointer in a seperate process to point to a different function. Thereby whenever the hooked member is called, it is passed to the external module.
To prevent this (anti-cheat), I want to be able to check whether all methods of a VTable point to the module they reside in.
SOLUTION CODE:
template<class T>
inline void **GetVTableArray(T *pClass, int *pSize)
{
void **ppVTable = *(void ***)pClass;
if(pSize)
{
*pSize = 0;
while(!IsBadReadPtr(ppVTable[*pSize], sizeof(UINT_PTR)))
(*pSize)++;
}
return ppVTable;
}
bool AllVTableMembersPointToCurrentModule(void *pClass)
{
DWORD dwOldProtect;
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
MODULEENTRY32 moduleEntry;
// Take a snapshot of all modules in the specified process
hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if(hModuleSnap == INVALID_HANDLE_VALUE)
return false;
// Set the size of the structure before using it
moduleEntry.dwSize = sizeof(MODULEENTRY32);
// Retrieve information about the first module (current process)
if(!Module32First(hModuleSnap, &moduleEntry))
{
CloseHandle(hModuleSnap);
return false;
}
// Grab the base address and size of our module (the address range where
// the VTable can validly point to)
UINT_PTR ulBaseAddress = reinterpret_cast<UINT_PTR>(moduleEntry.modBaseAddr);
UINT_PTR ulBaseSize = moduleEntry.modBaseSize;
// Get the VTable array and VTable member count
int nMethods;
void **ppVTable = GetVTableArray(pClass, &nMethods);
#ifdef VTABLE_FAKING
// Allow patching
VirtualProtect(ppVTable, nMethods * sizeof(UINT_PTR), PAGE_EXECUTE_READWRITE, &dwOldProtect);
// Now take the next module and set the first VTable pointer to point to an
// invalid address, outside of the current module's address range
Module32Next(hModuleSnap, &moduleEntry);
ppVTable[0] = moduleEntry.modBaseAddr;
#endif
// Don't allow people to overwrite VTables (can easily be bypassed, so make
// sure you check the VirtualProtect status of the VTable regularly with
// VirtualQuery)
VirtualProtect(ppVTable, nMethods * sizeof(UINT_PTR), PAGE_EXECUTE, &dwOldProtect);
// Clean up the snapshot object
CloseHandle(hModuleSnap);
// Ensure all VTable pointers are in our current module's address range
for(int i = 0; i < nMethods; ++i)
{
// Get address of the method this VTable pointer points to
UINT_PTR ulFuncAddress = reinterpret_cast<UINT_PTR>(ppVTable[i]);
// Check the address is within our current module range
if(ulFuncAddress < ulBaseAddress || ulFuncAddress > ulBaseAddress + ulBaseSize)
return false;
}
return true;
}
| The hijacked function pointer in the VTable can only be inside your process, as the other folks have already answered. The memory address only makes sense for your process. If someone is going to overwrite one of your VTable spots, then they would first have to hook something your process, which means running code inside your process. There exists plenty of win API that provides hooking.
See EnumProcessModule to go through all of the modules in your process. See this about modules info including base address of your module. You would then have to check your VTables to make sure those addressed exist inside of your module's address range.
To prevent VTable hijacking in the first place? I don't know how to do this, other than trying Microsoft's Detours library, which can in theory be used to detour any hook API call inside your process.
|
2,706,009 | 2,706,013 | C++: namespace conflict between extern "C" and class member | I stumbled upon a rather exotic c++ namespace problem:
condensed example:
extern "C" {
void solve(lprec * lp);
}
class A {
public:
lprec * lp;
void solve(int foo);
}
void A::solve(int foo)
{
solve(lp);
}
I want to call the c function solve in my C++ member function A::solve. The compiler is not happy with my intent:
error C2664: 'lp_solve_ilp::solve' : cannot convert parameter 1 from 'lprec *' to 'int'
Is there something I can prefix the solve function with? C::solve does not work
| To call a function in the global namespace, use:
::solve(lp);
This is needed whether the function is extern "C" or not.
|
2,706,040 | 2,706,053 | 'Scanner' does not name a type error in g++ | I'm trying to compile code in g++ and I get the following errors:
In file included from scanner.hpp:8,
from scanner.cpp:5:
parser.hpp:14: error: ‘Scanner’ does not name a type
parser.hpp:15: error: ‘Token’ does not name a type
Here's my g++ command:
g++ parser.cpp scanner.cpp -Wall
Here's parser.hpp:
#ifndef PARSER_HPP
#define PARSER_HPP
#include <string>
#include <map>
#include "scanner.hpp"
using std::string;
class Parser
{
// Member Variables
private:
Scanner lex; // Lexical analyzer
Token look; // tracks the current lookahead token
// Member Functions
<some function declarations>
};
#endif
and here's scanner.hpp:
#ifndef SCANNER_HPP
#define SCANNER_HPP
#include <iostream>
#include <cctype>
#include <string>
#include <map>
#include "parser.hpp"
using std::string;
using std::map;
enum
{
// reserved words
BOOL, ELSE, IF, TRUE, WHILE, DO, FALSE, INT, VOID,
// punctuation and operators
LPAREN, RPAREN, LBRACK, RBRACK, LBRACE, RBRACE, SEMI, COMMA, PLUS, MINUS, TIMES,
DIV, MOD, AND, OR, NOT, IS, ADDR, EQ, NE, LT, GT, LE, GE,
// symbolic constants
NUM, ID, ENDFILE, ERROR
};
class Token
{
public:
int tag;
int value;
string lexeme;
Token() {tag = 0;}
Token(int t) {tag = t;}
};
class Num : public Token
{
public:
Num(int v) {tag = NUM; value = v;}
};
class Word : public Token
{
public:
Word() {tag = 0; lexeme = "default";}
Word(int t, string l) {tag = t; lexeme = l;}
};
class Scanner
{
private:
int line; // which line the compiler is currently on
int depth; // how deep in the parse tree the compiler is
map<string,Word> words; // list of reserved words and used identifiers
// Member Functions
public:
Scanner();
Token scan();
string printTag(int);
friend class Parser;
};
#endif
anyone see the problem? I feel like I'm missing something incredibly obvious.
| parser.hpp incluser scanner.hpp and vice versa.
So one file evalated before the other.
You can use a forward declaration like
class Scanner;
or reorginaze your headers
|
2,706,076 | 2,706,145 | new >> how would i read a file that has 3 columns and each column contains 100 numbers into an array? | int exam1[100];// array that can hold 100 numbers for 1st column
int exam2[100];// array that can hold 100 numbers for 2nd column
int exam3[100];// array that can hold 100 numbers for 3rd column
int main()
{
ifstream infile;
int num;
infile.open("example.txt");// file containing numbers in 3 columns
if(infile.fail()) // checks to see if file opended
{
cout << "error" << endl;
}
while(!infile.eof()) // reads file to end of line
{
for(i=0;i<100;i++); // array numbers less than 100
{
while(infile >> [exam]); // while reading get 1st array or element
???// how will i go read the next number
infile >> num;
}
}
infile.close();
}
| int exam1[100];// array that can hold 100 numbers for 1st column
int exam2[100];// array that can hold 100 numbers for 2nd column
int exam3[100];// array that can hold 100 numbers for 3rd column
int main() // int main NOT void main
{
ifstream infile;
int num = 0; // num must start at 0
infile.open("example.txt");// file containing numbers in 3 columns
if(infile.fail()) // checks to see if file opended
{
cout << "error" << endl;
return 1; // no point continuing if the file didn't open...
}
while(!infile.eof()) // reads file to end of *file*, not line
{
infile >> exam1[num]; // read first column number
infile >> exam2[num]; // read second column number
infile >> exam3[num]; // read third column number
++num; // go to the next number
// you can also do it on the same line like this:
// infile >> exam1[num] >> exam2[num] >> exam3[num]; ++num;
}
infile.close();
return 0; // everything went right.
}
I assume you always have 3 numbers per line. If you know the exact number of lines, replace the while with a for from 0 to the number of lines.
|
2,706,112 | 2,706,121 | C++ Exact difference between having myMethod(Thing& a) or myMethod(Thing a)? | What is the exact difference between having myMethod(Thing& a) or myMethod(Thing a)? Because later you still ned to use &a if you want the address of the object.. I'm not sure when to use what..
| Three differences:
With a reference, you have a "shared" instance. So if you modify a you change the original and vice versa.
Performance. With Thing a you invoke the copy constructor. If the copy constructor has to do a lot of things, that could affect how fast the code runs.
A reference is guaranteed to work. If the class has a private copy constructor, you will not be able to do Thing a but you can always do Thing &a.
Finally, if you don't intend for the caller to be able to change the underlying object, you should probably pass by const reference (const Thing &a)
|
2,706,129 | 2,706,136 | Can a c++ class include itself as an member? | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
class Node {
char *cargo;
Node left;
Node right;
};
I can't declare left or right as Node types.
| No, because the object would be infinitely large (because every Node has as members two other Node objects, which each have as members two other Node objects, which each... well, you get the point).
You can, however, have a pointer to the class type as a member variable:
class Node {
char *cargo;
Node* left; // I'm not a Node; I'm just a pointer to a Node
Node* right; // Same here
};
|
2,706,132 | 2,706,189 | Handling Messages in Console Apps/DLLs in C++ Win32 | I would like to have the ability to process Win32 messages in a console app and/or inside a standalone DLL.
I have been able to do it in .NET with the following article and it works great in C# inside a console app and standalone DLL
http://msdn.microsoft.com/en-us/magazine/cc163417.aspx
Is there a way to do the equivalent with C/C++ Win32 APIs? I have tried doing RegisterClassEx(...) and CreateWindow(...) even passing in HWND_MESSAGE to hWndParent but the trouble is that after the "invisible" window is created messages are not being processed probably due to the lack of a message pump.
Where would the message pump go if you had a DLL entry point? I have tried creating another thread in a DLL and put while(GetMesage(..)) there but that did not work either.
Any ideas?
| You need a message pump yes. The window also has thread affinity so it needs to be created on the same thread that you're running the message pump on. The basic approach is sound, if you include more code it may become clear what the problem is.
|
2,706,198 | 2,706,230 | how to pass an array into an function and in the function count how many numbers are in a range? | #include <iostream>
#include <fstream>
using namespace std;
int calculate_total(int exam1[], int exam2[], int exam3[]); // function that calcualates grades to see how many 90,80,70,60
int exam1[100];// array that can hold 100 numbers for 1st column
int exam2[100];// array that can hold 100 numbers for 2nd column
int exam3[100];// array that can hold 100 numbers for 3rd column
// here i am passing an array into the function calcualate_total
int calculate_total(exam1[],exam2[],exam3[])
{
int above90=0, above80=0, above70=0, above60=0;
if((num<=90) && (num >=100))
{
above90++;
{
if((num<=80) && (num >=89))
{
above80++;
{
if((num<=70) && (num >=79))
{
above70++;
{
if((num<=60) && (num >=69))
{
above60++;
}
}
}
}
}
}
}
}
| use a vector.
you can initialize a vector like an array.
the vector has a method to give you the number of elements
|
2,706,245 | 2,706,312 | read pair of characters separated by \t c++ | Friends,
I want to read a pair of characters separated by \t. I want to continue reading the input until user enters z for any of the characters.
Here are the options I thought:
while (cin>>ch1>>ch2)
{
// process ch1 & ch2
}
std::string str;
while (getline(cin, str) ){
//split string
}
Also, I want to validate the input to make sure that it is correct. Please suggest the best way. If this is a duplicate, please point me to the right one.
Thanks.
| Despite its name, you can use std::getline() to read other things than lines. It takes an optional third parameter denoting the delimiter. The default one is '\n', but there's no reason you cannot use '\t' instead.
std::string line;
while( std::getline(is,line) ) { // read lines
std::istringstream iss(line);
std::string field;
while( std::getline(iss,field,'\t') { // read fields from line
// process field
}
}
|
2,706,277 | 2,706,298 | error C2146: syntax error : missing ';' before identifier 'vertices' | I would usually search for this error. But in VS C++ Express, this error comes up for just about every mistake you do. Any how I recieve this error below
error C2146: syntax error : missing ';' before identifier 'vertices'
everytime I add the following code at the top of my document
// Create vertex buffer
SimpleVertex vertices[] =
{
D3DXVECTOR3( 0.0f, 0.5f, 0.5f ),
D3DXVECTOR3( 0.5f, -0.5f, 0.5f ),
D3DXVECTOR3( -0.5f, -0.5f, 0.5f ),
};
below is the code in it's entirety. Cant figure out whats wrong. thanks
[EDIT]
// include the basic windows header file
#include "D3Dapp.h"
class MyGame: public D3Dapp
{
public:
bool Init3d();
};
MyGame game;
struct SimpleVertex
{
D3DXVECTOR3 Pos; // Position
};
// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
game.InitWindow(hInstance , nCmdShow);
return game.Run();
}
bool MyGame::Init3d()
{
D3Dapp::Init3d();
// Create vertex buffer
SimpleVertex vertices[] =
{
D3DXVECTOR3( 0.0f, 0.5f, 0.5f ),
D3DXVECTOR3( 0.5f, -0.5f, 0.5f ),
D3DXVECTOR3( -0.5f, -0.5f, 0.5f ),
}
return true;
}
new error
1>c:\users\numerical25\desktop\intro todirectx\msdntutorials\tutorial0\tutorial\tutorial\main.cpp(14) : error C2146: syntax error : missing ';' before identifier 'Pos'
|
error C2146: syntax error : missing ';' before identifier 'vertices'
Usually this error occurs when what's before the identifier isn't known to the compiler. In your case that means the compiler hasn't seen SimpleVertex yet.
|
2,706,296 | 2,706,305 | Use boost library in cocoa project | It is theoretically possible to use a boost library (e.g. boost threads) inside a cocoa project?
| Yes, there is nothing stopping you from doing that:
you can mix Objective-C and C++ - the result is called Objective-C++
you can of course also link to C and C++ libraries
|
2,706,357 | 2,706,383 | pop3 multiline problem | i'm making a client for pop3 and somehow i can't figure out how to handle multiline responses. There is no difference in the response from server whether it is single or multiline, it always ends with CRLF (considering the usual case) so how do I know if I should call recv() once more?
| Responses that can span more than one line (such as the contents of an email) are identified as such in the POP3 RFC.
The last line of a multi-line response just contains a dot "."
So look for "\r\n.\r\n"
That last line is a termination mark. It's not part of the actual message.
|
2,706,444 | 2,706,458 | error C2440: 'initializing' : cannot convert from 'const wchar_t [9]' to 'LPCSTR' | When I add the following to my code.
// Define the input layout
D3D10_INPUT_ELEMENT_DESC layout[] =
{
{ L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = sizeof(layout)/sizeof(layout[0]);
I get the following error
1>c:\users\numerical25\desktop\intro todirectx\msdntutorials\tutorial0\tutorial\tutorial\main.cpp(43) : error C2440: 'initializing' : cannot convert from 'const wchar_t [9]' to 'LPCSTR'
The error points straight to that line of code. if i remove the code, everything compiles correctly.
| The problem is that first element of D3D10_INPUT_ELEMENT_DESC needs a const char *, not a const wchar_t *. Just remove the L before the string.
|
2,706,495 | 2,706,504 | Use older version of MSVCR? | I have VS 2008 and I want my application to work with Windows 98 without needing to include MSVCR90.dll .. Win98 comes with MSVCR60 so how could I tell MSVC to do this? Is my only option to hunt down Visual studio 6?
Thanks
*also I want to avoid static linking msvcr
| You can't tell Visual Studio to use an earlier version of the runtime library. Even if you can get it to compile with the old library, the application itself is not going to run correctly because the compiler is going to insert calls to functions it expects to be in the library, which might not be the case.
also I want to avoid static linking msvcr
Why? That seems like a perfectly valid solution to this problem. Sure, you pay about 100kb in code size for it, but that's worth it over being forced to use Visual Studio 6's buggy and nonconforming compiler.
You could also just include the MSVC++ redistributable which would contain the correct DLLs and wouldn't require static linking of the standard library.
|
2,706,512 | 2,706,548 | STL container to pop() by priority? | I'm writing a thread-pool for Qt as QRunnable doesn't handle event loops in new threads.
Not too familiar with STL, what would be the best way to pop() something by priority? Priority should probably be a property of MyRunnable imo, but I can always give that info to an STL container when adding the runnable to the queue.
| Not familiar with QT, but as other suggest, use a priority_queue.
You'll also need a functor to allow the structure to access the priority information and specify the sorting order.
struct is_higher_priority {
bool operator()( MyRunnable const &l, MyRunnable const &b )
{ return l.priority > r.priority; }
};
std::priority_queue< MyRunnable, std::deque<MyRunnable>, is_higher_priority > q;
...
q.push( task_1 );
q.push( task_2 );
q.push( task_3 );
MyRunnable &highest = q.top();
highest.run();
q.pop();
|
2,706,538 | 2,706,609 | Event to handle Open With (WinApi) | I cannot find how I'm supposed to handle file opening in my program. For example if the user does Open With ... myprogram.exe then how do I handle that and do something with it. which WM_Message is sent?
Thanks
*no I mean if you have sometext.txt and openwith Notepad.exe, it magically displays the text, so how can I know if someone used Open With.
| There is no message sent, you will probably get it on the commandline, use argc/argv or GetCommandLine()
The shell first checks for a NoOpenWith value in KCR\Applications\myprogram.exe if it is not there, your app is listed in the open with dialog.
If the user chooses your app, the shell will use the command listed under HKCR\Applications\myprogram.exe\shell\open\Command if it exists (You could then assign DDE or Droptarget properties if that is how you want to handle the "incoming files")
If you really want to know if openwith was used, I guess you could register a command under the shell key that executes your app with a command line like myprogram.exe /openwith "%1"
|
2,706,539 | 2,706,549 | Writing a custom iterator -- what to do if you're at the end of the array? | I'm writing a custom iterator for a Matrix class, and I want to implement the increment method, which gets called when the iterator is incremented:
void MatrixIterator::increment()
{
// go to the next element
}
Suppose the iterator has been incremented too many times and now points to past the end of the matrix (i.e. past the one-past-the-end point). What is the best practice for this situation? Should I catch this with an assert, or should I just say it's the user's responsibility to keep track of where the iterator is pointing and it's none of my business?
| You can assert, but in general you are not required to do anything. C++ iterators are not supposed to catch errors. E.g. STL iterators don't do that.
|
2,706,575 | 2,706,587 | PInvoke Unbalances the stack | Good afternoon,
I have been working on a dll that can use CORBA to communicate to an application that is network aware. The code works fine if I run it as a C++ console application. However, I have gotten stuck on exporting the methods as a dll. The methods seems to export fine, and if I call a method with no parameters then it works as expected. I'm hung up on passing a C# string to a C++ method.
My C++ method header looks like this:
bool __declspec(dllexport) SpiceStart(char* installPath)
My C# DLL import code is as follows:
[DllImportAttribute("SchemSipc.dll", CharSet=CharSet.Ansi)]
private static extern bool SpiceStart(string installPath);
I call the method like so:
bool success = SpiceStart(@"c:\sedatools");
The call to SpiceStart throws the exception "PInvokeStackImbalance", which "is likely because the managed PInvoke signature does not match the unmanaged target signature."
Does anyone have any suggestions? If I remove the char* and string from the parameters, then the method runs just fine. However, I'd like to be able to pass the installation path of the application to the dll from C#.
Thanks in advance,
Giawa
| The calling conventions don't match. In C++, declare the function with the stdcall calling convention:
extern "C" bool __declspec(dllexport) __stdcall SpiceStart(char* installPath)
|
2,706,787 | 2,706,953 | nested function call faster or not? | I have this silly argument with a friend and need an authoritative word on it.
I have these two snippet and want to know which one is faster ? [A or B]
(assuming that compiler does not optimize anything)
[A]
if ( foo () );
[B]
int t = foo ();
if ( t )
EDIT : Guys, this might look a silly question to you but I have a hardware engineer friend, who was arguing that even WITHOUT optimization (take any processor, any compiler pair) CASE B is always faster because it DOES NOT fetch the memory for the result from previous instruction but directly accesses result from Common Data Bus by bypassing that data (remember the 5-stage pipeline).
While My Argument was that, without compiler informing how much data to copy or check, it is not possible to do that(you have to go to memory to get the data, WITHOUT compiler optimizing that)
| For the record, gcc, when compiling with optimization specifically disabled (-O0), produces different code for the two inputs (in my case, the body of foo was return rand(); so that the result would not be determined at compile time).
Without temporary variable t:
movl $0, %eax
call foo
testl %eax, %eax
je .L4
/* inside of if block */
.L4:
/* rest of main() */
Here, the return value of foo is stored in the EAX register, and the register is tested against itself to see if it is 0, and if so, it jumps over the body of the if block.
With temporary variable t:
movl $0, %eax
call foo
movl %eax, -4(%rbp)
cmpl $0, -4(%rbp)
je .L4
/* inside of if block */
.L4:
/* rest of main() */
Here, the return value of foo is stored in the EAX register, then pushed onto the stack. Then, the contents of the location on the stack are compared to literal 0, and if they are equal, it jumps over the body of the if block.
And so if we assume further that the processor is not doing any "optimizations" when it generates the microcode for this, then the version without the temporary should be a few clock cycles faster. It's not going to be substantially faster because even though the version with a temporary involves a stack push, the stack value is almost certainly still going to be in the processor's L1 cache when the comparison instruction is executed immediately afterwords, and so there's not going to be a round trip to RAM.
Of course the code becomes identical as soon as you turn on any optimization level, even -O1, and who compiles anything that is so critical that they care about a handful of clock cycles with all optimizations off?
Edit: With regard to your further information about your hardware engineer friend, I can't see how accessing a value in the L1 cache would ever be faster than accessing a register directly. I could see it being just about as fast if the value never even leaves the pipeline, but I can't see it being faster, especially since it still has to execute the movl instruction in addition to the comparison. But show him the assembly code above and ask what he thinks; it will be more productive than trying to discuss the problem in terms of C.
|
2,707,010 | 2,707,039 | Why doesn't ifstream read to the end? | I'm making a notepad-like program. To get the text from a file I read each character into the buffer by doing
while (!file.EOF())
{
mystr += file.get();
}
however if I load in an exe it stops after MZ but Notepad reads the whole exe.
I set my ifstream to binary mode but still no luck. What am I doing wrong?
Thanks
code:
(messy)
void LoadTextFromString(HWND ctrl, char* dirtypath, bool noquotes)
{
char *FileBuffer;
char *buf;
int count;
count = 0;
bool hasDot = false;
vector<int> quotes;
vector<string> files;
string temp;
if (noquotes)
{
goto noqu;
}
while(dirtypath[count] != 0)
{
if (dirtypath[count] == 34)
{
quotes.push_back(count);
}
count +=1;
}
if (quotes.size() < 3 || quotes.size() % 2 != 0)
{
return;
}
for (int i = 0; i < quotes.size(); i += 2)
{
temp = "";
for (int j = quotes[i] + 1; j < quotes[i + 1]; ++ j)
{
temp += dirtypath[j];
}
files.push_back(temp);
}
for(int i = 0; i < files.size(); ++i)
{
noqu:
if (!noquotes)
{
FileBuffer = (char*)files[i].c_str();
}
else
{
FileBuffer = dirtypath;
}
ifstream *tf;
tf = new ifstream(FileBuffer,ios::binary);
ifstream *file;
file = new ifstream(FileBuffer,ios::binary);
if(file->fail())
{
return;
}
int thelength;
thelength = 0;
while (!tf->eof())
{
if (tf->get() == 10)
{
thelength +=1;
}
thelength +=1;
}
tf->close();
if(thelength == 0)
{
SetWindowTextA(ctrl,"");
return;
}
buf = new char[thelength + 1];
int lenn;
lenn = 0;
char cr ;
cr = 10;
char tmp;
while (!file->eof())
{
buf[lenn] = file->get();
if (buf[lenn] == cr)
{
tmp = 13;
buf[lenn] = tmp;
buf[lenn + 1] = cr;
lenn += 1;
}
lenn += 1;
}
buf[lenn - 1] = 0;
file->read(buf,lenn);
SetWindowTextA(ctrl,buf);
file->close();
}
delete(buf);
}
|
however if I load in an exe it stops
after MZ
a file of type .exe can contain all kinds of bytes even 0's, you would need to check the byte value before appending to the string.
regarding MZ
|
2,707,048 | 2,707,073 | Check my anagram code from a job interview in the past | Had the following as an interview question a while ago and choked so bad on basic syntax that I failed to advance (once the adrenalin kicks in, coding goes out the window.)
Given a list of string, return a list of sets of strings that are anagrams of the input set. i.e. "dog","god", "foo" should return {"dog","god"}. Afterward, I created the code on my own as a sanity check and it's been around now for a bit. I'd welcome input on it to see if I missed anything or if I could have done it much more efficiently. Take it as a chance to improve myself and learn other techniques:
void Anagram::doWork(list input, list> &output)
{
typedef list < pair < string, string>> SortType;
SortType sortedInput;
// sort each string and pair it with the original
for(list< string >::iterator i = input.begin(); i != input.end(); ++i)
{
string tempString(*i);
std::sort(tempString.begin(), tempString.end());
sortedInput.push_back(make_pair(*i, tempString));
}
// Now step through the new sorted list
for(SortType::iterator i = sortedInput.begin(); i != sortedInput.end();)
{
set< string > newSet;
// Assume (hope) we have a match and pre-add the first.
newSet.insert(i->first);
// Set the secondary iterator one past the outside to prevent
// matching the original
SortType::iterator j = i;
++j;
while(j != sortedInput.end())
{
if(i->second == j->second)
{
// If the string matches, add it to the set and remove it
// so that future searches need not worry about it
newSet.insert(j->first);
j = sortedInput.erase(j);
}
else
{
// else, next element
++j;
}
}
// If size is bigger than our original push, we have a match
// - save it to the output
if(newSet.size() > 1)
{
output.push_back(newSet);
}
// erase this element and update the iterator
i = sortedInput.erase(i);
}
}
Here's a second pass at this after reviewing comments and learning a bit more:
void doBetterWork(list input, list> &output)
{
typedef std::multimap< string, string > SortedInputType;
SortedInputType sortedInput;
vector< string > sortedNames;
for(vector< string >::iterator i = input.begin(); i != input.end(); ++i)
{
string tempString(*i);
std::sort(tempString.begin(), tempString.end());
sortedInput.insert(make_pair(tempString, *i));
sortedNames.push_back(tempString);
}
for(list< string >::iterator i = sortedNames.begin(); i != sortedNames.end(); ++i)
{
pair< SortedInputType::iterator,SortedInputType::iterator > bounds;
bounds = sortedInput.equal_range(*i);
set< string > newSet;
for(SortedInputType::iterator j = bounds.first; j != bounds.second; ++j)
{
newSet.insert(j->second);
}
if(newSet.size() > 1)
{
output.push_back(newSet);
}
sortedInput.erase(bounds.first, bounds.second);
}
}
| The best way to group anagrams is to map the strings to some sort of histogram representation.
FUNCTION histogram
[input] -> [output]
"dog" -> (1xd, 1xg, 1xo)
"god" -> (1xd, 1xg, 1xo)
"foo" -> (1xf, 2xo)
Basically, with a linear scan of a string, you can produce the histogram representation of how many of each letters it contains. A small, finite alphabet makes this even easier (e.g. with A-Z, you just have an array of 26 numbers, one for each letter).
Now, anagrams are simply words that have the same histogram.
Then you can have a multimap data structure that maps a histogram to a list of words that have that histogram.
MULTIMAP
[key] => [set of values]
(1xd, 1xg, 1xo) => { "dog", "god" }
(1xf, 2xo) => { "foo" }
The canonical form trick
Instead of working on the histograms, you can also work on the "canonical form" of the strings. Basically, you define for each string, what its canonical form is, and two words are anagrams if they have the same canonical form.
One convenient canonical form is to have the letters in the string in sorted order.
FUNCTION canonize
[input] -> [output]
"dog" -> "dgo"
"god" -> "dgo"
"abracadabra" -> "aaaaabbcdrr"
Note that this is just one step after the histogram approach: you're essentially doing counting sort to sort the letters.
This is the most practical solution in actual programming language to your problem.
Complexity
Producing the histogram/canonical form of a word is practically O(1) (finite alphabet size, finite maximum word length).
With a good hash implementation, get and put on the multimap is O(1).
You can even have multiple multimaps, one for each word length.
If there are N words, putting all the words into the multimaps is therefore O(N); then outputting each anagram group is simply dumping the values in the multimaps. This too can be done in O(N).
This is certainly better than checking if each pair of word are anagrams (an O(N^2) algorithm).
|
2,707,106 | 2,707,674 | Chipmunk Physics or Box2D for C++ 2D GameEngine? | I'm developing what it's turning into a "cross-platform" 2D Game Engine, my initial platform target is iPhone OS, but could move on to Android or even some console like the PSP, or Nintendo DS, I want to keep my options open.
My engine is developed in C++, and have been reading a lot about Box2D and Chipmunk but still I can't decide which one to use as my Physics Middleware.
Chipmunk appears to have been made to be embedded easily, and Box2D seems to be widely used.
Chipmunk is C , and Box2D is C++, but I've heard the API's of Box2D are much worse than chipmunk's API's.
For now I will be using the engine shape creation and collision detection features for irregular polygons (not concave).
I value:
1) Good API's
2) Easy to integrate.
3) Portability.
And of course if you notice anything else, I would love to hear it.
Which one do you think that would fit my needs better ?
EDIT: I ended up writing an article about my particular choice, you can find it here
| You are right, chipmunk has been developed improving a lot of the places where Box2D falls down.
However, Box2D is definitely the more established platform and from my personal experience when making the decision of which engine to use, I found that Box2D had a much larger community following, so was easier to learn by example.
|
2,707,133 | 2,707,149 | Returning references while using shared_ptrs | Suppose I have a rather large class Matrix, and I've overloaded operator== to check for equality like so:
bool operator==(Matrix &a, Matrix &b);
Of course I'm passing the Matrix objects by reference because they are so large.
Now i have a method Matrix::inverse() that returns a new Matrix object. Now I want to use the inverse directly in a comparison, like so:
if (a.inverse()==b) { ... }`
The problem is, this means the inverse method needs to return a reference to a Matrix object. Two questions:
Since I'm just using that reference in this once comparison, is this a memory leak?
What happens if the object-to-be-returned in the inverse() method belongs to a boost::shared_ptr? As soon as the method exits, the shared_ptr is destroyed and the object is no longer valid. Is there a way to return a reference to an object that belongs to a shared_ptr?
| You do not need to return a reference from the inverse() method. Return the object itself. The compiler will create a temporary reference for passing to the equality operator, and that reference will go out of scope immediately after the operator returns.
To answer your question whether or not it's a memory leak.
Depends on where you're going to get that object that you're going to return from inverse(). If you're returning a reference to an object allocated on the heap, like so:
Matrix& inverse()
{
Matrix* m = new Matrix();
return *m;
}
then that's definitely a leak. Indeed, you're never going to free that memory, are you?
If you're returning a reference to a stack-allocated object, like so:
Matrix& inverse()
{
Matrix m;
return m;
}
then I wouldn't say it's a leak... Instead, it's a crash. A General Protection Fault, if you will. Or a memory corruption. Or something else out of a nightmare. Don't do this. Ever.
A stack-allocated object like that goes out of scope when the function returns, and that memory is reclaimed. But what's worse, it's reclaimed for the purposes of calling other functions, and allocating those functions' local variables. Therefore, if you retain a reference to a stack-allocated object, then you're pretty much screwed.
And finally, you might use some kind of custom storage for that Matrix, like so:
static Matrix _inversed;
Matrix& inverse()
{
_inversed = ...
return _inversed;
}
Technically, this wouldn't constitute a leak or a crash. But you really don't want to do it either, because it's not clear from the signature of the inverse() method that it actually returns a reference to shared instance, which will make it all too easy to forget this, and to fiddle with those "inversed" matrices, screwing up your data.
|
2,707,159 | 2,707,184 | Class type while deserialization in c++ | I am developing game editor in c++.I have implemented reflection mechanism using DiaSDK.Now I want to store state of the objects(Like Camera,Lights,Static mesh) in some level file via serialization.
And later on able to retrieve their state via deserialization.Serializing objects is not a problem for me.During deserialization I am getting class type as a string.So how to create instance of object using that class type string?so that I can create object of that particular type.
| When you serialize the class, you will need to emit its runtime type so that you can instantiate the correct type when deserializing. Otherwise, it is not possible to determine which runtime type to use.
A good technique for constructing classes based on a type string is to build a hash map from class names to factory objects capable of instantiating such a type. You will need to create that mapping based on the types that you might possibly deserialize. If that set of types can change, then a common approach is to provide a means by which a factory may be "registered" or "deregistered" with the map for a particular name.
|
2,707,318 | 2,707,335 | what is the wrong with this code"length indicator implementation"? | this is an implementation of length indicator field
but it hang and i think stuck at a loop and don't show any thing.
// readx22.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "fstream"
#include "stdio.h"
using namespace std;
class Student
{
public:
string id;
size_t id_len;
string first_name;
size_t first_len;
string last_name;
size_t last_len;
string phone;
size_t phone_len;
string grade;
size_t grade_len;
void read(fstream &ven);
void print();
};
void Student::read(fstream &ven)
{
size_t cnt;
ven >> cnt;
id_len=cnt;
id.reserve( cnt );
while ( -- cnt ) {
id.push_back( ven.get() );
}
ven >> cnt;
first_len=cnt;
first_name.reserve( cnt );
while ( -- cnt ) {
first_name.push_back( ven.get() );
}
ven >> cnt;
last_len=cnt;
last_name.reserve( cnt );
while ( -- cnt ) {
last_name.push_back( ven.get() );
}
ven >> cnt;
phone_len=cnt;
phone.reserve( cnt );
while ( -- cnt ) {
phone.push_back( ven.get() );
}
ven >> cnt;
grade_len=cnt;
grade.reserve( cnt );
while ( -- cnt ) {
grade.push_back( ven.get() );
}
}
void Student::print()
{
// string::iterator it;
for ( int i=0 ; i<id_len; i++)
cout << id[i];
}
int main()
{
fstream in;
in.open ("fee.txt", fstream::in);
Student x;
x.read(in);
x.print();
return 0;
}
thanks
| You probably should have used cnt-- instead of -- cnt everywhere. The first zero-byte string will trigger an extremely large loop that eventually consumes all memory (except maybe on a 64-bit OS). Actually, don't even bother with this fix. Loop over get() is extremely inefficient, just call read().
|
2,707,640 | 2,707,650 | Static Member Variables of the Same Class in C++ | I'm trying to create a class which contains a static pointer to an instance of itself. Here's an example:
A.h:
#include <iostream>
#ifndef _A_H
#define _A_H
class A {
static A * a;
};
A * a = NULL;
#endif
However, when I include A.h in another file, such as:
#include "A.h"
class B {
};
I get the following error:
ld: duplicate symbol _a in /Users/helixed/Desktop/Example/build/Example.build/Debug/Example.build/Objects-normal/x86_64/B.o and /Users/helixed/Desktop/Example/build/Example.build/Debug/Examplebuild/Objects-normal/x86_64/A.o
I'm using the Xcode default compiler on Mac OS X Snow Leopard.
| This line:
A * a = NULL;
needs to look like this:
A *A::a = NULL;
And you need to move it out of the header file, and put it in a source (.cpp) file.
The definition of a static member must exist only once in your program. If you put this line in the header file, it would be included in every source file which includes it, leading to a duplicate symbol error.
|
2,707,740 | 2,707,839 | Writing an ostream filter? | I'd like to write a simple ostream which wraps an argument ostream and changes the stream in some way before passing it on to the argument stream. The transformation is something simple like changing a letter or erasing a word
What would a simple class inheriting from ostream look like? What methods should I override?
| std::ostream is not the best place to implement filtering. It doesn't have the appropriate virtual functions to let you do this.
You probably want to write a class derived from std::streambuf containing a wrapped std::ostream (or a wrapped std::streambuf) and then create a std::ostream using this std::streambuf.
std::streambuf has a virtual function overflow which you can override and use to alter the bytes before passing them to the wrapped output class.
|
2,707,909 | 2,714,396 | How do I use Loki's small object allocator? | I need to use Loki's small object allocator but I am very confused as to how it works. I've read the documentation and lots of forums but it doesnt make sense: some of them say to use the stl, others use custom allocators. I just need to be able to test its performance with allocating and deallocating objects of different sizes. Could someone please provide a small example of how to use it?
| Ok, best I got was to make Loki's Small Object Allocator compliant with the STL. To do this I just created a wrapper class for the SmallObjAllocator class in Loki according to http://www.codeproject.com/kb/cpp/allocator.aspx?fid=16541&df=90&mpp=25&sort=Position&tid=1677312
|
2,707,923 | 2,708,155 | Inlining an array of non-default constructible objects in a C++ class | C++ doesn't allow a class containing an array of items that are not default constructible:
class Gordian {
public:
int member;
Gordian(int must_have_variable) : member(must_have_variable) {}
};
class Knot {
Gordian* pointer_array[8]; // Sure, this works.
Gordian inlined_array[8]; // Won't compile. Can't be initialized.
};
As even beginning C++ users know, the language guarantees that all non-POD members are initialized when constructing a class. And it doesn't trust the user to initialize everything in the constructor - one has to provide valid arguments to the constructors of all members before the body of the constructor even starts.
Generally, that's a great idea as far as I'm concerned, but I've come across a situation where it would be a lot easier if I could actually have an array of non-default constructible objects.
The obvious solution: Have an array of pointers to the objects. This is not optimal in my case, as I am using shared memory. It would force me to do extra allocation from an already contended resource (that is, the shared memory). The entire reason I want to have the array inlined in the object is to reduce the number of allocations.
This is a situation where I would be willing to use a hack, even an ugly one, provided it works. One possible hack I am thinking about would be:
class Knot {
public:
struct dummy { char padding[sizeof(Gordian)]; };
dummy inlined_array[8];
Gordian* get(int index) {
return reinterpret_cast<Gordian*>(&inlined_array[index]);
}
Knot() {
for (int x = 0; x != 8; x++) {
new (get(x)) Gordian(x*x);
}
}
};
Sure, it compiles, but I'm not exactly an experienced C++ programmer. That is, I couldn't possibly trust my hacks less. So, the questions:
1) Does the hack I came up with seem workable? What are the issues? (I'm mainly concerned with C++0x on newer versions of GCC).
2) Is there a better way to inline an array of non-default constructible objects in a class?
| For one thing, you can use an array wrapper (such as boost::array) to initialize the array with fixed values:
#include <boost/array.hpp>
class Gordian {
public:
int member;
Gordian(int must_have_variable) : member(must_have_variable) {}
};
namespace detail
{
boost::array<Gordian, 8> chop()
{
boost::array<Gordian, 8> t = {{0, 1, 4, 9, 16, 25, 36, 49}};
return t;
}
}
class Knot {
boost::array<Gordian, 8> array;
public:
Knot(): array(detail::chop()) {}
};
Another possibility would be an array of boost::optional (but there will be some size overhead):
#include <boost/optional.hpp>
class Gordian {
public:
int member;
Gordian(int must_have_variable) : member(must_have_variable) {}
};
class Knot {
boost::optional<Gordian> array[8];
public:
Knot()
{
for (int x = 0; x != 8; x++) {
array[x] = Gordian(x*x);
}
}
};
|
2,707,980 | 2,707,985 | How to convert a char* pointer into a C++ string? | I have a C++ string. I need to pass this string to a function accepting a char* parameter (for example - strchr()).
a) How do I get that pointer?
b) Is there some function equivalent to strschr() that works for C++ strings?
|
To get the C string equivalent of
the C++ string object use c_str
function.
To locate the first occurence of a
char in a string object use
find_first_of function.
Example:
string s = "abc";
// call to strlen expects char *
cout<<strlen(s.c_str()); // prints 3
// on failure find_first_of return string::npos
if(s.find_first_of('a') != string::npos)
cout<<s<<" has an a"<<endl;
else
cout<<s<<" has no a"<<endl;
Note: I gave the strlen just an example of a function that takes char*.
|
2,708,078 | 2,708,087 | What Should be the Structure of a C++ Project? | I have recently started learning C++ and coming from a Ruby environment I have found it very hard to structure a project in a way that it still compiles correctly, I have been using Code::Blocks which is brilliant but a downside is that when I add a new header file or c++ source file, it will generate some code and even though it is only a mere 3 or 4 lines, I do not know what these lines do. First of all I would like to ask this question:
What do these lines do?
#ifndef TEXTGAME_H_INCLUDED
#define TEXTGAME_H_INCLUDED
#endif // TEXTGAME_H_INCLUDED
My second question is, do I need to #include both the .h file and the .cpp file, and in which order.
My third question is where can I find the GNU GCC Compiler that, I beleive, was packaged with Code::Blocks and how do I use it without Code::Blocks? I would rather develop in a notepad++ sort of way because that is what I'm used to in Ruby but since C++ is compiled, you may think differently (please give advice and views on that as well)
Thanks in advance, ell.
EDIT: I'm on Windows XP & thanks for the lighting fast replies!
| To answer your questions:
The lines are include guards. They prevent the header file being included more than once in any given translation unit. If it was included multiple times, you would probably get multiple definition errors.
Header files are #included in .cpp files and in other headers. .cpp files are not normally #included.
The C++ compiler that comes with Code::Blocks is called MinGW GCC, and can be found in the bin directory of the MinGW installation. To find it, do a Windows search via explorer for 'g++'. To use it, you will need to put the directory it is in on your search path. Note the version of the compiler that ships with Code::Blocks is quite old - you can get a much more recent version from here.
|
2,708,127 | 2,708,257 | aligning extern constants (gcc) | I want to make some static constants globally visible. I'm pretty familiar how to do that in C++. The problem is that these constants need to be aligned to some exotic boundary. Do I have to specify the alignment in extern declaration? I'm using GCC4.5
in *.cpp file
static const constant_t constant __attribute__((aligned(64))) = {blah,blah,blah};
in *.h file
//Which one is correct?
extern const constant_t constant;
extern const constant_t constant __attribute__((aligned(64)));
| First, it looks like you're trying to declare it static in the C file, which is the old C way of saying internal (file) linkage. This is inconsistent with your goal of making it global.
Given that the static is removed, you should only need the attribute in the C file: The extern declaration says effectively "I want to use this name, when you finally find out its address, substitute that in here". In other words, once the address is assigned at the definition point in the C file, your extern will symbolically point to that same address.
|
2,708,176 | 2,708,193 | executable parameter c++ | if i got a c++ executable file like this: executable.exe and i want to add some parameters like:
executable.exe +username = pino
how do i get in c++ that i filled in pino as my username?
| Arguments to main. Your main is
int main(int argc, char **argv) {
...
}
All the command-line params are in argv. There are also Windows-specific APIs.
|
2,708,265 | 2,708,289 | Force to reimplement a static function in inherit classes | I have a program in C++ with plugins (dynamic libs). In the main program, I want to execute a static function to check if i can create a object of this type.
An example without dynamic libs (aren't neccesary to understand the problem):
#include "libs/parent.h"
#include "libs/one.h"
#include "libs/two.h"
int main(int argc, char * argv[])
{
Parent* obj;
if (One::match(argv[1]))
obj = new One();
else if (Two::match(argv[1]))
obj = new Two();
}
Now, i have a interface class named Parent. All plugins inherit from this class. Ideally, I have a virtual static function in Parent named match, and all the plugins need to reimplement this function.
The problem with this code is that i can't do a static virtual function in C++, so i don't know how to solve the problem.
Sorry for mi english, i did my best
| What you have here is classic factory pattern. You want to create an interface named IPluginFactory which would have two methods - match and create (or, optionally, combine them both in a single method). Then each of your plugin DLLs would have a class that implements this interface.
Parent obj;
IPluginFactory *one = new OneFactory();
IPluginFactory *two = new TwoFactory();
if (one->match(argv[1]))
obj = one->createObj();
else if (two->match(argv[1]))
obj = two->createObj();
|
2,708,291 | 2,708,307 | Stack Overflow Accessing Large Vector | I'm getting a stack overflow on the first iteration of this for loop
for (int q = 0; q < SIZEN; q++)
{
cout<<nList[q]<<" ";
}
nList is a vector of type int with 376 items. The size of nList depends on a constant defined in the program. The program works for every value up to 376, then after 376 it stops working.
Any thoughts?
| If by "stops working", you mean crashes, then you're probably reading past the end of the buffer. vector::operator[] is not range checked, so it will let you shoot yourself in the foot.
If you want to traverse a vector, use an iterator, or at the very least nList.size().
So with least modifications to your code:
for (int q = 0; q < nList.size(); q++)
{
cout << nList[q] << " ";
}
or with iterators
for (std::vector<int>::const_iterator it = nList.begin();
it != nList.end(); ++it) {
cout << *it << " ";
}
|
2,708,338 | 2,708,375 | std::cin >> *aa results in a bus error | I have this a class called PPString:
PPString.h
#ifndef __CPP_PPString
#define __CPP_PPString
#include "PPObject.h"
class PPString : public PPObject {
char *stringValue[];
public:
char *pointerToCharString();
void setCharString(char *charString[]);
void setCharString(const char charString[]);
};
#endif
PPString.cpp
#include "PPString.h"
char *PPString::pointerToCharString() {
return *stringValue;
}
void PPString::setCharString(char *charString[]) {
*stringValue = *charString;
}
void PPString::setCharString(const char charString[]) {
*stringValue = (char *)charString;
}
I'm trying to set the stringValue using std::cin:
main.cpp
PPString myString;
myString.setCharString("LOLZ");
std::cout << myString.pointerToCharString() << std::endl;
char *aa[1000];
std::cin >> *aa;
myString.setCharString(aa);
std::cout << myString.pointerToCharString() << std::endl;
The first one, which uses a const char works, but the second one, with a char doesn't, and I get this output:
copy and paste from STDOUT
LOLZ
im entering a string now...
Bus error
where the second line is what I entered, followed by pressing the return key.
Can anyone help me fixing this? Thanks...
| The setCharString with the char *s[] signature is dereferencing the first element of an array of pointers to char*. It has not been allocated. If you change the declaration of aa to char aa[1000];, it will probably run.
There are some other issues too (also pointed out by others). The assignment to the variable stringValue is also dereferencing memory that does not appear to have been allocated. It's hard to say what the usage is, but it should maybe not have the [] declaration. In addition, the assignment is storing a pointer to stack memory, which will likely not be valid after another function call.
|
2,708,340 | 2,708,546 | limit stl's vector max_size | How can I limit STL vector's max_size? Eventually by specialization. An example would be welcome.
| The way to do this is to replace the allocator. Note that vector and string are the only containers that actually check their allocators max_size right now. The idea is that since these containers guarantee that the elements are stored in contiguous memory, the container asks the allocator just how many elements the allocator can handle.
This is the idea
template<class T>
struct MyAllocator:std::allocator<T>
{
template <class U>
struct rebind { typedef MyAllocator<U> other; };
typedef typename std::allocator<T>::size_type size_type;
MyAllocator(size_type sz=1234)
: m_maxsize(sz)
{}
size_type max_size() const { return m_maxsize; }
private:
size_type m_maxsize;
};
then make a new vector
typedef std::vector<Type,MyAllocator<Type>> vec_t;
vec_t vec(vec_t::allocator_type(4567));
I haven't tried compiling this code, but it should work.
|
2,708,423 | 2,708,451 | C++ design related question | Here is the question's plot: suppose I have some abstract classes for objects, let's call it Object. It's definition would include 2D position and dimensions. Let it also have some virtual void Render(Backend& backend) const = 0 method used for rendering.
Now I specialize my inheritance tree and add Rectangle and Ellipse class. Guess they won't have their own properties, but they will have their own virtual void Render method. Let's say I implemented these methods, so that Render for Rectangle actually draws some rectangle, and the same for ellipse.
Now, I add some object called Plane, which is defined as class Plane : public Rectangle and has a private member of std::vector<Object*> plane_objects;
Right after that I add a method to add some object to my plane.
And here comes the question. If I design this method as void AddObject(Object& object) I would face trouble like I won't be able to call virtual functions, because I would have to do something like plane_objects.push_back(new Object(object)); and this should be push_back(new Rectangle(object)) for rectangles and new Circle(...) for circles.
If I implement this method as void AddObject(Object* object), it looks good, but then somewhere else this means making call like plane.AddObject(new Rectangle(params)); and this is generally a mess because then it's not clear which part of my program should free the allocated memory.
["when destroying the plane? why? are we sure that calls to AddObject were only done as AddObject(new something).]
I guess the problems caused by using the second approach could be solved using smart pointers, but I am sure there have to be something better.
Any ideas?
| Your actual problem seems to be managing the objects' lifetimes. Four possibilities that come to mind are:
Your container (i.e. Plane) assumes ownership of all contained objects and therefore deletes them once it's itself destroyed.
Your container (Plane) does not assume ownership and whoever added objects to your container will be responsible for destroying them.
The lifetime of your objects is managed automatically.
You circumvent the problem by providing the container with a clone of the actual object. The container manages a copy of the object, and the caller manages the original object.
What you currently have seems like approach #4. By doing:
plane_objects.push_back(new Object(object));
you insert a copy of the object into the container. Therefore the problem sort of disappears. Ask yourself whether this is really what you want, or if one of the above choices would be more suitable.
Options #1 and #2 are easy to implement, because they define a contract that your implementation simply has to follow. Option #3 would call for e.g. smart pointers, or some other solution involving reference counting.
If you want to keep following the approach of option #4, you could e.g. extend your Object class with a clone method, so that it returns the right type of object. This would get rid of the incorrect new Object(...).
class Object
{
public:
virtual Object* clone() const = 0;
...
};
...
Object* Rectangle::clone() const
{
return new Rectangle(*this); // e.g. use copy c'tor to return a clone
}
P.S.: Note how the STL containers seem to deal with this issue: Let's say you declare a vector<Foo>. This vector will contain copies of the objects inserted into it (option #4 in my answer). However, if you declare the collection as vector<Foo*>, it will contain references to the original objects, but it will not manage their lifetime (option #2 in my answer).
|
2,708,460 | 2,708,473 | How do Hex editors display data so quickly? | I'v created a Notepad-like application and if I load a 1MB file into the textbox, it takes about 1 minute. The Visual Studio Binary editor displays lines, Hex, and ascii versions in a fraction of a second. How do they get the data into the textbox so quickly?
Thanks
| They only read enough of the file to display what is viewable on screen. In other words, if your UI can only display 100 bytes at a time, you only need to read 100 bytes to fill the screen. If the user scrolls the window, you have to read additional bytes to fill in the missing pieces.
|
2,708,501 | 3,246,426 | Intel AVX intrinsics: any compatibility library out? | Are there any Intel AVX intrinsics library out? I'm looking for something similar as 'sse2mmx.h' header which fall-backs to MMX intrinsics if SSE2 integer intrinsics are not available on compile time. Thus if I had similar library for AVX I could write optimized code for new hardware which would have almost optimal speed in case AVX extension isn't available. Googling didn't help much so far :(
| Intel provides a AVX emulation header. I haven't tried it, but quoting the linked article "The AVX emulation header file uses intrinsics for the prior Intel instruction set extensions up to Intel SSE4.2. SSE4.2 support in your development environment as well as hardware is required in order to use the AVX emulation header file. To use simply have this file included: #include "avxintrin_emu.h" nstead of usual #include <immintrin.h>" - sounds like this is what you're looking for.
Intel also has an emulator, called SDE, which might be useful. I haven't used it for testing AVX code yet, but it worked fine on my machine for testing code using the AES-NI instruction sets on an older CPU, and I know it supports AVX emulation as well. SDE is especially useful for checking your CPUID handling code.
|
2,708,519 | 2,708,587 | Stopping Backtracking | Is there any way in C/C++ to stop a backtracking algorithm after finding the first solution without exiting the program.
I want my function to immediately exit the function,not to quit every level of recurrsion one by one stating return.
| You could use setjmp()/longjmp() in both C and C++ for a crude but effective way of bypassing the need to pass a flag all the way back.
|
2,708,735 | 2,708,745 | How to install MinGW correctly on Windows | I have recently started learning C++, but I require a compiler. I have tried the one packaged with Code::Blocks, but I have been told it is out of date.
I have tried reading the instructions on the website, but I simply don't know which files to download and un-zip. Is there a list of files to download? (latest version) and a folder structure I need?
| I was the person that pointed you at the more up-to-date version at Twilight Dragon. The file you want there is http://sourceforge.net/projects/tdm-gcc/files/TDM-MinGW%20Installer/1.908.0/tdm-mingw-1.908.0-4.4.1-2.exe/download which is a Windows binary installer - you just run it. Note that you don't actually need to do this - the version that comes with Code::Blocks will work OK for someone starting to learn C++.
|
2,708,948 | 2,709,039 | How does the compile choose which template function to call? | Regarding the below code, how does the compiler choose which template function to call?
If the const T& function is omitted, the T& function is always called.
If the T& function is omitted, the const T& function is always called.
If both are included, the results are as below.
#include <iostream>
#include <typeinfo>
template <typename T>
void function(const T &t)
{
std::cout << "function<" << typeid(T).name() << ">(const T&) called with t = " << t << std::endl;
}
template <typename T>
void function(T &t)
{
std::cout << "function<" << typeid(T).name() << ">(T&) called with t = " << t << std::endl;
}
int main()
{
int i1 = 57;
const int i2 = -6;
int *pi1 = &i1;
int *const pi3 = &i1;
const int *pi2 = &i2;
const int *const pi4 = &i2;
function(pi1); ///just a normal pointer -> T&
function(pi2); ///cannot change what we point to -> T&
function(pi3); ///cannot change where we point -> const T&
function(pi4); ///cannot change everything -> const T&
return 0;
}
/* g++ output:
function<Pi>(T&) called with t = 0x22cd24
function<PKi>(T&) called with t = 0x22cd20
function<Pi>(const T&) called with t = 0x22cd24
function<PKi>(const T&) called with t = 0x22cd20
*/
/* bcc32 output:
function<int *>(T&) called with t = 0012FF50
function<const int *>(T&) called with t = 0012FF4C
function<int *>(const T&) called with t = 0012FF50
function<const int *>(const T&) called with t = 0012FF4C
*/
/* cl output:
function<int *>(T&) called with t = 0012FF34
function<int const *>(T&) called with t = 0012FF28
function<int *>(const T&) called with t = 0012FF34
function<int const *>(const T&) called with t = 0012FF28
*/
| Here is a brief summary of the process the compiler goes through. It doesn't cover everything, but it gets you started.
In this case, the decision is made the same as a non-templated function. Given void f(int&) and void f(const int&), the first will be chosen for regular ints, and the second for const ints. The parameters simply match the inputs better this way: if you provide a variable you can modify, it calls a function that can modify them, if you provide a variable you can not modify, it calls a function that can not modify them.
In your sample code, pi2, being declared as a const int *, is a non-constant pointer to constant data. So within your function, you can change t, but not *t. By contrast, pi3 is a constant pointer to non-constant data. So you can change *t but not t.
If you changed your code slightly:
function(*pi1);
function(*p12);
function(*pi3);
function(*pi4);
In this case, the first and third would both resolve to the T& version, because *pi1 and *pi3 are both of type int& and can therefore be modified. *pi2 and *pi4 are both const int&, so they resolve to the const T& overload.
|
2,708,985 | 2,709,047 | Access violation reading location 0x00184000 | having troubles with the following line
HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB));
it appears the CreateBuffer method is having troubles reading &mVB. mVB is defined in box.h and looks like this
ID3D10Buffer* mVB;
Below is the code it its entirety. this is all files that mVB is in.
//Box.cpp
#include "Box.h"
#include "Vertex.h"
#include <vector>
Box::Box()
: mNumVertices(0), mNumFaces(0), md3dDevice(0), mVB(0), mIB(0)
{
}
Box::~Box()
{
ReleaseCOM(mVB);
ReleaseCOM(mIB);
}
float Box::getHeight(float x, float z)const
{
return 0.3f*(z*sinf(0.1f*x) + x*cosf(0.1f*z));
}
void Box::init(ID3D10Device* device, float m, float n, float dx)
{
md3dDevice = device;
mNumVertices = m*n;
mNumFaces = 12;
float halfWidth = (n-1)*dx*0.5f;
float halfDepth = (m-1)*dx*0.5f;
std::vector<Vertex> vertices(mNumVertices);
for(DWORD i = 0; i < m; ++i)
{
float z = halfDepth - (i * dx);
for(DWORD j = 0; j < n; ++j)
{
float x = -halfWidth + (j* dx);
float y = getHeight(x,z);
vertices[i*n+j].pos = D3DXVECTOR3(x, y, z);
if(y < -10.0f)
vertices[i*n+j].color = BEACH_SAND;
else if( y < 5.0f)
vertices[i*n+j].color = LIGHT_YELLOW_GREEN;
else if (y < 12.0f)
vertices[i*n+j].color = DARK_YELLOW_GREEN;
else if (y < 20.0f)
vertices[i*n+j].color = DARKBROWN;
else
vertices[i*n+j].color = WHITE;
}
}
D3D10_BUFFER_DESC vbd;
vbd.Usage = D3D10_USAGE_IMMUTABLE;
vbd.ByteWidth = sizeof(Vertex) * mNumVertices;
vbd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
vbd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA vinitData;
vinitData.pSysMem = &vertices;
HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB));
//create the index buffer
std::vector<DWORD> indices(mNumFaces*3); // 3 indices per face
int k = 0;
for(DWORD i = 0; i < m-1; ++i)
{
for(DWORD j = 0; j < n-1; ++j)
{
indices[k] = i*n+j;
indices[k+1] = i*n+j+1;
indices[k+2] = (i*1)*n+j;
indices[k+3] = (i*1)*n+j;
indices[k+4] = i*n+j+1;
indices[k+5] = (i*1)*n+j+1;
k+= 6;
}
}
D3D10_BUFFER_DESC ibd;
ibd.Usage = D3D10_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(DWORD) * mNumFaces*3;
ibd.BindFlags = D3D10_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = &indices;
HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB));
}
void Box::Draw()
{
UINT stride = sizeof(Vertex);
UINT offset = 0;
md3dDevice->IASetVertexBuffers(0, 1, &mVB, &stride, &offset);
md3dDevice->IASetIndexBuffer(mIB, DXGI_FORMAT_R32_UINT, 0);
md3dDevice->DrawIndexed(mNumFaces*3, 0 , 0);
}
//Box.h
#ifndef _BOX_H
#define _BOX_H
#include "d3dUtil.h"
Box.h
class Box {
public:
Box();
~Box();
void init(ID3D10Device* device, float m, float n, float dx);
void Draw();
float getHeight(float x, float z)const;
private:
DWORD mNumVertices;
DWORD mNumFaces;
ID3D10Device* md3dDevice;
ID3D10Buffer* mVB;
ID3D10Buffer* mIB;
};
#endif
[EDIT]
Arguements being passed for m and n dx is
m = 129, n = 129, dx = 1.0f (they are all floats)
m and n stand for rows and columns perspectively. dx is the width and height.
Thanks again for the help
| If you want a pointer to the data array of a vector, you should use &vec[0]. If you use &vec it will give you a pointer to the vector object, which might contain all kinds management structures/... that have nothing to do with the data you inserted into the vector.
The data itself is stored at continuous memory starting at &vec[0], so use that when you initialize your D3D structures.
|
2,709,037 | 2,709,093 | WM_KEYDOWN confusion | I'm trying to get my application to do something when CTRL+S is pressed. I'm just not sure how the W and L params work for WM_KEYDOWN. MSDN has something about bit fields which i'm not sure about. How can I detect CTRL and S?
Thanks
What do I do if another control aside from hWnd has focus?
| Well, this is the big list of virtual key codes.
CTRL-S is going to be sent through as 2 WM_KEYDOWN messages - a message when the ctrl key is pressed (VK_LCONTROL or VK_RCONTROL) followed by a 0x53 for the "S" key.
Rather than processing both messages, wait for the key down message for the 'S' press then call GetKeyState using the magic value VK_CONTROL (otheriwse you'd need to test individually for the left AND right control keys) to see if the S was pressed with CTRL held down.
--
Obviously, keyboard messages are sent directly to the window that has focus. To get accelerator combinations to work at the application scope you need to check the messages before dispatching them to the focus window - i.e. in your message pump. See the documentation for TranslateAccelerator.
If you want to handle system wide keypresses, the other answer points to the hot key api.
|
2,709,083 | 2,709,127 | Boost's "cstdint" Usage | Boost's C99 stdint implementation is awfully handy. One thing bugs me, though. They dump all of their typedefs into the boost namespace. This leaves me with three choices when using this facility:
Use "using namespace boost"
Use "using boost::[u]<type><width>_t"
Explicitly refer to the target type with the boost:: prefix; e.g., boost::uint32_t foo = 0;
Option № 1 kind of defeats the point of namespaces. Even if used within local scope (e.g., within a function), things like function arguments still have to be prefixed like option № 3.
Option № 2 is better, but there are a bunch of these types, so it can get noisy.
Option № 3 adds an extreme level of noise; the boost:: prefix is often ≥ to the length of the type in question.
My question is: What would be the most elegant way to bring all of these types into the global namespace? Should I just write a wrapper around boost/cstdint.hpp that utilizes option № 2 and be done with it?
Also, wrapping the header like so didn't work on VC++ 10 (problems with standard library headers):
namespace Foo
{
#include <boost/cstdint.hpp>
namespace boost_alias = boost;
}
using namespace Foo::boost_alias;
EDIT: I guess another option is to use the preprocessor to make it work on VC 10? Taking the snippet above:
#ifndef FOO_HPP_INCLUDED
#define FOO_HPP_INCLUDED
#if _MSC_VER >= 1600 /*VC++ 10*/ || defined USE_NATIVE_STDINT_HEADER
#include <stdint.h>
#else
namespace cstdint_wrapper
{
#include <boost/cstdint.hpp>
namespace boost_alias = boost;
}
using namespace cstdint_wrapper::boost_alias;
#endif
#endif
Less work, I guess?
| I just use C99's stdint.h (it's actually now in VS 2010). For the versions of Visual C/C++ that don't include it, I use a public domain version from MinGW that I modified to work with VC6 (from when I had to work in VC6):
http://snipplr.com/view/18199/stdinth/
There are a couple other options you might consider in this SO question: C99 stdint.h header and MS Visual Studio
If you'd like to continue using boost/cstdint.hpp, I'd say that the suggestion of implementing a wrapper header that brings the types into the global namespace would be the way to go.
Does boost/cstdint.hpp provide anything I should know about that isn't in stdint.h?
|
2,709,092 | 2,709,100 | Creating a 3d plane using Frank Luna's technique: what are sinf and cosf? | I am creating a 3d plane that lies on the x and z axis, and has hills that extend on the y axis. The bulk of the code looks like this:
float PeaksAndValleys::getHeight(float x, float z)const
{
return 0.3f*( z*sinf(0.1f*x) + x*cosf(0.1f*z) );
}
void PeaksAndValleys::init(ID3D10Device* device, DWORD m, DWORD n, float dx)
{
md3dDevice = device;
mNumRows = m;
mNumCols = n;
mNumVertices = m*n;
mNumFaces = (m-1)*(n-1)*2;
// Create the geometry and fill the vertex buffer.
std::vector<Vertex> vertices(mNumVertices);
float halfWidth = (n-1)*dx*0.5f;
float halfDepth = (m-1)*dx*0.5f;
for(DWORD i = 0; i < m; ++i)
{
float z = halfDepth - i*dx;
for(DWORD j = 0; j < n; ++j)
{
float x = -halfWidth + j*dx;
// Graph of this function looks like a mountain range.
float y = getHeight(x,z);
vertices[i*n+j].pos = D3DXVECTOR3(x, y, z);
// Color the vertex based on its height.
if( y < -10.0f )
vertices[i*n+j].color = BEACH_SAND;
else if( y < 5.0f )
vertices[i*n+j].color = LIGHT_YELLOW_GREEN;
else if( y < 12.0f )
vertices[i*n+j].color = DARK_YELLOW_GREEN;
else if( y < 20.0f )
vertices[i*n+j].color = DARKBROWN;
else
vertices[i*n+j].color = WHITE;
}
}
D3D10_BUFFER_DESC vbd;
vbd.Usage = D3D10_USAGE_IMMUTABLE;
vbd.ByteWidth = sizeof(Vertex) * mNumVertices;
vbd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
vbd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA vinitData;
vinitData.pSysMem = &vertices[0];
HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB));
// Create the index buffer. The index buffer is fixed, so we only
// need to create and set once.
std::vector<DWORD> indices(mNumFaces*3); // 3 indices per face
// Iterate over each quad and compute indices.
int k = 0;
for(DWORD i = 0; i < m-1; ++i)
{
for(DWORD j = 0; j < n-1; ++j)
{
indices[k] = i*n+j;
indices[k+1] = i*n+j+1;
indices[k+2] = (i+1)*n+j;
indices[k+3] = (i+1)*n+j;
indices[k+4] = i*n+j+1;
indices[k+5] = (i+1)*n+j+1;
k += 6; // next quad
}
}
D3D10_BUFFER_DESC ibd;
ibd.Usage = D3D10_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(DWORD) * mNumFaces*3;
ibd.BindFlags = D3D10_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
D3D10_SUBRESOURCE_DATA iinitData;
iinitData.pSysMem = &indices[0];
HR(md3dDevice->CreateBuffer(&ibd, &iinitData, &mIB));
}
My question pertains to the cosf and sinf. I am familiar with trigonometry and I understand sin, cosine, and tangent, but I am not familiar with cosf and sinf and what they do. From looking at this example, they have a lot to do with finding a y value.
| cosf and sinf are simply the float versions of cos and sin. The normal cos and sin functions return double values instead of floats. Note that all these functions work in radians, not degrees.
Combined in the way above, they give a landscape that looks somewhat like a mountain range, as in this plot.
|
2,709,124 | 2,709,688 | WxWidgets custom events | I'm trying to use a custom event in my WxWidgets C++ application, like described here.
In the constructor of my wxApp:
Connect(wxID_ANY, wxCommandEventHandler(APP::OnMyEvent));
Then the function that should catch the event:
void APP::OnMyEvent(wxCommandEvent& event)
{
exit(0); //testing
}
Finally, to test it:
wxCommandEvent MyEvent(wxEVT_COMMAND_BUTTON_CLICKED);
wxPostEvent(this, MyEvent);
I launch the thing...but it seems that the event is not posted or not caught.
Does someone understand this behaviour ?
| You appear to be using the following overload of Connect:
void Connect(wxEventType eventType, wxObjectEventFunction function,
wxObject* userData = NULL, wxEvtHandler* eventSink = NULL)
If so, then should an event of type wxID_ANY happen (never?), then the connected function will be called.
Perhaps you need:
Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(APP::OnMyEvent));
|
2,709,199 | 2,709,246 | C++ String manipulation isn't making sense to me | This particular assignment has to do with removing substrings from strings; I am trying some of the Stanford SEE courses online to learn some new languages.
What I've got so far is below, but if text = "hello hello" and remove ="el", it gets stuck in a loop, but if i change text to text = "hello hllo", it works, making me think I'm doing something obviously stupid.
There is a stipulation in the assignment not to modify the incoming strings, and instead to return a new string.
string CensorString1(string text, string remove){
string returned;
size_t found=0, lastfound=0;
found = (text.substr(lastfound,text.size())).find(remove);
while (string::npos != found ){
returned += text.substr(lastfound,found);
lastfound = found + remove.size();
found = (text.substr(lastfound,text.size())).find(remove);
}
returned += text.substr(lastfound,found);
return returned;
}
Guidance would be appreciated :-) Thanks
UPDATE
Took the very kind advice given and modified my code to this :
string CensorString1(string text, string remove){
string returned;
size_t found=0, lastfound=0;
found = text.find(remove);
while (string::npos != found ){
returned += text.substr(lastfound,found);
lastfound = found + remove.length();
found = text.find(remove,lastfound);
}
returned += text.substr(lastfound);
return returned;
}
But still behaves the same
Any more ideas folks?
| found = (text.substr(lastfound,text.size())).find(remove); is incorrect. It returns the index of the searched string in text.substr(lastfound,text.size()), but not in text.
You should perhaps change this to found = text.find(text, lastfound);.
Besides of being incorrect, taking a substring (this means, allocating a new string) and calculating an index in it is quite inefficient, unless the optimizer is super-smart.
Moreover, the final returned += text.substr(lastfound,found); is incorrect too: you need to add the last chunk of the text, not the one till found index (which is most likely empty, as lastfound can be smaller than found. Better would be returned += text.substr(lastfound);
Edit:
In the second example, you need to replace returned += text.substr(lastfound,found);
with returned += text.substr(lastfound,found-lastfound);. The second argument to substr is length, not position.
With this change, the test example runs fine in my test program.
(Addition by J.F. Sebastian:)
string CensorString1(string const& text, string const& remove){
string returned;
size_t found = string::npos, lastfound = 0;
do {
found = text.find(remove, lastfound);
returned += text.substr(lastfound, found-lastfound);
lastfound = found + remove.size();
} while(found != string::npos);
return returned;
}
|
2,709,210 | 2,709,413 | How do I define an Icon in QT with a compile time predefined image? | I have a png file on disk at compile time. I'd like to have it included into the compiled executable.
How do I define such an icon in Qt?
| You basically need to use the Qt resource system.
Check out Compiled-In Resources here.
Lets say this this your resource file
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>images/copy.png</file>
<file>images/cut.png</file>
<file>images/paste.png</file>
</qresource>
</RCC>
In your source you can now create QIcons by referencing images from the resource
QIcon(":/images/cut.png")
Don't forget to reference the resource file in your .pro
RESOURCES = application.qrc
This example uses images in Resource file for the icons
|
2,709,238 | 2,731,222 | WinApi equivalent of .NET KeyPreview | In .Net there is a feature called KeyPreview. How can I do this in WinApi. Maybe I don't necessarily need this but my hWnd has WM_KEYDOWN, but it does not receive it when my Text Box has focus. How can I achieve this?
Thanks
*Using pure Win32API...
is there an alternative, how could I handle the Text Box's WM_KEYDOWN?
| You can try subclassing the edit control. Either "instance subclassing", to trap messages for only one window, or "global subclassing" to trap messages for all windows of that class (in your application, not system-wide).
The example here (http://msdn.microsoft.com/en-us/library/ms997565.aspx) shows how to subclass an edit control and trap the WM_GETDLGCODE message -it wouldn't be that difficult to change it to WM_KEYDOWN.
You may have problems previewing the keys used for dialog commands, e.g. TAB or RETURN, as they may be trapped higher up the food chain. You may need to look at changing WM_GETDLGCODE as well.
|
2,709,257 | 2,709,290 | trying to sort a simple string in c++ | #include "stdio.h"
#include "conio.h"
#include <iostream>
using namespace std;
int main (void)
{
char my_char[] = "happy birthday";
int i;
bool j=false;
char my_char_temp[1];
do
{
for (i=0;i<sizeof(my_char)-2;i++)
{
j=false;
if (my_char[i+1] < my_char[i])
{
my_char_temp[0]=my_char[i+1];
my_char[i+1] = my_char[i];
my_char[i] = my_char_temp[0];
j=true;
}
}
}while (j);
cout << my_char;
}
What am I doing wrong?
I'm just trying to sort the letters within the char.
The output I get is completely wrong.
| You are resetting j to false each and every time you compare two characters.
This means that, if you swap two characters, and you are NOT at the end of your array, you will forget that you have swapped them.
Move the j=false; from inside the for-loop to just inside the do-loop.
And you owe me a bottle of Jack for saving your ass on a homework assignment on Sunday afternoon.
|
2,709,283 | 2,709,295 | C++ delete static_cast<void*> (pointer) behavior | suppose the code does the following:
T *pointer = new T();
delete static_cast<void*>(pointer);
what is result? Undefined, memory leak, memory is deleted?
| The behavior is undefined. Concerning the delete expression, the C++ standard says:
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined. (§5.3.5/3)
Then the footnote to this paragraph clearly states:
This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void (note 73).
|
2,709,315 | 2,709,502 | Is Boost.Tuple compatible with C++0x variadic templates? | I was playing around with variadic templates (gcc 4.5) and hit this problem :
template <typename... Args>
boost::tuple<Args...>
my_make_tuple(Args... args)
{
return boost::tuple<Args...>(args...);
}
int main (void)
{
boost::tuple<int, char> t = my_make_tuple(8, 'c');
}
GCC error message :
sorry, unimplemented: cannot expand 'Arg ...' into a fixed-length argument list
In function 'int my_make_tuple(Arg ...)'
If I replace every occurrence of boost::tuple by std::tuple, it compiles fine.
Is there a problem in boost tuple implementation? Or is this a gcc bug ?
I must stick with Boost.Tuple for now. Do you know any workaround ?
Thanks.
| It doesn't seem to like expanding Args... to T1, T2, T3, ..., T9 as Boost has it.
As a workaround, use constructs that don't require this expansion:
#include <boost/tuple/tuple.hpp>
template <typename... Args>
auto my_make_tuple(Args... args) -> decltype(boost::make_tuple(args...))
{
return {args...};
}
int main (void)
{
boost::tuple<int, char> t = my_make_tuple(8, 'c');
}
Another option might be to do the expanding manually, seeing that boost::tuple supports up to 10 arguments.
#include <boost/tuple/tuple.hpp>
template <unsigned, class, class...> struct nth_argument;
template <unsigned N, class Default, class T, class... Args>
struct nth_argument<N, Default, T, Args...>
{
typedef typename nth_argument<N - 1, Default, Args...>::type type;
};
template <class Default, class T, class... Args>
struct nth_argument<0, Default, T, Args...>
{
typedef T type;
};
template <unsigned N, class Default>
struct nth_argument<N, Default>
{
typedef Default type;
};
template <typename ...Args>
struct tuple_from_var_template
{
typedef boost::tuple<
typename nth_argument<0, boost::tuples::null_type, Args...>::type,
typename nth_argument<1, boost::tuples::null_type, Args...>::type,
typename nth_argument<2, boost::tuples::null_type, Args...>::type,
typename nth_argument<3, boost::tuples::null_type, Args...>::type,
typename nth_argument<4, boost::tuples::null_type, Args...>::type,
typename nth_argument<5, boost::tuples::null_type, Args...>::type,
typename nth_argument<6, boost::tuples::null_type, Args...>::type,
typename nth_argument<7, boost::tuples::null_type, Args...>::type,
typename nth_argument<8, boost::tuples::null_type, Args...>::type,
typename nth_argument<9, boost::tuples::null_type, Args...>::type
> type;
};
template <typename... Args>
typename tuple_from_var_template<Args...>::type my_make_tuple(Args... args)
{
return typename tuple_from_var_template<Args...>::type(args...);
}
int main (void)
{
boost::tuple<int, char> t = my_make_tuple(8, 'c');
}
|
2,709,339 | 2,709,368 | C++ R - tree implementation wanted | Does anyone know a good and simple to use in production code R-tree implementation? (actually, any implementations - R*, R+ or PR-tree would be great)
It doesn't matter if it is a template or library implementation, but some implementations that Google found look very disappointing...
| Check R-Trees code on http://www.superliminal.com/sources/sources.htm
also check
http://www.virtualroadside.com/blog/index.php/2008/10/04/r-tree-implementation-for-cpp/
|
2,709,434 | 2,709,510 | Assign RegEx submatches to variables or map (C++/C) | I need to extract the same type of information (e.g. First name, Last Name, Telephone, ...), from numerous different text sources, each with a different format & different order of the variables of interest.
I want a function that does the extraction based on a regular expression and returns the result as descriptive variables. In other words, instead of returning each match result as submatch[0], submatch[1], submatch[2], ..., have it do either of the following:
return std::map so that the submatches can be accessed via:
submatch["first_name"], submatch["last_name"], submatch["telephone"]
return a variables with the submatches so that the submatches can be accessed via:
submatch_first_name, submatch_last_name, submatch_telephone
I can write a wrapper class around boost::regex to do the first one, but I was hoping there would be a built-in or a more elegant way to do this in C++/Boost/STL/C.
| Can you use "named capture groups"? It seems like returning a map is exactly what you want.
For example, in RE2
Check wikipedia see if your favorite regex library supports named captures.
|
2,709,435 | 2,709,490 | C++ union data-structure, easy access of bits within a DWORD | I'm running through a set of DirectX tutorials online and I have the following structure:
struct CUSTOMVERTEX
{
FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag
DWORD color; // from the D3DFVF_DIFFUSE flag
}
My basic understanding of directX leads me to thing tha color is made up of 8-bit alpha, red, green and blue channels.
I am attempting to get east access to these channels. Rather than write the following code numerous times (within the CUSTOMVERTEX structure):
public: int red()
{
return (color & 0x00FF0000) >> 16;
}
I could write a more elegant somution with a combination of a union and a structure e.g.
struct CUSTOMVERTEX
{
FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag
#pragma pack(2)
union
{
DWORD color; // from the D3DFVF_DIFFUSE flag
struct
{
char a;
char r;
char g;
char b;
};
};
}
However this does not appear to function as expected, the values in r, g, & b almost appear the reverse of whats in color e.g. if color is 0x12345678 a = 0x78, r = 0x56. Is this an endieness issue?
Also what other problems could I be expecting from this solution? e.g. overflow from the color members?
I guess what I'm asking is ... is there a better way to do this?!
| Yes, this is an endianness issue. If you are supporting just one platform, you can lay out the struct members according to the architecture's endianness. If you are dealing with multiple architectures, you will need #define multiple struct member layouts, dependent on endianness.
Structs and unions always look more elegant to me, but bitwise operations are the more portable of the two. When I do stuff like this, I stick an assert into my startup code to make sure the struct is the size I expect it to me, before indeterminate nastiness ensues.
In C++, you might write a class that encapsulates your data and performs your operations for you.
|
2,709,487 | 2,709,532 | Displaying (rendering) HTML from a string in QT | I have html in a QString, what widget can I use to display it?
(QWebView is not necessary as I dont access Internet)
| QWebViews setHtml():
The QWebView class provides a widget that is used to view and edit web documents.
In Qt QWebView is the widget that renders pages for you - if you don't need the networking features it provides, simply don't use them.
|
2,709,524 | 2,709,935 | Which graphical environment? | Which graphical environment (MFC, ATL, QT etc.) should I concentrate on, in order to be more employable? I don't want to spend months learning something only to discover that "no one" really use this or this really sucks, and "all" pros are using only such and such.
| Compare the number of jobs on various employment web sites for each technology you are asking. I believe MFC is still in most demand, but may be wrong.
|
2,709,669 | 2,709,687 | RTTI and Portability in C++ | If a compiler doesn't "support" RTTI, does that mean that the compiler can not handle class hierarchies that have virtual functions in them? Or have I been misunderstanding the literature about how RTTI isn't portable, and the issues lie elsewhere?
Thank you all for your comments!
| RTTI is not needed for virtual functions.
It is mainly used for dynamic_cast and typeid.
|
2,709,699 | 2,709,751 | Using a variable in a mysql query, in a C++ MFC program | After extensive trawling of the internet, I still haven't found any solution for this problem.
I'm writing a small C++ app that connects to an online database and outputs the data in a listbox.
I need to enable a search function using an edit box, but I can't get the query to work while using a variable.
My code is:
res = mysql_perform_query (conn, "select distinct artist from Artists");
//res = mysql_perform_query (conn, "select album from Artists where artist = ' ' ");
while((row = mysql_fetch_row(res)) != NULL){
CString str;
UpdateData();
str = ("%s\n", row[0]);
UpdateData(FALSE);
m_list_control.AddString(str);
}
The first "res =" line is working fine, but I need the second one to work. I have a member variable m_search_edit set up for the edit box, but any way that I try to include it in the sql statement causes errors.
eg.
res = mysql_perform_query (conn, "select album from Artists where artist = '"+m_search_edit+" ' ");
causes this error:
error C2664: 'mysql_perform_query' : cannot convert parameter 2 from 'class CString' to 'char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called"
And when I convert m_search_edit to a char* it gives me a " Cannot add 2 pointers" error.
Is there any way around this?
| The problem here is that you are probably building for Unicode, which means that CString consists of wide characters. You can't directly concatenate an ASCII string with a wide character string (and you can't concatenate string literals with the + operator either).
I think the clearest way to build the query string here is by using the CT2CA macro to convert the contents of the edit control from Unicode to ASCII and CStringA::Format to insert them in the string
CStringA query;
query.Format("select album from Artists where artist = '%s'", CT2CA(m_search_edit));
res = mysql_perform_query(conn, query);
And as Thomas pointed out, you should be aware that this leaves the door open for SQL injection...
EDIT: I'm not sure where this mysql_perform_query API comes from, but from the error message you posted it looks like it also requires a writable buffer (char * instead of const char *). Since I can't find documentation for it, I don't know how big it expects that buffer to be, but to get a modifiable buffer out of a CString, look into the GetBuffer() and ReleaseBuffer() methods:
CStringA query;
query.Format(...); // Replace ... with parameters from above
char * buffer = query.GetBuffer(MAX_STRING_LENGTH); // make length big enough for mysql
res = mysql_perform_query(conn, buffer)
query.ReleaseBuffer();
EDIT2 (in response to latest comment):
Thank you for providing the definition of your mysql_perform_query function. When asking questions in the future, keep in mind it's helpful to know when you've created helper functions like this one.
In this case, your mysql_perform_query function never modifies the query string -- the only thing it does is pass it to mysql_query, which takes a const char *, so there's no reason you shouldn't declare its parameter const too. Once you do that, you'll find my first answer works (no need for GetBuffer/ReleaseBuffer):
MYSQL_RES *mysql_perform_query(MYSQL *conn, const char * query)
{
// Body as written in comment.
}
|
2,709,719 | 2,709,733 | Throwing out of range exception in C++ | This code works;
int at(int index) {
if(index < 1 || index >= size)
throw 0;
return x[index];
}
Yet this doesn't
int at(int index) {
if(index < 1 || index >= size)
throw std::out_of_range;
return x[index];
}
I get the error "expected primary expression before ';'". Now... it surprises me because I know std::out_of_range exists and I have
#include <stdexcept>
| Replace throw std::out_of_range; with throw std::out_of_range ("blah");. I.e. you need to create an object, you cannot throw a type.
|
2,710,010 | 2,710,030 | How to speed up calculation of length of longest common substring? | I have two very large strings and I am trying to find out their Longest Common Substring.
One way is using suffix trees (supposed to have a very good complexity, though a complex implementation), and the another is the dynamic programming method (both are mentioned on the Wikipedia page linked above).
Using dynamic programming
The problem is that the dynamic programming method has a huge running time (complexity is O(n*m), where n and m are lengths of the two strings).
What I want to know (before jumping to implement suffix trees): Is it possible to speed up the algorithm if I only want to know the length of the common substring (and not the common substring itself)?
| Will it be faster in practice? Yes. Will it be faster regarding Big-Oh? No. The dynamic programming solution is always O(n*m).
The problem that you might run into with suffix trees is that you trade the suffix tree's linear time scan for a huge penalty in space. Suffix trees are generally much larger than the table you'd need to implement for a dynamic programming version of the algorithm. Depending on the length of your strings, it's entirely possible that dynamic programming will be faster.
Good luck :)
|
2,710,098 | 2,710,183 | C++, generic programming and virtual functions. How do I get what I want? | This is what I would like to do using templates:
struct op1
{
virtual void Method1() = 0;
}
...
struct opN
{
virtual void MethodN() = 0;
}
struct test : op1, op2, op3, op4
{
virtual void Method1(){/*do work1*/};
virtual void Method2(){/*do work2*/};
virtual void Method3(){/*do work3*/};
virtual void Method4(){/*do work4*/};
}
I would like to have a class that simply derives from a template class that provides these method declarations while at the same time making them virtual. This is what I've managed to come up with:
#include <iostream>
template< size_t N >
struct ops : ops< N - 1 >
{
protected:
virtual void DoStuff(){ std::cout<<N<<std::endl; };
public:
template< size_t i >
void Method()
{ if( i < N ) ops<i>::DoStuff(); }
//leaving out compile time asserts for brevity
};
template<>
struct ops<0>
{
};
struct test : ops<6>
{
};
int main( int argc, char ** argv )
{
test obj;
obj.Method<3>(); //prints 3
return 0;
}
However, as you've probably guessed, I am unable to override any of the 6 methods I have inherited. I'm obviously missing something here. What is my error? No, this isn't homework. This is curiosity.
| Tested with GCC 4.3. Don't even know why I spent time on this :-/
#include <iostream>
template <std::size_t N>
struct mark
{ };
template <std::size_t N>
struct op : op <N - 1>
{
virtual void do_method (const mark <N>&) = 0;
};
template <>
struct op <1>
{
virtual void do_method (const mark <1>&) = 0;
};
struct test : op <2>
{
template <std::size_t K>
void
method ()
{ do_method (mark <K> ()); }
virtual void do_method (const mark <1>&)
{ std::cout << "1\n"; }
virtual void do_method (const mark <2>&)
{ std::cout << "2\n"; }
};
int
main ()
{
test x;
x.method <1> ();
x.method <2> ();
}
I don't know how to move the "prettifier" method() template function out of test.
|
2,710,194 | 2,710,313 | Register C function in Lua table | How to register a C function in Lua, but not in a global context, but as a table field?
| void register_c_function(char const * const tableName, char const * const funcName, CFunctionSignature funcPointer)
{
lua_getfield(lstate, LUA_GLOBALSINDEX, tableName); // push table onto stack
if (!lua_istable(lstate, -1)) // not a table, create it
{
lua_createtable(lstate, 0, 1); // create new table
lua_setfield(lstate, LUA_GLOBALSINDEX, tableName); // add it to global context
// reset table on stack
lua_pop(lstate, 1); // pop table (nil value) from stack
lua_getfield(lstate, LUA_GLOBALSINDEX, tableName); // push table onto stack
}
lua_pushstring(lstate, funcName); // push key onto stack
lua_pushcfunction(lstate, funcPointer); // push value onto stack
lua_settable(lstate, -3); // add key-value pair to table
lua_pop(lstate, 1); // pop table from stack
}
|
2,710,224 | 2,710,352 | Trying to make a plugin system in C++/Qt | I'm making a task-based program that needs to have plugins. Tasks need to have properties which can be easily edited, I think this can be done with Qt's Meta-Object Compiler reflection capabilities (I could be wrong, but I should be able to stick this in a QtPropertyBrowser?)
So here's the base:
class Task : public QObject
{
Q_OBJECT
public:
explicit Task(QObject *parent = 0) : QObject(parent){}
virtual void run() = 0;
signals:
void taskFinished(bool success = true);
}
Then a plugin might have this task:
class PrinterTask : public Task
{
Q_OBJECT
public:
explicit PrinterTask(QObject *parent = 0) : Task(parent) {}
void run()
{
Printer::getInstance()->Print(this->getData()); // fictional
emit taskFinished(true);
}
inline const QString &getData() const;
inline void setData(QString data);
Q_PROPERTY(QString data READ getData WRITE setData) // for reflection
}
In a nutshell, here's what I want to do:
// load plugin
// find all the Tasks interface implementations in it
// have user able to choose a Task and edit its specific Q_PROPERTY's
// run the TASK
It's important that one .dll has multiple tasks, because I want them to be associated by their module. For instance, "FileTasks.dll" could have tasks for deleting files, making files, etc.
The only problem with Qt's plugin setup is I want to store X amount of Tasks in one .dll module. As far as I can tell, you can only load one interface per plugin (I could be wrong?). If so, the only possible way to do accomplish what I want is to create a FactoryInterface with string based keys which return the objects (as in Qt's Plug-And-Paint example), which is a terrible boilerplate that I would like to avoid.
Anyone know a cleaner C++ plugin architecture than Qt's to do what I want?
Also, am I safely assuming Qt's reflection capabilities will do what I want (i.e. able to edit an unknown dynamically loaded tasks' properties with the QtPropertyBrowser before dispatching)?
| Sounds like you've been giving this a thorough thought, which is great and needed. I cannot comment on the Qt specifics, but be sure to not miss out on these pieces of plugin advice, particularly versioning: Plugin Architecture
EDIT: The original link above is borked (was added 8 years ago...). The Wayback Machine has a copy though
|
2,710,423 | 2,720,661 | Setting Position of source and listener has no effect | First time i've worked with OpenAL, and for the life of my i can't figure out why setting the position of the source doesn't have any effect on the sound. The sounds are in stero format, i've made sure i set the listener position, the sound is not realtive to the listener and OpenAL isn't giving out any error.
Can anyone shed some light?
Create Audio device
ALenum result;
mDevice = alcOpenDevice(NULL);
if((result = alGetError()) != AL_NO_ERROR)
{
std::cerr << "Failed to create Device. " << GetALError(result) << std::endl;
return;
}
mContext = alcCreateContext(mDevice, NULL);
if((result = alGetError()) != AL_NO_ERROR)
{
std::cerr << "Failed to create Context. " << GetALError(result) << std::endl;
return;
}
alcMakeContextCurrent(mContext);
SoundListener::SetListenerPosition(0.0f, 0.0f, 0.0f);
SoundListener::SetListenerOrientation(0.0f, 0.0f, -1.0f);
The two listener functions call
alListener3f(AL_POSITION, x, y, z);
Real vec[6] = {x, y, z, 0.0f, 1.0f, 0.0f};
alListenerfv(AL_ORIENTATION, vec);
I set the sources position to 1,0,0 which should be to the right of the listener but it has no effect
alSource3f(mSourceHandle, AL_POSITION, x, y, z);
Any guidance would be much appreciated
| Arrrr, Stero isn't localised. It all makes sense now because steros channels are already computed where mono isn't so panning is calculated by openAL.
|
2,710,507 | 2,710,520 | Mixing Objective-C and C++ | I'm trying to mix Objective-C with C++. When I compile the code, I get several errors.
A.h
#import <Cocoa/Cocoa.h>
#include "B.h"
@interface A : NSView {
B *b;
}
-(void) setB: (B *) theB;
@end
A.m
#import "A.h"
@implementation A
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.
}
-(void) setB: (B *) theB {
b = theB;
}
@end
B.h
#include <iostream>
class B {
B() {
std::cout << "Hello from C++";
}
};
Here are the errors:
/Users/helixed/Desktop/Example/B.h:1:0 /Users/helixed/Desktop/Example/B.h:1:20: error: iostream: No such file or directory
/Users/helixed/Desktop/Example/B.h:3:0 /Users/helixed/Desktop/Example/B.h:3: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'B'
/Users/helixed/Desktop/Example/A.h:5:0 /Users/helixed/Desktop/Example/A.h:5: error: expected specifier-qualifier-list before 'B'
/Users/helixed/Desktop/Example/A.h:8:0 /Users/helixed/Desktop/Example/A.h:8: error: expected ')' before 'B'
/Users/helixed/Desktop/Example/A.m:26:0 /Users/helixed/Desktop/Example/A.m:26: error: expected ')' before 'B'
/Users/helixed/Desktop/Example/A.m:27:0 /Users/helixed/Desktop/Example/A.m:27: error: 'b' undeclared (first use in this function)
| You need to name your .m files .mm. And you will be able to compile C++ code with Objective-C.
So, following your example, your AView.m file should be named AView.mm. It's simple as that. It works very well. I use a lot of std containers (std::vector, std::queue, etc) and legacy C++ code in iPhone projects without any complications.
|
2,710,719 | 2,710,868 | bitset to dynamic bitset | I have a function where i use bitset.Now i need to convert it to a dynamic bitset..
but i don't know how.
Can somebody help me ?
set<string> generateCandidates(set<string> ck,unsigned int k){
set<string> nk ;
for (set<string>::const_iterator p = ck.begin( );p != ck.end( ); ++p){
for (set<string>::const_iterator q = ck.begin( );q != ck.end( ); ++q){
bitset<4> bs1(*p);
bitset<4> bs2(*q);
bs1|= bs2 ;
if(bs1.count() == k){
nk.insert(bs1.to_string<char,char_traits<char>,allocator<char> >());
}
}
}
return nk;
}
| The difference isn't that big:
boost::dynamic_bitset<> bs1(*p);
boost::dynamic_bitset<> bs2(*q);
bs1 |= bs2;
if(bs1.count() == k){
std::string str;
boost::to_string(bs1, str);
nk.insert(str);
}
|
2,710,721 | 2,710,746 | Using a type parameter and a pointer to the same type parameter in a function template | I've written a template function to determine the median of any vector or array of any type that can be sorted with sort. The function and a small test program are below:
#include <algorithm>
#include <vector>
#include <iostream>
using namespace::std;
template <class T, class X>
void median(T vec, size_t size, X& ret)
{
sort(vec, vec + size);
size_t mid = size/2;
ret = size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}
int main()
{
vector<double> v;
v.push_back(2); v.push_back(8);
v.push_back(7); v.push_back(4);
v.push_back(9);
double a[5] = {2, 8, 7, 4, 9};
double r;
median(v.begin(), v.size(), r);
cout << r << endl;
median(a, 5, r);
cout << r << endl;
return 0;
}
As you can see, the median function takes a pointer as an argument, T vec. Also in the argument list is a reference variable X ret, which is modified by the function to store the computed median value.
However I don't find this a very elegant solution. T vec will always be a pointer to the same type as X ret. My initial attempts to write median had a header like this:
template<class T>
T median(T *vec, size_t size)
{
sort(vec, vec + size);
size_t mid = size/2;
return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}
I also tried:
template<class T, class X>
X median(T vec, size_t size)
{
sort(vec, vec + size);
size_t mid = size/2;
return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid];
}
I couldn't get either of these to work. My question is, can anyone show me a working implementation of either of my alternatives?
Thanks for looking!
| The idiomatic approach is to use iterators. To enable this, you can derive the return type from the iterator:
template <class I>
typename iterator_traits<I>::value_type median(I start, I finish)
{
...
}
|
2,710,750 | 2,710,775 | What is the correct less operator for simple class with two int members? | What is the correct operator< for the following class?
struct Person {
int height;
int width;
friend bool operator<(const Person&, const Person&);
};
Thanks!
| That's entirely up to you and how you would want people to naturally sort. If you want short people first, but skinny to come before tall if they are the same height:
friend bool operator<(const Person& a, const Person& b) {
return a.height != b.height ? a.height < b.height : a.width < b.width;
}
If you want some measure of a person's surface area to determine ordering:
friend bool operator<(const Person& a, const Person& b) {
return a.height * a.width < b.height * b.width;
}
|
2,710,765 | 5,233,034 | No-op deallocator for boost::shared_ptr | Is there a stock no-op deallocator in Boost to use with boost::shared_ptr for static objects, etc.
I know it's ultra-trivial to write, but I don't want to sprinkle my code with extra tiny functions if there is already one available.
| Yes there is one here:
#include <boost/serialization/shared_ptr.hpp> // for null_deleter
class Foo
{
int x;
};
Foo foo;
boost::shared_ptr< Foo > sharedfoo( &foo, boost::serialization::null_deleter() );
There is, of course, a danger with the fact that you need to know the function you call doesn't store the shared_ptr for later use, as it actually goes against the policy of shared_ptr in that the underlying object remains valid until that of the last instance of the shared_ptr.
|
2,710,844 | 2,710,874 | Why is 'unbounded_array' more efficient than 'vector'? | It says here that
The unbounded array is similar to a
std::vector in that in can grow in
size beyond any fixed bound. However
unbounded_array is aimed at optimal
performance. Therefore unbounded_array
does not model a Sequence like
std::vector does.
What does this mean?
| It appears to lack insert and erase methods. As these may be "slow," ie their performance depends on size() in the vector implementation, they were omitted to prevent the programmer from shooting himself in the foot.
insert and erase are required by the standard for a container to be called a Sequence, so unlike vector, unbounded_array is not a sequence.
No efficiency is gained by failing to be a sequence, per se.
However, it is more efficient in its memory allocation scheme, by avoiding a concept of vector::capacity and always having the allocated block exactly the size of the content. This makes the unbounded_array object smaller and makes the block on the heap exactly as big as it needs to be.
|
2,711,005 | 2,711,023 | 2D collision detection and stuff with OpenGL | I am working on a simple 2D openGL project. It contains a main actor you can control with the keyboard arrows. I got that to work okay. What I am wanting is something that can help explain how to make another actor object follow the main actor. Maybe a tutorial on openGL. The three main things I need to learn are the actor following, collision detection, and some kind of way to create gravity. Any good books or tutorials to help get me in the right direction would be great.
| You could use a physics library like Chipmunk Physics, which lets you attach springs and things between the two objects and detect when they hit each other and other things.
|
2,711,170 | 2,711,191 | returning a pointed to an object within a std::vector | I have a very basic question on returning a reference to an element of a vector .
There is a vector vec that stores instances of class Foo. I want to access an element from this vector . ( don't want to use the vector index) . How should I code the method getFoo here?
#include<vector>
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
class Foo {
public:
Foo(){};
~Foo(){};
};
class B {
public:
vector<Foo> vec;
Foo* getFoo();
B(){};
~B(){};
};
Foo* B::getFoo(){
int i;
vec.push_back(Foo());
i = vec.size() - 1;
// how to return a pointer to vec[i] ??
return vec.at(i);
};
int main(){
B b;
b = B();
int i = 0;
for (i = 0; i < 5; i ++){
b.getFoo();
}
return 0;
}
| Why use pointers at all when you can return a reference?
Foo& B::getFoo() {
vec.push_back(Foo());
return vec.back();
}
Note that references, pointers and iterators to a vectors contents get invalidated if reallocation occurs.
Also having member data public (like your vec here) isn't good practice - it is better to provide access methods for your class as needed.
|
2,711,272 | 2,711,282 | Declaring an uninitialized variable without a null constructor | Consider the DUPoint class, whose declaration appears below. Assume this code appears in a file named DUPoint.h:
#include <string>
class DUPoint {
public:
DUPoint (int x, int y);
int getX () const;
int getY () const;
void setX (int x);
void setY (int y);
void print();
private:
int x_;
int y_;
};
Is it true that you cannot declare an uninitialized DUPoint variable with a statement such as DUPoint P; using this class as currently configured because it has no null constructor?
| Yes, if there is a user-declared constructor, no default constructor will be generated implicitly by the compiler.
|
2,711,343 | 2,711,376 | Some exam questions about C++ vectors and arrays | Hey guys, I have a CS exam tomorrow. Just want to get a few questions cleared up. Thanks a lot, and I really appreciate the help.
Que 1.
What are parallel vectors?
Vectors of the same length that contain data that is meant to be processed together
Vectors that are all of the same data type
Vectors that are of the same length
Any vector of data type parallel
Que 2.
Arrays are faster and more efficient than vectors.
True
False
Que 3.
Arrays can be a return type of a function call.
True
False
Que 4.
Vectors can be a return type of a function call.
True
False
| Question 1
The term "parallel vector" is non-standard... (to me, it means that the dot product of their directions is 1!), so you will need to look at your notes and see what the teacher's own meaning of "parallel" is.
Question 2
This is a tricky question. Array construction (of primitives w/o initialization) is faster and more efficient than vector construction (because vectors will initialize their contents). However, if you are just passing around vectors by constant reference and using the subscript operator to access their content then there is no difference in efficiency (those subscript operations are inlined and don't perform any bounds checking). Best ask your teacher, because this is arguably not something that can be presented as a true/false question.
Question 3
Your teacher really likes trick questions, it would seem. No, you cannot return a fixed-sized array from a function; however, you can return an array as a pointer to the first element of a heap-allocated array. Most likely your teacher intends the answer to this question to be false, but the nuances are important.
Question 4
True. This is the only trivial question in this list.
|
2,711,430 | 2,711,460 | How do I prevent race condition WITHOUT using locks in C++? | How do I prevent a race condition WITHOUT locking or using mutexes/semaphors in C++? I'm dealing with a nested for loop in which I will be setting a value in an array:
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < o; ++k)
array[k] += foo(...);
More or less, I want to deal with this so that I can ensure different threads running at the same time don't write to array[k] at the same time. Any suggestions on how to approach this?
Edit: I am running on a Linux machine and I also have to use the Intel compiler. I will be using "icc" instead of "gcc" to compile the code.
| Assuming windows and that array contains elements of type LONG you could do something like:
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < o; ++k) {
LONG val = foo(...);
InterlockedAdd( &array[k], val);
}
If you're not working in Windows your platform may have a similar set of APIs. As long as your platform has an InterlockedCompareExchange() type of API you can write your own version of InterlockedAdd().
Something like the following (disclaimer - untested):
int InterlockedAdd( int volatile* pDest, int operand)
{
int curval = *pDest;
int oldval;
do {
oldval = curval;
curval = InterlockedCompareExchange( pDest, oldval + operand, oldval);
} while (curval != oldval);
return oldval+operand;
}
As far as I know, Boost only has limited support for atomic/interlocked operations, apparently only enough to support atomic manipulation of reference counts. I don't think that the support for interlocked operations in Boost is more than implementation detail (I'm currently dealing with an somewhat older version of Boost, so it's possible that this isn't the case anymore).
There are some portable libraries that support atomic compare and exchange and other atomic operations as documented parts of the interface:
Apache APR: http://apr.apache.org/docs/apr/1.4/group__apr__atomic.html
glib: http://library.gnome.org/devel/glib/stable/glib-Atomic-Operations.html
Intel Thread Building Blocks: http://www.threadingbuildingblocks.org/
Also note that C++0x will have support for atomic operations like compare/exchange - I'm not sure what the level of support is in current C++ compilers (it doesn't appear to being VS 2010).
|
2,711,432 | 2,771,613 | boost::python string-convertible properties | I have a C++ class, which has the following methods:
class Bar {
...
const Foo& getFoo() const;
void setFoo(const Foo&);
};
where class Foo is convertible to std::string (it has an implicit constructor from std::string and an std::string cast operator).
I define a Boost.Python wrapper class, which, among other things, defines a property based on previous two functions:
class_<Bar>("Bar")
...
.add_property(
"foo",
make_function(
&Bar::getFoo,
return_value_policy<return_by_value>()),
&Bar::setFoo)
...
I also mark the class as convertible to/from std::string.
implicitly_convertible<std::string, Foo>();
implicitly_convertible<Foo, std::string>();
But at runtime I still get a conversion error trying to access this property:
TypeError: No to_python (by-value) converter found for C++ type: Foo
How to achieve the conversion without too much boilerplate of wrapper functions? (I already have all the conversion functions in class Foo, so duplication is undesirable.
| I ended up giving up and implementing something similar to custom string class conversion example in Boost.Python FAQ, which is a bit verbose, but works as advertised.
|
2,711,522 | 2,711,560 | What happens if I assign a negative value to an unsigned variable? | I was curious to know what would happen if I assign a negative value to an unsigned variable.
The code will look somewhat like this.
unsigned int nVal = 0;
nVal = -5;
It didn't give me any compiler error. When I ran the program the nVal was assigned a strange value! Could it be that some 2's complement value gets assigned to nVal?
| For the official answer - Section 4.7 conv.integral
"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]
This essentially means that if the underlying architecture stores in a method that is not Two's Complement (like Signed Magnitude, or One's Complement), that the conversion to unsigned must behave as if it was Two's Complement.
|
2,711,613 | 2,711,635 | How can free() immediately followed by assignment of NULL lead to a dangling pointer? | How can the below code result in a dangling pointer.
{
char *cPointer = malloc ( some constant number );
/* some code */
free ( cPointer );
cPointer = NULL;
/* some code */
}
| It can't.
This would:
char * a = malloc(556);
char * b = a;
free(a);
a = NULL;
b is now dangling pointer, because the object it pointed to it's gone but b still stores address to memory where the object used to be, you get funny results when you try to access it - it depends if the memory has been reused or is untouched.
|
2,711,672 | 2,711,930 | Building Boost with LSB C++ Compiler | I want to build my program with LSB C++ Compiler from the Linux Standard Base http://www.linuxfoundation.org/collaborate/workgroups/lsb. Program depends on the Boost library, built with gcc 4.4 version. Compilation fails. Is it possible to build the Boost library with LSB C++ Compiler? Alternatively, is it possible to build the Boost library with some old gcc version, what version is recommended? My final goal is to get my executable and third-party Boost libraries running on most Linux distributions.
Generally, what can be done to get better binary compatibility for Linux distributions, developing C++ closed-source application depending on the Boost library?
| LSB C++ compiler is not actually a compiler. The lsbc++ executable is a wrapper around GCC compiler that is installed on your system (the actual compiler can be controlled via --lsb-cxx option). You will most likely hack into boost build system for it to call LSB wrapper instead of native gcc compiler.
So the issues that may arise are most likely not that LSB compiler can't compile the language constructs, but instead, that there are some linking issues.
For example, LSB compiler by default discards any shared libraries the code is linked against, unless they belong to LSB. This may lead to linking errors if BOOST relies on such libraries. This can be controlled via LSBCC_SHAREDLIBS environment variable, but you should make sure you ship these libs along with your product.
Another issue is that LSB falls behind GCC compiler releases (and BOOST may crawl into all dark corners of compilers). As far as I know, GCC 4.4 is not tested sufficiently, so you'd better try it with 4.3 compiler.
And Google doesn't seem to find anything related to building boost with LSBCC, so if you manage to do it, please, share your experience, for example, as your own answer to your question.
|
2,711,704 | 2,722,699 | Is factory method proper design for my problem? | here is my problem and I'm considering to use factory method in C++, what are your opinions ?
There are a Base Class and a lot of Subclasses.
I need to transfer objects on network via TCP.
I will create objects in first side, and using this object I will create a byte array TCP message, and send it to other side.
On the other side I will decompose TCP message, I will create object and I will add this object to a polymorphic queue.
| Short answer: Yes.
Long Answer: The factory method pattern is what you want.
Your network messages need to include the type and size of the object to deserialize in the message header and then on the recipient side your factory method can consume and deserialize the rest of the message body to construct the objects.
A good strategy to make this simple is to have all your classes store the data that they will be serialising and sending over the wire in a private struct. Other non-serialized class data would be outside this struct. That way you can just dump the whole struct on the network with minimal work. Obviously you may have to take into account byte order considerations if you're going cross platform (ie, big to little or little to big endian).
Something like this (I'm sure this is far from perfect as I'm just writing it off the top of my head):
enum VehicleType
{
VehicleType_Car,
VehicleType_Bike
};
class Vehicle
{
virtual size_t GetDataSize() = 0;
virtual void* GetData() = 0;
};
class Bike : Vehicle
{
private:
VehicleType _type;
size_t _dataSize;
struct BikeData
{
char[100] name;
// etc
} _data;
public:
Bike(void* data)
: Bike(static_cast<BikeData*>(data)->name)
{
}
Bike(char[]& name)
: _type(VehicleType_Bike), _dataSize(sizeof(BikeData))
{
memset(&_data.name, 0, 99);
strncpy(&_data.name, name, 99);
}
virtual size_t GetDataSize() { return _dataSize; }
virtual void* GetData() { return &_data; }
};
class Car : Vehicle
{
// etc
};
void SendVehicle(int socket, const Vehicle& vehicle)
{
write(socket, vehicle.GetData(), vehicle.GetDataSize());
}
Vehicle* ReceiveVehicle(int socket)
{
VehicleType type;
size_t dataSize;
read(socket, &type, sizeof(VehicleType));
read(socket, &dataSize, sizeof(size_t));
BYTE* data = new BYTE[dataSize];
read(socket, &data, dataSize);
Vehicle v* = CreateVehicle(type, dataSize, data);
delete[] data;
return v;
}
// The factory method.
Vehicle* CreateVehicle(VehicleType type, size_t dataSize, void* data)
{
switch(type)
{
case VehicleType_Car: return new Car(data);
case VehicleType_Bike: return new Bike(data);
}
return 0;
}
You could even avoid some memory fragmentation by using the buffer you read off the socket as the Bike's _data structure.
As always, reading up on the pattern you're using is a good idea. Here is the Wikipedia article on the Factory Method Pattern.
You should also look into the Boost Serialization library. It it will help you serialize data across systems with different endianness and word sizes. The method I have detailed above is very simple and doesn't deal with stuff like that.
|
2,711,705 | 2,711,740 | Is there any way to limit the size of an STL Map? | I want to implement some sort of lookup table in C++ that will act as a cache. It is meant to emulate a piece of hardware I'm simulating.
The keys are non-integer, so I'm guessing a hash is in order. I have no intention of inventing the wheel so I intend to use std::map for this (though suggestions for alternatives are welcome).
The question is, is there any way to limit the size of the hash to emulate the fact that my hardware is of finite size? I'd expect the hash's insert method to return an error message or throw an exception if the limit is reached.
If there is no such way, I'll simply check its size before trying to insert, but that seems like an inelegant way to do it.
| First thing is that a map structure is not a hash table, but rather a balanced binary tree. This has an impact in the lookup times O(log N) instead of O(1) for an optimal hash implementation. This may or not affect your problem (if the number of actual keys and operations is small it can suffice, but the emulation of the cache can be somehow suboptimal.
The simplest solution that you can do is encapsulate the actual data structure into a class that checks the size in each insertion (size lookups should be implemented in constant time in all STL implementations) and fails if you are trying to add one too many elements.
class cache {
public:
static const int max_size = 100;
typedef std::map<key_t, value_t> cache_map_t;
void add( key_t key, value_t value ) {
cache_map_t::const_iterator it = m_table.find( key );
if ( it != m_table.end() && m_table.size() == max_size ) {
// handle error, throw exception...
} else {
m_table.insert( it, std::make_pair(key,value) );
}
}
private:
cache_map_t m_table;
};
// Don't forget, in just one translation unit:
const int cache::max_size;
|
2,711,732 | 2,711,845 | Should boost library be dependent on structure member alignments? | I found, the hard way, that at least boost::program_options is dependent of the compiler configured structure member alignment.
If you build boost using default settings and link it with a project using 4 bytes alignment (/Zp4) it will fail at runtime (made a minimal test with program_options). Boost will generate an assert indicating a possible bad calling convention but the real reason is the structure member alignment.
Is there any way to prevent this? If the alignment makes the code incompatible shouldn't this be included in library naming?
| You need to ensure that your program and the libraries you link with have the same ABI.
The number of compiler switches that can alter the ABI of C++ classes and functions could be too large so it is clearly a problem to name more than 3000 combinations.
You could take a look here for a more detailed rationale.
|
2,711,780 | 2,711,804 | Question about char input | This is what I'm trying to do...
char input[4];
cin >> input;
cout << "Input[0]: " << input[0] << "Input[1]: " << input[1] << "Input[2]: " << input[2] << "Input[3] " << input[3]<< "Input[4] " << input[4] <<endl;
However, when I enter "P F" I get an output of this: Input[0]:P Input[1]: Input[2]:(A weird looking square with two zeros on top and a zero and 4 on the bottom) Input[3] Input[4]
Why do I get that weird character instead of F?
| cin >> separates inputs by a space, hence when you enter P<space>F, only the P is accepted into input, and F is queued for the next cin >>.
Thus after that cin >> input line, your input will look like
input[0] = 'P';
input[1] = '\0';
// input[2] = garbage;
// input[3] = garbage;
// input[4] = buffer-overflow;
Perhaps you want to use cin.getline:
cin.getline(input, 4);
cout << ...;
(Or better, use std::string which has flexible string length.)
|
2,711,848 | 2,711,926 | Finding latest release links on website for C++ Application | Basically I have written a game plugin that will allow server admins to update their administration tools from within game rather than having to go download it and install it. The releases are updated regularly, and the beta versions are nightly builds.
I am trying to find a way to grab the links from the website, but I cannot think of anyway to do this off of the top of my head. Was hoping someone here might be able to suggest something that would work.
http://www.sourcemod.net/snapshots.php
Thats the website, basically I am trying to grab the links for the latest stable branch, and latest development branch.
| The solution is simple and can be broken down into a few steps:
Fetching the links & files: Use cURL/cURLpp or Poco C++. They are easy but you may spend a few hours to learn :)
Processing/Extracting the links: Use TidyHTML to make sure the HTML is converted to valid XHTML and use XPath to extract the links. Can use libxml2 & libxslt. I'd prefer Qt C++
Fetch the extracted links and save them to pre-defined paths. Boost Filesystem may ease your task with file system.
Note that if I were to do this (well, I've done this before), I'd use only Qt C++ as it provides everything I need. Btw, Qt C++ has a dead simple way to send GET/POST requests & fetch files :) Good luck!
EDIT:
Qt C++ XML also provides CSS-like selectors which avoids you using any other libraries: http://doc.trolltech.com/4.6/qt4-6-intro.html#dom-access-api
In short: Just go for Nokia Qt C++ in all the steps. Download from: http://qt.nokia.com/downloads
|
2,711,959 | 2,711,971 | C++ array of classes | I working on a game but I have a problem with the initialization of the level. (feld is just field in german)
class level{
private:
feld spielfeld[10][10];
public:
/*
other stuff
*/
void init_feld();
};
void level::init_feld()
{
for(int i=0;i!=10;i++){
for(int n=0;n!=10;n++){
spielfeld[i][n] = new feld(land, i, n);
}
}
}
The Error:
Error: no match for »operator=« in »((level*)this)->level::spielfeld[i][n] = (operator new(24u), (, ((feld*))))« /home/nick/stratego/feld.h:18:11:
Remark: candidate is: feld& feld::operator=(const feld&) Process terminated with status 1 (0 minutes, 0 seconds) 2 errors, 0 warnings
| spielfeld[i][n] is a feld object, new feld(land, i, n) dynamically allocates a new feld object and returns a pointer to that object. If you want to assign to a feld value to spielfeld[i][n] you could use:
spielfeld[i][n] = feld(land, i, n);
Alternatively you may be able to set the appropriate members of spielfeld[i][n] directly or using other member functions.
|
2,712,070 | 2,771,958 | Producing Mini Dumps for _caught_ SEH exceptions in mixed code DLL | I'm trying to use code similar to clrdump to create mini dumps in my managed process.
This managed process invokes C++/CLI code which invokes some native C++ static lib code, wherein SEH exceptions may be thrown (e.g. the occasional access violation).
C# WinForms
->
C++/CLI DLL
->
Static C++ Lib
->
ACCESS VIOLATION
Our policy is to produce mini dumps for all SEH exceptions (caught & uncaught) and then translate them to C++ exceptions to be handled by application code. This works for purely native processes just fine; but when the application is a C# application - not so much.
The only way I see to produce dumps from SEH exceptions in a C# process is to not catch them - and then, as unhandled exceptions, use the Application.ThreadException handler to create a mini dump. The alternative is to let the CLR translate the SEH exception into a .Net exception and catch it (e.g. System.AccessViolationException) - but that would mean no dump is created, and information is lost (stack trace information in Exception isn't as rich as the mini dump).
So how can I handle SEH exceptions by both creating a minidump and translating the exception into a .Net exception so that my application may try to recover?
Edit
By "not catching exceptions" I also mean catching and then rethrowing, which does preserve the rich exception information.
Right now I'm considering never supressing System.Exception or anything deriving from System.SystemException. This means AccessViolation (and friends) always cause the program to end and produce a dump, and all other exceptions thrown need to derive from some sub-type (ApplicationException?).
| I found that with Vectored Exception Handling I can get a first-chance notification of any SEH exception and use this occasion to produce a mini dump.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.