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,254,588 | 2,254,643 | CMake not using appropriate output command line argument for compiler | I'm working with CMake, and my program compiles fine with g++. However, I also wish to compiled it with bcc32 and cl.
I am running into an issue -- I'm telling cmake to use those compilers by doing a command line somewhat like "cmake -DCMAKE_CXX_COMPILER=cl" or whatnot, and it picks up the compiler correctly (ie, in that case, the MSVC variable is set to true).
However, it still seems to be using the gnu command line arguments, which causes the compiler to fail on the CXX compiler test (ie, it tries to use -o to specify and output file for cl instead of /Fe, and instead of -e for bcc32).
Is there some proper way to specify which compiler to use, or some way to fix this?
| You must use the -G parameter which defines for which compiler the make files should be generated. Just start cmake --help to see which generators are available. For example, -G "Visual Studio 9 2008" will create makefiles for 32-bit Visual Studio 2008.
|
2,254,634 | 2,254,668 | Algorithm for finding possible ways of simple, multiple encryption with the alphabet | When using a simple encryption method in which the letters are replaced by the indexing numbers of the alphabet, there are multiple ways of decrypting them, ex. ABOR is 121518 but 121518 could also be AYEAH or LAER.
Well I need an algorithm to calculate how many possible ways there are for a given number to decrypt the message via the described method (ex 1225 has 5 - ABBE, AVE, ABY, LBE, LY ).
Help me if you want to.
| You can do it recursively.
The total number of ways of encoding the first n digits is (the number of ways of encoding the first n-1 digits if the last digit is 1 <= d <= 9) + (the number of ways of encoding the first n-2 digits if the last two digits are 10 <= dd <=26).
Cache results or use dynamic programming to prevent exponential explosion. The technique is very similar to calculating Fibonacci numbers.
Here's how you could do it in Python, to demonstrate the principle:
# s is of form [1-9][0-9]*
s = '121518'
a=1 # Cache of f(i - 2)
b=1 # Cache of f(i - 1)
for i in range(1, len(s)):
a, b = b, a * (10 <= int(s[i - 1: i + 1]) <= 26) + b * (s[i] != '0')
print b
You could do it in a similar way in C++, but as this seems to be a homework / learning exercise, I hope you don't mind that I'll leave you to work out the details in C++.
|
2,254,645 | 2,254,677 | Program crash with pointers trying to make strcpy-like | This is my second problem today, pointers are giving me nightmares .
I'm trying to make a program that do the same thing that strcpy() function do..
Once i try it..it crashes and i'm 100% sure that's a pointers issue in my code. I think because there is some sort of an unintiallized pointer(*copied) ..But i've assigned NULL to it ...so can anybody tell me what's Null assignment is exactly for ? because i think i misunderstand its use. and tell me please what corrections can be made to the program to run normally .
#include <iostream>
using namespace std;
void mycpy(char *b , char *a);
int main()
{
char *original = "this is a text" ;
char *copied = 0 ;
mycpy(copied , original);
for(int i = 0 ; *(copied+i) ;i++) cout << *(copied+i) ;
return 0;
}
void mycpy(char *b , char *a){
for(int i = 0 ; *(a+i) ; i++) *(b+i) = *(a+i);
}
Thanks in advance .
| Well, your mycpy is almost right (although you could've used brackets instead of arithmetic, i.e. a[i] instead of *(a+1)). In order to print the copied string correctly, the last character must be zero, but the last one is not copied by your function. So it should rather be like
void mycpy(char *b , char *a)
{
int i;
for(i = 0 ; *(a+i) ; i++) *(b+i) = *(a+i);
*(b+i) = 0; // or "\0", doesn't matter
}
Furthermore the variable
char *copied = 0 ;
doesn't point to valid memory, so you're reading from memory position 0 which is illegal. You could define the variable as array
char copied[20];
|
2,254,706 | 2,254,966 | How to start developing with OpenGL and C++, what tools do I need to install on windows | I am inspired to start programming some things in OpenGL, using c++.
Can anyone list here what tools should be installed to start this process.
Ie
IDE
Compiler
OpenGL download etc?
| The Ne-He tutorials (to which @wich has already kindly provided a link) are quite good for what they are (but at least the last time I looked carefully, the OpenGL the teach and work with is quite dated).
glut, however, I'd generally avoid. It has a fair number of bugs, and nobody's working on fixing them. It was basically abandoned in a beta test state in the late 1990s, so it seems doubtful (at best) that anybody will ever even try to fix them.
A couple of alternatives to glut (both apparently in active development) are GLFW and FLTK. Between these, GLFW is much closer to glut in character -- a small toolkit for abstracting away most of the OS-dependent parts, so you can produce OpenGL programs with relatively little hassle. FLTK is really a full-blown GUI toolkit (though rather small as GUI toolkits go) that has a built-in glut emulation (that, at least the last time I played with it, seemed considerably better implemented than glut itself).
I suppose I should also point out one more alternative to glut: freeglut is a free re-implementation of the glut API. I can't say I really recommend it, but at least it's been actively developed a lot more recently than the original glut.
When/if you decide you want to play around with shaders, both AMD and nVidia have developer web pages. nVidia's, in particular, has a huge amount of free "stuff" available (just beware that it's easy to burn all too many hours playing around with their demos and such).
|
2,254,909 | 2,255,054 | Boost random number generator | Does anyone have a favorite boost random number generator and can you explain a little on how to implement it into code. I am trying to get the mersenne twister to work and was wondering if anyone had preference towards one of the others.
| This code is adapted from the boost manual at http://www.boost.org/doc/libs/1_42_0/libs/random/index.html:
#include <iostream>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
using namespace std;
int main() {
typedef boost::mt19937 RNGType;
RNGType rng;
boost::uniform_int<> one_to_six( 1, 6 );
boost::variate_generator< RNGType, boost::uniform_int<> >
dice(rng, one_to_six);
for ( int i = 0; i < 6; i++ ) {
int n = dice();
cout << n << endl;
}
}
To explain the bits:
mt19937 is the mersenne twister generator,which generates the raw random numbers. A typedef is used here so you can easily change random number generator type.
rng is an instance of the twister generator.
one_to_six is an instance of a distribution. This specifies the numbers we want to generate and the distribution they follow. Here we want 1 to 6, distributed evenly.
dice is the thing that takes the raw numbers and the distribution, and creates for us the numbers we actually want.
dice() is a call to operator() for the dice object, which gets the next random number following the distribution, simulating a random six-sided dice throw.
As it stands, this code produces the same sequence of dice throws each time. You can randomise the generator in its constructor:
RNGType rng( time(0) );
or by using its seed() member.
|
2,255,061 | 2,255,316 | Qt Visual Studio 2008 Add-in problem | I have Qt 2009.05 and Qt VS Add-in 1.1.3 installed on my computer with Visual Studio 2008. When I create simple Qt Application and build it, I'm receiveing this error.
1>LINK : fatal error LNK1181: cannot open input file 'qtmain.lib'
When I searched whole disk this file to add in Visual Studio library include variable, I doesn't find. I have qtmain.prl in my qt/lib directory but not qtmain.lib...
| Your qt\lib directory should contain all the lib files. You have probably downloaded qt source package but you haven't built it. Download pre-built version for Visual Studio from here.
|
2,255,164 | 2,255,231 | Help with geometry problem - don't have any idea | I am preparing myself for programming competitions and i would like to know how can i solve this problem. I guess it's geometry problem, and it seems i can't get any ideas about solving it.
Here it is:
There is a yard in which there are wolves and sheep. In the yard there are also blocks which do not allow to pass. The wolves are represented with 'w' and the sheep with 's', while the blocks are with '#' and the space where everyone can move is '.' . So a possible input will look like:
8 8
.######.
#..s...#
#.####.#
#.#w.#.#
#.#.s#s#
#s.##..#
#.w..w.#
.######.
The 2 numbers above the yard are rows x columns.
As you can see, by this there can be formed sectors of different kind in the yard. Here are two sectors:
####
#.w#
####
#s.#
In the first one there is a wolf and in the second a sheep. Because they are placed in two different sectors (i.e. the wolf can't get to the sheep), he can't eat it. If they were in a same sector, the wolf would eat the sheep.
My question for you is this: Given an input like the ones above, how should i calculate how many sheep will survive ? How can i represent the 'yard' in c++ ? How should the algorithm looks like ? Are there any materials for understanding similar problems and issues ?
Any help is appreciated. Thank you in advance.
| What you are looking for here is to find the connected components of the graph, then you just need to count the number of wolves and sheep in each one.
using namespace std;
int w, h;
cin >> w >> h;
vector<string> grid(h);
for (int i = 0; i < h; ++i)
cin >> grid[i];
vector< vector<bool> > seen(h, vector<bool>(w, false));
int survived = 0;
const int mx[] = {-1, 0, 1, 0}, my[] = {0, -1, 0, 1};
for (int i = 0; i < h; ++i)
for (int j = 0; j < w; ++j)
if (!seen[i][j] && grid[i][j] != '#')
{
int sheep = 0, wolves = 0;
typedef pair<int, int> point;
stack<point> s;
s.push(point(i, j));
while (!s.empty())
{
point p = s.top();
int x = p.first, y = p.second;
if (grid[x][y] == 'w') wolves++;
if (grid[x][y] == 's') sheep++;
for (int k = 0; k < 4; ++k)
{
int x2 = x + mx[k], y2 = y + my[k];
if (x2<0 || x2>=h || y2<0 || y2>=w) continue;
if (grid[x2][y2] == '#' || seen[x2][y2]) continue;
s.push(point(x2, y2));
}
}
survived += max(0, sheep - wolves);
}
cout << "Surviving sheep = " << survived << endl;
Running time and memory usage is optimal at O(rows x columns).
Note that code is untested, but I believe this should work.
|
2,255,171 | 2,255,259 | Is there a way to check which order symbols are loaded into an application in linux? | I know that there is the /proc/proc#/maps file that shows the libraries that are loaded, but is there a way to find out in which order the symbols are loaded?
| You can get all sorts of debug information using the LD_DEBUG environment variable. For example:
$ LD_DEBUG=files ls
This will execute ls and show you the shared libraries as they are loaded. Use LD_DEBUG=help for a list of other options.
|
2,255,449 | 2,255,463 | C++ Declaring int in the for loop | Haven't used C++ in a while. I've been depending on my Java compiler to do optimization.
What's is the most optimized way to do a for loop in C++? Or it is all the same now with moderm compilers? In the 'old days' there was a difference.
for (int i=1; i<=100; i++)
OR
int i;
for (i=1; i<=100; i++)
OR
int i = 1;
for ( ; i<=100; i++)
Is it the same in C?
EDIT:
Okay, so the overwhelming consensus is to use the first case and let the complier optimize with it if it want to.
| I'd say that trivial things like this are probably optimized by the compiler, and you shouldn't worry about them. The first option is the most readable, so you should use that.
EDIT: Adding what other answers said, there is also the difference that if you declare the variable in the loop initializer, it will stop to exist after the loop ends.
|
2,255,496 | 2,255,507 | why are special characters read false from file | Hi my program saves some settings (mostly string) to a text file, to retrieve them later, but alas! The special characters come back unrecognizable!
saveSettings saves the strings one by one...
void email::saveSettings(string filename){
ofstream savefile(filename.c_str(),ios::out | ios::trunc);
email settingsemail(this);
savefile <<mailprog<<endl;
...
loadSettings retrieves them...
bool loadSettings(string filename){
char chtemp[255];
ifstream savefile(filename.c_str(), ios::in);
if (savefile.is_open()){
savefile.getline(chtemp,255);
mailprog=chtemp;
savefile.getline(chtemp,255);
smtp=chtemp;
...
some text includes the letter 'é', which is read back as '8'
thank you for any hint
| Maybe you should consider use a unicode version of getline : )
See this article for further info
|
2,255,608 | 2,255,639 | Force Application to Wait Until WinExec Has Completed | How do I force my application to wait until WinExec has completed?
| WinExec is no longer recommended. You can use CreateProcess and WaitForSingleObject as shown in this example on Creating Processes.
|
2,255,685 | 2,255,767 | How can I read/load images in C++? | i am more a java developer and there is a standard way of reading images :
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.png"));
} catch (IOException e) {
}
but what is the c++ way of loading images? I want to load all images in a specific directory into an array or so.
| Personally, I prefer the ImageMagick library.
There are many available graphics processing libraries, and there is not a single choice that stands out as clearly superior to the others. My advice is to make a short list of 3 or 4, take a look at the documentation for each, and try to write a simple half-page program with each. Use whichever one you personally find easiest to use.
|
2,255,752 | 2,255,789 | How does operator overloading (especially 'new') arity work? | I've never quite understood how the argument lists for operator overloading are determined in a systematic way, and I'm particularly confused by a problem I have now.
When you overload a unary operator it has one argument, or zero if it's a class member. When you overload a binary operator it has two arguments, or one if it's a class member. At least that's the way it would seem to work. I'm having a problem with operator new (not a class member) however.
In a codebase I'm working in, as in other places I have seen in the past (like here for example) there is a define like #define new new(__FILE__, __LINE__) and a corresponding function with the signature void *new(size_t size, const char *file, unsigned line) or something like it for memory debugging. I note that the one in my project is actually different from the previously linked one. This presents a problem for me, because for some reason it's messing up a placement new. I've looked in The C++ Programming Language, and if it explains this I'm missing it.
Is new special in this regard, i.e. does it have specific language defined extra debug signatures? It doesn't seem like it because, as I noted above, I've seen slightly different signatures in different places. If it does, what other operators have non-obvious signatures, and what are they? Are these varied signatures instead some implementation specific extras? If so, are there any general rules as to what most implementations do? Alternatively, is it an arity issue like I implied in my title? Can you just tack on as many extra arguments as you want in the signature and if you call new with the arguments between the new keyword itself and the new type you want you can just do whatever? Or am I even more confused, and there's something else I'm missing?
Most importantly in the short term (although I'd really like to understand this), what's going on the messes up my placement new? The macro is causing an expansion something like new ("file.cpp", 100) (class_pointer) class_t. Is the problem the two groups in parenthesis maybe, or something else?
| The arity of an overloaded operator is whatever you declare. For the operators named after symbols (+), if you define them to have extra args, they will only be invoked via an explicit call. (operator +(a, b, c, d, e)). For operator new, you must give it at least one arg, but you may give it as many as you want. Regular operator overloading determines which one gets called.
|
2,255,841 | 2,256,489 | Iterating & containers of smart pointers | I have a container of smart pointers to mutable objects. I have to write two for_each loops, one for accessing the objects as read-only data and another for mutable data. The compiler is telling me that std::vector< boost::shared_ptr<Object> > is not the same as std::vector< boost::shared_ptr<const Object> >, note the const.
Here is my example code:
#include <vector>
#include "boost/shared_ptr.hpp"
#include <iterator>
class Field_Interface
{ ; };
typedef boost::shared_ptr<Field_Interface> Ptr_Field_Interface;
typedef boost::shared_ptr<const Field_Interface> Ptr_Const_Field_Interface;
struct Field_Iterator
: std::input_iterator<std::forward_iterator_tag, Ptr_Field_Interface>
{
// forward iterator methods & operators...
};
struct Const_Field_Iterator
: std::input_iterator<std::forward_iterator_tag, Ptr_Const_Field_Interface>
{
// forward iterator methods & operators...
};
struct Field_Functor
{
virtual void operator()(const Ptr_Field_Interface&) = 0;
virtual void operator()(const Ptr_Const_Field_Interface&) = 0;
};
class Record;
typedef boost::shared_ptr<Record> Ptr_Record;
typedef boost::shared_ptr<const Record> Ptr_Const_Record;
class Record_Base
{
protected:
virtual Field_Iterator beginning_field(void) = 0;
virtual Field_Iterator ending_field(void) = 0;
virtual Const_Field_Iterator const_beginning_field(void) = 0;
virtual Const_Field_Iterator const_ending_field(void) = 0;
void for_each(Field_Functor * p_functor)
{
Field_Iterator iter_begin(beginning_field());
Field_Iterator iter_end(ending_field());
for (; iter_begin != iter_end; ++ iter_begin)
{
(*p_functor)(*iter_begin);
}
}
};
class Record_Derived
{
public:
typedef std::vector<Ptr_Field_Interface> Field_Container;
typedef std::vector<Ptr_Record> Record_Container;
private:
Field_Container m_fields;
Record_Container m_subrecords;
};
Given all the above details, how do I implement the pure abstract methods of Record_Base in Record_Derived?
I've tried:
returning m_fields.begin(), which
returns conversion errors (can't
convert std::vector<...> to
Field_Iterator)
returning &m_fields[0], which is
dangerous, because it assumes stuff
about the internals of std::vector.
BTW, I'm not using std::for_each because I have to iterate over a container of fields and a container of sub-records.
| What you're doing resembles both the Composite and Visitor patterns. Those two patterns mesh well together, so it seems you are on the right track.
To implement the composite pattern, assign the following roles (refer to Composite pattern UML diagram):
Leaf -> Field
Composite -> Record
Component -> Abstract base class of Field and Record (can't think of a good name)
Component operations that are called on Composite types, are passed on recursively to all children (Leaves and other nested Composite types).
To implement the Visitor pattern, overload operator() in your functor classes for each Component subtype (Field and Record).
I recommend that you get a copy of the Design Patterns book by the "Gang of Four", which explains these concepts better and goes into much more detail than I possibly can.
Here is some sample code to whet your appetite:
#include <iostream>
#include <vector>
#include "boost/shared_ptr.hpp"
#include "boost/foreach.hpp"
class Field;
class Record;
struct Visitor
{
virtual void operator()(Field& field) = 0;
virtual void operator()(Record& field) = 0;
};
class Component
{
public:
virtual bool isLeaf() const {return true;}
virtual void accept(Visitor& visitor) = 0;
};
typedef boost::shared_ptr<Component> ComponentPtr;
class Field : public Component
{
public:
explicit Field(int value) : value_(value) {}
void accept(Visitor& visitor) {visitor(*this);}
int value() const {return value_;}
private:
int value_;
};
class Record : public Component
{
public:
typedef std::vector<ComponentPtr> Children;
Record(int id) : id_(id) {}
int id() const {return id_;}
Children& children() {return children_;}
const Children& children() const {return children_;}
bool isLeaf() const {return false;}
void accept(Visitor& visitor)
{
visitor(*this);
BOOST_FOREACH(ComponentPtr& child, children_)
{
child->accept(visitor);
}
}
private:
int id_;
Children children_;
};
typedef boost::shared_ptr<Record> RecordPtr;
struct OStreamVisitor : public Visitor
{
OStreamVisitor(std::ostream& out) : out_(out) {}
void operator()(Field& field) {out_ << "field(" << field.value() << ") ";}
void operator()(Record& rec) {out_ << "rec(" << rec.id() << ") ";}
std::ostream& out_;
};
int main()
{
RecordPtr rec(new Record(2));
rec->children().push_back(ComponentPtr(new Field(201)));
rec->children().push_back(ComponentPtr(new Field(202)));
RecordPtr root(new Record(1));
root->children().push_back(ComponentPtr(new Field(101)));
root->children().push_back(rec);
OStreamVisitor visitor(std::cout);
root->accept(visitor);
}
In Record, you may want to provide methods for manipulating/accessing children, instead of returning a reference to the underlying children vector.
|
2,256,086 | 2,256,103 | std::string::replace standard implementation? | In every language that I can think of, except C++, the function Replace essentially replaces all pieces of a string, whereas C++'s string class does not support simple operations like the following:
string s = "Hello World";
s = s.Replace("Hello", "Goodbye");
echo s; // Prints "Goodbye World"
This seems the most common use of any type of string replace function, but there doesn't seem to be a standard replace function in C++. Am I missing something here?
EDIT: I'm aware that there's not a built-in replace function like this in the standard library -- I'm wondering if there is a more or less standard implementation made from standard algorithms or something of that sort.
| You're not missing anything, its not in the standard library.
You can either write that yourself using find(), replace() etc. or use an implementation like replace_all() from Boosts string algorithm library.
|
2,256,160 | 2,256,218 | Is it reasonable to use std::basic_string<t> as a contiguous buffer when targeting C++03? | I know that in C++03, technically the std::basic_string template is not required to have contiguous memory. However, I'm curious how many implementations exist for modern compilers that actually take advantage of this freedom. For example, if one wants to use basic_string to receive the results of some C API (like the example below), it seems silly to allocate a vector just to turn it into a string immediately.
Example:
DWORD valueLength = 0;
DWORD type;
LONG errorCheck = RegQueryValueExW(
hWin32,
value.c_str(),
NULL,
&type,
NULL,
&valueLength);
if (errorCheck != ERROR_SUCCESS)
WindowsApiException::Throw(errorCheck);
else if (valueLength == 0)
return std::wstring();
std::wstring buffer;
do
{
buffer.resize(valueLength/sizeof(wchar_t));
errorCheck = RegQueryValueExW(
hWin32,
value.c_str(),
NULL,
&type,
&buffer[0],
&valueLength);
} while (errorCheck == ERROR_MORE_DATA);
if (errorCheck != ERROR_SUCCESS)
WindowsApiException::Throw(errorCheck);
return buffer;
I know code like this might slightly reduce portability because it implies that std::wstring is contiguous -- but I'm wondering just how unportable that makes this code. Put another way, how may compilers actually take advantage of the freedom having noncontiguous memory allows?
EDIT: I updated this question to mention C++03. Readers should note that when targeting C++11, the standard now requires that basic_string be contiguous, so the above question is a non issue when targeting that standard.
| I'd consider it quite safe to assume that std::string allocates its storage contiguously.
At the present time, all known implementations of std::string allocate space contiguously.
Moreover, the current draft of C++ 0x (N3000) [Edit: Warning, direct link to large PDF] requires that the space be allocated contiguously (§21.4.1/5):
The char-like objects in a
basic_string object shall be stored
contiguously. That is, for any
basic_string object s, the identity
&*(s.begin() + n) == &*s.begin() + n
shall hold for all values of n such
that 0 <= n < s.size().
As such, the chances of a current or future implementation of std::string using non-contiguous storage are essentially nil.
|
2,256,194 | 2,256,206 | Nested statements in sqlite | I'm using the sqlite3 library in c++ to query the database from *.sqlite file. can you write a query statement in sqlite3 like:
char* sql = "select name from table id = (select full_name from second_table where column = 4);"
The second statement should return an id to complete the query statement with first statement.
| Yes you can, just make sure that the nested query doesn't return more than one row. Add a LIMIT 1 to the end of the nested query to fix this. Also make sure that it always returns a row, or else the main query will not work.
If you want to match several rows in the nested query, then you can use either IN, like so:
char* sql = "select name from table WHERE id IN (select full_name from second_table where column = 4);"
or you can use JOIN:
char* sql = "select name from table JOIN second_table ON table.id = second_table.full_name WHERE second_table.column = 4"
Note that the IN method can be very slow, and that JOIN can be very fast, if you index on the right columns
|
2,256,238 | 2,257,547 | .NET compiler - CLR assembly metadata access / reflection from non-managed C++ | I have a compiler that targets the .NET runtime (CLR). The current version of the compiler is written in standard C++ (non-managed). The compiler currently lacks support to reference assemblies at compile time, so the way I "import" .NET libraries is with a utility stub generator that is written in .NET, which reflects any assembly and emits a signature stub for it in my custom language. I pre-generate stubs for all the .NET assemblies I use. At compile time, my compiler compiles the stub files to populate the symbol tables, etc. so that it can resolve types and methods from the .NET API. That is my version of "using". This was temporary, however, and now I want to add an actual "using" or "import" directive to the compiler. I need to access the metadata / type info in referenced assemblies at compile time.
My question: I need suggestions on how to access a CLR assembly metadata from non-managed C++. Or, I need justification to convert it to a managed C++ app and use the .NET reflection support. The purpose for pure C++ is that I can also compile on Linux for Mono, plus I also have partial backends for another runtime besides CLR.
| I think it is done by CoCreateObject() the CLSID_CorMetaDataDispenser coclass, asking for IID_IMetaDataDispenser interface. IMetaDataDispenser::OpenScope() lets you open the assembly metadata. Ask for IID_IMetaDataAssemblyImport, it has a bunch of methods to iterate the metadata.
Watch out for .NET 4.0, it's around the corner and I'm pretty sure the metadata format has changed. Although that should only be an issue for generating metadata, reading should be backwards compatible as long as you get the 4.0 version of the interfaces. <cor.h> has CLSIDs for the version specific metadata coclasses.
I'll assume that you're not interested in Irony.
|
2,256,351 | 2,256,355 | Why am I getting "undefined reference to `glibtop_init'" during linking? | I'm building a very small C/C++ project using eclipse and i'm getting the following during build:
make all
Building file: ../Metric.cpp
Invoking: GCC C++ Compiler
g++ -I/usr/include/glib-2.0 -I/usr/include/libgtop-2.0 -I/usr/lib/glib-2.0/include -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"Metric.d" -MT"Metric.d" -o"Metric.o" "../Metric.cpp"
Finished building: ../Metric.cpp
Building target: linuxMonitor
Invoking: GCC C++ Linker
g++ -L/usr/lib -o"linuxMonitor" ./Metric.o
./Metric.o: In function main':
/home/mike/workspace_c/linuxMonitor/Debug/../Metric.cpp:27: undefined reference toglibtop_init'
collect2: ld returned 1 exit status
make: *** [linuxMonitor] Error 1
What I can't figure out is why the linking is failing, or which linking flags to use to make this darn thing work! -L/usr/lib should be point the linker to the directory where the library is, but it still fails. When I do -l/usr/lib/myLibrary.a it still fails saying that it can't find -l/usr/lib/myLibrary.a
Any tips or advice on using the right commands for the linker would be appreciated! I'm stuck!
-Mike
| Your library file should be libsomething.a and the g++ option -lsomething
The manpage of g++ is more specific about this :
-l library
...
The linker searches a standard list of directories for the library,
which is actually a file named liblibrary.a. The linker then uses
this file as if it had been specified precisely by name.
The directories searched include several standard system
directories plus any that you specify with -L.
...
The only difference between using an -l option and
specifying a file name is that -l surrounds library with lib and .a
and searches several directories.
|
2,256,426 | 2,256,456 | Convert collection of T into collection of QVariant in Qt | In Qt, how can I convert a typed collection of objects such as a QList<T> into a QList<QVariant>? I suppose I could construct a new list and copy the elements over, converting each to a QVariant along the way, but is there a shortcut?
| Thanks to the Qt IRC chat room. It was staring me right in the face.
QList<MyClass> source = ...;
QVariant variant = QVariant::fromValue(source);
The variant here is a QList<QVariant>.
|
2,256,444 | 2,259,428 | how to write pthread_create on the same function? | Could someone please help with this? I have the following:
// part_1
if (pthread_create(&threadID, NULL, ThreadMain,
(void *) clientSocket) != 0) {
cerr << "Unable to create thread" << endl;
exit(1);
}
// part_2
void *ThreadMain(void *clientSocket) {
pthread_detach(pthread_self());
...
delete (TCPSocket *) clientSocket;
return NULL;
}
I would to have part_2 in part_1 ( I mean without calling TreadMain() function )
thanks for your replies
| If all you want to do is simply move the function for part2 inside part1, you can create a local class inside of part1, with a static member function...
class LocalFunctor
{
public:
static void *ThreadFunc(void* clientSocket)
{
pthread_detach(pthread_self());
...
delete (TCPSocket *) clientSocket;
return NULL;
}
};
then call LocalFunctor::ThreadFunc within pthread_create
pthread_create(&threadID, NULL, LocalFunctor::ThreadFunc,(void *) clientSocket)
If you're going to do this more than once, look at boost::thread or wrap this up inside a template helper class.
|
2,256,527 | 2,257,168 | how to clear the unneccessary input stream in C++ | I would like to make the user input a center number of character, e.g. 10, however, the user might input more than 10.
for(int i = 0 ; i< 10 ; i++)
cin>>x;
The extra character could make my code crash since I will ask for input later.
How can I clear the input at this moment when the user input more than 10?
Thanks so much!
| By the way, to avoid duplicating all that code every time, I once wrote a little template function to do that work:
template<typename InType> void AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString, InType & Result)
{
do
{
Os<<Prompt.c_str();
if(Is.fail())
{
Is.clear();
Is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Is>>Result;
if(Is.fail())
Os<<FailString.c_str();
} while(Is.fail());
}
template<typename InType> InType AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString)
{
InType temp;
AcquireInput(Os,Is,Prompt,FailString,temp);
return temp;
}
The first overload may be preferred if you want to avoid copying, the second may be more convenient for builtin types.
Usage examples:
//1st overload
int AnInteger;
AcquireInput(cout,cin,"Please insert an integer: ","Invalid value.\n",AnInteger);
//2nd overload (more convenient, in this case)
int AnInteger=AcquireInput(cout,cin, "Please insert an integer: ","Invalid value.\n");
|
2,256,647 | 2,256,705 | is it possible in C or C++ to create a function inside another? | Could someone please tell me if this is possible in C or C++?
void fun_a();
//int fun_b();
...
main(){
...
fun_a();
...
int fun_b(){
...
}
...
}
or something similar, as e.g. a class inside a function?
thanks for your replies,
| Wow, I'm surprised nobody has said yes! Free functions cannot be nested, but functors and classes in general can.
void fun_a();
//int fun_b();
...
main(){
...
fun_a();
...
struct { int operator()() {
...
} } fun_b;
int q = fun_b();
...
}
You can give the functor a constructor and pass references to local variables to connect it to the local scope. Otherwise, it can access other local types and static variables. Local classes can't be arguments to templates, though.
|
2,256,913 | 2,256,919 | Creating a directory In C or C++ | How to create a directory with C code (other than the method of forking and using mkdir) ? Is there anything like dirent.h? dirent.h only allows to read directories. (without using external library)
| Use the mkdir function.
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
|
2,256,945 | 2,256,974 | Removing a non empty directory programmatically in C or C++ | How to delete a non empty directory in C or C++? Is there any function? rmdir only deletes empty directory. Please provide a way without using any external library.
Also tell me how to delete a file in C or C++?
| You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty and you can remove it via the syscall.
To enumerate directories on Unix, you can use opendir(), readdir(), and closedir(). To remove you use rmdir() on an empty directory (i.e. at the end of your function, after deleting the children) and unlink() on a file. Note that on many systems the d_type member in struct dirent is not supported; on these platforms, you will have to use stat() and S_ISDIR(stat.st_mode) to determine if a given path is a directory.
On Windows, you will use FindFirstFile()/FindNextFile() to enumerate, RemoveDirectory() on empty directories, and DeleteFile() to remove files.
Here's an example that might work on Unix (completely untested):
int remove_directory(const char *path) {
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
if (d) {
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) {
int r2 = -1;
char *buf;
size_t len;
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
continue;
len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);
if (buf) {
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf)) {
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);
else
r2 = unlink(buf);
}
free(buf);
}
r = r2;
}
closedir(d);
}
if (!r)
r = rmdir(path);
return r;
}
|
2,256,950 | 19,513,296 | OpenSSL Ignore Self-signed certificate error | I'm writing a small program with the OpenSSL library that is suppose to establish a connection with an SSLv3 server. This server dispenses a self-signed certificate, which causes the handshake to fail with this message: "sslv3 alert handshake failure, self signed certificate in certificate chain."
Is there a way I can force the connection to proceed? I've tried calling SSL_CTX_set_verify like so:
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
But it does not seem to change anything.
Any suggestions?
| By default OpenSSL walks the certificate chain and tries to verify on each step, SSL_set_verify() does not change that, see tha man page. Quoting it:
The actual verification procedure is performed either using the
built-in verification procedure or using another application provided
verification function set with SSL_CTX_set_cert_verify_callback(3).
So the solution is to create a simple callback and set that one, so that you override all certificate-chain walking:
static int always_true_callback(X509_STORE_CTX *ctx, void *arg)
{
return 1;
}
SSL_CTX_set_cert_verify_callback(CTX, always_true_callback);
|
2,257,464 | 2,257,524 | Google Test and Visual Studio 2010 RC | Has anyone tried to build gtest 1.4.0 under VS 2010 RC?
I get about 400 errors when I try to build it.
Thanks in advance.
| it fails on its own tr1::tuple implementation - adding GTEST_USE_OWN_TR1_TUPLE=0 to my preprocessor defines fixed the problem for me (bugtracker issue).
|
2,257,614 | 2,257,676 | Why does my RSS grow with stack allocated memory | I have written a small server application. It stores a lot of data in strings. When stresstesting it, RSS memory grows (spotted by $top).
I have ran the program through "Instrument" - Mac OS X memory leak applicaton and it find only some minor leaks - the memory leaked was a couple of hundred bytes and the program continuously grows. When searching deeper, it seems like two functions is responsible for a large majority of the memory footprint:
std::string serialize()
{
//Build basic message
std::string result="";
//std::cout << "result: " << result << "\n";
result+=m_topic+d;
//std::cout << "result: " << result << "\n";
result+=m_message+d;
//std::cout << "result: " << result << "\n";
char buf[12];
std::cout << m_severity << "\n";
snprintf(buf, sizeof(buf), "%d", m_severity);
//std::cout << "Buffer:" << buf << "\n";
std::string temp(buf);
result+=temp+d;
//std::cout << "result: " << temp << "\n";
int messagelength=strlen(result.c_str());
snprintf(buf, sizeof(buf), "%d", messagelength);
//std::cout << "Buffer:" << buf << "\n";
std::string temp2(buf);
temp2+=d;
temp2+=result;
//std::cout << "result: " << temp2 << "\n";
return temp2;
}
and
std::string message::prettyPrint()
{
struct tm *Sys_T= NULL;
time_t Tval = 0;
Tval = time(NULL);
Sys_T = localtime(&Tval);
std::string date;
char buf[10];
sprintf(buf,"%d:%d:%d (%d/%d 2010)",Sys_T->tm_hour, Sys_T->tm_min, Sys_T->tm_sec, Sys_T->tm_mday, Sys_T->tm_mon);
date+=std::string(buf);
char sevbuf[10];
sprintf(sevbuf,"%d",m_severity);
delete Sys_T;
std::string printed= "---------------------Message--------------------- \n";
printed+= +"\n "+ date + ": [[" + getTopic() + "]]\n\n" +
+ " Message:" + m_message + "\n"
+ " Severity " + std::string(sevbuf) +" \n";
//+ " Serialized " + serialize() + "\n";
return printed;
}
As you can see this is merely stack allocated objects.
At the same time, the "Instrument" memory observer reports that the number of "active" allocated memory does not grow.
I am not so familiar with programming or these terms - my question is:
Can my application leak memory that is not reported by memory leak searching application?
Is RSS not reporting the "active" memory set but also the historical ones?
| Even though your objects are merely stack allocated, the class implementations may allocate memory in the heap. For example, std::string will do this.
Allocating and deallocating memory in the heap can lead to fragmentation, which would explain the increased memory usage. See http://en.wikipedia.org/wiki/Malloc#Heap-based
Edit: Looking closer at your code, there are other problems -- as the others have pointed out.
|
2,257,873 | 2,257,886 | Writing to a class pointer gives me an access violation error | Please view this image of the crash after I choose to debug it in MVS2010:
http://i48.tinypic.com/dr8q9u.jpg
Here's the Game.h header that shows the Game class structure, and in the picture you will see the offending method that's causing the access violation (setBot(botInfo * b)).
class botInfo; // Forward declaration
class Game {
int gameState;
int flagDropTime;
botInfo * bot;
public:
Game();
~Game(void);
void startGame();
void gameOver(int victoriousTeam);
void resetBall();
void hideBall();
int getState();
void setBot(botInfo * bot);
botInfo * getBot();
};
From an instance of botInfo (another class) I'm calling a function with this code,
(Game _dsbTrench is a member variable of the botInfo instance).
botInfo * botPointer = this;
_dsbTrench->setBot(botPointer);
Problem is, whenever I call this it causes an exception:
Unhandled exception at 0x72332569 (PubBot.dll) in MERVBot.exe: 0xC0000005: Access violation writing location 0xcdcdcdd5.
So whats the cause of this error? And how can I fix it?
Thanks.
| I don't think there is enough information for me to help. But I will try.
You are writing to memory that is not assigned to your program by the operating system -- you need to allocate the memory before you write to it.
You should not be passing the this parameter to other functions -- your offset calculations are probably off -- can't you use a reference ? .
Have you allocated memory for dsbtrench ?
-- edit --
As mentioned by the other answers"0xCDCDCDCD" is a sentinel variable used for uninitialized words.
|
2,258,115 | 2,258,193 | Templated Vector and Colour Maths library (Specialisation) | I have created a maths library that operates via templates, it allows the user to specify the size and type of the array within a class which is then used to create a maths vector of any dimension up to four. As soon as I went to create a colour class, it struck me how similar the vector and colour class are. Is there anyway in which I could reduce code reuse and use some form of inheritance or specialisation to separate:
Specific functionality (ie vector3 does not have a setXYZW() function, instead only a setXYZ()) to the dimension of which it can only be used in.
Colour class and vector class can both (in terms of array data member) be of size ranging from 1 to 4 and the both share the same operators, but differ in their use in some circumstances such as a multiply vector differs from a multiply colour.
My knowledge of templates is not that good, so I would very much appreciate if anyone can show me the best solution to such a situation?
template < std::size_t N = 3, typename T = float >
class Vector
{
typedef T Degree, Radian;
private:
T m_vecEntry[N];
public:
// arithmetic operations
Vector operator + (const Vector & _vector) const;
Vector operator - (const Vector & _vector) const;
Vector operator * (const Vector & _vector) const;
Vector operator * (float _val) const;
};
template < std::size_t N = 4, typename T = float >
class Colour
{
private:
T m_colEntry[N];
public:
// arithmetic operations
Colour operator + (const Colour& _colour) const;
Colour operator - (const Colour& _colour) const;
Colour operator * (const Colour& _colour) const;
Colour operator * (float _val) const;
};
| Your classes have a fair amount of duplicated code, it is advisable that you do something about it. A possible solution follows.
First, you take the common functionality to a base class:
template <class Derived, std::size_t N, typename T>
class VectorBase
{
protected:
VectorBase() {} // Prevent instantiation of base
Derived operator + (const Derived & _vector) const {
std::cout << "Base addition\n";
return Derived();
}
Derived operator * (T _val) const {
std::cout << "Base scalar multiplication\n";
return Derived();
}
T m_components[N];
};
Then you derive from it your Vector and Colour classes. In each derived class you use using Base::operation; to state explicitly that the corresponsing operation from the base class makes sense in the derived class.
For operations that don't make sense in the derived class you provide an alternative definition or not provide it at all (it will not be accessible since you didn't write using).
You can also add operations that were not in the base class, like Vector::norm:
template < std::size_t N = 3, typename T = float >
class Vector : VectorBase<Vector<N, T>, N, T>
{
typedef VectorBase<Vector<N, T>, N, T> Base;
typedef T Degree, Radian;
public:
using Base::operator+; // Default implementation is valid
using Base::operator*; // Default implementation is valid
T norm() const { // Not present in base class
return T();
}
};
template < std::size_t N = 4, typename T = float >
class Colour : VectorBase<Colour<N, T>, N, T>
{
typedef VectorBase<Colour<N, T>, N, T> Base;
public:
using Base::operator+; // Default implementation is valid
Colour operator * (T _val) const { // Redefines version in base class
std::cout << "Colour scalar multiplication\n";
return Colour();
}
};
The only trick in this code is that I've used the CRTP to make base class operations work with derived types.
Here is a little test program:
int main()
{
Vector<> va, vb;
va + vb;
va.norm();
va * 3.0;
Colour<> ca, cb;
ca + cb;
ca * 3.0f;
}
It prints:
Base addition
Base scalar multiplication
Base addition
Colour scalar multiplication
|
2,258,239 | 2,258,253 | Trying to use C++ in an iPhone app | I am trying to use c++ in an iphone app. I added the line
#include <cstring>
in one of my files.
I get "error: cstring: no such file or directory". What do I need to do to get it working?
My understanding is that gcc is being called, but not g++. How can I change that, or what flag can I add to force gcc to compile c++?
| Objective-C++ files must have the .mm extension by default in an iPhone app... otherwise it's probably a crazy path setting. Anything weird in the build settings?
|
2,258,259 | 2,258,284 | Creating a wchar to multibyte char function | The libc library I'm currently using is missing wctomb() so I'm looking to come up with a replacement implementation. What are some complexities I should beware of? Can I simply grab each byte in the wchar and stick them inside an char array?
| You might want to pick up a copy of P.J. Plauger's book, "The Standard C Library" - it provides a basic implementation of wctomb() along with a discussion of wide character support in general.
|
2,258,353 | 2,258,396 | What API/SDK to use for this Windows Application? | I'm going to create a utility with GUI that will run on Windows operating systems.
It should require minimum (or zero!) amount of additional libraries, files or DLLs to run because it will be executed from an installer. Because of this, i don't want to use .NET for it will require user to install .NET Framework. I know today, most of Windows installed system come with .NET Framework but in my case i cannot be sure.
The utility will...
send some data to a web site and
parse the returning data,
collect some hardware info, like MAC address,
CPU type and make, hard-disk serial
number
I suppose native Win32 API could be used for all of those above, but instead of hassling with Win32, i'd prefer using a more developer friendly API, or SDK.
Thanks in advance.
| Win32 API is the only way, and of course there are standard API - for sending data over the internet, you could use WinInet.lib/dll, to obtain information about the MAC, you could use the GetAdaptersInfo by using Iphlpapi.lib/dll,(here's a link on how to use it) for the Hard disk serial number you could use GetVolumeInformation by using kernel32.lib/dll. For the CPU Id, you might look into GetSystemInfomation
Edit: There's a C++ code, but you can easily derive a wrapper from this site Unfortunately, with WinAPI is not easy, no such thing as RAD with WinAPI but what you gain out of it is lightweight code instead of relying on SDK's, frameworks and dragging buggy dll's around with your application.
Hope this helps,
Best regards,
Tom.
|
2,258,365 | 2,258,388 | Vector (push_back); g++ -O2; Segmentation fault | I'm having problem with vector, (in the usage of push_back) but it only appears when using additional g++ flag -O2 (I need it).
#include <cstdio>
#include <vector>
typedef std::vector<int> node;
typedef std::vector<node> graph;
int main()
{
int n, k, a, b, sum;
bool c;
graph g(n, node());
c = scanf("%i%i", &n, &k);
for(int i=0; i<n; i++)
{
sum=2;
for(int j=0; j<i; j++)
sum*=2;
for(int j=0; j<sum; j++)
{
if(j%2==0)
c = scanf("%i", &a);
else
{
c = scanf("%i", &b);
a += b;
g[i].push_back(a); //---------------LINE WHICH CAUSES SEGMENTATION FAULT
}
}
}
for(int i=n-2; i>=0; i--)
{
for(size_t j=0; j<g[i].size(); j++)
{
if(g[i+1][(j*2)] >= g[i+1][(j*2)+1])
g[i][j] = g[i+1][j*2];
else
g[i][j] = g[i+1][(j*2)+1];
}
}
printf("%i\n", g[0][0]);
return 0;
}
| I think you have:
graph g(n, node());
c = scanf("%i%i", &n, &k);
in the reverse order. As it stands, the variable 'n' which you use to size graph is not initialised.
|
2,258,409 | 2,259,814 | How can I build an application like Thunderbird? Which language should I select? | I don't want to build the Thunderbird functionality. I just want to build a project with plug-in features, cross platform, and easy to install. Is there any document which point to the development of Firefox or Thunderbird?
I know the Thunderbird is build in C++, then how can i get these kind of graphics and all other function.
Please help me.
| In the spirit of other answers, I feel obliged to point out that Mozilla provides the platform they used to build their applications, including Firefox and Thunderbird, -- see XULRunner.
With XULRunner you
develop interfaces in XUL (cross-platform UI description language that Firefox and Thunderbird use) or even HTML,
develop program logic in JavaScript or, if you really need to, C++ (or even Python, like Komodo does),
have support for the same extension mechanism as used Firefox/Thunderbird
Here's a partial list of applications built on top of XULRunner: XULRunner Hall of Fame.
To answer your original question, the Mozilla platform provides rich functionality on many platforms by specifying a set of cross-platform APIs (e.g. (oversimplifying) XUL for interface definitions) and implementing each API on each platform.
Implementing such a cross-platform layer from scratch is lots of work, so instead of trying to look at and copy Thunderbird's implementation, you should pick one of the cross-platform solutions mentioned in the answers here (Mozilla, Eclipse, QT, wxWidgets, etc.)
Each has its strengths and weaknesses, without knowing your current expertise and requirements it's not possible to pick one for you.
|
2,258,539 | 2,258,571 | usage of hashtable and map | The hashtable and map is hashtable is implemented as a hash function but map is implemented as a tree.
My question is, in what situation, hashtable can not be used but a map is a must?
| One motivation for choosing to use a map over a hashtable is the constraints which each one places on the key type used in the template instantiation. As described in the documentation for hash_map in the SGI implementation of STL, an instantiation hash_map requires provision of a functor which hashes K. The STL includes a functor, std::hash, which does this, but it is only implemented for a limited set of types T.
Instantiation of std::map on the other hand only requires a functor which compares objects of type K to generate a weak ordering. The standard functor std::less will work for any T which defines an operator<.
This means that, for many user-defined types, adding the support necessary to use the type as a key in a std::map is much less than that required to use it in a std::hash_map.
Aside from the question of overhead,
Only std::map, not std::hash_map, guarantees that the keys will be ordered, so if this is a requirement, use std::map
hash_map is not part of the standard, so while some STL implementations include it, this is not true of all implementations. Using hash_map therefore has potential impact on the portability of your program.
|
2,258,561 | 2,258,621 | getting the length of an array using strlen in g++ compiler | could someone explain why i am getting this error when i am compiling the source using following g++ compiler
#include <cstdio>
#include <string>
using namespace std;
int main()
{
char source_language[50];
scanf("%16s\n",source_language);
int length = sizeof(source_language);
int sizeofchar = strlen(source_language);
printf("%d\n",sizeofchar);
}
this gives me following error
test.cpp: In function ‘int main()’:
test.cpp:31: error: ‘strlen’ was not declared in this scope
when i change the #include <string> into #include <string.h> or #include<cstring> , it works fine, i need to figure out what is the difference using #include<string> and #include<string.h> . really appreciate any help
| C++ programmers normally have to deal with at least 2 flavours of string: raw C-style strings, usually declared as char *str; or char str[123];, which can be manipulated with strlen() etc.; and C++-style strings, which have the type std::string and are manipulated with member functions like string::length(). Unfortunately this leads to a bit of confusion.
In C, #include <string.h> declares strlen() et al.
In C++, you need #include <cstring> instead, which declares them in the std namespace, so you can either call these functions as std::strlen() etc. or you need to follow up with using namespace std;, in which case you can then just call them as strlen() etc. as usual.
C++ also has a totally separate header called <string>, which declares the C++ type std::string. This header has nothing to do with strlen(), so including it will not let you access strlen().
I don't know why Mehrdad Afshari deleted his answer, which I'm essentially repeating here.
|
2,258,742 | 2,277,453 | How can I get an NPAPI plugin to read an "src" tag | i'm a little stuck on getting a plugin to work. I need it to take a "src" parameter but I can't seem to make it do this.
So i've basically got the npsimple basic plugin.
It's probably something really silly i'm missing
Joe
| You should get src as one of the parameters that are passed to NPP_New():
NPError NPP_New
(NPMIMEType pluginType,
NPP instance, uint16 mode,
int16 argc, char *argn[],
char *argv[], NPSavedData *saved)
{
char* srcValue = 0;
for(int i=0; i<argc; ++i)
{
if(strcmp("src", argn[i]) == 0) {
srcValue = argv[i];
break;
}
}
/* ... */
}
|
2,258,834 | 2,258,996 | Combine boost::lexical_cast and std::transform | I would like to write something like this, which cannot be compiled:
std::vector<A> as;
std::vector<B> bs( as.size() );
std::transform( as.beginn(), as.end(), bs.begin(), boost::lexical_cast<B> );
But this is not working, so I created a functor which is doing this for me:
template<typename Dest>
struct lexical_transform
{
template<typename Src>
Dest operator()( const Src& src ) const
{
return boost::lexical_cast<Dest>( src );
}
};
Is there an easier way to do this?
| lexical_cast has two template arguments: target type and source type. Under normal usage, the second is deduced from the call.
However, here you want to take the address of the function, and you need to specify all the template arguments:
std::transform( as.begin(), as.end(), bs.begin(), boost::lexical_cast<B, A> );
|
2,258,885 | 2,259,019 | Do other tasks while a system() command is being executed | I have this c++ program that is doing a simple ping on a specified ip address. I am not into networking so i'm just using the system() command in c++ to execute the ping from a shell and store the results in a file, that's easy.
The problem is that i want some dots to be printed on the screen while the system() command is being executed. i tried with:
while(system(cmd))
{
//execute the task here
}
but no success. I think that i should create threads or something.
Can you help me ? What exactly i am supposed to do in order to get this done as i want to ?
| You need to create a forked process using fork, like this, and using popen to read the input from the output of the command ping google.com and process it accordingly. There is an interesting guide by Beej on understanding the IPC mechanisms which is included in the code sample below...
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int rv;
FILE *ping;
char buf[2000];
switch(pid = fork()) {
case -1:
perror("fork"); /* something went wrong */
exit(1); /* parent exits */
case 0:
// We're the child
ping = popen("ping google.com", "r");
if (ping != NULL){
fgets(buf, sizeof(buf), ping);
pclose(ping);
rv = 0;
}else{
perror("popen failed");
rv = -1;
}
exit(rv);
default:
// We're the parent...
wait(&rv);
}
// Now process the buffer
return 0;
}
Hope this helps,
Best regards,
Tom.
|
2,258,900 | 2,259,152 | Unexplained out_of_range in string::substr | I have been getting a really annoying error about an std::out_of_range when calling substr. The exact error is
terminate called after throwing an
instance of 'std::out_of_range'
what(): basic_string::substr
I'm absolutely sure that tmp_request has a length greater then 1. No matter what I pass to substr—1, 2, or bodypos—it always throws that error. I'm using g++ on Unix.
Only interesting thing I can include is the string has multiple "\r\n", including one "\r\n\r\n".
In one cpp file:
std::string tmp_request, outRequest;
tmp_request = SS_Twitter->readData();
outRequest = SS_Twitter->parse(tmp_request);
In another:
std::string parse(const std::string &request)
{
std::map<std::string,std::string> keyval;
std::string outRequest;
if(request[0]=='P')
{
if(request.find("register")!=std::string::npos)
{ //we have a register request
size_t bodypos = request.find("username");
if(bodypos==std::string::npos)
{
HttpError(400,"Malformed HTTP POST request. Could not find key username.",request);
}
else
{
std::string body = request.substr(bodypos);
StringExplode(body,"&", "=",keyval);
outRequest = "doing stuff";
}
}
Update:
std::string request2("P\r\nregister\r\nusername=hello\r\n\r\n");
std::string body = request2.substr(4);
That throws the same error. Now I know this is perfectly valid and correct code, but it's still throwing the error.
//removed source link
| I modified your sample slightly to decrease amount of indentation used.
There are 5 "test cases" and none causes any problem. Could you please provide a sample request to reproduce the problem you're having.
EDIT: Forgot to mention: if this sample as it is (with commented-out bits) doesn't produce that error, your best bet is that you have a bug in your StringExplode function. You could post its source, to get a more helpful advice.
EDIT2:
In your StringExplode, change results[tmpKey] = tmpKey.substr(found+1); to results[tmpKey] = tmpResult[i].substr(found+1);. Change int found to size_t found, and remove all of if (found > 0), that will fix your mysterious out_of_range. You were substr-ing a wrong string. Just in case, here's the code with a fix:
void StringExplode(std::string str, std::string objseparator, std::string keyseperator,
std::map <std::string, std::string> &results)
{
size_t found;
std::vector<std::string> tmpResult;
found = str.find_first_of(objseparator);
while(found != std::string::npos)
{
tmpResult.push_back(str.substr(0,found));
str = str.substr(found+1);
found = str.find_first_of(objseparator);
}
if(str.length() > 0)
{
tmpResult.push_back(str);
}
for(size_t i = 0; i < tmpResult.size(); i++)
{
found = tmpResult[i].find_first_of(keyseperator);
while(found != std::string::npos)
{
std::string tmpKey = tmpResult[i].substr(0, found);
results[tmpKey] = tmpResult[i].substr(found+1);
found = tmpResult[i].find_first_of(keyseperator, found + results[tmpKey].size());
}
}
}
Initial test code:
#include <iostream>
#include <map>
#include <string>
std::string parse(const std::string &request)
{
std::map<std::string,std::string> keyval;
std::string outRequest;
if(request[0] != 'P')
return outRequest;
if(request.find("register") == std::string::npos)
return outRequest;
//we have a register request
size_t bodypos = request.find("username");
if(bodypos==std::string::npos)
{
// HttpError(400,"Malformed HTTP POST request. Could not find key username.",request);
// you said HttpError returns, so here's a return
return outRequest;
}
std::string body = request.substr(bodypos);
// StringExplode(body,"&", "=",keyval);
outRequest = "doing stuff";
return outRequest;
}
int main()
{
std::string request("P\r\nregister\r\nusername=hello\r\n\r\n");
std::cout << "[" << parse(request) << "]\n";
request = "Pregisternusername=hello\r\n\r\n";
std::cout << "[" << parse(request) << "]\n";
request = "Pregisternusername=hello";
std::cout << "[" << parse(request) << "]\n";
request = "registernusername=hello";
std::cout << "[" << parse(request) << "]\n";
request = "";
std::cout << "[" << parse(request) << "]\n";
return 0;
}
This outputs, predictably:
[doing stuff]
[doing stuff]
[doing stuff]
[]
[]
|
2,259,025 | 2,259,163 | How do I get boost::condition::timed_wait to compile? | I want to wait on a condition for up to 1 second. I've try passing in time_duration:
boost::posix_time::time_duration td = boost::posix_time::milliseconds(50);
readerThread_cond_.timed_wait(lock, boost::bind(&XXXX::writeCondIsMet, this), td);
but I get the error:
/usr/include/boost/thread/pthread/condition_variable.hpp:156:
error: no match for ‘operator+’ in
‘boost::get_system_time() +
wait_duration’
I've also tried passing a xtime:
boost::xtime t;
boost::xtime_get(&t, boost::TIME_UTC);
readerThread_cond_.timed_wait(lock, boost::bind(&XXXX::writeCondIsMet, this), td);
but I get the error:
I'm linking with libboost_thread and libboost_date_time and the code compiles and run ok when I use just use wait, but the error message it seems to related to resolving the templates in the boost header files. It seems to be saying I am not passing in the right thing, but I just don't understand it.
| I think it's the argument order.
As I've never had a problem with timed_wait, I looked at some details at the boost reference to boost.thread, condition_variable_any, timed_wait. What I find most interesting is this:
template<typename lock_type,typename duration_type,typename predicate_type>
bool timed_wait(lock_type& lock,duration_type const& rel_time,predicate_type predicate);
The time-duration is actually the second argument, not the third.
[edit] BTW, you really should check the return value of timed_wait, as otherwise you won't know whether you the condition got signaled, or a timeout occurred. timed_wait will not throw due to a timeout![/edit]
|
2,259,193 | 2,259,218 | How do I see the output of my code using Visual C++ 2008? | I wrote some very simple code since I'm just starting C++ and I want to get warmed up with the syntax and compiler before our binary tree assignment.
#include <iostream>
using namespace std;
int main(){
cout << "Hello";
return 0;
}
The only output I'm receiving is:
1> Build started: Project: First-BinaryTree, Configuration: Debug Win32 ------
1>Compiling...
1>First-BinaryTree.cpp
1>Build log was saved at "file://c:\Users\Administrator\Documents\Visual Studio 2008\Projects\First-BinaryTree\First-BinaryTree\Debug\BuildLog.htm"
1>First-BinaryTree - 0 error(s), 0 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
It appears to have run correctly, but I don't see Hello in the output anywhere.
| It seems that you have just built the project, without starting it. If you want to start it, you have to go to Debug->Run. However, keep in mind that in that way the executable will be started, it'll run and its window will disappear in some fraction of second, since it does almost nothing. If you want to be able to see the output, you may:
place a breakpoint on the return 0 (so the debugger will pause the program before its end);
start the program without debugging (if I recall correctly you have to do CTRL+F5, however there's the related menu item in the Debug menu); VS.NET will add a "Press a key to exit" message before the end of the application, however the debugger won't be attached to your executable;
add just before the return the following code:
cout<<"Press Return to exit...";
cin.sync();
cin.ignore();
For the flushing thing that someone mentioned, I'm not sure if it's needed: at the end of the program the cout object is destroyed, so it should flush itself automatically (correct me if I am wrong).
|
2,259,321 | 2,259,328 | usleep() function does not allow a loop to continue | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int i=0;
while(i<10)
{
printf("%d", i);
usleep(10000); // or sleep(1)
i++;
}
return 0;
}
I want the program to last 10 secs, i.e. print 1 - wait 1 sec - print 2 - wait 1 sec and so on until the end. But it doesn't do that - it just waits for all the time (10 secs) and then prints the whole array of numbers together without any time delays between them, it just prints 0123456789 at once.
EDIT: I tried with sleep() instead of usleep but it's the same
How to fix it ? And why it's like that ?
| Your output buffer is not being flushed. By default, output is written when a new line appears in the stream. Change your printf to this:
printf("%d\n", i);
or try this:
printf("%d", i);
fflush(stdout);
Also, if you want to remove the line-buffering behaviour, you can use setvbuf() and the _IONBUF mode.
|
2,259,395 | 2,259,444 | How can I convert this C++ function from using long to this other type? | I have this original C++ function called "s":
long s(long n) {
long sum = 0;
long m;
m = (long) sqrt(n);
for (long i = 2; i < m; i++)
if ((n % i) == 0) sum += (i + (n/i));
if (n>1) sum += 1;
if ((m*m) == n) sum += m;
return sum;
}
I've been struggling to convert this function over to using the GMP's mpz type, so that it will allow for arbitrarily long integers.
This is my attempt at it:
void s(mpz_t n, mpz_t *final)
{
mpz_t sum;
mpz_t m;
mpz_t temp;
mpz_init (sum);
mpz_init (m);
mpz_init (temp);
mpz_set_str (sum, "0", 10);
mpz_sqrt(m, n);
for (mpz_t i, mpz_init(i), mpz_set_str(i, "2", 10); mpz_cmp(i,m)< 0; mpz_add_ui(i, i, 1))
{
mpz_mod(temp, n, i);
if (mpz_cmp_si(temp, 0) == 0)
{
// use divexact since we know they are divisable
mpz_divexact(temp, n, i);
mpz_add(temp, temp, i);
mpz_add(sum, sum, temp);
}
}
if (mpz_cmp_si(n, 1) > 0) mpz_add_ui(sum, sum, 1);
mpz_mul(temp, m, m);
if (mpz_cmp(temp, n) == 0) mpz_add(sum, sum, m);
final = sum;
}
The whole original program can be found here: http://pastebin.com/mf751592
What am I doing wrong? I seemed to initially have trouble because I couldn't return type mpz_t. So instead, I passed in a pointer to what I want the function to return.
I'm still struggling with it though. Can someone point me in the right direction?
This line: for (mpz_t i, mpz_init(i), mpz_set_str(i, "2", 10); mpz_cmp(i,m)< 0; mpz_add_ui(i, i, 1))
Gives this error: 23: error: cannot initialize arrays using this syntax
| You were mostly on the right track. However, both function parameters should be of type mpz_t. So the header's like:
void s(mpz_t n, mpz_t final)
You don't need final = sum at the end. Instead, just use final everywhere you use sum. Also, do:
mpz_t i;
for (mpz_init_set_ui(i, 2); mpz_cmp(i,m) < 0; mpz_add_ui(i, i, 1))
for the for loop. A call is like:
mpz_t final, n;
mpz_init(final);
mpz_init_set_ui(n, 5);
s(n, final);
EDIT: As noted by Steve314, you should do a mpz_clear for every mpz_init. Since you can have the caller pass an initted final, that leaves cleaning up m, temp, and i.
|
2,259,476 | 2,259,502 | Rotating a point about another point (2D) | I'm trying to make a card game where the cards fan out. Right now to display it Im using the Allegro API which has a function:
al_draw_rotated_bitmap(OBJECT_TO_ROTATE,CENTER_X,CENTER_Y,X
,Y,DEGREES_TO_ROTATE_IN_RADIANS);
so with this I can make my fan effect easily. The problem is then knowing which card is under the mouse. To do this I thought of doing a polygon collision test. I'm just not sure how to rotate the 4 points on the card to make up the polygon. I basically need to do the same operation as Allegro.
for example, the 4 points of the card are:
card.x
card.y
card.x + card.width
card.y + card.height
I would need a function like:
POINT rotate_point(float cx,float cy,float angle,POINT p)
{
}
Thanks
| First subtract the pivot point (cx,cy), then rotate it (counter clock-wise), then add the point again.
Untested:
POINT rotate_point(float cx,float cy,float angle,POINT p)
{
float s = sin(angle);
float c = cos(angle);
// translate point back to origin:
p.x -= cx;
p.y -= cy;
// rotate point
float xnew = p.x * c - p.y * s;
float ynew = p.x * s + p.y * c;
// translate point back:
p.x = xnew + cx;
p.y = ynew + cy;
return p;
}
|
2,259,544 | 2,259,615 | Is wchar_t needed for unicode support? | Is the wchar_t type required for unicode support? If not then what's the point of this multibyte type? Why would you use wchar_t when you could accomplish the same thing with char?
| No.
Technically, no. Unicode is a standard that defines code points and it does not require a particular encoding.
So, you could use unicode with the UTF-8 encoding and then everything would fit in a one or a short sequence of char objects and it would even still be null-terminated.
The problem with UTF-8 and UTF-16 is that s[i] is not necessarily a character any more, it might be just a piece of one, whereas with sufficiently wide characters you can preserve the abstraction that s[i] is a single character, tho it does not make strings fixed-length under various transformations.
32-bit integers are at least wide enough to solve the code point problem but they still don't handle corner cases, e.g., upcasing something can change the number of characters.
So it turns out that the x[i] problem is not completely solved even by char32_t, and those other encodings make poor file formats.
Your implied point, then, is quite valid: wchar_t is a failure, partly because Windows made it only 16 bits, and partly because it didn't solve every problem and was horribly incompatible with the byte stream abstraction.
|
2,259,565 | 2,259,768 | New To Socket Programming, Need Help Understanding How To Connect | I have a C++ Program listening for incoming socket connections on port 2222.
I have an Adobe AIR/Flex application that attempts to connect to it, when I click a button.
When I Connect To My Socket Over My Intranet, My C++ program hears and accepts the incoming socket connection and Everything Works Fine:
var Sock:Socket=new Socket("192.168.1.100",2222);
But When I Try To Connect Using My Real IP, I Get Error #2031:
var Sock:Socket=new Socket("76.18.24.118",2222);
Both programs are running on my laptop computer. I am behind a router, but have configured that router with port forwarding so that port 2222 maps to my laptop.
What Am I Missing? I am very new to this, so perhaps I'm missing something obvious to you smarties.
| Port forwarding does not mean that you can use an external IP address, your laptop is still on the private 192.168 network. What it means is that when someone tries to connect on 78.18.24.118:2222 the router converts the IP address to 192.168.1.100:2222. This effectively allows you to run a server inside your network but allows an outside client to connect to you.
Look up DNAT for more information.
|
2,259,612 | 2,259,878 | "nice" keyword in c++? | So I was doing some simple C++ exercises and I noticed an interesting feat. Boiled down to bare metal one could try out compiling the following code:
class nice
{
public:
nice() {}
};
int main()
{
nice n;
return 0;
};
The result is a compilation error that goes something like this:
<file>.cpp: In function ‘int main()’:
<file>.cpp:11: error: expected `;' before ‘n’
<file>.cpp:11: warning: statement is a reference, not call, to function ‘nice’
<file>.cpp:11: warning: statement has no effect
And this was using regular g++ on Max OS X, some of my friends have tried in on Ubuntu as well, yielding the same result.
The feat seems to lie in the word "nice", because refactoring it allows us to compile. Now, I can't find the "nice" in the keyword listings for C++ or C, so I was wondering if anyone here had an idea?
Also, putting
class nice n;
instead of
nice n;
fixes the problem.
P.S. I'm a relative C++ newbie, and come from the ActionScript/.NET/Java/Python world.
Update:
Right, my bad, I also had an
#include <iostream>
at the top, which seems to be the root of the problem, because without it everything works just fine.
| It is a namespace problem but not with namespace std. The header <iostream> is pulling in <unistd.h>
If you try
class nice
{
public:
nice() {};
};
int main(int argc, char *argv[])
{
nice n;
return 0;
}
there is no problem.
Simply add
#include <unistd.h>
and you will get the "expected ‘;’ before ‘n’" error. Namespace std does not enter the picture.
So the solution is the same as before - put class nice in its own namespace and it will not clash with the global ::nice().
|
2,259,678 | 44,711,819 | Easiest way to rotate by 90 degrees an image using OpenCV? | What is the best way (in c/c++) to rotate an IplImage/cv::Mat by 90 degrees? I would assume that there must be something better than transforming it using a matrix, but I can't seem to find anything other than that in the API and online.
| As of OpenCV3.2, life just got a bit easier, you can now rotate an image in a single line of code:
cv::rotate(image, image, cv::ROTATE_90_CLOCKWISE);
For the direction you can choose any of the following:
ROTATE_90_CLOCKWISE
ROTATE_180
ROTATE_90_COUNTERCLOCKWISE
|
2,259,697 | 2,259,708 | Huge Amount of Linker Issues with Release Build Only | Anyone have idea on this? Linker errors are way out of my wheelhouse, especially ones like this.
Is there any more info I should include?
1>Linking...
1>freeglut_static.lib(freeglut_window.obj) : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification
1>LIBCMTD.lib(dbgheap.obj) : error LNK2005: __heap_alloc already defined in LIBCMT.lib(malloc.obj)
1>LIBCMTD.lib(dbgheap.obj) : error LNK2005: __recalloc already defined in LIBCMT.lib(recalloc.obj)
1>LIBCMTD.lib(dbgheap.obj) : error LNK2005: __msize already defined in LIBCMT.lib(msize.obj)
1>LIBCMTD.lib(malloc.obj) : error LNK2005: _V6_HeapAlloc already defined in LIBCMT.lib(malloc.obj)
1>LIBCMTD.lib(dbghook.obj) : error LNK2005: __crt_debugger_hook already defined in LIBCMT.lib(dbghook.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_pHeaderDefer already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: __get_sbh_threshold already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: __set_sbh_threshold already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: __set_amblksiz already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: __get_amblksiz already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_heap_init already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_find_block already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_free_block already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_alloc_block already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_alloc_new_region already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_alloc_new_group already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_resize_block already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_heapmin already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(sbheap.obj) : error LNK2005: ___sbh_heap_check already defined in LIBCMT.lib(sbheap.obj)
1>LIBCMTD.lib(isctype.obj) : error LNK2005: __isctype_l already defined in LIBCMT.lib(isctype.obj)
1>LIBCMTD.lib(isctype.obj) : error LNK2005: __isctype already defined in LIBCMT.lib(isctype.obj)
1>LINK : warning LNK4098: defaultlib 'LIBCMTD' conflicts with use of other libs; use /NODEFAULTLIB:library
| You seem to be linking projects built with different CRT library settings, one with Multi-Threaded, another one with Multi-Threaded Debug. Adjust the settings for all the projects to use the very same flavour of the library and the issue should go away!
|
2,259,864 | 2,259,871 | static variable construction in C++ | How do compilers know how to correctly handle this code?
struct Foo
{
int bar;
Foo()
{
bar = 3;
}
Foo& operator=(const Foo& other)
{
bar = other.bar;
return *this;
}
int SetBar(int newBar)
{
return bar = newBar;
}
};
static Foo baz;
static Foo someOtherBaz = baz;
static int placeholder = baz.SetBar(4);
What would the final value of someOtherBaz.bar be?
| The value of someOtherBaz.bar would be 3.
Static objects within a translation unit are constructed in the order they appear within the TU (note, there is no defined order of static object in different translation units).
First, baz will be constructed with the default constructor. This will set baz.bar to 3.
Next someOtherBaz will be constructed via the copy constructor. Since no copy constructor was defined, a default copy constructor will be used which will just copy each field. So someOtherBaz.bar will be given the value of 3.
Finally, to construct placeholder, baz.SetBar will be called which will also change the value of baz (but not someOtherBaz since they are independent objects; while you created someOtherBaz based on the value of baz, they are different objects so can change independently).
So, at the end, you'll have:
baz.bar: 4
someOtherBaz.bar: 3
placeholder: 4
|
2,260,127 | 2,260,135 | Game Programming: .DAT file? | I've seen a lot of games use something similar to a .DAT file or a specific file type that the game has for itself. I'm just beginning with C++ and DirectX and I was interested in keeping my information in something similar to a .DAT.
My initial conception was that it would hold information on the files you wanted to store within the .DAT file. Something similar to a .RAR file. Unfortunately, my googleing skills did not help me in finding the answers.
Right now I'm simply loading textures and sound files from a folder called Data.
EDIT: While I understand that .DAT is short for data, and I've found that a .DAT file generally contains any assortment of information, I'm still unsure about how to go about doing something as packing images and sound files into any type of file and being able to read them.
I'm not sure about using fstreams to achieve my task, however I will look into streams related to storing data and how to properly read from that data. Meanwhile if anyone has another answer to offer based on this new information, it would be appreciated.
EDIT: Thanks to the answers, I stumbled across a similar question on stackoverflow and felt I'd share it here. Combining resources into a single binary file
| I don't think there is really such thing as .dat file format. It's short for "data," and different applications just put in some proprietary stuff in it and call it ".dat." You can read up on fstream classes to do file IO in C++. See Input/Output with files.
What you then do is make up your own file format. For example, first 4 byte is int that indicates the number of blocks in the .dat and for each block, you have 4 byte indicating the length of each block, 4 byte indicating the type of the block, the variable length data itself .. something like that.
|
2,260,386 | 2,260,397 | Referring to const value at compile time - when is a const's definition really available? | I tried
const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // g++ cries "error: array bound is not an integer constant"
int main()
{
const int j[] = { 0, 1, 2, 3 };
float g[j[3]]; // compiler is happy :)
return 0;
}
What is the difference between the two aggregates? How come referring to a const aggregate's element inside main() is valid when it's invalid at the global scope?
| In C++ sizes in array declaration have to be Integral Constant Expressions (ICE). By definition, ICE in C++ cannot include a value taken from an array, regardless of whether it is a const array or not. So, in both cases i[3] and j[3] are not ICEs and cannot be used as sizes in array declarations. For this reason both declarations - f and g - are illegal in C++.
However, since you are using GCC, in the second case a non-standard compiler extension comes into play. When you are declaring an automatic array, GCC allows you to specify a non-constant size (i.e. run-time size) for the array (this is basically C99's VLAs carried over to C++). This is why it is "happy", even though the code is not legal in C++. Compile in -ansi -pedantic-error mode and you should get a diagnostic message (an error) for each declaration.
|
2,260,861 | 2,260,893 | Strange occurence with string and special character | #include <iostream>
#include <string>
using namespace std;
string mystring1, mystring2, mystring3 = "grové";
int main(){
mystring1 = "grové";
getline( cin, mystring2 ); //Here I type "grové" (without "")
cout << "mystring1= " << mystring1 << endl;
cout << "mystring2= " << mystring2 << endl;
cout << "mystring3= " << mystring3 << endl;
return 0;
}
The output of above code is:
mystring1= grov8
mystring2= grové
mystring3= grov8
although when I cut and paste the code here it comes as:
mystring1= grovΘ
mystring2= grové
mystring3= grovΘ
Why does the content of mystring2 differ from mystring1 and mystring3?
| Assuming you use Microsoft Windows: Your source code has a different encoding from that of the windows command line.
Type chcp in the command line to see the current console codepage. (Mine is 850)
You have three options:
Change the codepage/encoding of your source code to the codepage/encoding of your console.
Change the codepage/encoding of the console to the codepage/encoding of your source file.
Use a library (or Windows API) to change the encoding on the fly.
|
2,261,026 | 2,261,101 | Distinguish between const and non-const method with same name in boost::bind | When I use boost::bind with a method name which is declared both const and non-const I am getting in ambiguous error, for example
boost::bind( &boost::optional<T>::get, _1 )
How can I solve this problem?
| The problem together with workarounds is descibed in FAQ part of Boost.Bind reference.
You could also make use of utility functions like the following:
#include <boost/bind.hpp>
#include <boost/optional.hpp>
template <class Ret, class Obj>
Ret (Obj::* const_getter(Ret (Obj::*p) () const)) () const
{
return p;
}
template <class Ret, class Obj>
Ret (Obj::* nonconst_getter(Ret (Obj::*p)())) ()
{
return p;
}
int main()
{
boost::bind( const_getter(&boost::optional<int>::get), _1 );
boost::bind( nonconst_getter(&boost::optional<int>::get), _1 );
}
|
2,261,054 | 2,261,080 | If i develop c++ win32 GUI in xp ,will i have problem to run in it deferent win os's | i need to develop win32 GUI in c++ (plain win32 windows.h thing ) , I'm developing it in xp os
how much problem will i have to port it to vista and windows 7 ?
| There's a 'define' in Microsoft Visual Studio that allows you to indicate the minimum Windows platform that you want to support. It's WINVER.
If you compile with WINVER=0x0501, then you are targetting Windows XP and above.
This means that you cannot call e.g. Windows 7 specific functions since they will only be defined if WINVER is set to 0x0700 or higher.
For the rest, check the Windows development documents that you will find on MSDN. I noticed that in practice you won't have any problems unless you are doing special things with Windows Services or device-related things.
|
2,261,169 | 2,261,182 | concatenate files without copying their contents | (In C/C++/Linux)
Is there a way to concatenate file A and file B (or actually append one A's content to that of B) only by altering the file system without the overhead of data copying? File A then can be discarded.
Thanks
| If the files were block-structured, and if the OS supported block-structured files (as some do) then (in principle) yes. But as you are asking about Linux, I assume you are talking about a byte-stream oriented file system, where a disk block may not be completely used. In this case, some copying is inevitable and in practice you have to copy the whole file.
|
2,261,202 | 2,261,224 | Why is scanf results different from user input? | char* ReadNumericFormat = "%i";
int Read(void)
{
int Storage;
__asm
{
LEA EAX, [Storage]
PUSH EAX
PUSH DWORD PTR [ReadNumericFormat]
CALL DWORD PTR [scanf]
ADD ESP, 8
MOV EAX, DWORD PTR [Storage]
}
}
when the user enters "023919" the procedure returns 19.
this is a feature or darkness is a standard?
| Actually that's because you've entered an octal number.
In C, numbers starting with 0 will be interpreted as octal (base-8) literals. Hence, in your input
023919
scanf find a leading zero without an x following, so assumes it's an octal number. Then it consumes 2 and 3, until 9 which is not a valid octal digit and stop. So scanf now has
023
which is
2*8 + 3 = 19
So the procedure returns 19.
Use the format %d instead of %i to prevent this.
|
2,261,348 | 2,264,393 | Clean way to refactor test code | Background:
I currently write test cases for the client side of a network protocol. As part of the tests I have to simulate several different expected and unexpected responses from the server (wrong header, connection lost, unexpected messages, timeouts).
Each of these test-cases can be accessed by its unique address.
My problem:
The current implementation is split into several parts:
An enum containing all the addresses of the test-cases
A class Tests containing all tests as static functions
A number of defines which map the function name to the corresponding enum + _FUNC
A wrapper class which takes an address a function and a name as argument
A method which returns a list of wrapper-class objects, one object for each test-case
For each message received the server checks the list of test-cases and either executes the test-case corresponding to the address or falls back to a default response.
The Question:
This implementation requires me to update at least five different locations for each new test-case and the class Test grows rather fast. Is there a good way to refactor it?
Example code:(this code is not valid c++)
enum TestAddress
{
TEST_CONNECTION_BREAKDOWN = 0x100,
TEST_ALL_IS_GOOD = 0x101,
}
class Wrapper : AbstrTestCase //AbstrTestCase requires applies and test implementations
{
typedef testFun;
Wrapper(TestAddress addr,testFun func,string name)
boolean applies(int ad,...){return addr == ad;}
int test(...){return func(...);}
}
class Test
{
static int testConnectionBreakDownFunc (...)
static int testAllIsGoodFunc(...)
}
#define TEST_CONNECTION_BREAKDOWN_FUNC Test::testConnectionBreakDownFunc
#define TEST_ALL_IS_GOOD_FUNC Test::testAllIsGoodFunc
list<AbstrTestCase*> GetTests()
{
list<AbstrTestCase*> tlist;
tlist.push_back(new Wrapper(TEST_ALL_IS_GOOD,TEST_ALL_IS_GOOD_FUNC,"TEST_ALL_IS_GOOD"));
...
tlist.push_back(new Wrapper(TEST_CONNECTION_BREAKDOWN,TEST_CONNECTION_BREAKDOWN_FUNC,"TEST_CONNECTION_BREAKDOWN_FUNC"));
return tlist;
}
Related: My last atemp to at least clean up the code in GetTests() was an additional define for the arguments of wrapper
#define WRAP_ARGS(N) N,N##_FUNC,#N
tlist.push_back(new Wrapper(WRAP_ARGS(TEST_CONNECTION_BREAKDOWN));
#undef WRAP_ARGS(N)
while it results in cleaner looking code, it only hides the problem
| I have had similar problems as you did. The approach I usually take is manage this via a script in order to automate the addition of code to the different places. A comment marks the point for the script to process the file so you don't need to write a complicated parser. Something like:
/* automatic code insertion point. Don't remove this comment */
Then you write a small script. There are many things macros can't do, and obscuring the code in order to write less is seldom a good idea. So write your script that updates the five locations.
|
2,261,351 | 2,261,565 | How to add menubar in my program with Visual Studio 2008? | I managed to create the menubar in the menu editor by clicking and writing text to each menu item i wanted.
I cant see any button to get the code to include the menu in my program.
How i can get this menu working?
C++
| depends on whether you are using pure win32 api or MFC. But being a newbie i will first assume that you are using win32 api. do a simple google search for forgers win32 tutorials.
just to satisify you, edit the main.cpp file and change the WNDCLASSEX structure, under the lpszMenuName part.
See, you just cant keep using visual studio's code generation features. You have to understand the code behind the menu, and it is not hard. other wise you will never understand the more advanced features. No offence but these things are covered all over the internet.
|
2,261,366 | 2,261,396 | put different class in hierarchy in one container in C++ | Some times we have to put different objects in the same hierarchy in one container. I read some article saying there are some tricks and traps. However, I have no big picture about this question. Actually, this happens a lot in the real word.
For example, a parking lot has to contain different types of cars; a zoo has to contain different types of animals; a book store has to contain different types of books.
I remember that one article saying neither of the following is a good design, but I forgot where it is.
vector<vehicle> parking_lot;
vector<*vehicle> parking_lot;
Can anybody offer some basic rules for this kind of question?
| The problem with vector<vehicle> is that the object only holds vehicles. The problem with vector<vehicle*> is that you need to allocate and, more importantly, free the pointers appropriately.
This might be acceptable, depending on your project, etc...
However, one usually uses some kind of smart-ptr in the vector (vector<boost::shared_ptr<vehicle>> or Qt-something, or one of your own) that handles deallocation, but still permits storing different types objects in the same container.
Update
Some people have, in other answers/comments, also mentioned boost::ptr_vector. That works well as a container-of-ptr's too, and solves the memory deallocation problem by owning all the contained elements. I prefer vector<shared_ptr<T>> as I can then store objects all over the place, and move them using in and out of containers w/o issues. It's a more generic usage model that I've found is easier for me and others to grasp, and applies better to a larger set of problems.
|
2,261,440 | 2,261,447 | Dynamic allocation of memory | Lets consider following two codes
First:
for (int i=0;i<10000000;i++)
{
char* tab = new char[500];
delete[] tab;
}
Second:
for (int i=0;i<10000000;i++)
{
char tab[500];
}
The peak memory usage is almost the same, but the second code runs about 20 times faster than the first one.
Question
Is it because in first code array is stored on heap, and in the second one array is stored on stack?
|
Is it because in first code array is stored on heap, and in the second one array is stored on stack?
Yes, Stack allocation is much faster as all the second code sample is doing is moving (adding/subtracting) the stack pointer rather than manipulating the heap.
If you want to know more, these two questions cover the subject
C++ Which is faster: Stack allocation or Heap allocation
What and where are the stack and heap
|
2,261,482 | 2,261,522 | Multithreaded Server Issue | I am writing a server in linux that is supposed to serve an API.
Initially, I wanted to make it Multi-threaded on a single port, meaning that I'd have multiple threads working on various request received on a single port.
One of my friends told me that it not the way it is supposed to work. He told me that when a request is received, I first have to follow a Handshake procedure, create a thread that is listening to some other port dedicated to the request and then redirect the requested client to the new port.
Theoretically, it's very interesting but I could not find any information on how to implement the handshake and do the redirection. Can someone help?
If I'm not wrong in interpreting your responses, once I create a multithreaded server with a main thread listening to a port, and creates a new thread to handle requests, I'm essentially making it multithreaded on a single port?
Consider the scenario where I get a large number of requests every second. Isn't it true that every request on the port should now wait for the "current" request to complete? If not, how would the communication still be done: Say a browser sends a request, so the thread handling this has to first listen to the port, block it, process it, respond and then unblock it.
By this, eventhough I'm having "multithreads" , all I'm using is one single thread at a time apart from the main thread because the port is being blocked.
| What your friend told you is similar to passive FTP - a client tells the server that it needs a connection, the server sends back the port number and the client creates a data connection to that port.
But all you wanted to do is a multithreaded server. All you need is one server socket listening and accepting connections on a given port. As soon as the automatic TCP handshake is finished, you'll get a new socket from the accept function - that socket will be used for communication with the client that has just connected. So now you only have to create a new thread, passing that client socket to the thread function. In your server thread, you will then call accept again in order to accept another connection.
|
2,261,496 | 2,261,525 | How to write Cyrillic text in C++ console | For example, if I write:
cout << "Привет!" << endl; //it's hello in Russian
In the console it would be something like ╧ЁштхЄ!.
OK, I know that we can use:
setlocale(LC_ALL, "Russian");
But after that, command line arguments in Russian do not work (if I start my program through a BAT file):
StartProgram.bat
chcp 1251
MyProgram.exe -user=Олег -password=Пароль
So, after setlocale the program can't read Russian arguments properly.
This happens because the BAT file in CP1251, but the console is in CP866.
So, there is a question:
How can I write Russian text in the C++ console and at the same time have Russian command line arguments read properly.
| See this entry from Michael Kaplan's blog:
http://www.siao2.com/2008/03/18/8306597.aspx
|
2,261,536 | 2,261,545 | how to discover .dlls my application is using | i am trying my hand at using the crystal space api in my graphics applications.
crystal space website
The applications compile fine but i am having hell with the dlls(dynamic link libraries). The compiled application crashes at run time and i suspect its because of not finding the needed dlls.
The only solution i currently have is cutting and pasting my application executable to a folder having all necessary libraries.(which is about 300mb).
Is there a way that i can find out the dlls my app needs so that i can copy them?(instead of using all dlls)
Any help will be appreciated.
PS: i am using g++ and codeblocks ide
from dr deo
| You can use Dependency Walker.
Dependency Walker is a free utility that scans any 32-bit or 64-bit Windows module (exe, dll, ocx, sys, etc.) and builds a hierarchical tree diagram of all dependent modules.
|
2,261,635 | 2,261,729 | Partially truncating a stream (fstream or ofstream) in C++ | I am trying to partially truncate (or shorten) an existing file, using fstream. I have tried writing an EOF character, but this seems to do nothing.
Any help would be appreciated...
| I don't think you can. There are many functions for moving "up and down" the wrapper hierarchy for HANDLE<->int<->FILE *, at least on Windows, but there is no "proper" to extract the FILE * from an iostreams object (if indeed it is even implemented with one).
You may find this question to be of assistance.
Personally I would strongly recommend steering clear of iostreams, they're poorly designed, heavily C++, and nasty to look at. Take a look at Boost's iostreams, or wrap stdio.h if you need to use classes.
The relevant function for stdio is ftruncate().
|
2,261,756 | 2,261,819 | Overloaded operator is never called in C++ | I'm writing a math library as a practical exercise. I've run into some problems when overloading the = operator. When I debuged it, I noticed that the call to vertex1 = vertex2 calls the copy constructor instead.
In the header file I have:
//constructors
vector3();
vector3( vector3 &v );
vector3(float ix, float iy, float iz);
//operator overloading
vector3 operator =(vector3 p);
....
In the source file I implemented:
vector3 vector3::operator =(vector3 p)
{
vector3 v3;
v3.x = p.x;
v3.y = p.y;
v3.z = p.z;
return v3;
}
Later on I have a crossproduct method, and I want to use it like so:
vector3 v3;
v3 = v1.crossProduct(v2);
The error message is:
error: no matching function for call to `vector3::vector3(vector3)'
but I do not want to call the copy constructor.
| There are mistakes in your code. Your copy-constructor must take a const&. The reference will avoid making a copy (which you wouldn't be able to do, being the copy-constructor), and it should be const since you're not modifying it:
vector3(const vector3&);
Temporary variables can be bound to const&, but cannot be bound to a mutable reference. That is, with your code you could do:
vector3 a;
vector3 b(a);
but not:
vector3 a(some_calculation()); // some_calculation returns a vector3
Additionally, your operator= is incorrect. Like the copy-constructor, it should generally take a const&, but it should return a reference to this. That's how chaining works:
int a, b, c;
a = b = c = 0;
// a.operator=(b.operator=(c.operator=(0)));
Returning a temporary is unorthodox, and doesn't accomplish anything. In your case, you could assign over and over and never change the value. Weird:
vector 3 a, b;
a = b; // doesn't change a...?!
operator= needs to change this.
|
2,261,847 | 2,262,748 | GetRawInputData vs GetAsyncKeyState() | Well, I'm trying to avoid using the deprecated DirectInput.
But I need, at each "frame" or "iteration" of the game to snatch ALL KEY STATES so that I can act accordingly. For example, if the player is down on the VK_RIGHT key then he will move just a smidgen right on that frame.
The problem with WM_INPUT messages is they can appear an unpredictable number of times per frame, because of the way the game loop is written:
MSG message ;
while( 1 )
{
if( PeekMessage( &message, NULL, 0, 0, PM_REMOVE ) )
{
if( message.message == WM_QUIT )
{
break ; // bail when WM_QUIT
}
TranslateMessage( &message ) ;
DispatchMessage( &message ) ;
}
else
{
// No messages, so run the game.
Update() ;
Draw() ;
}
}
So if more than one WM_INPUT message is stacked there then they will all get processed before Update()/Draw().
I resolved this issue by using an array of BOOL to remember what keys were down:
bool array_of_keys_that_are_down[ 256 ] ;
case WM_INPUT :
if( its keyboard input )
{
array_of_keys_that_are_down[ VK_CODE ] = TRUE ;
}
That works fine because the Update() function checks
void Update()
{
if( array_of_keys_that_are_down[ VK_RIGHT ] )
{
// Move the player right a bit
}
}
BUT the problem is now that WM_INPUT messages don't get generated often enough. There's a delay of about 1 second between the first press of VK_RIGHT and subsequent VK_RIGHT messages, even if the player had his finger down on it the whole time. Its not like DirectInput where you can keyboard->GetDeviceState( 256, (void*)array_of_keys_that_are_down ); (snatch out all key states each frame with a single call)
So I'm lost. Other than resorting to GetAsyncKeystate() function calls for each key I need to monitor, I see no way to avoid using DirectInput if you can't snatch out all key states each frame reliably.
It seems to me that DirectInput was a very good solution to this problem, but if it was deprecated, then there really must be some way to do this conveniently using Win32 api only.
Currently array_of_keys_that_are_down gets reset back to all FALSE's every frame.
memset( array_of_keys_that_are_down, 0, sizeof( array_of_keys_that_are_down ) ) ;
*EDIT
I've been working on this problem and one solution is to only reset a key state, once its been released
case WM_INPUT :
if( its keyboard input )
{
if( its a down press )
array_of_keys_that_are_down[ VK_CODE ] = TRUE ;
else
array_of_keys_that_are_down[ VK_CODE ] = FALSE ;
}
I don't like this solution though because it seems flimsy. If the user switches away from the application while down on a key, then that key will be "stuck" until he switches back and presses that same key again because we'll never get the upstroke WM_INPUT message. It makes for weird "sticky key" bugs.
| You can use GetKeyboardState instead. What you generally want is two arrays; one stores the previous frames' input state, and one stores the current. This allows things like differentiating between being held and being triggered.
// note, cannot use bool because of specialization
std::vector<unsigned char> previous(256);
std::vector<unsigned char> current(256);
// in update_keys or similar:
current.swap(previous); // constant time, yay
GetKeyboardState(¤t[0]); // normally do error checking
And you're done.
|
2,261,848 | 2,265,617 | How to print each function call during execution in WinDbg? | I am debugging an application written in VC++.
How do i make WinDbg print the function name and all the values of the arguments to the functions during execution of the debuged process?
| Ok, i just found out that it can be done using the "wt" command.
|
2,261,858 | 2,262,650 | boost::python Export Custom Exception | I am currently writing a C++ extension for Python using Boost.Python. A function in this extension may generate an exception containing information about the error (beyond just a human-readable string describing what happened). I was hoping I could export this exception to Python so I could catch it and do something with the extra information.
For example:
import my_cpp_module
try:
my_cpp_module.my_cpp_function()
except my_cpp_module.MyCPPException, e:
print e.my_extra_data
Unfortunately Boost.Python seems to translate all C++ exceptions (that are subclasses of std::exception) into RuntimeError. I realize that Boost.Python allows one to implement custom exception translation however, one needs to use PyErr_SetObject which takes a PyObject* (for the exception's type) and a PyObject* (for the exception's value)--neither of which I know how to get from my Boost.Python classes. Perhaps there is a way (which would be great) that I simply have not found yet. Otherwise does anyone know how to export a custom C++ exception so that I may catch it in Python?
| The solution is to create your exception class like any normal C++ class
class MyCPPException : public std::exception {...}
The trick is that all boost::python::class_ instances hold a reference to the object's type which is accessible through their ptr() function. You can get this as you register the class with boost::python like so:
class_<MyCPPException> myCPPExceptionClass("MyCPPException"...);
PyObject *myCPPExceptionType=myCPPExceptionClass.ptr();
register_exception_translator<MyCPPException>(&translateFunc);
Finally, when you are translating the C++ exception to a Python exception, you do so as follows:
void translate(MyCPPException const &e)
{
PyErr_SetObject(myCPPExceptionType, boost::python::object(e).ptr());
}
Here is a full working example:
#include <boost/python.hpp>
#include <assert.h>
#include <iostream>
class MyCPPException : public std::exception
{
private:
std::string message;
std::string extraData;
public:
MyCPPException(std::string message, std::string extraData)
{
this->message = message;
this->extraData = extraData;
}
const char *what() const throw()
{
return this->message.c_str();
}
~MyCPPException() throw()
{
}
std::string getMessage()
{
return this->message;
}
std::string getExtraData()
{
return this->extraData;
}
};
void my_cpp_function(bool throwException)
{
std::cout << "Called a C++ function." << std::endl;
if (throwException)
{
throw MyCPPException("Throwing an exception as requested.",
"This is the extra data.");
}
}
PyObject *myCPPExceptionType = NULL;
void translateMyCPPException(MyCPPException const &e)
{
assert(myCPPExceptionType != NULL);
boost::python::object pythonExceptionInstance(e);
PyErr_SetObject(myCPPExceptionType, pythonExceptionInstance.ptr());
}
BOOST_PYTHON_MODULE(my_cpp_extension)
{
boost::python::class_<MyCPPException>
myCPPExceptionClass("MyCPPException",
boost::python::init<std::string, std::string>());
myCPPExceptionClass.add_property("message", &MyCPPException::getMessage)
.add_property("extra_data", &MyCPPException::getExtraData);
myCPPExceptionType = myCPPExceptionClass.ptr();
boost::python::register_exception_translator<MyCPPException>
(&translateMyCPPException);
boost::python::def("my_cpp_function", &my_cpp_function);
}
Here is the Python code that calls the extension:
import my_cpp_extension
try:
my_cpp_extension.my_cpp_function(False)
print 'This line should be reached as no exception should be thrown.'
except my_cpp_extension.MyCPPException, e:
print 'Message:', e.message
print 'Extra data:',e.extra_data
try:
my_cpp_extension.my_cpp_function(True)
print ('This line should not be reached as an exception should have been' +
'thrown by now.')
except my_cpp_extension.MyCPPException, e:
print 'Message:', e.message
print 'Extra data:',e.extra_data
|
2,261,897 | 2,261,908 | What library I can use for sending POST and GET requests in C++? |
Possible Duplicate:
What C++ library should I use to implement a HTTP client?
What library I can use for sending POST and GET requests in C++
| You can use libcurl or its c++ wrapper curlpp
|
2,261,917 | 2,261,926 | Which IDE Should I use for C++ on Windows? | Which IDE for C++ should I use on Windows?
Is there an IDE with support for editing over SSH on a GNU/Linux server?
I have very big C++ project without docs and editing it with text editor very difficult =(
| On Windows I prefer:
Visual Studio + WinSCP
|
2,262,011 | 2,262,395 | Adding C++ Object to Objective-C Class | I'm trying to mix C++ and Objective-C, I've made it most of the way but would like to have a single interface class between the Objective-C and C++ code. Therefore I would like to have a persistent C++ object in the ViewController interface.
This fails by forbidding the declaration of 'myCppFile' with no type:
#import <UIKit/UIKit.h>
#import "GLView.h"
#import "myCppFile.h"
@interface GLViewController : UIViewController <GLViewDelegate>
{
myCppFile cppobject;
}
@end
However this works just fine in the .mm implementation file (It doesn't work because I want cppobject to persist between calls)
#import "myCppFile.h"
@implementation GLViewController
- (void)drawView:(UIView *)theView
{
myCppFile cppobject;
cppobject.draw();
}
| You should use opaque pointers and only include C++ headers in the file that implements your Objective-C class. That way you don't force other files that include the header to use Objective-C++:
// header:
#import <UIKit/UIKit.h>
#import "GLView.h"
struct Opaque;
@interface GLViewController : UIViewController <GLViewDelegate>
{
struct Opaque* opaque;
}
// ...
@end
// source file:
#import "myCppFile.h"
struct Opaque {
myCppFile cppobject;
};
@implementation GLViewController
// ... create opaque member on initialization
- (void)foo
{
opaque->cppobject.doSomething();
}
@end
|
2,262,029 | 2,262,216 | Is there a way to find out whether a class is a direct base of another class? | I'm wondering whether there is a way to find out whether a class is a direct base of another class i.e. in Boost type trait terms a is_direct_base_of function. As far as I can see, Boost doesn't seem to support this kind of functionality, which leads me to think that it's impossible with the current C++ standard.
The reason I want it is to do some validation checking on two macros that are used for a reflection system to specify that one class is derived from another, as in the example code below.
header.h:
#define BASE A
#define DERIVED B
class A {};
class B : public A
{
#include <rtti.h>
};
rtti.h:
// I want to check that the two macro's are correct with a compile time assert
Rtti<BASE, DERIVED> m_rtti;
Although the macros seem unnecessary in this simple example, in my real world scenario rtti.h is a lot more complex.
One possible avenue would be to compare the size of the this pointer with the size of a this pointer cast to the base type and somehow trying to figure out whether it's the size of the base class itself away or something. (Yeah, you're right, I don't know how that would work either!)
| I asked myself, "What C++ constructs do differentiate between direct inheritance vs. indirect?" It comes to mind that C++ constructors of derived types directly call constructors for their direct base(s) only. So code like this:
Derived::Derived() : Base() {}
Is only valid if Base is is a direct base of Derived. And since you are injecting the code of rtti.h into the body of Derived, you can tolerate the restriction that this technique is only directly visible within the derived class itself (i.e. it is not as general as a hypothetical type_traits::is_direct_base_of, but does not need to be).
So since we probably don't want to mess around with the default constructors per se, how about adding some special-purpose ones?
#define BASE A
#define DERIVED B
struct rtti_tag {}; // empty type
class A
{
protected:
A(rtti_tag) { assert(false); } // never actually called
};
#include <rtti.h>
class B : public A
{
IS_DIRECT_BASE_OF(DERIVED, BASE); // fails to compile if not true
};
rtti.h:
#define IS_DIRECT_BASE_OF(_B_, _A_) _B_(rtti_tag tag) : _A_(tag) \
{ assert(false); } // never actually called
This code compiles for me with g++ 4.2; if I insert a new class in the inheritance hierarchy, the assertion breaks and compilation fails with what I think is a reasonably descriptive diagnostic:
In constructor ‘B::B(rtti_tag)’:
error: type ‘A’ is not a direct base of ‘B’
...
|
2,262,232 | 2,262,268 | What does the "c" mean in cout, cin, cerr and clog? | What does the "c" mean in the cout, cin, cerr and clog names?
I would say char but I haven't found anything to confirm it.
|
The "c" stands for "character" because iostreams map values to and from byte (char) representations. [Bjarne Stroustrup's C++ Style and Technique FAQ]
|
2,262,386 | 2,458,382 | Generate sha256 with OpenSSL and C++ | I'm looking to create a hash with sha256 using openssl and C++. I know there's a similar post at Generate SHA hash in C++ using OpenSSL library, but I'm looking to specifically create sha256.
UPDATE:
Seems to be a problem with the include paths. It can't find any OpenSSL functions even though I included
#include "openssl/sha.h"
and I included the paths in my build
-I/opt/ssl/include/ -L/opt/ssl/lib/ -lcrypto
| Here's how I did it:
void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
void sha256_string(char *string, char outputBuffer[65])
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
int sha256_file(char *path, char outputBuffer[65])
{
FILE *file = fopen(path, "rb");
if(!file) return -534;
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
const int bufSize = 32768;
unsigned char *buffer = malloc(bufSize);
int bytesRead = 0;
if(!buffer) return ENOMEM;
while((bytesRead = fread(buffer, 1, bufSize, file)))
{
SHA256_Update(&sha256, buffer, bytesRead);
}
SHA256_Final(hash, &sha256);
sha256_hash_string(hash, outputBuffer);
fclose(file);
free(buffer);
return 0;
}
It's called like this:
static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);
|
2,262,574 | 2,262,614 | Pass by reference impossible? | I'm trying to use a for_each loop in my code, but I'm getting the following error:
cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'std::pair<_Ty1,_Ty2> &'
here's the offending code:
typedef stdext::hash_map<
std::string, std::list<DefaultTestContext>
> CompleteTestList;
static void RunMappedTests(pair<string, list<DefaultTestContext>>& tests)
{
RunAllTestsInList(tests.second);
}
void RunTestsInParallel(CompleteTestList& testList)
{
for_each(testList.begin(), testList.end(), RunMappedTests);
}
Of course, the easy fix is to change RunMappedTests's parameter to be pass-by-value instead of pass-by-reference. Unfortunately, in this case, it comes with a huge performance penalty. It will have to copy a string, AND a list of ~64 byte data blocks. The amount of copying done is scary. I also NEED to modify the original elements in the map.
Anyone dealt with this before? Any easy fixes I don't know about?
| std::map<T1, T2>::value_type is std::pair<const T1, T2>. Change the parameter of RunMappedTests to pair<const string, list<DefaultTestContext>> &.
|
2,262,628 | 2,262,694 | Changing background of text in edit control | Can you change the background of text in area of edit control that would stay static?
| In the parent of the edit control, handle the WM_CTLCOLORSTATIC message, the wParam of this message is the HDC that the Edit control is about to draw with,
for most CTLCOLOR messages, if you set text and background colors into this DC, the control will use the colors you set.
You can also return an HBRUSH and the contol will use that for any brush painting that it wil do, but many controls don't use brushes much, so that will have limited effect for some
CTLCOLOR messages. Your best bet here is to return the DC brush, and set the DC Brush color to match the BkColor of the DC.
LRESULT lRet = 0; // return value for our WindowProc.
COLORREF crBk = RGB(255,0,0); // use RED for Background.
...
case WM_CTLCOLORSTATIC:
{
HDC hdc = (HDC)wParam;
HWND hwnd = (HWND)lParam;
// if multiple edits and only one should be colored, use
// the control id to tell them apart.
//
if (GetDlgCtrlId(hwnd) == IDC_EDIT_RECOLOR)
{
SetBkColor(hdc, crBk); // Set to red
SetDCBrushColor(hdc, crBk);
lRet = (LRESULT) GetStockObject(DC_BRUSH); // return a DC brush.
}
else
{
lRet = DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
break;
|
2,262,652 | 2,264,425 | binding to member variables | The following example from boost bind does not work for me:
#include <boost/bind.hpp>
struct A
{
int data;
};
int main()
{
A a;
boost::bind(&A::data, _1)(a) = 1;
}
error: assignment of read-only location 'boost::bind [with A1 = boost::arg<1>, M = int, T = A](&A::data, (<unnamed>::_1, boost::arg<1>())).boost::_bi::bind_t<R, F, L>::operator() [with A1 = A, R = const int&, F = boost::_mfi::dm<int, A>, L = boost::_bi::list1<boost::arg<1> >](((A&)(& a)))'
Am I doing anything wrong? The compiler is g++ 4.4.0
| UncleBens' solution is fine but I thought I'd add that if you use Boost.Lambda the problem disappears:
#include <boost/lambda/bind.hpp>
struct A {
int data;
};
int main() {
namespace bll = boost::lambda;
A a;
bll::bind(&A::data, bll::_1)(a) = 1;
}
And so it does if you use boost::mem_fn:
#include <boost/mem_fn.hpp>
struct A {
int data;
};
int main() {
boost::mem_fn(&A::data)(a) = 1;
}
|
2,262,689 | 2,262,719 | Faster method for exporting embedded data | For some reasons, i'm using the method described here: http://geekswithblogs.net/TechTwaddle/archive/2009/10/16/how-to-embed-an-exe-inside-another-exe-as-a.aspx
It starts off from the first byte of the embedded file and goes through 4.234.925 bytes one by one! It takes approximately 40 seconds to finish.
Is there any other methods for copying an embedded file to the hard-disk? (I maybe wrong here but i think the embedded file is read from the memory)
Thanks.
| Once you know the location and size of the embedded exe , then you can do it in one write.
LPBYTE pbExtract; // the pointer to the data to extract
UINT cbExtract; // the size of the data to extract.
HANDLE hf;
hf = CreateFile("filename.exe", // file name
GENERIC_WRITE, // open for writing
0, // no share
NULL, // no security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (INVALID_HANDLE_VALUE != hf)
{
DWORD cbWrote;
WriteFile(hf, pbExtract, cbExtract, &cbWrote, NULL);
CloseHandle(hf);
}
|
2,262,883 | 2,263,046 | URLDownloadToFile API, how can it be used asynchronously? | How can this API URLDownloadToFile be used asynchronously? I need to show the progress of the download via SendMessage to a client window, which can't be done as the API appears to be synchronous and it never sends the OnProgress until the download completes.
I have also seen some example codes involving IMoniker interface, but I can't find an example that involves asynchronous reading of data and saving them to a file.
Thanks in advance.
| Use URLOpenPullStream instead.
|
2,262,984 | 2,264,101 | Graphics Gems IV. Binary Image Thinning Using Neigborhood Maps | What does this expression's algorithm mean?
p = ((p<<1)&0666) | ((q<<3)&0110) | (Image->scanLine(y+1)[x+1] != 0);
Algorithm "Binary Image Thinning Using Neigborhood Maps" in a book "Graphics Gems IV":
static int masks[] = {0200, 0002, 0040, 0010};
uchar delete_[512] =
{
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,1,0,0,1,1, 0,1,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,1,1,1,0,1,1, 0,0,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 1,1,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 0,0,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 1,1,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,1,1,1,0,1,1, 1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0, 1,1,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,1,1,1,0,1,1, 1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,1,1,1,0,1,1, 0,0,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, 0,0,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0, 1,1,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,1,1,1,0,1,1, 1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0, 1,1,1,1,0,0,1,1,
0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
1,0,1,1,1,0,1,1, 1,1,1,1,1,1,1,1
};
int xsize, ysize;
int x, y;
int i;
int count = 1;
int p, q;
uchar *qb;
int m;
xsize = Image->width();
ysize = Image->height();
qb = (uchar*) malloc (xsize*sizeof(uchar));
qb[xsize-1] = 0;
while(count)
{
count = 0;
for (i = 0; i < 4; ++i)
{
m = masks[i];
p = Image->scanLine(0)[0] != 0;
for (x = 0; x < xsize-1; ++x)
qb[x] = p = ((p<<1)&0006) | (Image->scanLine(0)[x+1] != 0);
// Scan image for pixel deletion candidates.
for (y = 0; y < ysize-1; ++y)
{
q = qb[0];
p = ((q<<3)&0110) | (Image->scanLine(y+1)[0] != 0);
for (x = 0; x < xsize-1; ++x)
{
q = qb[x];
p = ((p<<1)&0666) | ((q<<3)&0110) | (Image->scanLine(y+1)[x+1] != 0);
qb[x] = p;
if ((p&m)==0 && delete_[p])
{
count++;
Image->scanLine(y)[x] = 0;
}
}
| (See commented source code)
The variables m, p, q, and elements of the qb array are 9-bit numbers that represent the 3x3-pixel "neighborhood" of a pixel.
Suppose your image looks like this (each letter represents a pixel, which is either 'on' or 'off' (1 or 0, black or white):
---x---
0123456
| 0 abcdefg
| 1 hijklmn
y 2 opqrstu
| 3 vwxyz{|
The pixel at (x,y) location (2,1) is j. The neighborhood of that pixel is
bcd
ijk // 3x3 grid centered on j
pqr
Since each pixel has a binary value, the neighborhood can be represented in 9 bits. The neighborhood above can be written out linearly, expressed in binary as bcd_ijk_pqr. The grouping of 3 pixels in a row makes octal a good choice, since each octal digit represents three bits.
Once you have a neighborhood expressed as a 9-bit value, you can do bit-manipulation on it. An operation such as ((p << 1) & 0666) takes a neighborhood, shifts all bits to the left one position, and clears the rightmost column of bits. For example, the shift changes bcd_ijk_pqr to cdi_jkp_qr@ (where @ represents a 'null' bit, by default 0). Then the mask changes it to cd@_jk@_qr@. Expressed in 3x3 grid form:
cd@
jk@
qr@
Essentially, the whole grid has been shifted to the left.
Similarly, an operation such as ((q << 3) & 0110) shifts all bits three positions (moves rows up) and clears the first two columns of bits. So bcd_ijk_pqr becomes ijk_pqr_@@@ and then after the masking, becomes @@k_@@r_@@@.
The gist of the algorithm is to evaluate the neighborhood of each pixel to determine whether to turn that pixel off (delete it). This line does the evaluation:
if ((p&m)==0 && delete_[p])
Everything that precedes that line is done to set up the neighborhood in p. The code is written so that each pixel value is read exactly once per pass.
The qb array stores the neighborhood for each pixel in the previous scanline. Note that the elements of qb are only 8-bits wide. This means the upper-left pixel of the neighborhood is omitted. That is not a problem, since any time qb is used, it gets shifted up a row.
So to answer your question about what this line does:
p = ((p<<1)&0666) | ((q<<3)&0110) | (Image->scanLine(y+1)[x+1] != 0);
It creates the neighborhood of a pixel by merging the following:
the neighborhood of the previous pixel on the same line, shifted to the left
the right column of the neighborhood of the pixel one row higher, shifted up
the (x+1,y+1) pixel of the image, put into the "southwest" corner
For example, the neighborhood about j is calculated as:
p = bc@_ij@_pq@ | @@d_@@k_@@@ | r
bc@ | @@d | @@@ bcd
p = ij@ | @@k | @@@ = ijk
pq@ | @@@ | @@r pqr
|
2,263,145 | 2,263,157 | .Net-like IntelliSense for VC++? | Up until now in VC++, when I want to see everything I do :: . This shows all of my objects. Is there a way to make it like c# so it checks as you type without needing :: . Thanks
| I don't know of a free way to do this, but you could check out Visual Assist.
|
2,263,154 | 2,263,172 | "using typedef-name ... as class" on a forward declaration | I'm doing some policy-based designs here and I have the need to typedef lots of template types to shorten the names.
Now the problem comes that when I need to use a pointer to one of those types I try to just forward-declare it but the compiler complains with a test.cpp:8: error: using typedef-name ‘Test1’ after ‘class’
It's nothing to do with sizes as I don't need the obj at all, its just a pointer in a ".h" file where I don't want to bring the whole template in.
This is g++:
//Works
class Test{};
class Test;
//Doesn't work
class Test{};
typedef Test Test1;
class Test1;
Any hint?
| That's correct. A typedef-name cannot be used in such a forward declaration (this is technically called an elaborated type specifier, and if such a specifier resolves to a typedef-name, the program is ill-formed).
I don't understand why you actually need the forward declaration in the first place. Because if you already have the typedef in place, why not just use that typedef? It's just aswell denoting that class.
Edit: From your comment, it seems you need a designated forward declaration header, much in the same vain of <iosfwd>. So, if you template is called Test_Template_Name_Long, this a header can look like
TestFwd.h
template<typename A, typename B>
class Test_Template_Name_Long;
typedef Test_Template_Name_Long<int, bool> Test1;
Then you can just use that header, instead of doing class Test1, which the compiler has no clue about what it is (and will think it is a new class, independent of any template and typedef).
|
2,263,193 | 2,263,213 | How to extract the Windows OEM Key from Windows | How would I go about extracting the Windows OEM Key from the Registry and saving it to a file.
| You're well into unsupported territory here. The product key is stored in encrypted form in the registry. You might want to look at Magical Jellybean Keyfinder's code, which is available under the GPL.
|
2,263,249 | 2,263,316 | Shatter Glass desktop Win32 effect for windows? | I would like a win32 program that takes the desktop and acts like it is shattering glass and in the end would put the pieces back together is there way reference on Doing this kind of effect with C++?
| I wrote a program (unfortunately now lost) to do something like this a few years ago.
The desktop image can be retrieved by creating a DC for the screen, creating a compatible bitmap, then using BitBlt to copy the screen contents into the bitmap. Then use GetDIBits to get the pixels from this bitmap in a known format.
This link doesn't do exactly that, but it demonstrates the principle, albeit using MFC. I couldn't find a Win32-specific example:
http://www.flounder.com/screencapture.htm
For the shattering effect, best to use Direct3D or OpenGL. (Further details are up to you.) Create a texture using the bitmap data saved earlier.
By way of window for associating with OpenGL or D3D, create a borderless window that fills the entire screen and doesn't do painting or background erasing. This will prevent any flicker when switching from the desktop image to the copy of the desktop image being used to draw.
(If using D3D, you'll also find GetMonitorInfo useful in conjunction with IDirect3D9::GetAdapterMonitor and friends, as you'll need to create a separate device for each monitor and you'll therefore need to know which portion of the desktop corresponds to that device.)
|
2,263,474 | 2,264,742 | Can I write Windows drivers with Delphi 2010? | I've always heard that Delphi can do almost anything C++ can do...except write Windows drivers. Is this correct, and if so, why is that?
I recently read a blog post online that may indicate a possible solution for writing drivers with Delphi, but it's 3 years old and I don't know how accurate this information is.
So, with the latest version of Delphi (2010), would it be technically possible to write a Windows driver?
| It may be technically possible to write some drivers with Delphi, but as far as a general answer goes, I'd say: you can't easily write drivers with Delphi.
First, there's a difference between user-mode driver (UMDF) drivers and kernel-mode (KMDF) drivers. UMDF drivers should be possible with Delphi. KMDF drivers aren't easily possible though, because
1) Delphi's linker can't produce them and
2) Delphi's object file format is different from the COFF format the Microsoft linker uses by default.
3) Delphi's RTL makes the assumption it lives in user-mode and may do certain things that one shouldn't do in kernel-land (I think e.g. of the way exceptions are handled; also different memory management), so you'd have to be very careful on which RTL functions are safe to use. There are also difficulties with System and SysInit units (see the comment by Ritsaert Hornstra to another answer here).
I'm not saying these aren't problems that cannot be overcome (cf. the post you link to) if you're really dedicated, but it won't be straightforward.
Secondly, KMDF drivers (I don't know about UMDF, actually - can anyone comment?) for Win64 have to be in 64-bit code. Since currently, there is no 64-bit Delphi compiler, writing them is a definite no-no.
|
2,263,514 | 2,263,545 | How to get keyboard input in an Homemade OS? | How to get keyboard input in an Homemade OS?
| Given that no further explanations are given, I'll assume a x86 platform.
You need to install a handler for the keyboard interrupt. Here is an example as a Linux module that you can probably get inspiration from: http://tldp.org/LDP/lkmpg/2.4/html/x1210.html
And also:
http://wiki.osdev.org/Interrupts
If you give more detail about your OS (architecture? real or protected mode?) we can probably give you better answers.
|
2,263,643 | 2,263,664 | How to get the cursor point in a Window instead of whole desktop? | How to get the cursor point in a Window instead of whole desktop?
| In Win32 you use ScreenToClient or MapWindowPoints to convert from system coordinates to window coordinates
|
2,263,681 | 2,263,700 | c++ compile error: ISO C++ forbids comparison between pointer and integer | I am trying an example from Bjarne Stroustrup's C++ book, third edition. While implementing a rather simple function, I get the following compile time error:
error: ISO C++ forbids comparison between pointer and integer
What could be causing this? Here is the code. The error is in the if line:
#include <iostream>
#include <string>
using namespace std;
bool accept()
{
cout << "Do you want to proceed (y or n)?\n";
char answer;
cin >> answer;
if (answer == "y") return true;
return false;
}
Thanks!
| You have two ways to fix this. The preferred way is to use:
string answer;
(instead of char). The other possible way to fix it is:
if (answer == 'y') ...
(note single quotes instead of double, representing a char constant).
|
2,263,690 | 2,263,733 | What claims, if any, can be made about the accuracy/precision of floating-point calculations? | I'm working on an application that does a lot of floating-point calculations. We use VC++ on Intel x86 with double precision floating-point values. We make claims that our calculations are accurate to n decimal digits (right now 7, but trying to claim 15).
We go to a lot of effort of validating our results against other sources when our results change slightly (due to code refactoring, cleanup, etc.). I know that many many factors play in to the overall precision, such as the FPU control state, the compiler/optimizer, floating-point model, and the overall order of operations themselves (i.e., the algorithm itself), but given the inherent uncertainty in FP calculations (e.g., 0.1 cannot be represented), it seems invalid to claim any specific degree of precision for all calulations.
My question is this: is it valid to make any claims about the accuracy of FP calculations in general without doing any sort of analysis (such as interval analysis)? If so, what claims can be made and why?
EDIT:
So given that the input data is accurate to, say, n decimal places, can any guarantee be made about the result of any arbitrary calculations, given that double precision is being used? E.g., if the input data has 8 significant decimal digits, the output will have at least 5 significant decimal digits... ?
We are using math libraries and are unaware of any guarantees they may or may not make. The algorithms we use are not necessarily analyzed for precision in any way. But even given a specific algorithm, the implementation will affect the results (just changing the order of two addition operations, for example). Is there any inherent guarantee whatsoever when using, say, double precision?
ANOTHER EDIT:
We do empirically validate our results against other sources. So are we just getting lucky when we achieve, say, 10-digit accuracy?
| Unless your code uses only the basic operations specified in IEEE 754 (+, -, *, / and square root), you do not even know how much precision loss each call to library functions outside your control (trigonometric functions, exp/log, ...) introduce. Functions outside the basic 5 are not guaranteed to be, and are usually not, precise at 1ULP.
You can do empirical checks, but that's what they remain... empirical. Don't forget the part about there being no warranty in the EULA of your software!
If your software was safety-critical, and did not call library-implemented mathematical functions, you could consider http://www-list.cea.fr/labos/gb/LSL/fluctuat/index.html . But only critical software is worth the effort and has a chance to fit in the analysis constraints of this tool.
You seem, after your edit, mostly concerned about your compiler doing things in your back. It is a natural fear to have (because like for the mathematical functions, you are not in control). But it's rather unlikely to be the problem. Your compiler may compute with a higher precision than you asked for (80-bit extendeds when you asked for 64-bit doubles or 64-bit doubles when you asked for 32-bit floats). This is allowed by the C99 standard. In round-to-nearest, this may introduce double-rounding errors. But it's only 1ULP you are losing, and so infrequently that you needn't worry. This can cause puzzling behaviors, as in:
float x=1.0;
float y=7.0;
float z=x/y;
if (z == x/y)
...
else
... /* the else branch is taken */
but you were looking for trouble when you used == between floating-point numbers.
When you have code that does cancelations on purpose, such as in Kahan's summation algorithm:
d = (a+b)-a-b;
and the compiler optimizes that into d=0;, you have a problem. And yes, this optimization "as if floats operation were associative" has been seen in general compilers. It is not allowed by C99. But the situation has gotten better, I think. Compiler authors have become more aware of the dangers of floating-point and no longer try to optimize so aggressively. Plus, if you were doing this in your code you would not be asking this question.
|
2,263,960 | 2,264,064 | Errors thrown from stl when compiling a module which uses the "Meschach" library | I'm working on a module which uses a shared library, which in turn has a static library linked to it. The shared library build works fine and generates a .so. When I try to use it in the module, I get a variety of errors, most of which are based on stl (stl collections to be specific), at the compilation stage. The errors look like:
In file included from /usr/include/c++/4.3/list:68,
from /home/gayan/LHIMo/LHI/src/CalcEngine/include/JuncNodeInfo.h:11,
from /home/gayan/LHIMo/LHI/src/CalcEngine/include/RiverFlowParameter.h:11,
from Main.cpp:11:
/usr/include/c++/4.3/bits/stl_list.h:465:11: error: macro "catch" requires 3 arguments, but only 1 given
This is given in most places which use list, vector or map.
Please help me to resolve this.
Sample code: "CalcEngine.h" in the library:
#ifndef LHI_CALCENGINE_H_
#define LHI_CALCENGINE_H_
extern "C"{
#include <matrix2.h>
}
class CalcEngine{
public:
protected:
};
#endif /* LHI_CALCENGINE_H_ */
Main.cpp in the application:
#include <iostream>
#include <CalcEngine.h>
#include <list> // The compilation fails as soon as this is added
int main(int argc, char** argv){
return -1;
}
I feel this has something to do with the matrix2.h file but could not pinpoint it. The file could be found here
| Doing some googling it seems like the Meschach library has a macro called catch (defined err.h indirectly included by matrix2.h) causing c++ code having exception catching to fail.
Try
#undef catch
after you are done including the meschach headers and see if works better.
|
2,264,137 | 2,264,224 | Unwind a function call | This is a difficult problem to describe so please let me know if anything is unclear.
I am trying to solve a possible deadlock situation in my C++ app and I am having trouble visualizing an appropriate solution. The restrictions placed on me by the two libraries I am trying to connect make my problem very complex and troublesome but it can all boil down to a simple diagram. Quite simply I have a situation like so
Python | Thread 1 Thread 2
|
Action 1 -|-> GIL LOCK --> Random Calls
Action 2 | GIL LOCK <----------------------------- [Action 2]
| Action 1 -- signals ---> Do_Action_1
| Wait Forever Wait on Action 2
Action 2 happens to be a timer firing, the library I am using has this timer code that will call functions after a set amount of time.
Trouble occurs when a timer fires while I am destroying the timer handler (Action 1). The timer handler will wait for the timers to finish their functions and the timer functions cannot finish because they are waiting to call a python function. In order to get into python they need to take the GIL which is being held by the timer handler destruction action.
I am wondering if its possible for me from Thread 1 to interrupt its wait on the GIL and unwind its stack to put it out of harms way of this deadlock. Although I fear going down to far into specific OS implementations I just can not think of any better solution.
In other words, I want to cancel the Action 2 call from thread 1. Is this in ANY way possible?
I should mention that I cannot edit the operation in Thread 2 ie, I cannot edit that library that is managing that thread.
I can modify python's GIL lock to maybe be a try lock or a timed lock or maybe even a wait on a condition but that would be really hard to pull off.
I suppose the best solution would be to modify python to wait on the gil and a named condition that my Thread 1 can signal when I want to cancel its wait on the GIL. But before going down that route I want to know if I am missing anything.
| If you're destroying the timer handler, I figure you're exiting the program. Before you try to exit and begin killing the timers, can you set a flag to prevent Action 1 and have Thread 1 terminate itself? I hope I'm reading your diagram right, because it doesn't exactly match with the text...
|
2,264,486 | 2,264,512 | Is down-casting 'this' to a derived class is correct? | Have a class Hero. Sometimes I need a deep copy (when all members are copied by value) of this class as a kind of some derived class:
class Hero
{
public:
// members, w/o getters/setters
public:
// Constructors
Hero();
Hero(...)
~Hero();
inline SuperHero* asSuperHero() {
// Here should be retured SuperHero instance initialized with all members of Hero class
}
};
class SuperHero : public Hero
{
private:
// Shouldn't be instantianed manually
SuperHero();
public:
// This class-only specific method
void helpAround();
};
The more obvious way is to implement SuperHero constructor which takes all members and do theirs copy manually (because there is no copy constructor in C++ for derived classes): SuperHero(member1, member2, ...) (kind of this). But when I change amount of Hero members, I alway will should change theirs copy in SuperHero constructors.
To avoid this I would implement asSuperHero() in the following way:
inline SuperHero* asSuperHero() {
return static_cast<SuperHero *>(this);
}
Here I there is no need to copy all members etc. Is this way C++ correct, design-corrent and C++ safe?
Thanks,
| Why not just have the derived class's constructor use the base class's copy constructor?
eg:
class SuperHero : public Hero
{
...
SuperHero(const Hero &hero) : Hero(hero) {
}
...
};
|
2,264,565 | 2,264,636 | Debugging in Linux using core dumps | What are the 'best practices' when it comes to debugging core dumps using GDB?
Currently, I am facing a problem:
The release version of my application is compiled without the '-g' compiler flag.
The debug version of my application (compiled with '-g') is archived (along with the source code, and a copy of the release binary).
Recently, when a user gave me a core dump, I tried debugging it using
gdb --core=./core.pid ./my_app_debug-bin
The core was created by my_app_release-bin. There seems to be some kind of mismatch between the core file and the binary.
On the other hand, if I try
gdb --core=./core.pid ./my_app_release-bin
the core matches but I am unable to get source code line numbers (although I get the function names).
Is this what is practised? Because I feel I am missing something here.
| It sounds like there are other differences between your release and debug build then simply the absence/presence of the -g flag. Assuming that's the case, there is nothing you can do right now, but you can adjust your build to handle this better:
Here's what we do at my place of work.
Include the -g flag when building the release version.
Archive that version.
run strip --strip-unneeded on the binary before shipping it to customers.
Now, when we get a crash we can use the archived version with symbols to do debugging.
One thing to note is that if your release version includes optimization, debugging may be difficult even with symbols. For example, the optimizer can reorder your code so even though the debugger will say you crashed on line N, you can't assume that the code actually executed line N-1.
|
2,264,588 | 2,264,901 | Vim search for class | How do I define a vim function such that when called with
Foo
it searches via vimgrep for
\s*class Foo
or
\s*struct Foo
?
[This is poorman's cscope/ctag; I want to be able to type in a class name, and have it search for the class.]
If this is easy, is there a way I can tell it to look under my cursor to use that 'word' as the name to search for?
Thanks!
| Here's a hack from a vim novice which seems to work:
function! SearchFunc()
let l:filenames = substitute(glob("*.c") . glob("*.cpp") . glob("*.h"), '\n', ' ', 'g')
try
execute 'vimgrep /^\s*\(struct\|class\)\s*' . expand("<cword>") . '/ ' . l:filenames
catch
echon 'No results found.'
sleep 800m
endtry
endfunction
nmap <Leader>fi :call SearchFunc()^M
This should search for the word under the cursor when you type \fi.
Explicating the code:
If you call vimgrep normally in a function and it doesn't find any results, it throws an error which looks fairly ugly, hence I wrapped it inside of a try/catch/endtry block. When an error happens, we presume it's because there was no match, and we display a message, then pause briefly so it doesn't immediately disappear.
"nmap" maps a key sequence in "normal mode" to do something. In this case, it calls the function we just defined. You have to type Ctrl-V, Ctrl-M at the end of the line to create the ^M, so it simulates you pressing return.
If you'd like to change the function to take any argument you could change it like this:
function! SearchFunc(findme)
let l:filenames = substitute(glob("*.c") . glob("*.cpp") . glob("*.h"), '\n', ' ', 'g')
try
execute 'vimgrep /^\s*\(struct\|class\)\s*' . a:findme . '/ ' . l:filenames
catch
echon 'No results found.'
sleep 800m
endtry
endfunction
Then you can call it by typing
:call SearchFunc('foo')
But it would seem easier to just use the built-in <cword> feature.
|
2,264,615 | 2,264,648 | how to search properly the vector for a value | The problem I have, I have to add to a vector, the missing chars.
For example I have initially
s,a,p,i,e,n,t,i,a
and I have to add missing chars to it
s,a,p,i,e,n,t,i,a,b,c,d ...
I am trying to use this code to search for an existing value.
for(char c='a';c!='z';++c)
{
if (vec.end()!=find(vec.begin(),vec.end(),c))
vec.push_back(c);
}
The find returns last when it fails to locate a value. But how do I know if last value was in it?
EDIT
When the for loop starts, for 'a' returns vec.end() so it should not go in, but goes in, and adds 'a' again in the end.
See this in debugger
alt text http://img203.imageshack.us/img203/2048/bb1f.jpg
(The bug I have, the value in last position gets inserted twice, I have to omit this)
| Nope, end() is not the last element of the vector but past it. To iterate over all elements you normally do
for(it= vec.begin(); it!= vec.end(); it++) ...
So whatever your problem is, this is ok.
|
2,264,637 | 2,264,845 | Using Intel Threading Building Blocks (TBB) in Linux | I want to use Intel Threading Building Blocks (TBB) in Linux. Can anyone suggest a good IDE for that and possibly any steps to integrate TBB with that IDE?
Thanks,
Rakesh.
| As long as I know TBB is a set of C++ libraries which purpose to handle task of parallelization of code. So there is no need in any integration(exactly as you using STL) and you can use whatever IDE you wish, e.i. Eclipse, KDevelop and more.
|
2,264,760 | 2,264,768 | Efficient way of finding distance between two 3D points | I am writing a code in C++ and want to compute distance between two points.
Question 1:
I have two points P(x1, y1, z1) and Q(x2, y2, z2) , where x, y and z are floats/doubles.
I want to find the distance between these two points. One way to do it is :
square_root(x_diffx_diff + y_diffy_diff + z_diff*z_diff)
But this is probably not the most efficient way . (e.g. a better formula or a ready made utility in math.h etc )
Question 2:
Is there a better way if I just want to determine if P and Q are in fact the same points?
My inputs are x, y and z coordinates of both the points.
Thank you
| Do you need the actual distance? You could use the distance squared to determine if they are the same, and for many other purposes. (saves on the sqrt operation)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.