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 |
|---|---|---|---|---|
5,855,566 | 5,855,634 | C++ parsing small float from string | I want my code to read parameters in from a file. I have this line in that file:
tol=1e-10
and I use atof to parse this into a float:
double tol;
char * c = "1e-10"
tol=atof(c);
However, it is parsed as 0 instead of 1e-10.
Edit: It turns out that it does parse correctly, I'm sorry to have bothered you guys. I forgot ... | This code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
double d = atof( "1e-10" );
cout << d << endl;
}
prints 1e-10.
|
5,855,808 | 5,855,885 | When I define a pointer to a class the error:expected constructor, destructor, or type conversion before '*' token happened | int buffer[gSizeOfGrid][gSizeOfGrid];
CList *currentCList;
Grid *currentGrid; //this line get the error
int aroundinfo[4];
//other functions are not revelant maybe? They don't
//use currentGrid.
the class Grid has the header:
class Grid
{
public:
Grid();
//create default cList object for the grid .
Grid(CL... | This is because class Grid is not visible to the pointer currentGrid. Just do following and it should work;
class Grid;
Grid *currentGrid;
I assume that you may not want to #include the Grid header before this declaration as, Grid itself is using CList. The best way should be to include all the headers before this dec... |
5,855,810 | 5,855,902 | how to connect two programs (c++,qt) | I have 2 programs. Console and QT. Console program should make some data , and qt program should than show this data. But this should be separate programs, and i do not know how can i tell QT program to do somthing from my Console. Two programs are local and Qt program is always running (so that i can not just run it e... | You might consider using something like QFileSystemWatcher to poll for changes in a particular directory, then have your console program write the file there. That way the Qt program would get a notification when the contents of the directory change.
|
5,855,928 | 5,858,764 | C# get string/characters value from c++ function which return char pointer | I've a DLL written in C++. A function of this DLL is like the following code:
C++ code:
char _H *GetPalette() {
-------Functions body
-------Functions body
return pPaletteString;
}
Now I want to get the Pallet String from that GetPalette() function in C# code.
How cou... | You can define your C++ function in C# code with string return type.
[DllImport("cl.dll")]
private static extern string GetPalette();
And than simply call it from in your C# code.
string palette = GetPalette();
Within DllImport attribute you might need to set correct calling convention CallingConvention and character... |
5,856,250 | 5,865,410 | using nsight to debug | I am using NSight to debug my CUDA code and I have question:
how can I place a breakpoint for a specific thread and block?
When I place a breakpoint on the kernel the debugger always stops at thread 0 of block 0.
| try to use CUDA Debug Focus. you can debug any thread in any block you want...
|
5,856,301 | 5,862,002 | Identifying the position in the original string from a given Boost token_iterator | If a string has been processed using a Boost tokenizer is it possible to get the position in the original string that a given token iterator is pointing to:
boost:tokenizer<> tok( "this is the original string" );
for(tokenizer<>::iterator it=tok.begin(); it!=tok.end();++it)
{
std::string strToken = *it;
int cha... | This appears to be what you're looking for:
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
int main()
{
typedef boost::tokenizer<> tok_t;
std::string const s = "this is the original string";
tok_t const tok(s);
for (tok_t::const_iterator it = tok.begin(), it_end = tok.end(); it != it_end... |
5,856,353 | 5,856,541 | C++ replacement for BYTE C macro | I'm trying to port the C openGL texture loading code found here:
http://www.nullterminator.net/gltexture.html
to C++. In particular I'm trying to deal with reading some textures in from a file, what is the best way of rewriting the following code in an idiomatic and portable manner:
GLuint texture;
int width = 256, he... | The C code should work just fine when compiled as C++.
Rather than use the BYTE type, just use the OpenGL-defined type GLbyte, which is the actual type the APIs take anyway. It is defined in gl.h thus:
typedef signed char GLbyte;
A very quick (untested!) translation of the above code into C++ would be something like:... |
5,856,425 | 5,856,452 | why C++ Initialization list is before brace? | I want to know what's difference in the following two class.
example 1:
class A
{
string name;
public:
A(const char* _name):name(_name){}
void print(){cout<<"A's name:"<<name<<endl;}
};
example 2:
class A
{
string name;
public:
A(const char* _name){name(_name);}
void print(){cout<<"A's name:"<<name<<endl;}}
w... | That's just how the language is defined. The member initializers should be placed before the body of the constructor.
|
5,856,431 | 5,858,339 | Practical C++ Sockets or Virtual machine? | I'm trying to use this library to the sockets in c + +: Practical C++ Sockets (http://cs.baylor.edu/~donahoo/practical/CSockets/practical/)
I tried a simple example of a multicast sender and receiver multicast
on Mac OSX I send and receive multicast msg.
I created a virtual machine with Windows XP and I feel the same ... | multicast only works on the same subnet so make sure your virtual machine has the same subnet as your main computer. This is why Bonjour by apple only works with devices on the same subnet because it uses multicast.
|
5,856,581 | 5,856,610 | cast integral type passed by reference | If you have an integral type t1 and a function getting a possibly smaller integral type t2 by reference, would it be problematic to call function((t2)var_t1) ?
| It would be fine to cast to t2 if and only if the function took a const reference, in which case the temporary produced by the cast to t2 could be bound to it.
Since this defeats the purpose of a reference to an integral type I would assume that the reference is non-const, so the answer is: yes, it would be problemati... |
5,856,607 | 5,856,646 | How to get time elapse percentage? | Im trying to get the time elapse percentage, what I do is first check a time interval, them I want to get the percentage of the elapsed time in that time interval, if that makes sense
Here is my code:
if ( ofGetElapsedTimeMillis() > lastTimeCheck + timePeriod ) {
lastTimeCheck = ofGetElapsedTimeMillis();
cout <... | Do you mean the time between lastTimeCheck and lastTimeCheck + timePeriod? That would be
float p = (float)(ofGetElapsedTimeMililis() - lastTimeCheck) / (float)(timePeriod);
You can probably lose one of the float casts too, but I think it's safer and no less readable to leave them in. If you need to guarantee that p is... |
5,856,759 | 5,856,847 | Can a class share a namespace's name? | Is the following C++ code valid?
namespace Foo
{
class Bar
{
// Class code here.
};
}
namespace Foo
{
namespace Bar
{
void SomeFunction();
{
// Function code here.
}
}
}
In other words, can there be a namespace with the same name as a class?
| You cannot have the arrangement you have in your question because there is no way to disambiguate Bar.
My compiler says:
error C2757: 'Bar' : a symbol with this name already exists and therefore this name cannot be used as a namespace name
|
5,857,009 | 5,857,284 | Classes as parameters error | In Weapon.h, when I try and take a class 'Entity*' as a parameter, it says "Syntax error: identifier 'Entity'" when I compile. Additionally when I roll over the text 'target', Visual C++ Express 2010 gives me the text " *target". The Entity class is fine and I'm pretty sure it's included correctly.
(I won't post Playe... | Your headers include each other because your classes refer to each other. (But your compiler doesn't suffer from a stackoverflow because of your include guards - that's a good thing!)
You should arrange your header files hierarchically, ie there are files at the 'top' which #include nothing and files 'below' which inc... |
5,857,206 | 5,858,353 | Creating a process attached to a console but with redirected standard IO handles | I have a command line application that executes other programs according to a user provided script. Some of the executed child processes are cmd.exe running various .cmd scripts. Some of the .cmd scripts are setting the console window title using the title Windows shell command. And here is the problem. If user request... | Apparently, all that needs to be done for the child process to be attached to the parent's console is to not use dwCreationFlags |= CREATE_NO_WINDOW;.
|
5,857,240 | 14,119,344 | Why there is no placement delete expression in C++? | Why C++ hasn't placement delete that directly corresponds to the placement new, i.e. calls the destructor and calls appropriate placement delete operator?
For example:
MyType *p = new(arena) MyType;
...
//current technique
p->~MyType();
operator delete(p, arena);
//proposed technique
delete(arena) p;
| operator delete is unique in being a non-member or static member function that is dynamically dispatched. A type with a virtual destructor performs the call to its own delete from the most derived destructor.
struct abc {
virtual ~abc() = 0;
};
struct d : abc {
operator delete() { std::cout << "goodbye\n"; }
}... |
5,857,310 | 5,857,326 | Ambiguous Reference/Value Versions of Functions | Consider the following function prototypes:
void Remove(SomeContainer& Vec, const std::size_t Index);
SomeContainer Remove(SomeContainer Vec, const std::size_t Index);
The second is implemented in terms of the first. That is to say, they are functionally identical in every way except that one is pass-by-reference an... | Return type is not an basis of function overloading.
Overloading of functions can only be with one of the following criteria:
No of arguments
Type of arguments &
Sequence of arguments
The return type can be ignored by the caller and hence it is not a valid criteria for function overloading.
Having said the above, ... |
5,857,621 | 5,858,077 | Avoiding Over-Use of Namespaces | My library uses several nested namespaces, laid out like the following:
Library name
Class name 1
Class name 2
Class name 3
[...]
Utilities
Class name 1
[...]
Class name 2
[...]
Class name 3
[...]
[...]
The "Utilities" namespace co... | Look at how the standard library (or boost) is organized. Nearly all of it is inside the single std namespace. There's just little to be gained by putting everything inside its own namespace.
Boost puts most things inside boost, while major libraries get a single subnamespace (boost::mpl, or boost::filesystem, for exam... |
5,857,783 | 5,870,171 | Working with Bluetooth in android kernel development linux | I want to know how can I work with Bluetooth in android using C/C++ not JAVA API if somebody have useful links or can give advice ?
I found this post but I want to know if i gives complete information ?
| During my research I found this, and now I want somebody tell me what is hciattach, hcid and where to know how can I work in Userspace
bluez: it provides 'hcid' daemon and it's responsible for all related bluetooth services
dbus-daemon: the bridge between hcid and system server
D-Bus is a simple inter-process communi... |
5,857,863 | 5,857,928 | is there light linux c++ IDE+Visual debugger like eclipse cdt? | its so heavy when i use it with xming /xserver is there something better but with the same great function eclipse have for linux c++ development / visual debugging
| Nice UI for debugger: Nemiver
Light C++ IDE: Geany
|
5,857,914 | 5,858,060 | Writing and Printing an extra 0 to sorted files and cutting node (singly linked list)off the end C++ | That may seem kind of vague so really sorry. I am writing to a file and printing to a console the sorted nodes in this singly linked list. Unfortunately, in the sort list, it both prints and writes an extra 0 at the front and cuts a value off the end. Here is the code:
void SLLIntStorage::Read(istream& r)
{
char c[... | It seems you read one entry too much. You first read an entry in the line r >> head->data;
just before the for-loop. Then you read an additional numberOfInts entries in the for-loop for a total of numberOfInts+1 entries.
|
5,857,941 | 5,862,948 | Process Id's and process names | I'm creating a windows program that basically scans the system to see if a particular process is running or not. I have the process name (AcroRd32.exe) and nothing else.
From what I've read the easiest way to create a snapshot of all processes using CreateToolhelp32Snapshot and then iterate through each process looking... | The fastest way to scan for processes is via NTDLL's NtQuerySystemInformation call. It provides you with a list of names and process IDs of all processes on the system with a single call (or more in rare cases, i.e. large # of processes). You can combine NtQuerySystemInformation and use a hash to do string comparison... |
5,857,979 | 8,795,398 | Max edit distance and suggestion based on word frequency | I need a spell checker with the following specification:
Very scalable.
To be able to set a maximum edit distance for the suggested words.
To get suggestion based on provided words frequencies (most common word first).
I took a look at Hunspell:
I found the parameter MAXDIFF in the man but doesn't seem to work as ... | We decided to use Apache Solr, which exactly fulfills our needs.
http://wiki.apache.org/solr/SpellCheckComponent#spellcheck
|
5,858,146 | 5,869,206 | SWIG : unrecognized template type contained in vector | I can't manage to have a valid SWIG output from a definition like this :
std::vector< namespaceA::refPtr< namespaceB::myObj > >
First of all, I have a custom definition of std::vector
namespace std {
template<class T> class vector {
public:
typedef size_t size_type;
typedef T value_type;
typedef value_t... | Instead of
%template(MyObjRefPtrVector) std::vector< MyObjRefPtr > >
the template declaration should be
%template(MyObjRefPtrVector) std::vector< namespaceA::refPtr< namespaceB::MyObj > >
|
5,858,150 | 5,860,991 | Problem with boost ublas matrix product | I'm trying to use the ublas part of Boost but I'm not able to multiply matrices and assign the result to other matrices for some reason.
This works:
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace boost::numeric::ublas;
typedef symmetric_matrix<int,lower> symatrix;
... | You are not guaranteed to always get a symmetric matrix back when you multiply two symmetric matrices. So this error might be related to that, although I have no idea why the code works when I change your type to a symmetric_matrix type to a double.
|
5,858,413 | 5,858,457 | C++ Pointer question | I'm new to pointers in C++. I'm not sure why I need pointers like char * something[20] as oppose to just char something[20][100]. I realize that the second method would mean that 100 block of memory will be allocated for each element in the array, but wouldn't the first method introduce memory leak issues.
If someone ... | You allocate 20 pointers in the memory, then you will need to go through each and every one of them to allocate memory dynamically:
something[0] = new char[100];
something[1] = new char[20]; // they can differ in size
And delete them all separately:
delete [] something[0];
delete [] something[1];
EDIT:
const char* te... |
5,858,560 | 5,858,680 | "LNK2019: unresolved external symbol ..." on static library chain | aeon made me realize i need to revise my question.
I have a chain of static c++ libraries that build just fine.
For 3 libraries A,B,C ("->" means a dependency): if A->B and A->C than when i build A everything builds successfully.
I'm referencing A from a c++ console application and when i build that application i get u... | There is no such thing as a static library chain - a static library does not carry with it information on which libraries it depends. You therefore need to resolve this error by linking with the library that contains the function(s) that cause the error.
|
5,858,646 | 5,864,371 | Optimizing variable-length encoding | I've got a case where I need to compress a lot of often small values. Thus I compress them with a variable-length byte encoding (ULEB128, to be specific):
size_t
compress_unsigned_int(unsigned int n, char* data)
{
size_t size = 0;
while (n > 127)
{
++size;
*data++ = (n & 127)|128;
n >>= 7;
}
*dat... | If your unsigned int values are limited to a specific range - say, 32 bits - you can unroll the loop:
size_t
compress_unsigned_int(unsigned int n, char* data)
{
size_t size;
if (n < 0x00000080U) {
size = 1;
goto b1;
}
if (n < 0x00004000U) {
size = 2;
goto b2;
}
if (n < 0x00200000U) {
si... |
5,858,920 | 5,858,944 | how to write contents for linked list to a file | I have a write function which im using to write the contents of a list to a file. The list contains only numbers.
list<int>::iterator pos;
for (pos = listStorage.begin(); pos != listStorage.end(); ++pos)
{
out << *pos << endl;
}
return out;
I am getting an error on compilation;
error C2679: bi... | I'm fairly certain this is a const issue. Is your listStorage object declared as const? If so, you need to declare your iterator as
const list<int>::iterator pos;
|
5,859,110 | 5,859,179 | After leaving the function my array is empty | In a previous question (changing value from function) I got help, which lead me to the next problem:
I used a string split and then a simple copy
int Crawl :: splitUrl(char ***arr, int max_length, char *url)
{
int idx=0;
char * p;
int i;
p = strtok (url,"/"); // call the strtok with str as 1st arg for the 1... | After I made your code compilable, it worked "fine", at least in the sense that it outputs the expected result. I make no comment on style or safety:
const int maxUrlSplit = 10;
const int maxUrlSize = 64;
int splitUrl(char ***arr, int max_length, char *url)
{
int idx=0;
char * p;
int i;
p = strtok (url,"... |
5,859,140 | 5,859,254 | Properly Overloading new/delete new[]/delete[] | This is a follow up to my previous question,
Initializing a class using malloc
Accepted answer on the question works and gives me new/delete on the avr-gcc, here is the problem but my overloaded new delete wracks havoc on regular gcc, what is the proper way to overload new delete all my classes derive from a common bas... | 'new' and 'delete' can overloaded inside the common Object base class. So, that will be applicable only to that hierarchy.
class Object {
public:
void* operator new (size_t size);
void operator delete (void *p);
};
class Derived : public Object {
// uses the above versions of new/delete
};
[Note: It's an added ad... |
5,859,455 | 5,859,814 | How to implement a generic button class that executes different functions on click? | Okay, I'm using SDL with C++ and I started working on a simple GUI for my Map Editor. From a working prototype of a single button, I wrote a generic GUIObject class and a generic Button class. But I have a problem now, In order for the class to be reusable, I need to be able to set for each button what function it call... | You can do it using function/functor/method pointers. (functions should be enough and relatively simple)
you can pass a pointer to the callback function in you button constructor.
Here is a basic example using function pointers.
class Button
{
typedef void(*eventFunction)();
Button( eventFunction funcPtr ) ... |
5,859,585 | 5,860,168 | Thrift C++ Trouble compiling provided Tutorial - Cannot Instantiate Abstract Class on TProcessor | I am trying to compile the sample c++ tutorial given in Thrift 0.5.0. I followed the directions in the tutorial\README and was able to generate the example Calculator code with no problem. But when I try and compile Calculator_server.cpp, I get the error:
error C2259: 'tutorial::CalculatorProcessor' : cannot instantiat... | The reason why you get this error is because you cannot create objects of an Abstract Class Aapache::thrift::TProcessor is an abstract class, which means that it has pure virtual methods, either directly defined in the class, or inherited from base class.
In your case, it's clearly the latter.
What you want to do is im... |
5,859,853 | 5,860,278 | Replacing console aplication interface with an MFC | I have a phone-book program written in C++, that uses the MVC model, now what I want is to replace the View component, that's basically the console window, with an MFC. How would I do that?
| Following is a schematic representation of MVC. View component is lossely coupled from the Model and the Controller and that is the whole point behind MVC design pattern. Without changing the external interfaces of View, you should be easily able to replace internal implementation by MFC. And that is what you should do... |
5,859,862 | 5,860,073 | What happens when .h & .cpp Doxygen tags conflict? | I have .h & .cpp files in my project that have /brief tags in both locations: what does doxygen do when there is a conflict between the 2 potential locations for documentation?
| It is in the documentation :
Having more than one brief or detailed description is allowed (but not recommended, as the order in which the descriptions will appear is not specified).
And the documentation for the brief command:
If multiple \brief commands are present they will be joined.
|
5,860,025 | 5,860,548 | glBlendFunc and alpha channel | I'm trying to render some transparent objects using:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
However, I don't get the result I want.
I draw a fully opaque square, and then i draw a semi-transparent square. The colors are just as a I would expect however, the alpha channel is NOT fully white as I want.
Basic... | You basically want separate blend functions for color and alpha, and this is achieved by using glBlendFuncSeparate:
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
Does the blend func you want.
|
5,860,100 | 5,860,268 | How to interpolate a color sequence? | I need to interpolate or change gradually a sequence of colors, so it goes from colorA to colorB to colorC to colorD and them back to colorA, this need to be based on time elapsed in milliseconds, any help will be much appreciated (algorithms, pseudo code will be great).
Note that I am working with RGB, it could be 0-2... | Your code is mostly correct, but you are doing the interpolation backwards: i.e. you are interpolating B->A, then C->B, then D->C, etc. This causes the discontinuity when switching colors.
You should replace this:
colorT.r = colors[colorsIndex].r * p + ( colors[colorsIndex+1].r * ( 1.0 - p ) );
with:
colorT.r = colors... |
5,860,401 | 5,860,469 | C++ FILE without writing to disk | I'm using a library that has quite a few functions that write to a FILE but none that seem to conveniently dump the same data to an object in memory. Is there any way to create a FILE object (or override it) that stores the data in memory instead of writing to disk -- I'd like to avoid the performance hit of opening/w... | Beside the already mentioned GNU's fmemopen(), which is known in POSIX as open_memstream, similar solution can be obtained combining mmap() (using MAP_ANONYMOUS) or any other OS-specific function that returns a file descriptor to a block of memory, and fdopen().
EDIT: that was wrong, mmap doesn't create a file descript... |
5,860,604 | 5,860,865 | how do I access (e.g., cout) the current value of iterators in multi-dimensional STL vectors (C++) | I'm still very much a neophyte in using STL. The following code fragment populates a 3D vector (S) and compiles (g++) fine.
const int maxBonds = 6;
vector< vector< vector<int> > > S;
S.resize(maxBonds);
populate(S); // function that returns S with various layers filled with int data in rows and columns.
for (vector<vec... | If what you need is the current vector "index", i think that the standard way to do this is to increment another value.
unsigned int countSlayer = 0;
for (vector<vector<vector<int> > >::iterator Slayer = S.begin(); Slayer != S.end(); Slayer++, ++countSlayer) {
cout << "Layer # " << countSlayer << " contains " << ... |
5,860,783 | 5,861,555 | template Base Class initialization | while in visual c++ the code below is accepted, g++ will generate the error:
"class Derived does not have any field name Base"
which is following the standard?
template <class T>
class Base
{
public:
Base(){};
};
template <class T>
class Derived:public Base<T>
{
public:
Derived():Base(){}
};
BTW: both accept
... | MSVC++ is not correct. Base is a template, not a type.
Note that in the usual case, Base is looked up in the scope of Derived<T>, which means that it will first find the injected class name inherited from Base<T>, which refers to the type Base<T>. But as you have a dependent base class, the name inherited from Base<T>... |
5,860,795 | 5,860,861 | System.DLLNotFoundException when the DLL exists | I am getting the following error when we load up a DLL in our program that throws the following error:
Unable to load DLL 'xxx.dll': The specified procedure could not be found. (Exception from HRESULT: 0x8007007F)
This doesn't make sense to me because the DLL exists and is built into our installer every time we make a... | The error isn't saying that the DLL doesn't exist; it's saying that the DLL is missing the procedure call you're trying to make. This most likely means there is another DLL with the same file name earlier in the search path, that's an older version.
Are you installing the DLL into the same folder as the calling applica... |
5,860,801 | 5,861,196 | Using a generic type with an adjacency_list | Using Boost with a simple Graph project I have defined two type of adjacency_list, one with directed edges and the other with undirected ones like this:
typedef adjacency_list < vecS, vertex_distributed_storage, directedS, Node > directedAdjacencyList;
typedef adjacency_list < vecS, vertex_distributed_storage, undirect... |
declare a generic type for my
functions so I can give both directed
and undirected adjacency_list's
Exactly. Or, to be more precise, you should have several option on how generic you need to be:
template<typename GraphT>
void loadGraph(GraphT &graph);
// or
template<typename A, typename B, typename C, typename D>... |
5,860,815 | 5,860,824 | Syntax "Foo(int v) : val_(v) {}"? | I am going through some code and I am having dificulty in comprehending the syntax:
struct Foo {
int val_;
Foo(int v) : val_(v) {} //--->THIS LINE
};
The colon : seems like a member access operator.
Can I get a clear explanation the above line?
| Its initializing val_ to v.
See: Constructor Initialization Lists
|
5,860,816 | 5,860,854 | why can't I put "cout <<" as a function argument in for_each? | std::vector<int> my_ints;
my_ints.push_back(1);
my_ints.push_back(2);
my_ints.push_back(3);
my_ints.push_back(4);
std::for_each(my_ints.begin(), my_ints.end(), std::cout.operator <<);
| Because that's a member function, and for_each wants a function object that takes a single parameter.
You'll have to write your own function:
void print_to_stdout(int i)
{
std::cout << i;
}
std::for_each(my_ints.begin(), my_ints.end(), print_to_stdout);
Another alternative is to mix std::mem_fun and std::bind1st ... |
5,860,818 | 5,861,057 | Dynamic library uses statics libraries, undefined symbols appears | I've look for a solutions to my trouble and just get some clues, but I could not find any consistent solution:
I have the code of a dynamic library (libdyna.so), that uses the functions of 3 statics libraries (libone.a, libtwo.a, libthree.a) and the log4cpp library.
And when I built it the first time everything looked... | You could use linker option --whole-archive, it will include whole static libraries and will probably solve your problem, although the library could become quite big.
g++ -shared -o libdyna.so dyna.o -Wl,-whole-archive -la -lb -lc -Wl,-no-whole-archive
man ld:
For each archive mentioned on the command line after the ... |
5,860,882 | 5,864,048 | How do I prevent AccessViolationException when returning a string from C++ to C# on 64-bit Windows? | I am using a third-party, proprietary DLL for which the source code is not available to me. Wrapper code that appears to have been auto-generated using SWIG 1.3.39 is, however, available to me. The wrapper code consists of a C++ file that compiles (using some headers that describe the DLL) to a DLL and of a C# projec... | The proper way to do this is to have your managed code allocate the buffer to which the unmanaged code will be writing (the string data). Assuming that's impractical for some reason, what you need to do is allocate the string data in a way that can be deallocated from managed code.
The usual approach is to allocate the... |
5,860,999 | 5,861,669 | Why doesn't my signal handler (which throws an exception) trigger more than once? | I am trying to set up an exception handler using sigaction. It works well for the first exception. But the sigaction handler is not called after the 1st exception and the program ends abruptly when the second signal happens.
#include <iostream>
#include <signal.h>
#include <exception>
#include <string.h>
typedef void ... | Signals and exceptions are not related to each other. What you're using (throwing exceptions from async signal handlers) is only portable between the few compilers that support it, such as GCC and Intel C/C++ with -fnon-call-exceptions.
That said, what you forgot to do is unblock the signal: when a signal handler is ex... |
5,861,244 | 5,861,733 | Cleanup on Thread Exit | When my thread exits its handle needs to be closed and reset to NULL. Rather than doing this upon the thread-closure event (e.g. ::WaitForSingleObject( s_hMyThread, TIMEOUT );), would it be valid to close the handle and reset it as the very last thing in the thread, before it returns, like this?
DWORD MyThread( LPVOID... | You can do it.
Closing a thread handle does not terminate the associated thread or remove the thread object. The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.
However, if you'll do it, you'll lose to ability to check from the m... |
5,861,497 | 5,861,541 | C++ const variable in function declaration |
Possible Duplicate:
What is the difference between const int*, const int * const, and int const *?
I am trying to understand how const works in a function parameter. What is the difference between void function(int const *&i); and void function(const int *&i);? And I would appreciate if you gave an example of their i... | They are the same, just read it from right to left:
First example: i is a reference to a pointer of a constant integer.
Second example: i is a reference to a pointer of an integer constant.
The placement of const only changes things on either side of the pointer. For example:
const int* i
means: i is a pointer to a c... |
5,861,722 | 5,921,671 | Force boost::asio::buffer to copy by value | I use boost::asio::buffer to send a message using
void Send(const std::string& messageData)
{
socket.async_write(boost::asio::buffer(messageData), ...);
}
And encounter "string iterator not dereferencable" runtime error somewhere within io_service' thread. When I create objects' variable to store message data for ... | Answer from boost-users mailing lists:
If it did, it would be completely useless as you do not have access to
any of the buffers in your completion handler.
The way to use buffer() is to pass in references to storage that you
guarantee the lifetime of in some other way.
You can either have it stored in an external obje... |
5,861,729 | 5,861,823 | Why does my C++0x code fail to compile if I include the "-ansi" compiler option? | I've come across a really weird error that only pops up if I use the ansi flag.
#include <memory>
class Test
{
public:
explicit Test(std::shared_ptr<double> ptr) {}
};
Here's the compilation, tested with gcc 4.5.2 and 4.6.0 (20101127):
g++ -std=c++0x -Wall -pedantic -ansi test.cpp
test.cpp:6:34: error: expected... | For the GNU C++ compiler, -ansi is another name for -std=c++98, which overrides the -std=c++0x you had earlier on the command line. You probably want just
$ g++ -std=c++0x -Wall minimal.cpp
(-pedantic is on by default for C++, so it's unnecessary to say it again. If you want pickier warnings, try adding -Wextra.)
|
5,861,963 | 5,861,972 | How to integrate webkit into a C++ Windows application | I've downloaded a nightly build of webkit which includes a dll, pdb. There are no header files and I can't find documentation on the API and usage of the dll.
I'm looking for example code to integrate this into a C++ application, and how to start requests, render them to window or ideally a Direct X texture.
So far m... | Why dont you use QWebKit from Qt? see this
|
5,862,216 | 5,862,302 | Merge two std::queue | Is there any function in stl that joins two std::queue objects?
| The std::queue adapter doesn't support iteration so you'd actually have to roll your own method to do this. But given that you need this functionality, you should probably consider a different container. If you need random access, the probably std::deque. If you only need front/back access like a queue consider std::li... |
5,862,261 | 5,862,323 | clearing memory allocated in stack in c++ | I was implementing a chess bot in c++ using recursive algorithms and the program evaluates over a million nodes per move.
Over time the memory it takes up gets to over 1 GIG of RAM...
But I don't really need the variables that were previously declared after I'm done with the move...
So how do I manually flush the stack... | Stack-based storage is reclaimed as soon as the function call in which it resides returns.
Is it possible that you were using heap-allocated memory (i.e. calling new) within your recursive function? Alternatively, if you're simply looking at the Windows Task Manager or an equivalent, you may be seeing "peak" usage, or... |
5,862,558 | 5,862,709 | gdb reports wrong values in simple program. Why? | #include <iostream>
int main ()
{
int* a = new int[15];
a[0] = 42;
a[1] = 43;
std::cerr << a[0];
return 0;
}
gdb says a = 0xffffffff and 'print a[0]' gives 'cannot access memory address' but why? If run outside of gdb, the program prints out '42' as expected. What is going on here? Compiled with 'g++ test2.... | Which platform are you are on? The gstabs+ debugger format is not universally supported, if you want to use it you must acquaint yourself with the fascinating differences between COFF, DWARF 2 and probably some other exe/debug formats I've never heard of. Bottom line - read the gdb manual. But your code will almost cer... |
5,862,652 | 5,862,681 | What does the 'new' keyword do in c++? |
Possible Duplicates:
When to use “new” and when not to, in C++?
When should I use the new keyword in C++?
What is the difference between A a; and A a = new A(); ?
Edited:
A* a = new A();
My mistake.
| When inside a function,
A a
declares a variable on the stack and calls A's default constructor* on a. This variable is automatically cleaned up when the variable goes out of scope.
A a = new A();
won't compile, however
A* a = new A();
creates a new A on the heap and calls A's default constructor* on the newly allo... |
5,862,700 | 5,863,297 | asynchronous communication between c++ and c# in the same app | Is there any way I can asynchronously communicate with c# code from c++, in the same process?
I mean that I have to mix managed c# and unmanaged c++ (using pInvoke) in the same WindowsCE based application. The c# part is the core of the application. The c++ part of code has a thread that listens for events and when an ... | Communicating asynchronously between C# and C++ is no different to communicating asynchronously between two parts of a C# application- you just end up calling a different function at the end- that is, C#'s delegate types will turn into function pointers on the C++ end courtesy of the .NET JIT. This is known as reverse ... |
5,862,757 | 5,881,751 | How do I link to a library with Code::Blocks? | C++ GUI Tutorial: undefined reference to TextOut
I have the same problem, but I'm new to programming and Code::Blocks, and I want to use the GDI32 library. How can I install it? I'm very confused because I can use the windows.h header, but some functions like TextOut aren't available.
| The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not c... |
5,862,770 | 6,031,228 | how to clear the key buffer while using kbhit() and getch() | heu so I'm using the above stated windows functions which luckily are for windows 2000 and up, but in making a game on the console I've run into a problem: as soon as a key is pressed the console gets passed the kbhit() function no matter if a key is not pressed again...
is there some way I can clear the keyboard pres... | Whoever told you that kbhit() was a Windows function misinformed you. kbhit(), getch() and their relatives are actually part of the (C language bindings to the) MS-DOS API. Their presence in the runtime libraries for OS/2, Win32, and other C/C++ compilers is simply to be a porting aid for MS/PC/DR-DOS programs. The ... |
5,862,902 | 5,892,366 | Array allocation of SWIG C++ type from Python | I'm writing a python script for a program that has exposed its C++ API using SWIG.
A SWIG exposed function has an interface like this:
void writePixelsRect(JoxColor* colors, int left, int top, int width, int height);
JoxColor is a POD struct looking like this:
struct JoxColor {
float r, g, b, a;
};
I can easily c... | This is kinda tricky, but could you, at least for this part of the code, use a pure-ctypes solution? Basically manually look at the symbols exported by the shared libary file to find the name that the writePixelsRect function was exported as. C++ does name mangling, so while it might just be writePixelsRect if the li... |
5,863,224 | 5,863,335 | Lockless using InterlockedCompareExchange | I am trying to make following snip of code lockless using interlocked operations, Any idea how to translate this?
if (m_Ref == 0xFFFF)
m_Ref = 1;
else
{
if (++m_Ref == 1)
CallSomething(); //
}
I was thinking something like
if (InterlockedCompareExchange(&m_Ref, 1, 0xFFFF) != 0xFFFF))
{
if (Interlo... | This looks correct at a superficial glance, but every time you use two interlocked operations in a row you are exposing yourself to the ABA problem. In this case one thread fail to change it from 0xFFFF to 1 (the ICX returns !=0xFFFF) so it goes ahead and takes the if branch and increments it. Before it runs the Interl... |
5,863,888 | 5,864,133 | How to get current UTC date in boost? | Given this is a basic question, I imagine there might be duplicates, but I could not find any.
I simply want to get the current iso_date ( like 20110503 ) from boost.
Any pointers ?
| I assume you're looking for a Boost.Date_Time-based solution?
#include <locale>
#include <string>
#include <iostream>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
std::string utc_date()
{
namespace bg = boost::gregorian;
static char const* const fmt = "%Y%m%d";
std::ostringstream ... |
5,863,966 | 5,864,056 | c++ Segmentation Fault for loop | I am getting a segmentation fault in the following code:
Node *pointerArray[6];
int onesNeighbor[]={2,3,6};
Node *createNode(int localDistance)//////creates a node
{
Node *newNode;
newNode=new Node;
newNode->wasVisited=false;
newNode->shortestDistance=localDistance;
return newNode;
}
void inser... | As a completely blind guess, without the declarations of the 2 arrays, caused by an off by one error addressing them. Either j<=2 should be j<2 and/or count=1 should be count=0. Just my attempt at psychic debugging.
Update: New version is not much clearer - you like to leave way too much to the imagination. There ar... |
5,864,043 | 5,864,067 | Vector push_back in while and for loops returns SIGABRT signal (signal 6) (C++) | I'm making a C++ game which requires me to initialize 36 numbers into a vector. You can't initialize a vector with an initializer list, so I've created a while loop to initialize it faster. I want to make it push back 4 of each number from 2 to 10, so I'm using an int named fourth to check if the number of the loop is ... | You do not initialize i. Use for (int i = 0; i<36;). Also, a new variable forth is allocated on each iteration of the loop body. Thus the test fourth==0 will always yield false.
I want to make it push back 4 of each number from 2 to 10
I would use the most straight forward approach:
for (int value = 2; value <= 10; +... |
5,864,112 | 5,864,135 | C++ Using a while loop | I'm trying to write a c++ program to read a line of inputed code (eg The Hat is flat) and get the program to output the number of capital letters the code has. (in this example it would have to output 2). I have written a piece of code using cin.get() but my code is not entering the while loop. Please help me. and plea... | flag is initialised to 0, !flag is therefore 1, and your while loop is never entered.
You could fix this with:
while (!(flag == -1))
or
while (flag != -1)
|
5,864,171 | 5,864,218 | Template argument cannot be deduced | I'm trying to use std::transform to merge two equal size vectors into a vector of pairs.
int main()
{
vector<string> names;
// fill it with names
vector<int> nums;
// fill it with numbers
typedef pair<int,string> Pair_t;
vector<Pair_t> pv;
transform(nums.begin(), nums.end(),
... | This is due to a bug in the current version of VC10 whereby the overload of make_pair cannot be resolved properly.
There is a discussion about this exact problem here, along with a workaround using a C++0x lambda expression, which is supported by VC10.
|
5,864,377 | 5,864,387 | Read from file (C++) | I can't figure out why this won't read from my file...
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int acctNum;
int checks;
double interest;
double acctBal;
double monthlyFee;
const int COL_SZ = 3;
ifstream fileIn;
fileIn... | Edit
Looking at your input you can't read such complex input with just
while(fileIn >> acctNum >> acctBal >> monthlyFee >> checks)
This code is setup to read data formatted in the following form:
11 12.12 11.11 13.13 14.12
11 12.12 11.11 13.13 14.12
11 12.12 11.11 13.13 14.12
Instead you'll have to read the various ... |
5,864,401 | 5,864,425 | Does explicit template instantiation go in cpp or header file? | Does explicit template instantiation go in cpp or header file?
| I've always done it in a cpp file. In a header, it would violate the one definition rule, at least (in the usual case) when the header was included in more than one cpp file (though there are ways to avoid that, which can be useful under a few, specific circumstances).
|
5,864,466 | 5,864,484 | C++ Multiple Inheritance - why you no work? | I am trying to figure out an interesting multiple inheritance issue.
The grandparent is an interface class with multiple methods:
class A
{
public:
virtual int foo() = 0;
virtual int bar() = 0;
};
Then there are abstract classes that are partially completing this interface.
class B : public A
{
public:
int... | You don't have diamond inheritance. The B and C base classes of D each have their own A base class subobject because they do not inherit virtually from A.
So, in D, there are really four pure virtual member functions that need to be implemented: the A::foo and A::bar from B and the A::foo and A::bar from C.
You proba... |
5,864,540 | 5,864,560 | Infinite loop with cin when typing string while a number is expected | In the following loop, if we type characters as the cin input instead of numbers which are expected, then it goes into infinite loop. Could anyone please explain to me why this occurs?
When we use cin, if the input is not a number, then are there ways to detect this to avoid abovementioned problems?
unsigned long ul_x1... | Well you always will have an infinite loop, but I know what you really want to know is why cin doesn't keep prompting for input on each loop iteration causing your infinite loop to freerun.
The reason is because cin fails in the situation you describe and won't read any more input into those variables. By giving cin ba... |
5,864,624 | 5,864,882 | Avoiding need for #define with expression templates | With the following code, "hello2" is not displayed as the temporary string created on Line 3 dies before Line 4 is executed. Using a #define as on Line 1 avoids this issue, but is there a way to avoid this issue without using #define? (C++11 code is okay)
#include <iostream>
#include <string>
class C
{
public:
C(con... | Expression templates that do store by reference typically do so for performance, but with the caveat they only be used as temporaries
Taken from the documentation of Boost.Proto (which can be used to create expression templates):
Note An astute reader will notice that the object y defined above will be left holding a ... |
5,864,669 | 5,865,158 | C++ -- why don't apply ptr_fun on ciCharLess when calling lexicographical_compare | Question 1>
I would like to know why in case I we have to use not2(ptr_fun(ciCharCompare)), while in case II, we just need to use ciCharLess. Why not use ptr_fun(ciCharLess) instead?
Question 2>
Is there a general rule that I can follow when to use which form?
Thank you
case I:
int ciCharCompare(char c1, char c2)
{
//... |
Why not use ptr_fun(ciCharLess) instead?
You could use ptr_fun(ciCharLess) if you wanted. All ptr_fun does is convert your function pointer into a functor, which contains some typedefs such as result_type. Most algorithms don't need it, but some (particularly binders such as not2) do need it.
Generally speaking, beca... |
5,864,837 | 5,864,870 | statically define an array based on a variable value C/C++ | I want to define a 2D array statically. The size of the array is determined by a variable.
How do I do this? I do not want to dynamically define the array. I heard that there is a way to do this.
| If one of the dimensions of the array is variable, then the size must be variable, then it must be dynamically sized - or sized in such a way that the the array is statically sized larger than the largest value that the variable could be.
|
5,864,858 | 5,865,109 | Parsing a C++ source file after preprocessing | I am trying to analyze c++ files using my custom made parser (written in c++). Before start parsing, I will like to get rid of all #define. I want the source file to be compilable after preprocessing. So best way will be to run C Preprocessor on the file.
cpp myfile.cpp temp.cpp
// or
g++ -E myfile.cpp > templ.cpp
[N... | You realize that g++ -E adds some of its own lines to its output which indicate line numbers in the original file? You'll find lines like
# 2 "foo.cc" 2
which indicate that you're looking at line 2 of file foo.cc . These lines are inserted whenever the regular sequence of lines is disrupted.
|
5,864,862 | 5,865,075 | Compile Error in Boost throw_exception.hpp | I am trying to use Boost's lexical_cast for my C++ project but am running into compilation errors using Visual Studio 2010 Professional.
Error is as follows:
1> VLGUI_Frame.cpp
1>c:\users\dev\external\boost_1_46_1\boost\throw_exception.hpp(54): error C2143: syntax error : missing ')' before 'constant'
1>c:\users\dev\e... | It looks like the actual error lies in the header before <boost/throw_exception.hpp>. E.g. your translation unit contains something like
#include "myheader.hpp"
#include <boost/throw_exception.hpp>
//You translation-unit specific code in here
where "myheader.hpp" contains something like
class MyClass
{
//Members
... |
5,865,638 | 5,865,920 | Function calling -Objective C | I am new to Objective-C. I am porting C++ code into Objective-C. I have
this function call eventLog() in
samples.cpp and I have declared this
function in samples.h. I have its
definition on EventLog.cpp by
including the samples.h header file.
samples.h
class samples
{
declaration;
}
samples.cpp
#include "samples.h"
v... | Looks good except are you doing your
#import <Foundation/Foundation.h>
@interface EventLog : NSObject {
}
- (void)eventLog;
@end
and
#import "EventLog.h"
#import "Samples.h"
@implementation EventLog
- (void)eventLog
{
//definition
}
@end
? If you don't have the class "wrappers" in place, you're bound to r... |
5,865,899 | 5,866,375 | Can creation of composite objects from temporaries be optimised away? | I've asked a few questions which have touched around this issue, but I've been getting differing responses, so I thought best to ask it directly.
Lets say we have the following code:
// Silly examples of A and B, don't take so seriously,
// just keep in mind they're big and not dynamically allocated.
struct A { int x[... | There are different ways of optimizing the code that you have, but rvalue references are not one. The problem is that neither A nor B can be moved at no cost, since you cannot steal the contents of the object. Consider the following example:
template <typename T>
class simple_vector {
typedef T element_type;
type... |
5,866,004 | 5,866,164 | Template Class Linked List Insertion Error | When I attempt to insert this 'food' object into my template class linked list 'test'. I get this error:
request for member ‘addNode’ in ‘test’, which is of non-class type ‘Catalog<FoodSource>()
Here's my coding, What am I doing wrong?
##main:##
int main(void)
{
Catalog<FoodSource> test();
FoodSource food();... | You just found one of the many warts present in the C++ syntax. The standard requires that if an expression can be interpreted both as a declaration and as a definition then it must be considered as a declaration. For example your code
Catalog<FoodSource> test();
is not defining a variable named test but is instead de... |
5,866,023 | 5,866,055 | help with newbie c++ code | I am learning C++ and need help with my code. I don't understand how I get compiler errors in my second function. It's almost a mirror of the first, but I don't get any errors from the first.
#include <iostream>
using namespace std;
// Function prototypes
int getLargest(int[], int);
int getSmallest(int[],int);
int ma... | In getSmallest()
for (count = 1; count < size2; count++)
You forgot to declare count
for (int count = 1; count < size2; count++)
|
5,866,546 | 5,867,528 | If a midi tempo change occur, will it change all remaining tempo change's time? | I'm decoding midi files now, it is not simple, but anyway I want to do it for myself.
I know that tempo change affects all tracks, but I'm just think that it affects all upcoming tempo changes's time. I'm just want to sure before I accept that theory.
| First, to correct the comment by @sehe, MIDI tempo changes do not use BPM for their units, though they are absolute. Tempo changes use microseconds per quarter note, not beats per minute.
That said, MIDI tempo changes are not relative to each other, so you don't need to worry about tempo changes effecting each other. O... |
5,866,566 | 5,866,634 | c++ design pattern question. single interface multiple implementations? |
Possible Duplicate:
How do you declare an interface in C++?
Hi,
What's the preferable way to create single interface and multiple implementations in c++?
For example, I'd like to implement kqueue for mac and epoll for linux and share the interface.
Thank you
| The Strategy Pattern is probably what you are looking for.
The Abstract Factory Pattern can help you fill in the right implementation when starting up.
|
5,866,856 | 5,866,926 | Undefined reference linker error when implementing function declared in anonymous namespace | When defining a function signature in an anonymous namespace within a .hpp, is it valid to place the implementation of that function within the .cpp? When I do so I get an undefined reference error.
Example:
//hpp
#ifndef __BAR_HPP_
#define __BAR_HPP_
namespace foo
{
namespace
{
struct Bar
{
... | Think of this:
namespace foo
{
struct Bar
{
void func();
};
}
void Bar::func() { /*impl...*/ }
Your code doesn't work for the same reason this code doesn't -- the definition is being provided in the wrong scope. What's needed is:
void foo::Bar::func() { /*impl...*/ }
But what do you put in place o... |
5,867,035 | 5,867,218 | memcpy that doesn't really make sense to me | I have some socket connection code that makes use of boost::asio which reads from a socket the first 5 chars, from which it can determine if the sent string was compressed using zlib library. The project I'm currently doing is a rewrite of something existing, so I took some of the existing code and made it more C++ li... | The purpose of the memcpy is to render the code unportable,
and introduce awkward bugs when the code is compiled on another
machine. What it does is set maxsz to some value depending on
what you just read. Whether the value is correct depends on the
machine. (If I can trust the names, there is also undefined
behavio... |
5,867,110 | 5,867,173 | Is assembly code created for Default Constructor in C++ | If I do not define a default constructor in a class in C++ , or any other constructors, I have read that the compiler creates a default constructor for you. But I created a test class, compiled it to assembly code and checked to find that nothing of the sort is created.
Can someone clarify how the code for default cons... | Default constructor is created if you need it, e.g:
class Foo {
std::string s;
};
...
Foo f;
12.1:
The default constructor (12.1), copy
constructor and copy assignment
operator (12.8), and destructor (12.4)
are special member functions. The
implementation will implicitly declare
these member functions fo... |
5,867,242 | 5,867,281 | How to put the contents of getenv() into a string |
Possible Duplicate:
How to read Linux environment variables in c++
How can the following be changed to do what it's supposed to do?
string s = getenv("PATH");
| You have to check that the getenv succeeded first:
char const* tmp = getenv( "PATH" );
if ( tmp == NULL ) {
// Big problem...
} else {
std::string s( tmp );
// ...
}
(Supposing I've guessed correctly with regards to "what it's
supposed to do".)
|
5,867,251 | 5,867,444 | Sharing a variable between C and C++ libraries dilemma | I have a simple problem.
I have two libraries, one compiled in C, other compiled in C++, where the C library is linked and loaded by the C++ library. I need to declare a struct instance in the C library that both can read and write to.
How do you accomplish this?
Thanks
EDIT: added that it's to be an instance of a st... | You need to create a single header file which is included by modules in both the C and C++ libraries:
#ifndef YOURSTRUCT_H
#define YOURSTRUCT_H
#ifdef __cplusplus
extern "C" {
#endif
struct YourStruct
{
// your contents here
};
#ifdef __cplusplus
}
#endif
// UPDATE: declare an instance here:
extern... |
5,867,386 | 5,867,960 | Is there a simple C or C++ API to modify selinux contexts? | In C or C++ if I want to modify the filesystem permissions of a file I can us a standard library function (chmod), which is very similar to the utility that one can execute from the UNIX prompt.
Is there an equivalently simple way to set the selinux context for a file? If so, what libraries do I need to link to and wha... | #include <selinux/selinux.h>
typedef char *security_context_t;
int setfilecon(const char *path, security_context_t con);
is probably the function you are looking for. You have to link against libselinux.
|
5,867,864 | 5,868,053 | pinvoke from vb.net using structs in call | I'm really struggling with the following pinvoke call. I've tried numerous different ways of doing this but still no joy.
The call runs through, but I get a 'Bad parameter' message back with suggests there is something wrong with the struct, since I've ran through a c++ example of this code and the parameters are al... | I don't know VB.Net syntax, but if you understand C# then here are the proper P/Invoke declarations for DVSNET_CHANNEL_INFO and DVSNET_OpenChannel:
[StructLayout(LayoutKind.Sequential)]
struct DVSNET_CHANNEL_INFO
{
uint lStructSize;
uint dwStreamNo;
uint nProtocol;
IntPtr hWndDisplay;
uint b... |
5,867,889 | 5,868,211 | Graph traversal with A* algorithm | Hey, I'm AI Student and gonna try my homework that is implementation of A* algorithm in order to traversal a graph. i use c++ codes and what i made for now is below code which is only a Graph class + insertedge and vertices functions.
but now i'm confused of how to define cost function (f= h(n) + g(n)) ...
also any cod... | What you have is only a graph search algorithm.
You forgot the essence of the A* algorithm, that is the h(n) cost, that comes from an heuristic calculation.
You have to implement a method, the h(n) that will calculate, based on yours heuritics, the possible cost from actual path to the final path, and this value will b... |
5,868,087 | 5,868,117 | C++ cin.get before a loop | hey guys, i'm designing a C++ program that reads a sequence of one or more positive real numbers terminated by a negative number. To test that this has been done correctly i'm outputting the 5th number entered by the user. i am using a while loop to populate my array HOWEVER, my cin.get(x) is making my program not comp... | If you are really trying to read character-by-character, change cin.get(x) to x = cin.get(), but from the context I'm guessing you want to read a whole number. For that, use cin >> x.
|
5,868,145 | 5,868,593 | QRegExp containing line feed, enter | I have no clue how to use QRegExp. I am trying to remove selected characters from QString but don't know how to write it as regular expression, never worked with those :( I want to remove all line feeds, enters, |, ¦, ¶ and §.
Thanks
Ps: I wish to use QString & QString::remove ( const QRegExp & rx ) and not QString & Q... | mystring.remove(QRegExp("[\\n\\r|\xA6\xB6\xA7]")); (untested)
|
5,868,246 | 5,868,272 | Output file to specific folder C++ Windows 7 | I am using C++ and trying to output a file to a specific place, a folder with a specified name in the same directory as the executable. Couldn't find a great resource on an easy way to do this but I know it must be possible.
My example. I am saving a log file and instead of having it save to the same directory as the e... | This code:
#include <fstream>
#include <iostream>
int main() {
std::ofstream of( "C:\\mydir\\somewhere\\log.txt" );
of << "hello\n";
}
will write "hello" to the file log.txt in the directory c:\mydir\somewhere, assuming the directory exists. And yes, mkdir is the right function to use. If you don't want to h... |
5,868,393 | 5,868,422 | C++: error while declaring a multimap iterator | I have a stupid problem due to my lack of knowledge about C++ templates.
I have a template class Token and a template class Task.
A Task contains some Token* inside a multimap; and I want to iterate over them.
So, in one of my function, I wrote:
template <typename C>
void Task<C>::f() {
// some code...
multima... | You want:
typename multimap<string, Token<C>* >::iterator it;
That error is so common that I think the compiler writers should make it:
error: expected ‘;’ before ‘it’ - did you forget a typename?
|
5,868,431 | 5,869,301 | What is the structure of virtual tables in C++? |
For Example I have two "intefaces" and class type:
class IPlugin
{
public:
virtual void Load(void) = 0;
virtual void Free(void) = 0;
};
class IFoo
{
public:
virtual void Foo(void) = 0;
};
class Tester: public IPlugin, public IFoo
{
public:
Tester() {};
~Tester() {};
... | Virtual tables in C++ is an implementation detail. One possible implementation is shown on the diagram below.
Two instances of the class (A and B) exists. Each instance has two vtbl pointers and the vtbl contains pointers to actual code.
In your example there is no instance data, but I have for illustrative purposes a... |
5,868,585 | 5,868,764 | How to represent this in Java | typedef struct _dmk {
unsigned short int m : 5; // 0 - 31
unsigned short int d : 5; // 0 - 31
unsigned short int c : 1; // 0 - 1
unsigned short int i : 5; /* 0 - 31 */
unsigned short int ip : 10; /* 0 - 1024 */
unsigned short int mj : ... | Just use the Java way, like getM() and setM(). Of course you have to write teir code.
Your structure describes a bit table. The first 5 bits contain the field m the next 5 bits (crossing the byte boundary) contains d and so on.
JFC (the Java API) has no implementation which can help you, so if you use structures like t... |
5,868,760 | 5,868,782 | Howto combine unit testing with assert() | Suppose that the preconditions of my object's functions are checked with assert(). How can I then, without ripping my hair off in the process, write meaningful unit tests that catches the precondition failures when I pass invalid parameters to the functions?
I mean, assert() will abort(), so how can I then perform all ... | You could replace assert() with a macro that calls your unit-testing framework when unit-testing but evaluates to assert() otherwise.
|
5,868,887 | 5,868,936 | Use of "using" in header files | I understood, that I should not use this in a header file:
using namespace foo;
Because it brings the namespace foo in the global scope for anyone who uses my header file.
Can I prevent this from happening, if I do it in my own namespace? For example like this:
namespace my_lib
{
using namespace foo;
// my st... | Yes. That is better than using using namespace foo at global level.
Yet better would be if you use foo::name syntax.
Now the using namespace foo should be restricted to the scope of the namespace my_lib, right?
Yes. It brings all the names from the namespace foo in the namespace my_lib which might cause name collis... |
5,868,947 | 5,868,972 | Difference between static variable inside and outside of a function? | static int count;
int main()
{
static int count;
}
Is there any difference between static variables declared inside and outside any function?
(I mean the scope and visibility of the variable count)
| Your first count is only accessible within the module (code in that file). Your second count is only accessible within main.
|
5,869,245 | 5,869,404 | C preprocessor macro to convert string of Fortran program to lowercase? | I would like to do the following:
In a FORTRAN program
call myPackageFunction("MPI_User_function")
...shall be transfered BY A C PREPROCESSOR MAKRO to...
call myPackageFunction("mpi_user_function_")
The reason why I want to do that is that the user of my package (an average MATLAB and Fortran user) doesn't have to know... | The C preprocessor cannot do this sort of transformation.
You will probably need to write a custom script that does this, that is automatically called by your build system before the compiler runs.
|
5,869,442 | 5,870,740 | C++ compile time function execution | I have string tags in my code that are converted to numbers and used to search values in a tag-value structure.
I have something like this:
void foo()
{
type value = search("SomeTag");
}
Where search is defined like this:
type search(const char* tag)
{
return internal_search(toNumber(tag));
}
Because all the ... | You cannot operate on string literals at compile-time, so what you want isn't feasible in the way you suggested. However, if you're contemplating to process these strings at compile-time, then this means you know all strings at compile-time, and from that you might arrive at acceptable approximations to what you want. ... |
5,869,479 | 5,869,565 | How to hide an implementation helper template? | Suppose that I have two template functions declared in a header file:
template <typename T> void func1(const T& value);
template <typename T> void func2(const T& value);
And suppose that the implementation of these functions (also in a header file and not in a source file, because they are templates) uses some impleme... | A common approach (as used in many Boost libraries, for example) is to put the helper in a namespace called details, possibly in a separate header (included from the "public" header).
There's no way to prevent it from being visible, and callable, but this quite clearly indicates that it is part of the implementation, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.