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,731,170 | 2,731,370 | Multiple Producers Single Consumer Queue | I am new to multithreading and have designed a program that receives data from two microcontroller measuring various temperatures (Ambient and Water) and draws the data to the screen. Right now the program is singly threaded and its performance SUCKS A BIG ONE.
I get basic design approaches with multithreading but not well enough to create a thread to do a task but what I don't get is how to get threads to perform seperate task and place the data into a shared data pool. I figured that I need to make a queue that has one consumer and multiple producers (would like to use std::queue). I have seen some code on the gtkmm threading docs that show a single Con/Pro queue and they would lock the queue object produce data and signal the sleeping thread that it is finished then the producer would sleep. For what I need would I need to sleep a thread, would there be data conflicts if i didn't sleep any of the threads, and would sleeping a thread cause a data signifcant data delay (I need realtime data to be drawn 30 frames a sec)
How would I go about coding such a queue using the gtkmm/glibmm library.
| Here's a suggestion:
1. Have two threads, that are responsible for obtaining data and placing into a buffer. Each thread has it's own (circular) buffer.
2. There will be a third thread that is responsible for getting data from the buffers and displaying on the screen.
3. The screen thread sends messages to the data threads requesting some data, then displays the data. The messages help synchronize execution and avoid dead-locks.
4. None of the threads should "wait on single or multiple objects", but poll for events.
Think of this scenario using people. One person is delivering water temperature readings. Another person delivering ambient temperature readings. A third person receives or asks for the data and displays the data (on a white board). The objective is to keep everybody operating at maximum efficiency without any collisions.
|
2,731,210 | 2,732,214 | Type to use as template parameter to compare double values | I got this n-dimensional point object:
template <class T, unsigned int dimension> class Obj {
protected:
T coords[dimension];
static const unsigned int size = dimension;
public:
Obj() { };
Obj(T def) { for (unsigned int i = 0; i < size; ++i) coords[i]=def; };
Obj(const Obj& o) { for (unsigned int i = 0; i < size; ++i) coords[i] = o.coords[i]; }
const Obj& operator= (const Obj& rhs) { if (this != &rhs) for (unsigned int i = 0; i < size; ++i) coords[i] = rhs.coords[i]; return *this; }
virtual ~Obj() { };
T get (unsigned int id) { if (id >= size) throw std::out_of_range("out of range"); return coords[id]; }
void set (unsigned int id, T t) { if (id >= size) throw std::out_of_range("out of range"); coords[id] = t; }
};
and a 3D point class which uses Obj as base class:
template <class U> class Point3DBase : public Obj<U,3> {
typedef U type;
public:
U &x, &y, &z;
public:
Point3DBase() : x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { };
Point3DBase(U def) : Obj<U,3>(def), x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { };
Point3DBase(U x_, U y_, U z_) : x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { x = x_; y = y_; z= z_; };
Point3DBase(const Point3DBase& other) : x(Obj<U,3>::coords[0]), y(Obj<U,3>::coords[1]), z(Obj<U,3>::coords[2]) { x = other.x; y = other.y; z = other.z; }
// several operators ...
};
The operators, basically the ones for comparison, use the simple compare-the-member-object approach like:
friend bool operator== (const Point3DBase<U> &lhs, const Point3DBase<U> rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z); }
Then it occured to me that for the comparion of double values the simply equality approach is not very useful since double values should be compared with an error margin. What would be the best approach to introduce an error margin into the point? I thought about an epsDouble type as template parameter but I can't figure out how to achieve this.
edit:
I've seen chained output stream operators that call the output stream operator of the type of the output stream operator ... Is there a way to delegate the comparison to a custom type that represents a float point type?
| If you want one epsilon value for all instances of a given floating type, it's actually quite simple:
template <>
bool operator<(const Point3DBase<double>& lhs, const Point3DBase<double>& rhs)
{
}
If not, then I shall orient you toward Policy-based Design as Alexandrescu showed:
namespace detail
{
template <class U>
struct DefaultComparator: std::binary_function<bool, U, U>
{
bool operator()(U lhs, U rhs) const { return lhs < rhs; }
};
}
template < class U, class Comparator = detail::DefaultComparator<U> >
class Point3DBase;
template < class U, class C>
bool operator<(Point3DBase<U,C> const& lhs, Point3DBase<U,C> const& rhs)
{
return C()(lhs,rhs);
}
Note that you can still define a safe default by specializing DefaultComparator
namespace detail
{
template <>
struct DefaultComparator<float> {};
template <>
struct DefaultComparator<double> {};
}
With this definition, it is not possible to use operator== without passing a Comparator parameter oneself. Another solution would be to allow it but provide a default epsilon in the definition of the two specialization above.
All other operations (>, <=, >=, ==, !=) can be trivially derived (though perhaps not efficiently) from <, for example by deriving from boost::equality_comparable and/or boost::less_than_comparable.
|
2,731,211 | 2,731,300 | Windows Build System: How to build a project (from its source code) which doesn't have *.sln or Visual C++ proj file (*.vcproj) | I'm facing this problem. So, I need to build the support libraries (zlib, libtiff, libpng, libxml2, libiconv) with "Multithreaded DLL" (/MD) & "Multithreaded DLL Debug" (/MDd) run-time options. But the problem is there is no direct way . I mean there is no *.sln / *.vcproj file which I can open in Visual C++ and build it.
I'm aware with the GNU build system:
$./configure --with-all-sorts-of-required-switches
$./make
$./make install
During my search I've encountered with something called CMake which generates *.vcproj & *.sln file but for that CMakeLists.txt is required. Not all projects provide CMakeLists.txt.
I've never compiled anything from Visual C++ Command Line.
Generally most projects provide makefile. Now how do I generate *.vcproj / *.sln from this?
Can I compile with mingw-make of MinGW?
If I can, how do I set different options ("Multi-Threaded"(/MT), "Multi-Threaded Debug"(/MTd), "Multi-Threaded DLL"(/MD), "Multi-Threaded DLL Debug"(/MDd)) for run-time libraries?
I don't know what other ways are available. Please throw some light on this.
| I believe all those projects include a .vcproj file (open/build in VC) and/or VC makefile (build with nmake).
|
2,731,262 | 2,739,174 | Where can I find simple beta cdf implementation | I need to use beta distribution and inverse beta distribution in my project.
There is quite good but complicated implementation in GSL, but I don't want to use such a big library only to get one function.
I would like to either, implement it on my own or link some simple library. Do you know any sources that could help me? I'm looking for any books/articles about numerical approximation of beta CDF and its inverse, libraries where it could be implemented. Any other suggestions would be also appreciated.
Any programming language, but C++/C# preffered.
| Well, I found some other libraries/implementations:
Boost library for C++
Some code in C# at google code
And simple but not exactly perfect implementation of inverse beta cdf
|
2,731,419 | 2,732,105 | What does enabling STL iterator debugging really do? | I've enabled iterator debugging in an application by defining
_HAS_ITERATOR_DEBUGGING = 1
I was expecting this to really just check vector bounds, but I have a feeling it's doing a lot more than that. What checks, etc are actually being performed?
Dinkumware STL, by the way.
| There is a number of operations with iterators which lead to undefined behavior, the goal of this trigger is to activate runtime checks to prevent it from occurring (using asserts).
The issue
The obvious operation is to use an invalid iterator, but this invalidity may arise from various reasons:
Uninitialized iterator
Iterator to an element that has been erased
Iterator to an element which physical location has changed (reallocation for a vector)
Iterator outside of [begin, end)
The standard specifies in excruciating details for each container which operation invalidates which iterator.
There is also a somehow less obvious reason that people tend to forget: mixing iterators to different containers:
std::vector<Animal> cats, dogs;
for_each(cats.begin(), dogs.end(), /**/); // obvious bug
This pertain to a more general issue: the validity of ranges passed to the algorithms.
[cats.begin(), dogs.end()) is invalid (unless one is an alias for the other)
[cats.end(), cats.begin()) is invalid (unless cats is empty ??)
The solution
The solution consists in adding information to the iterators so that their validity and the validity of the ranges they defined can be asserted during execution thus preventing undefined behavior to occur.
The _HAS_ITERATOR_DEBUGGING symbol serves as a trigger to this capability, because it unfortunately slows down the program. It's quite simple in theory: each iterator is made an Observer of the container it's issued from and is thus notified of the modification.
In Dinkumware this is achieved by two additions:
Each iterator carries a pointer to its related container
Each container holds a linked list of the iterators it created
And this neatly solves our problems:
An uninitialized iterator does not have a parent container, most operations (apart from assignment and destruction) will trigger an assertion
An iterator to an erased or moved element has been notified (thanks to the list) and know of its invalidity
On incrementing and decrementing an iterator it can checks it stays within the bounds
Checking that 2 iterators belong to the same container is as simple as comparing their parent pointers
Checking the validity of a range is as simple as checking that we reach the end of the range before we reach the end of the container (linear operation for those containers which are not randomly accessible, thus most of them)
The cost
The cost is heavy, but does correctness have a price? We can break down the cost:
extra memory allocation (the extra list of iterators maintained): O(NbIterators)
notification process on mutating operations: O(NbIterators) (Note that push_back or insert do not necessarily invalidate all iterators, but erase does)
range validity check: O( min(last-first, container.end()-first) )
Most of the library algorithms have of course been implemented for maximum efficiency, typically the check is done once and for all at the beginning of the algorithm, then an unchecked version is run. Yet the speed might severely slow down, especially with hand-written loops:
for (iterator_t it = vec.begin();
it != vec.end(); // Oops
++it)
// body
We know the Oops line is bad taste, but here it's even worse: at each run of the loop, we create a new iterator then destroy it which means allocating and deallocating a node for vec's list of iterators... Do I have to underline the cost of allocating/deallocating memory in a tight loop ?
Of course, a for_each would not encounter such an issue, which is yet another compelling case toward the use of STL algorithms instead of hand-coded versions.
|
2,731,459 | 2,734,185 | C++ program to calculate quotients of large factorials | How can I write a c++ program to calculate large factorials.
Example, if I want to calculate (100!) / (99!), we know the answer is 100, but if i calculate the factorials of the numerator and denominator individually, both the numbers are gigantically large.
| expanding on Dirk's answer (which imo is the correct one):
#include "math.h"
#include "stdio.h"
int main(){
printf("%lf\n", (100.0/99.0) * exp(lgamma(100)-lgamma(99)) );
}
try it, it really does what you want even though it looks a little crazy if you are not familiar with it. Using a bigint library is going to be wildly inefficient. Taking exps of logs of gammas is super fast. This runs instantly.
The reason you need to multiply by 100/99 is that gamma is equivalent to n-1! not n!. So yeah, you could just do exp(lgamma(101)-lgamma(100)) instead. Also, gamma is defined for more than just integers.
|
2,731,594 | 2,739,100 | Exporting DLLs in a C++ project | I've encountered a strange behavior in __declspec(dllexport) in my project.
I have a C++ project that uses classes, namespaces, try-catches and more cpp elements.
When exporting any dummy function in this DLL, no other C project will be able to load it with LoadLibrary (Getting error 'module not found').
Is it possible to load dynamically C++ dlls through C projects?
These projects are Windows Mobile projects, but they should behave the same as on regular PC win32.
I'm stuck on it and any help will be appreciated.
Thank you,
Emil.
| I found the problem. It was really a dependency dll problem. It was not found in the directory of the loading DLL.
Thank you all.
|
2,731,598 | 2,731,747 | LINK : fatal error LNK1104: cannot open file "Iphlpapi.lib" | So I'm using Visual C++ 6.0, and trying to compile some source code, but upon compilation I get this:
Linking...
LINK : fatal error LNK1104: cannot open file "Iphlpapi.lib"
Error executing link.exe.
I'm using the correct SDK, and the directories are correct. I've checked, double checked, and triple checked. The file is the specified directory. I can't figure out what the problem is. Any ideas?
Service Pack 6
SDK for Windows Server 2003 SP1 //Sounds odd, since I'm running XP SP3, but this has worked for me in the past.
Like I've said, it worked in the past for me, flawlessly. I don't understand why it won't work now.
| I'm sure that you have some problems with your project configuration. Try moving that file to the folder with your source code. Check the way you add it (via input libraries) to your project. Try creating a new project and moving that .lib into your code folder (after adding it to used libraries).
|
2,731,610 | 4,819,544 | Stopping Windows Mobile 6.5 tab reordering | I have a C++ Visual Studio 2008 Windows Mobile 6.5 application that uses a tab control. I've noticed that depending on how careful you are with the stylus, when using the tab control you can accidentally re-order the tabs. It's difficult to do deliberately, but it's very easy to do when you're not trying. I assume this is a new "feature" of Windows Mobile 6.5 as it doesn't happen in Windows Mobile 6.1 with the same code.
Is there a window style or something I can set that will lock the tab order such that people don't accidentally re-arrange them?
Also, is there an MSDN page that describes this behavior and how it is supposed to work? I've looked, but have come up empty.
Thanks,
PaulH
| Turns out it is a feature of the WTL tab class I was using. I ended up subclassing it and removing the tab reordering feature.
-PaulH
|
2,732,085 | 2,732,111 | Is there a way to make `enum` type to be unsigned? | Is there a way to make enum type to be unsigned? The following code gives me a warning about signed/unsigned comparison.
enum EEE {
X1 = 1
};
int main()
{
size_t x = 2;
EEE t = X1;
if ( t < x ) std::cout << "ok" << std::endl;
return 0;
}
I've tried to force compiler to use unsigned underlying type for enum with the following:
enum EEE {
X1 = 1,
XN = 18446744073709551615LL
// I've tried XN = UINT_MAX (in Visual Studio). Same warning.
};
But that still gives the warning.
Changing constant to UINT_MAX makes it working in GNU C++ as should be according to the standard. Seems to be a bug in VS. Thanks to James for hint.
| You might try:
enum EEE {
X1 = 1,
XN = -1ULL
};
Without the U, the integer literal is signed.
(This of course assumes your implementation supports long long; I assume it does since the original question uses LL; otherwise, you can use UL for a long).
|
2,732,178 | 2,740,095 | Extracting text from PDF with Poppler (C++) | I'm trying to get my way through Poppler and its (lack of) documentation.
What I want to do is a very simple thing: open a PDF file and read the text in it. I'm then going to process the text, but that doesn't really matter here.
So... I saw the poppler_page_get_text function, and it kind of works, but I have to specify a selection rectangle, which is not very handy. Isn't there just a very simple function that would output the PDF text in order (maybe line by line?).
| You should be able to set the selection rectangle to the pageSize/MediaBox of the page and get all the text.
I say should because before you start wondering why you get surprised by the output of poppler_page_get_text, you should be aware of how text gets laid out on a page. All graphics are laid out on a page using a program expressed in post-fix notation. To render the page, this program is executed on a blank page.
Operations in the program can include, changing colors, position, current transformation matrix, drawing lines, bezier curves and so on. Text is laid out by a series of text operators that are always bracketed by BT (begin text) and ET (end text). How or where text is placed on a page is at the sole discretion of the software that generates the PDF. For example, for print drivers, the code responds to GDI calls for DrawString and translates that into text drawing operations.
If you are lucky, the text on the page is laid out in a sane order with sane font usage, but many programs that generate PDF aren't so kind. Psroff, for example liked to place all the plain text first, then the italic text, then the bold text. Words may or may not be placed in reading order. Fonts may be re-encoded so that 'a' maps to '{' or whatever. Then you might have ligatures where multiple characters are replaced by single glyphs - the most common ones are ae, oe, fi, fl, and ffl.
With all of this in place, the process of extracting text is decidedly non-trivial, so don't be surprised if you see poor quality results from text extraction.
I used to work on the text extraction tools in Acrobat 1.0 and 2.0 - it's a real challenge to get right.
|
2,732,246 | 2,732,252 | Proper use of of typedef in C++ | I have coworkers who occasionally use typedef to avoid typing. For example:
typedef std::list<Foobar> FoobarList;
...
FoobarList GetFoobars();
Personally, I always hate coming across code like this, largely because it forces me to go lookup the typedef so I can tell how to use it. I also feel like this sort of thing is a potential slippery slope... If you do this, why aren't you doing it more? (pretty soon, your code is totally obfuscated). I found this SO question regarding this issue:
when should I use typedef in C
I have two questions: 1) am I truly alone in disliking this? 2) If the vast majority of people think this sort of typedef use is OK, what criteria do you use to determine whether to typedef a type?
| The two big arguments for this type of typedef are the reduced typing, which you've already mentioned, and the ease of changing over to a new type of container. A FoobarList could be backed by a vector or a list or a deque and switching would often just require changing a typedef.
Your dislike of them when it comes to looking them up, is quite reduced when dealing with IDEs, since I can just hover over the type name, and the IDE tells me what it's defined as.
The more useful situations are when you have nested containers - you can give the names some semantic meaning without having to define entire classes:
typedef std::list<Foobar> FoobarList;
typedef std::map <string, FoobarList> GizmosToFoobarsMap;
You can also save a LOT of typing when dealing with iterators of these types (although that's reduced now that C++0x has auto.)
|
2,732,287 | 2,732,422 | Read All Files in Directory? | How would I go about reading all files in a directory?
In C# I would get a DirectoryInfo object, and get all files into a FileInfo[] object.
Is there similar functionality in the STD namespace in C++?
| Using Windows API, you can find all the files in a directory using FindFirstFile() with FindNextFile() in a loop.
|
2,732,292 | 2,732,323 | Setting the Cursor Position in a Win32 Console Application | How can I set the cursor position in a Win32 Console application? Preferably, I would like to avoid making a handle and using the Windows Console Functions. (I spent all morning running down that dark alley; it creates more problems than it solves.) I seem to recall doing this relatively simply when I was in college using stdio, but I can't find any examples of how to do it now. Any thoughts or suggestions would be greatly appreciated. Thanks.
Additional Details
Here is what I am now trying to do:
COORD pos = {x, y};
HANDLE hConsole_c = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL );
char * str = "Some Text\r\n";
DWDORD len = strlen(str);
SetConsoleCursorPosition(hConsole_c, pos);
WriteConsole(hConsole_c, str, len, &dwBytesWritten, NULL);
CloseHandle(hConsole_c)
The text string str is never sent to the screen. Is there something else that I should be doing? Thanks.
| See SetConsoleCursorPosition API
Edit:
Use WriteConsoleOutputCharacter() which takes the handle to your active buffer in console and also lets you set its position.
int x = 5; int y = 6;
COORD pos = {x, y};
HANDLE hConsole_c = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole_c);
char *str = "Some Text\r\n";
DWORD len = strlen(str);
DWORD dwBytesWritten = 0;
WriteConsoleOutputCharacter(hConsole_c, str, len, pos, &dwBytesWritten);
CloseHandle(hConsole_c);
|
2,732,322 | 2,732,560 | Custom Windows GUI library | I always wondered how software such as iTunes, Winamp etc is able to create its own UI.
How is this accomplished under the Windows platform? Is there any code on the web explaining how one would create their own custom GUI?
| WinAmp doesn't usually supply its own GUI at all -- it delegates that to a "skin". You can download dozens of examples and unless memory fails me particularly badly, documentation is pretty easily available as well.
From the looks of things, I'd guess iTunes uses some sort of translation layer to let what's basically written as a native Mac UI run on Windows (the same kind of thing that Apple recently decided was so evil that they're now forbidden on the iPhone and apparently the iPad).
Since saying anything that could possibly be construed as negative about Apple is often treated as heresy, I'll point to all the .xib files that are included with iTunes for Windows. An .XIB file (at least normally) is produced by Apple's Interface Builder to hold resources for OS/X programs, and compiled to a .NIB file prior to deployment. Windows doesn't normally use either .XIB or .NIB files at all, and it appears likely to me that Apple includes a compatibility layer to use them on Windows (though I've never spent any time looking to figure out what file it's stored in or anything like that).
Edit: (response to Mattias's latest comment). Rendering it is tedious but fairly straightforward. You basically take the input from the skin (for example) and create an owner draw control (e.g. a button) and render the button based on that input.
The easiest way to do this is to have fixed positions for your controls, and require the user to draw/include bitmaps for the background and controls. In this case, you just load the background bitmap and display it covering the entire client area of your application (and you'll probably use a borderless window, so that's all that shows). You'll specify all your controls as owner-drawn, and for each you'll load their bitmap and blit it to the screen for that control. Since there won't (usually) be a visible title bar, you'll often need to handle WM_NCHITTEST (or equivalent on other systems) to let the user drag the window around.
If you want to get a bit more complex, you can add things like allowing them to also specify a size and position for each control, as well as possibly specifying that some controls won't show up at all. Again, this isn't really terribly difficult to manage -- under Windows, for example, most controls are windows, and you can specify a size and position when you create a window. If the user loads a different skin at run-time, you can call MoveWindow to move/resize each control as needed.
|
2,732,694 | 2,732,769 | Copy vector of values to vector of pairs in one line | I have the following types:
struct X { int x; X( int val ) : x(val) {} };
struct X2 { int x2; X2() : x2() {} };
typedef std::pair<X, X2> pair_t;
typedef std::vector<pair_t> pairs_vec_t;
typedef std::vector<X> X_vec_t;
I need to initialize instance of pairs_vec_t with values from X_vec_t. I use the following code and it works as expected:
int main()
{
pairs_vec_t ps;
X_vec_t xs; // this is not empty in the production code
ps.reserve( xs.size() );
{ // I want to change this block to one line code.
struct get_pair {
pair_t operator()( const X& value ) {
return std::make_pair( value, X2() ); }
};
std::transform( xs.begin(), xs.end(), back_inserter(ps), get_pair() );
}
return 0;
}
What I'm trying to do is to reduce my copying block to one line with using boost::bind. This code is not working:
for_each( xs.begin(), xs.end(), boost::bind( &pairs_vec_t::push_back, ps, boost::bind( &std::make_pair, _1, X2() ) ) );
I know why it is not working, but I want to know how to make it working without declaring extra functions and structs?
| something like this?
using boost::lambda;
X2 x;
transform(..., (bind(std::make_pair<X,X2>, _1, ref(x))));
I cant check at the moment, but if recalled correctly from memory, the above is valid.
|
2,732,700 | 2,732,803 | C++: Switching from MSVC to G++: Global Variables | I recently switched to Linux and wanted to compile my Visual Studio 2010 C++ source code, which uses only the STL, on G++.
My Linux machine currently isn't available but I can try to tell you what is going on, first:
As I try to compile my project, all global variables I use in main and which perfectly work on MSVC result in myGlobalVar is not defined in this scope errors.
My project is built nearly the same as the example below:
// myclass.h
class myClass
{
// ....
};
extern myClass globalInstance;
// myclass.cpp
#include "myclass.h"
// myClass functions located here
myClass globalInstance;
// main.cpp
#include "myclass.h"
int main( )
{
// Accessing globalInstance results in an error: Not defined in this scope
}
What am I doing wrong?
Where are the differences between G++ and MSVC in terms of global variables?
| you need to compile as follow:
g++ main.cpp myclass.cpp -o myapp
NOT as follow:
g++ main.cpp -o myapp which will miss global variable declaration in myclass.cpp file.
|
2,732,978 | 2,733,015 | C++, how to declare a struct in a header file | I've been trying to include a structure called "student" in a student.h file, but I'm not quite sure how to do it.
My student.h file code consists of entirely:
#include<string>
using namespace std;
struct Student;
while the student.cpp file consists of entirely:
#include<string>
using namespace std;
struct Student {
string lastName, firstName;
//long list of other strings... just strings though
};
Unfortunately, files that use #include "student.h" come up with numerous errors like
error C2027: use of undefined type 'Student'
error C2079: 'newStudent' uses undefined struct 'Student' (where newStudent is a function with a `Student` parameter)
error C2228: left of '.lastName' must have class/struct/union
It appears the compiler (VC++) does not recognize struct Student from "student.h"?
How can I declare struct Student in "student.h" so that I can just #include "student.h" and start using the struct?
| You should not place an using directive in an header file, it creates unnecessary headaches.
Also you need an include guard in your header.
EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.
|
2,733,125 | 2,733,137 | kill unsigned / signed comparison error | In general, I want warnings of unsigned vs signed.
However, in this particular case, I want it suppressed;
std::vector<Blah> blahs;
for(int i = 0; i < blahs.size(); ++i) { ...
I want to kill this comparison.
Thanks!
(using g++)
| You should fix, not suppress. Use an unsigned type:
for (size_t i = 0; i < blahs.size(); ++i)
You can also use unsigned, but size_t is more appropriate here (and may have a different, larger, range). If you're only using i to iterate and don't need its value in the loop, use iterators instead:
for (auto iter = blahs.begin(), end = blahs.end(); iter != end; ++iter)
If your compiler does not support auto, replace auto with T::iterator or T::const_iterator, where T is the type of blahs. If your compiler supports a fuller subset of C++11, though, do this:
for (auto& element : blahs)
Which is best of all.
Strictly speaking, the above is not "correct". It should be:
typedef std::vector<Blah> blah_vec;
blah_vec blahs;
for (blah_vec::size_type i = 0; i < blahs.size(); ++i)
But this can be verbose, and every implementation I know uses size_t as size_type anyway.
If for some reason you really need a signed integer type for i, you'll have to cast:
// assumes size() will fit in an int
for (int i = 0; i < static_cast<int>(blahs.size()); ++i)
// assumes i will not be negative (so use an unsigned type!)
for (int i = 0; static_cast<size_t>(i) < blahs.size(); ++i)
// and the technically correct way, assuming i will not be negative
for (int i = 0; static_cast<blah_vec::size_type>(i) < blahs.size(); ++i)
|
2,733,141 | 2,733,798 | Strassen's Algorithm for Matrix multiplication c# implementation | I'm just doing a self-study of Algorithms & Data structures and I'd like to know if anyone has a C# (or C++) implementation of Strassen's Algorithm for Matrix Multiplication?
I'd just like to run it and see what it does and get more of an idea of how it goes to work.
| Disclaimer: I haven't tried any of these out, but they appear to be what OP is looking for. These links were just from looking through some Google Code Search results.
I found a C# version. The project doesn't have any frills; it's just the source. However, it appears to be doing the algorithm just from my first cursory scan. In particular, you will want to look at this file.
For C++, I found some code in this google code project. The code is, of course, in English, but the wiki is all in a Cyrillic-written language (Russian?). You will want to look mostly at this file. It appears to have both a serial and and parallel version of Strassen's algorithm.
These projects may not be fully correct, but they are things at which you might want to look more closely.
|
2,733,158 | 2,733,177 | What is the difference between declaring an enum with and without 'typedef'? | The standard way of declaring an enum in C++ seems to be:
enum <identifier> { <list_of_elements> };
However, I have already seen some declarations like:
typedef enum { <list_of_elements> } <identifier>;
What is the difference between them, if it exists? Which one is correct?
| C compatability.
In C, union, struct and enum types have to be used with the appropriate keyword before them:
enum x { ... };
enum x var;
In C++, this is not necessary:
enum x { ... };
x var;
So in C, lazy programmers often use typedef to avoid repeating themselves:
typedef enum x { ... } x;
x var;
|
2,733,377 | 2,742,729 | Is there a way to test whether a C++ class has a default constructor (other than compiler-provided type traits)? | Traits classes can be defined to check if a C++ class has a member variable, function or a type (see here).
Curiously, the ConceptTraits do not include traits to check if a C++ class defines a default constructor or given constructor?
Can traits be used to check the constructor presence?
If yes, how?
If not, why it is not possible?
| Sorry for answering may own question.
Googling I have found that the actual reason we can not check if a class has constructor or a destructors is that, the known technique used to detect if a class has a member is based on taking the address of the member. But constructors and destructors have no name, we can not take the address of them.
If we can not take the address, I don't see a way to make the compiler react to a construction without instantiating it directly, but in this case there is no detection at compile time but an error.
So to answer my own question, I would say that with the current techniques it is not possible to detect them and compiler support is needed. But C++ has revealed a lot of surprises, and things that were not possible at a given time, were revealed are possible using another technique.
I hope a C++ language expert is reading that and can give a more clear explanation.
|
2,733,379 | 2,737,579 | How do I get Eclipse CDT to ignore files | I have a C++ project in Eclipse. The project uses Perforce and Eclipse has the Perforce plugin installed. Everything was fine, until I decided to create a git repo in my project. I created the git repo to snapshot some changes which I wasn't ready to commit. Everything was fine until I refreshed my files in Eclipse. Two problems have occurred:
Eclipse found my .git folder, and indexed all of the files inside of it.
Eclipse also decided to add all the git file to my pending change list.
If I create a new file within Eclipse, I'd like it to add it to Perforce, but if it happens to find a file, I don't want it to do anything with it. I'd also like to give Eclipse a list of file types to always ignore, just like I do with my .gitignore file.
I'm using the P4WSAD plugin, but I'm pretty sure the problem can occur anytime you have files you want Eclipse to not see.
| Just add a file .p4ignore in your project root and add everything you want P4WSAD to ignore, such as
.git
See the docu on P4WSAD for more info.
That should take care of the Perforce part of your question. For the Eclipse part, please see this SO question.
|
2,733,459 | 2,733,526 | What is the rationale to not allow overloading of C++ conversions operator with non-member functions | C++0x has added explicit conversion operators, but they must always be defined as members of the Source class. The same applies to the assignment operator, it must be defined on the Target class.
When the Source and Target classes of the needed conversion are independent of each other, neither the Source can define a conversion operator, neither the Target can define a constructor from a Source.
Usually we get it by defining a specific function such as
Target ConvertToTarget(Source& v);
If C++0x allowed to overload conversion operator by non member functions we could for example define the conversion implicitly or explicitly between unrelated types.
template < typename To, typename From >
operator To(const From& val);
For example we could specialize the conversion from chrono::time_point to posix_time::ptime as follows
template < class Clock, class Duration>
operator boost::posix_time::ptime(
const boost::chrono::time_point<Clock, Duration>& from)
{
using namespace boost;
typedef chrono::time_point<Clock, Duration> time_point_t;
typedef chrono::nanoseconds duration_t;
typedef duration_t::rep rep_t;
rep_t d = chrono::duration_cast<duration_t>(
from.time_since_epoch()).count();
rep_t sec = d/1000000000;
rep_t nsec = d%1000000000;
return posix_time::from_time_t(0)+
posix_time::seconds(static_cast<long>(sec))+
posix_time::nanoseconds(nsec);
}
And use the conversion as any other conversion.
For a more complete description of the problem, see here or on my Boost.Conversion library..
So the question is: What is the rationale to non allow overloading of C++ conversions operator with non-member functions?
| With the current rules, to work out whether you can convert between two classes you only need to look in two places: the source and target definitions. If you could define conversions as non-member functions the conversion function could be anywhere which might make finding the cause of unwanted or ambiguous conversions much more difficult (in addition to making the compiler work harder to find possible conversion in all cases where a conversion was need or possible e.g. operator overloading).
I don't think that your proposed template would be very practical. Although you could explicitly specialize it for conversion where you did have an appropriate special case, it would still catch all other conversions causing ambiguities with any pre-existing conversions.
These are perhaps two potential factors in not allowing such conversion.
|
2,733,668 | 2,734,726 | QWidget keyPressEvent override | I'm trying for half an eternity now overriding QWidgets keyPressEvent function in QT but it just won't work. I've to say i am new to CPP, but I know ObjC and standard C.
My problem looks like this:
class QSGameBoard : public QWidget {
Q_OBJECT
public:
QSGameBoard(QWidget *p, int w, int h, QGraphicsScene *s);
signals:
void keyCaught(QKeyEvent *e);
protected:
virtual void keyPressEvent(QKeyEvent *event);
};
QSGameBoard is my QWidget subclass and i need to override the keyPressEvent and fire a SIGNAL on each event to notify some registered objects.
My overridden keyPressEvent in QSGameBoard.cpp looks like this:
void QSGameBoard::keyPressEvent(QKeyEvent *event) {
printf("\nkey event in board: %i", event->key());
//emit keyCaught(event);
}
When i change QSGameBoard:: to QWidget:: it receives the events, but i cant emit the signal because the compiler complains about the scope. And if i write it like this the function doesn't get called at all.
What's the problem here?
| EDIT:
As pointed out by other users, the method I outlined originally is not the proper way to resolve this.
Answer by Vasco Rinaldo
Use Set the FocusPolicy to Qt::ClickFocus to get the keybordfocus by
mouse klick. setFocusPolicy(Qt::ClickFocus);
The previous (albeit imperfect) solution I gave is given below:
Looks like your widget is not getting "focus". Override your mouse press event:
void QSGameBoard::mousePressEvent ( QMouseEvent * event ){
printf("\nMouse in board");
setFocus();
}
Here's the source code for a working example:
QSGameBoard.h
#ifndef _QSGAMEBOARD_H
#define _QSGAMEBOARD_H
#include <QWidget>
#include <QGraphicsScene>
class QSGameBoard : public QWidget {
Q_OBJECT
public:
QSGameBoard(QWidget *p, int w, int h, QGraphicsScene *s);
signals:
void keyCaught(QKeyEvent *e);
protected:
virtual void keyPressEvent(QKeyEvent *event);
void mousePressEvent ( QMouseEvent * event );
};
#endif /* _QSGAMEBOARD_H */
QSGameBoard.cpp
#include <QKeyEvent>
#include <QLabel>
#include <QtGui/qgridlayout.h>
#include <QGridLayout>
#include "QSGameBoard.h"
QSGameBoard::QSGameBoard(QWidget* p, int w, int h, QGraphicsScene* s) :
QWidget(p){
QLabel* o = new QLabel(tr("Test Test Test"));
QGridLayout* g = new QGridLayout(this);
g->addWidget(o);
}
void QSGameBoard::keyPressEvent(QKeyEvent* event){
printf("\nkey event in board: %i", event->key());
}
void QSGameBoard::mousePressEvent ( QMouseEvent * event ){
printf("\nMouse in board");
setFocus();
}
main.cpp
#include <QtGui/QApplication>
#include <QtGui/qmainwindow.h>
#include "QSGameBoard.h"
int main(int argc, char *argv[]) {
// initialize resources, if needed
// Q_INIT_RESOURCE(resfile);
QApplication app(argc, argv);
QMainWindow oM;
QGraphicsScene o;
QSGameBoard a(&oM, 1, 2, &o);
oM.setCentralWidget(&a);
a.show();
oM.show();
// create and show your widgets here
return app.exec();
}
|
2,733,816 | 2,733,999 | How do I declare and initialize a 2d int vector in C++? | I'm trying to do something like:
#include <iostream>
#include <vector>
#include <ctime>
class Clickomania
{
public:
Clickomania();
std::vector<std::vector<int> > board;
};
Clickomania::Clickomania()
: board(12, std::vector<int>(8,0)) <<<<<<<
{
srand((unsigned)time(0));
for(int i = 0; i < 12; i++)
{
for(int j = 0; j < 8; j++)
{
int color = (rand() % 6) + 1;
board[i][j] = color;
}
}
}
However, apparently I can't initialize the "board" vector of vectors this way.
How can I create a public member of a 2d vector type and initialize it properly?
| Compiling your code with g++, the error I get is that neither srand() nor rand() were declared. I had to add #include <cstdlib> for the code to compile. But once I did that, it worked just fine. So, I'd say that other than adding that include statement, your code is fine. You're initializing the vector correctly.
Perhaps the code you have doesn't quite match what you posted? I would assume that if your actual code didn't include cstdlib, that you would have quickly understood that that was the problem rather than something with vector. So, if your code doesn't quite match what you posted, maybe that's the problem. If not, what compiler are you using?
|
2,734,401 | 2,734,470 | Having template function defination in cpp file - Not work for VC6 | I have the following source code :
// main.cpp
#include "a.h"
int main() {
A::push(100);
}
// a.cpp
#include "a.h"
template <class T>
void A::push(T t) {
}
template void A::push(int t);
// a.h
#ifndef A_H
class A {
public:
template <class T>
static void push(T t);
};
#endif
The code compiled charming and no problem under VC2008.
But when come to my beloved VC6, it give me error :
main.obj : error LNK2001: unresolved
external symbol "public: static void
__cdecl A::push(int)" (?push@A@@SAXH@Z)
Any workaround? I just want to ensure my function definition is re-inside cpp file.
| The problem solved by using
// main.cpp
#include "a.h"
int main() {
A::push<int>(100);
}
It seems that you need to provide more hint to VC6, compared with VC2008.
|
2,734,562 | 2,734,568 | C++ Char without Limit | I'm pretty well versed in C#, but I decided it would be a good idea to learn C++ as well. The only thing I can't figure out is chars. I know you can use the string lib but I also want to figure out chars.
I know you can set a char with a limit like this:
#include <iostream>
using namespace std;
int main()
{
char c[128] = "limited to 128";
cout << c << endl;
system("pause");
return 0;
}
But how would I make a char without a limit? I've seen chars with * but I though that was for pointers. Any help is greatly appreciated.
| You can use a vector of char.
|
2,734,884 | 2,740,824 | ISO/IEC Website and Charging for C and C++ Standards | The ISO C Standard (ISO/IEC 9899) and the ISO C++ Standard (ISO/IEC 14882) are not published online; instead, one must purchase the PDF for each of those standards. I am wondering what the rationale is behind this... is it not detrimental to both the C and C++ programming languages that the authoritative specification for these languages is not made freely available and searchable online? Doesn't this encourage the use of possibly inaccurate, non-authoritative sources for information regarding these languages?
While I understand that much time and effort has gone into developing the C and C++ standards, I am still somewhat puzzled by the choice to charge for the specification. The OpenGroup Base Specification, for example, is available for free online; they make money by charging for certification. Does anyone know why the ISO standards committees don't make their revenue in certifying standards compliance, instead of charging for these documents? Also, does anyone know if the ISO standards committee's atrociously looking website is intentionally made to look that way? It's as if they don't want people visiting and buying the spec.
One last thing... the C and C++ standards are generally described as "open standards"... while I realize that this means that anyone is permitted to implement the standard, should that definition of "open" be revised? Charging for the standard rather than making it openly available seems contrary to the spirit of openness.
P.S. I do have a copy of the ISO/IEC 9899:1999 and ISO/IEC 14882:2003, so please no remarks about being cheap or anything... although if you are tempted to say such things, you might want to consider the high school, undergraduate, and graduate students who might not have all that much extra cash. Also, you might want to consider the fact that the ISO website is really sketchy and they don't even tell you the cost until you proceed to the checkout... doesn't really encourage one to go and get a copy, now does it?
Edit / Comment
It occurs to me that if the ISO standards committees were to make their revenues from certification that it would incentivize smaller but more frequent changes to the standard rather than very large revisions very infrequently. It would also incentivize creating an implementable standard (I doubt the ISO C++ committee would have introduced "export" in the first place if they got their revenues from certification).
I have found a solution to one of the annoyances of not having the PDF online.... I have uploaded my copy of the standards into my Google Docs, so that I can still access it from any computer without carrying it around.
| For what it's worth, Herb Sutter wrote an article touching on this issue, and there's a fair bit of discussion in the comments:
http://herbsutter.com/2010/03/03/where-can-you-get-the-iso-c-standard-and-what-does-open-standard-mean/
As he mentions, "open" does not necessarily mean "no-cost". As far as students or others with limited financial means who might want free versions of thee documents, note that:
many references that students may want (or even be required to access) are not free
for most work, the standards simply aren't a requirement - there is plenty of freely available documentation that is more than adequate for much of the work that almost anyone might want to do with C or C++
the draft documents are freely downloadable in many cases; while they aren't the standard, the final draft versions are very close and might be good enough for a lot of uses.
If you're serious about C or C++ programming, I'd suggest that you should have a copy of the standards (though I wouldn't say it's a requirement). I'd also suggest that there shouldn't be an expectation that they'd be free, just as for any occupation or avocation the 'tools of the trade' are generally not free - whether those tools are physical objects like hammers, or information such as manuals or specifications.
In fact, I'd argue that a good set of references would be preferable to a set of the standards, if you could only have one or the other or you're starting out (you'd probably want a couple different ones for C++, while Harbison & Steele is all that's needed for C).
Don't get me wrong - I'm not opposed to them being made freely available (and I'm happy that they're currently rather inexpensive), but I don't think there's any reason to expect them to free.
The answers to the SO question, "Where do I find the current C or C++ standard documents?", have pointers to cheap versions and free draft versions. Also note that the current C99 standard (with TC1 and TC2 incorporated) is available for free download:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
There's a note that N1124 "is a WG14 working paper, but it reflects the consolidated standard at the time of issue".
|
2,734,920 | 2,734,942 | Question regarding inheritance in wxWidgets | Currently I'm attempting to write my own wxObject, and I would like for the class to be based off of the wxTextCtrl class.
Currently this is what I have:
class CommandTextCtrl : public wxTextCtrl {
public:
void OnKey(wxKeyEvent& event);
private:
DECLARE_EVENT_TABLE()
};
Then later on I have this line of code, which is doesn't like:
CommandTextCtrl *ctrl = new CommandTextCtrl(panel, wxID_ANY, *placeholder, *origin, *size);
...and when I attempt to compile the program I receive this error:
error: no matching function for call to ‘CommandTextCtrl::CommandTextCtrl(wxPanel*&, <anonymous enum>, const wxString&, const wxPoint&, const wxSize&)’
It seems that it doesn't inherit the constructor method with wxTextCtrl. Does anyone happen to know why it doesn't inherit the constructor?
Thanks in advance for any help!
| C++ does not inherit constructors (you may be thinking of Python, which does;-). A class w/o explicitly declared ctors, like your CommandTextCtrl, in C++, only has default and copy ctors supplied implicitly by C++ rules.
So, you need to explicitly define a ctor with your desired signature, which basically "bounces back" to the base class's -- with the CommandTextCtrl(...): wxTextCtrl(...) {} kind of syntax, of course.
|
2,734,990 | 2,735,100 | What are the disadvantages of using templates? | Some of the disadvantages would be
its syntax is complex
compiler generates extra code
| They are hard to validate. Template code which doesn't get used tends to be seldom compiled at all. Therefore good coverage of test cases is a must. But testing is time-consuming, and then it may turn out the code never needed to be robust in the first place.
|
2,735,101 | 2,735,111 | number of digits in a hex escape code in C/C++ | I'm having a dispute with a colleague of mine. She says that the following:
char* a = "\x000aaxz";
will/can be seen by the compiler as "\x000aa". I do not agree with her, as I think you can have a maximum number of 4 hex characters after the \x. Can you have more than 4 hex chars?
Who is right here?
| §2.13.2/4:
The escape \xhhh consists of the
backslash followed by x followed by
one or more hexadecimal digits that
are taken to specify the value of the
desired character. There is no limit
to the number of digits in a
hexadecimal sequence. A sequence of
octal or hexadecimal digits is terminated by the first character that is
not an octal digit or a hexadecimal
digit, respectively.
She is right.
However, you can terminate it early by eager catenation: the sequence of literals "\x000a" "axz" specifies a single four-character string literal. (2.13.4/3)
Also note that Unicode uses 21-bit code points; it doesn't stop at 16 bits.
|
2,735,151 | 2,735,161 | How do I output an individual character when using char *[] = "something" | I've been playing with pointers to better understand them and I came across something I think I should be able to do, but can't sort out how. The code below works fine - I can output "a", "dog", "socks", and "pants" - but what if I wanted to just output the 'o' from "socks"? How would I do that?
char *mars[4] = { "a", "dog", "sock", "pants" };
for ( int counter = 0; counter < 4; counter++ )
{
cout << mars[ counter ];
}
Please forgive me if the question is answered somewhere - there are 30+ pages of C++ pointer related question, and I spent about 90 minutes looking through them, as well as reading various (very informative) articles, before deciding to ask.
| mars[i][j] will print the j'th character of the i'th string.
So mars[2][1] is 'o'.
|
2,735,194 | 2,737,133 | Operator issues with cout | I have a simple package class which is overloaded so I can output package data simply with cout << packagename. I also have two data types, name which is a string and shipping cost with a double.
protected:
string name;
string address;
double weight;
double shippingcost;
ostream &operator<<( ostream &output, const Package &package )
{
output << "Package Information ---------------";
output << "Recipient: " << package.name << endl;
output << "Shipping Cost (including any applicable fees): " << package.shippingcost;
The problem is occurring with the 4th line (output << "Recipient:...). I'm receiving the error "no operator "<<" matches these operands". However, line 5 is fine.
I'm guessing this has to do with the data type being a string for the package name. Any ideas?
| You must be including a wrong string header. <string.h> and <string> are two completely different standard headers.
#include <string.h> //or in C++ <cstring>
That's for functions of C-style null-terminated char arrays (like strcpy, strcmp etc). cstring reference
#include <string>
That's for std::string. string reference
|
2,735,294 | 2,735,354 | Templates, Function Pointers and C++0x | One of my personal experiments to understand some of the C++0x features: I'm trying to pass a function pointer to a template function to execute. Eventually the execution is supposed to happen in a different thread. But with all the different types of functions, I can't get the templates to work.
#include <functional>
int foo(void) {return 2;}
class bar {
public:
int operator() (void) {return 4;};
int something(int a) {return a;};
};
template <class C>
int func(C&& c)
{
//typedef typename std::result_of< C() >::type result_type;
typedef typename std::conditional<
std::is_pointer< C >::value,
std::result_of< C() >::type,
std::conditional<
std::is_object< C >::value,
std::result_of< typename C::operator() >::type,
void>
>::type result_type;
result_type result = c();
return result;
}
int main(int argc, char* argv[])
{
// call with a function pointer
func(foo);
// call with a member function
bar b;
func(b);
// call with a bind expression
func(std::bind(&bar::something, b, 42));
// call with a lambda expression
func( [](void)->int {return 12;} );
return 0;
}
The result_of template alone doesn't seem to be able to find the operator() in class bar and the clunky conditional I created doesn't compile. Any ideas? Will I have additional problems with const functions?
| How about using decltype?
template <class C>
auto func(C&& c) -> decltype(c()) {
auto result = c();
return result;
}
|
2,735,315 | 2,735,337 | C++ cin whitespace question | Programming novice here. I'm trying to allow a user to enter their name, firstName middleName lastName on one line in the console (ex. "John Jane Doe"). I want to make the middleName optional. So if the user enters "John Doe" it only saves the first and last name strings. If the user enters "John Jane Doe" it will save all three.
I was going to use this:
cin >> firstName >> middleName >> lastName;
then I realized that if the user chooses to omit their middle name and enters "John Doe" the console will just wait for the user to enter a third string... I know I could accomplish this with one large string and breaking it up into two or three, but isn't there a simpler way to do it with three strings like above?
I feel like I'm missing something simple here...
Thanks in advance.
| Use getline and then parse using a stringstream.
#include <sstream>
string line;
getline( cin, line );
istringstream parse( line );
string first, middle, last;
parse >> first >> middle >> last;
if ( last.empty() ) swap( middle, last );
|
2,735,417 | 2,735,500 | How do explicit template instantiations affect what the linker can find? | See the following code and please clear my doubts.
As ABC is a template, why does it not show an error when we put the definition of the ABC class member function in test.cpp?
If I put test.cpp code in test.h and remve 2, then it works fine. Why?
.
// test.h
template <typename T>
class ABC {
public:
void foo( T& );
void bar( T& );
};
// test.cpp
template <typename T>
void ABC<T>::foo( T& ) {} // definition
template <typename T>
void ABC<T>::bar( T& ) {} // definition
template void ABC<char>::foo( char & ); // 1
template class ABC<char>; // 2
// main.cpp
#include "test.h"
int main() {
ABC<char> a;
a.foo(); // valid with 1 or 2
a.bar(); // link error if only 1, valid with 2
}
| In both cases you are doing an explicit instantiation. In the second case, only ABC<char>::foo is being instantiated, while in the first case ABC<char>::bar is also being instantiated.
A different similar example may clarify the implications:
// test.h
template <typename T>
class ABC {
public:
void foo( T& );
void bar( T& );
};
// test.cpp
template <typename T>
void ABC<T>::foo( T& ) {} // definition
template <typename T>
void ABC<T>::bar( T& ) {} // definition
template void ABC<char>::foo( char & ); // 1
template class ABC<char>; // 2
// main.cpp
#include "test.h"
int main() {
ABC<char> a;
a.foo(); // valid with 1 or 2
a.bar(); // link error if only 1, valid with 2
}
In the example, in main the compiler cannot see foo nor bar definitions, so it cannot instantiate the methods. The compiler, when processing main.cpp will accept the code in main gladly, since you are telling it that ABC is a template and that it has those two functions, and will assume that they will be defined in some other translation unit.
In the translation unit that contains test.cpp the compiler is seeing both method definitions, and the both of the instantiations (method/class) can be fully processed. If only the method instantiation ([1]) is present, the compiler will only generate that method, and will leave bar undefined. So any code that includes test.h, links against the compiled test.cpp and uses only foo method will compile and link, but usage of bar will fail to link due to it being undefined.
Explicitly instantiating the class template generates the symbols for all the member methods, and in that case, any translation unit that includes test.h and links against the compiled test.cpp object file will both compile and link.
|
2,735,605 | 2,735,637 | Pointer to auto_ptr instead of a classical double pointer | I'm quite new to smart pointers and was trying to refactor some existing code to use auto_ptr. The question I have is about double pointers and their auto_ptr equivalent, if that makes sense.
I have a function that accepts a double pointer as its parameter and the function allocates resources for it:
void foo ( Image** img ) { ... *img = new Image(); ...}
This function is then used like this:
Image* img = NULL;
foo ( &img );
...
delete img;
I want to use auto_ptr to avoid having to call delete explicitly. Is the following correct?
void foo ( auto_ptr<Image>* img ) { ... *img = auto_ptr<Image>(new Image()); ...}
and then
auto_ptr<Image> img = NULL;
foo ( &img );
Thanks.
| std::auto_ptr<> has weird copy semantics (actually it's move semantics, rather than copy semantics) and is often not what you want when you want a smart pointer. For example, it cannot be put into STL containers.
If your standard library comes with TR1 support, use std::tr1::shared_ptr<> instead. (If it doesn't, use boost's boost::shared_ptr<>, which is what std::tr1::shared_ptr<> was taken from.)
If you want to stick with std::auto_ptr<> for your code, you can pass it into the function per non-const reference:
void foo ( std::auto_ptr<Image>& img ) { ... img.reset(new Image();) ...}
std::auto_ptr<Image> img;
foo ( img );
...
// no need to delete
Or you could just return the pointer:
std::auto_ptr<Image> foo () {return std::auto_ptr<Image> img(new Image();)}
|
2,735,918 | 2,735,928 | sizeof derived already from base | is it possible to return the sizeof a derived class already from base class/struct?
imho the size of a class is a kind of property of itself, like the weight of a human being. But I don't want to write the same function in every class.
many thanks in advance
Oops
PS: so code to make my question more clear:
template <typename T>
struct StructBase {
size_t size<T>(){
return sizeof(T);
}
};
struct MyStruct: public StructBase<MyStruct> {
double d1;
double d2;
double d3;
MyStruct(): d1(0), d2(0), d3(0){}
//I do not want to do this here
//size_t size(){ //return size<MyStruct> ;}
};
int main(void) {
MyStruct m;
std::cout << m.size(); //nop ?!?
}
| You can't overload the sizeof operator. And I'm not sure what you are asking:
class A {
int x, y;
};
then:
size_t n = sizeof( A );
gives you the size of class A - I don't see where derivation comes into this.
Edit: and regarding your expanded question, I don't see why you can't say:
MyStruct m;
std::cout << sizeof( m );
Note that size is not a property like weight - weight can change, and is different for different instances. The size of a class must be known by the compiler at compile time and cannot ever change.
|
2,735,982 | 2,736,086 | Memory leak using shared_ptr | Both code examples compile and run without problems.
Using the second variant results in a memory leak. Any ideas why?
Thanks in advance for any help.
Variant 1:
typedef boost::shared_ptr<ParameterTabelle> SpParameterTabelle;
struct ParTabSpalteData
{
ParTabSpalteData(const SpParameterTabelle& tabelle, const string& id)
:Tabelle(tabelle), Id(id)
{
}
const SpParameterTabelle& Tabelle;
string Id;
};
Variant 2:
struct ParTabSpalteData
{
ParTabSpalteData(const SpParameterTabelle& tabelle, const string& id)
:Id(id)
{
// causes memory leak
Tabelle2 = tabelle;
}
SpParameterTabelle Tabelle2;
string Id;
};
| Have you checked, that you do not have cyclic shared pointer references?
For example:
class A {
public: shared_ptr<A> x;
};
shared_ptr<A> a1(new A());
shared_ptr<A> a2(new A());
a1->x = a2;
a2->x = a1;
Here a1 and a2 will never be released, because they have pointers to each other which keeps them alive.
So in your case check if SpParameterTabelle has a reference on ParTabSpalteData or if there is another possibility to get a cyclic reference.
|
2,736,060 | 2,736,300 | lexical_cast int to string | Is it safe to ignore exception of boost::lexical_cast when converting int to std::string?
| Exception raised by lexical cast when converting an int to std::string are not associated to the conversion, but to resource unavailable. So you can ignore this in the same way you ignore the exception bad_alloc raised by operator new.
|
2,736,062 | 2,736,495 | How to determine the end of an integer array when manipulating with integer pointer? | Here is the code:
int myInt[] ={ 1, 2, 3, 4, 5 };
int *myIntPtr = &myInt[0];
while( *myIntPtr != NULL )
{
cout<<*myIntPtr<<endl;
myIntPtr++;
}
Output: 12345....<junks>..........
For Character array: (Since we have a NULL character at the end, no problem while iterating)
char myChar[] ={ 'A', 'B', 'C', 'D', 'E', '\0' };
char *myCharPtr = &myChar[0];
while( *myCharPtr != NULL )
{
cout<<*myCharPtr<<endl;
myCharPtr++;
}
Output: ABCDE
My question is since we say to add NULL character as end of the strings, we rule out such issues!
If in case, it is rule to add 0 to the end of integer array, we could have avoided this problem. What say?
| C-strings convention is that a char* finish by a '\0' char. For array or any other C++ container there are other idioms that can be applied. Next follows my preferences
The best way to iterate on sequences is to use the Range-based for-loop included on C++0x
int my_array[] = {1, 2, 3, 4, 5};
for(int& x : my_array)
{
cout<<x<<endl;
}
If your compiler don't provide this yet, use iterators
for(int* it = std::begin(array); it!=std::end(array); ++it)
{
cout<<*it<<endl;
}
And if you can not use neither std::begin/end
for(int* it = &array[0]; it!=&array[sizeof(array)]; ++it)
{
cout<<*it<<endl;
}
P.S Boost.Foreach emulates the Range-based for-loop on C++98 compilers
|
2,736,454 | 2,736,489 | C++: retrieve map values and insert into second map | I have one map within one header file class:
class One
{
// code
typedef map<string, int> MapStrToInt;
inline MapStrToInt& GetDetails(unsigned long index)
{
return pData[index];
}
// populate pData....
private:
MapStrToInt *pData;
};
And a second class which implements another map and wants to get the first 10 details from the class One's map.
class Two
{
// code
One::MapStrToInt pDataTen;
int function1()
{
for (int i =0; i < 10; i ++)
{
One::MapStrToInt * pMap = &(One::GetDetails(i));
pDataTen.insert(pair<string, int>(pMap->first,pMap->second));
}
}
}
When I compile this, it states that pMap:
has no member named 'first'
has no member named 'second'
Any suggestions?
Thanks..
| You are using pointers to your maps, instead of plain map objects. Thus, indexing them is the same as indexing into an array of maps. (This may actually be what you want, judging from your comments.)
However, first and second are members of an element within your map, not of the map itself. So you should iterate over the map to get its individual elements, then insert them into the second map.
Now, it is not quite clear whether you want to get 10 elements from the first map in your array, or 1 element each from 10 maps in your array. Here is how to do the former:
One::MapStrToInt& map = One::GetDetails(0);
MapStrToInt::iterator it = map.begin();
for (int i =0; i < 10 && it != map.end(); i++, it++)
{
pDataTen.insert(*it);
}
|
2,736,828 | 2,736,879 | Is Ogre's use of Exceptions a good way of using them? | I've managed to get through my C++ game programming career so far virtually never touching exceptions but recently I've been working on a project with the Ogre engine and I'm trying to learn properly. I've found a lot of good questions and answers here on the general usage of C++ exceptions but I'd like to get some outside opinions from here on whether Ogre's usage is good and how best to work with them.
To start with, quoting from Ogre's documentation of it's own Exception class:
OGRE never uses return values to indicate errors. Instead, if an error occurs, an exception is thrown, and this is the object that encapsulates the detail of the problem. The application using OGRE should always ensure that the exceptions are caught, so all OGRE engine functions should occur within a try{} catch(Ogre::Exception& e) {} block.
Really? Every single Ogre function could throw an exception and be wrapped in a try/catch block? At present this is handled in our usage of it by a try/catch in main that will show a message box with the exception description before exiting. This can be a bit awkward for debugging though as you don't get a stack trace, just the function that threw the error - more important is the function from our code that called the Ogre function. If it was an assert in Ogre code then it would go straight to the code in the debugger and I'd be able to find out what's going on much easier - I don't know if I'm missing something that would allow me to debug exceptions already?
I'm starting to add a few more try/catch blocks in our code now, generally thinking about whether it matters if the Ogre function throws an exception. If it's something that will stop everything working then let the main try/catch handle it and exit the program. If it's not of great importance then catch it just after the function call and let the program continue. One recent example of this was building up a vector of the vertex/fragment program parameters for materials applied to an entity - if a material didn't have any parameters then it would throw an exception, which I caught and then ignored as it didn't need to add to my list of parameters. Does this seem like a reasonable way of dealing with things? Any specific advice for working with Ogre is much appreciated.
| You don't need to wrap every last call to Ogre in try { ... } catch. You do it wherever you can meaningfully deal with the exception. This may be at the individual call site in some cases, or it could be in a high-level loop of some sort. If you can't deal with it meaningfully anywhere, don't catch it at all; let the debugger take over.
In particular, you shouldn't catch exceptions in main() for precisely the reason you cite (at least, not during development; you should in production).
|
2,736,829 | 2,736,839 | show a simple progress bar in C++ | Here is the problem:
I want to show a progress bar (just as a text like "Remaining 35%...") during a C++ function execution. I've done the first part which is the progress bar but the problem is how do I show the progress bar during the other functions execution?
I just want to start showing the bar when execution enters a specific function and reach 100% when leaving the function.
How do I do this in C++? any suggestion?
thanks in advance!
/Niklas
| Use a separate thread to update the progress bar. That should give "near real" progress of your application.
|
2,737,013 | 2,737,022 | Static variables in static method in base class and inheritance | I have these C++ classes:
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base
{
};
class B : public Base
{
};
Will the x static variable be shared among A and B, or will each one of them have it's own independent x variable (which is what I want)?
| There will only be one instance of x in the entire program. A nice work-around is to use the CRTP:
template <class Derived>
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base<A> { };
class B : public Base<B> { };
This will create a different Base<T>, and therefore a distinct x, for each class that derives from it.
You may also need a "Baser" base to retain polymorphism, as Neil and Akanksh point out.
|
2,737,058 | 2,737,457 | How to migrate Cppunit tests into GoogleTest? | I have a bunch of module tests written in CPPunit with some mocks created by hand. I am looking for a way to migrate them to GoogleTest as smoothly as possible.
Have you tried such an operation?
What was the effort needed?
| Google Test and Cppunit seem to share somewhat the same syntax for invoking tests but as I suspect have too much differences in that syntax.
I'm almost sure you can't somehow automate it and this operation would require rethinking and recompositioning of your tests to follow the Google Test semantics (if you use something specialized to create your mocks, then porting them to Google Mock would require even more effort, simply because Google Mock's approach is not the obvious one and is actually complicated).
I would say that you'd better rethink the following questions: "why do I need to port my tests", "what would be the benefit of this operation" and "do I really want to study a whole new testing framework and then rewrite all of my tests for some purpose".
|
2,737,131 | 2,737,146 | c++: Reference array of maps | I have a function which creates an array of Maps:
map<string, int> *pMap
And a function which writes maps to the array:
int iAddMap(map<string, int> mapToAdd, map<string, int> *m, int i)
{
m = &(pMap[i]);
memcpy(m, mapToAdd, sizeof(map<string, int>));
}
And a function to get maps from the array
map<string, int>& getMap(int i)
{
return pMap[i];
}
I can write maps to the array without any issue, but every get call results in a seg fault:
int val;
// val defined after this
map<string, int> * pGetMap = &(getMap(val));
Any suggestions on why this is happening?
| You cannot use memcpy() to copy objects like maps, or indeed any other kind of C++ container - you need to use assignment, which takes into account the map's underlying structure and se,mantics. And you should be using a vector <map>, as you actually seem to want a copy rather than a pointer.
|
2,737,500 | 2,737,575 | How to pass a const unsigned char * from c++ to c# | So I have a function in unmanaged c++ that gets called when some text happens to have "arrived":
#using <MyParser.dll>
...
void dump_body(const unsigned char *Body, int BodyLen)
{
// Need to pass the body to DumpBody, but as what type?
...
MyParser::Parser::DumpBody(???);
}
DumpBody is a static function defined in a C# DLL that should take one parameter of type?
Body holds an array of characters (text) of length BodyLen.
There's obviously some marshalling to be done here but I have no idea how.
Please help.
| void dump_body(const unsigned char *body, int bodyLen)
{
// you might want a different encoding...
String ^str = gcnew String((sbyte*)body, 0, bodyLen, gcnew ASCIIEncoding);
MyParser::Parser::DumpBody(str);
}
DumpBody will take a string.
|
2,737,541 | 2,738,804 | c++ quick sort running time | I have a question about quick sort algorithm. I implement quick sort algorithm and play it.
The elements in initial unsorted array are random numbers chosen from certain range.
I find the range of random number effects the running time. For example, the running time for 1, 000, 000 random number chosen from the range (1 - 2000) takes 40 seconds. While it takes 9 seconds if the 1,000,000 number chosen from the range (1 - 10,000).
But I do not know how to explain it. In class, we talk about the pivot value can effect the depth of recursion tree.
For my implementation, the last value of the array is chosen as pivot value. I do not use randomized scheme to select pivot value.
int partition( vector<int> &vec, int p, int r) {
int x = vec[r];
int i = (p-1);
int j = p;
while(1) {
if (vec[j] <= x){
i = (i+1);
int temp = vec[j];
vec[j] = vec[i];
vec[i] = temp;
}
j=j+1;
if (j==r)
break;
}
int temp = vec[i+1];
vec[i+1] = vec[r];
vec[r] = temp;
return i+1;
}
void quicksort ( vector<int> &vec, int p, int r) {
if (p<r){
int q = partition(vec, p, r);
quicksort(vec, p, q-1);
quicksort(vec, q+1, r);
}
}
void random_generator(int num, int * array) {
srand((unsigned)time(0));
int random_integer;
for(int index=0; index< num; index++){
random_integer = (rand()%10000)+1;
*(array+index) = random_integer;
}
}
int main() {
int array_size = 1000000;
int input_array[array_size];
random_generator(array_size, input_array);
vector<int> vec(input_array, input_array+array_size);
clock_t t1, t2;
t1 = clock();
quicksort(vec, 0, (array_size - 1)); // call quick sort
int length = vec.size();
t2 = clock();
float diff = ((float)t2 - (float)t1);
cout << diff << endl;
cout << diff/CLOCKS_PER_SEC <<endl;
}
| Most likely it's not performing well because quicksort doesn't handle lots of duplicates very well and may still result in swapping them (order of key-equal elements isn't guaranteed to be preserved). You'll notice that the number of duplicates per number is 100 for 10000 or 500 for 2000, while the time factor is also approximately a factor of 5.
Have you averaged the runtimes over at least 5-10 runs at each size to give it a fair shot of getting a good starting pivot?
As a comparison have you checked to see how std::sort and std::stable_sort also perform on the same data sets?
Finally for this distribution of data (unless this is a quicksort exercise) I think counting sort would be much better - 40K memory to store the counts and it runs in O(n).
|
2,737,921 | 2,766,936 | Thumbnail Provider not working | I'm trying to write a Windows Explorer thumbnail handler for our custom file type. I've got this working fine for the preview pane, but am having trouble getting it to work for the thumbnails.
Windows doesn't even seem to be trying to call the DllGetClassObject entry point.
Before I continue, note that I'm using Windows 7 and unmanaged C++.
I've registered the following values in the registry:
HKCR\CLSID\<my guid>
HKCR\CLSID\<my guid>\InprocServer32 (default value = path to my DLL)
HKCR\CLSID\<my guid>\InprocServer32\ThreadingModel (value = "Apartment")
HKCR\.<my ext>\shellex\{E357FCCD-A995-4576-B01F-234630154E96} (value = my guid)
I've also tried using the Win SDK sample, and that doesn't work. And also the sample project in this article (http://www.codemonkeycodes.com/2010/01/11/ithumbnailprovider-re-visited/), and that doesn't work.
I'm new to shell programming, so not really sure the best way of debugging this. I've tried attaching the debugger to explorer.exe, but that doesn't seem to work (breakpoints get disabled, and none of my OutputDebugStrings get displayed in the output window). Note that I tried setting the "DesktopProcess" in the registry as described in the WinSDK docs for debugging the shell, but I'm still only seeing one explorer.exe in the task manager - so that "may" be why I can't debug it??
Any help with this would be greatly appreciated!
Regards,
Dan.
| I stumbled across this since you mentioned my blog ( codemonkeycodes.com ).
What problem are you having with my sample? Did you register you DLL using regsvr32? What version of Windows 7 are you on, 32 or 64?
Update:
I can't say what is or isn't working for you. I just downloaded the sample from my site, followed the directions and change the function
STDMETHODIMP CThumbnailProvider::GetThumbnail... to look like
{
*phbmp = NULL;
*pdwAlpha = WTSAT_UNKNOWN;
ULONG_PTR token;
GdiplusStartupInput input;
if (Ok == GdiplusStartup(&token, &input, NULL))
{
//gcImage.LogBuffer();
Bitmap * pBitmap = new Bitmap(188, 141);
if( pBitmap )
{
Color color(0, 0, 0);
pBitmap->GetHBITMAP(color, phbmp);
}
}
GdiplusShutdown(token);
if( *phbmp != NULL )
return NOERROR;
return E_NOTIMPL;
}
I registered the DLL and then created a new file with the proper extension, and tada, I had a nice black thumbnail.
I wish I could help you. Maybe you want to email me your code?
|
2,737,954 | 2,738,023 | Binding to object properties in C++ | I've seen in WPF where you can bind control values to properties of other controls. How is that binding accomplished in C++?
For example, if I have a class called Car and a guage control called RPM, how do I tie the value of RPM to the member variable Car.RPM, so that when Car.RPM changes, it is automatically (as in without a specific update call coded by me) reflected by the RPM control?
General answers or directions to pertinent resources would be fine also, as I'm just beginning to dabble in C++ and haven't had much Google luck with this particular question.
EDIT: See comments for further clarification.
| It sounds like you want to have a pointer to the value Car.RPM in the gauge control. But the control will never be updated like you want to.
In pure C++ this sounds like work for the Observer-Observable pattern, or a simple callback function.
|
2,738,015 | 2,738,087 | WINAPI SetLastError versus C++ Keword Throw | What is the difference between the WINAPI SetLastError() and the C++ keyword throw? For example, are SetLastError(5); and throw 5; the same?
| SetLastError sets a simple global variable, it does nothing to the flow of the program.
throw would stop the flow of the running program, unwind the stack until it is caught somewhere with a try - catch clause. The program flow would then continue from the end of the catch.
I suggest reading this article, which explains the concept of exceptions. And read up on C++ exceptions.
Also, don't throw 5, throw an non-built in object, preferably inherited by std::exception. An object can contain some state telling the catch clause what to do with the error.
|
2,738,076 | 2,740,226 | Boost ASIO read X bytes synchroniously into a vector | I've been attempting to write a client/server app with boost now, so far it sends and receives but I can't seem to just read X bytes into a vector.
If I use the following code
vector<uint8_t> buf;
for (;;)
{
buf.resize(4);
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
}
And the packet is bigger then 4 bytes then it seems it keeps writing into those 4 bytes until the entire packet has been received, however I want it to fetch 4 bytes, then allow me to parse them, and then get the rest of the packet.
Can anyone provide me with a working example, or at least a pointer on how to make it work properly ?
Regards, Xeross
| You say that the socket has more than 4 bytes available to read, in which case your code is correctly continuously looping since an eof won't be encountered until all the data is read. It seems to me that you want to use read() rather than read_some() since the latter might return with less than the four bytes you want. From the read_some documentation.
The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.
You need to read the first 4 bytes (using read), process them (you don't need to be in a loop to do this), and then do a looping read and process the data until you get an error condition or eof.
I think you want more like that below:
vector<uint8_t> buf(4);
try
{
size_t len = read(socket, boost::asio::buffer(buf));
assert(len == 4);
// process the 4 bytes in buf
}
catch (boost::system::system_error &err)
{
// handle the error e.g by returning early
}
boost::system::error_code error;
while (!error)
{
size_t len = socket.read_some(boost::asio::buffer(buf), error);
// process len bytes
}
|
2,738,260 | 2,738,302 | False sense of security with `snprintf_s` | MSVC's "secure" sprintf funcions have a template version that 'knows' the size of the target buffer. However, this code happily paints 567890 over the stack after the end of bytes...
char bytes[5];
_snprintf_s( bytes, _TRUNCATE, "%s", "1234567890" );
Any idea what I do wrong, or is this a known bug?
(I'm working in VS2005 - didn't test in 2008 or 2010)
| It does appear to be a bug in Visual C++ 2005 (I'm having trouble getting to that link; Google also has it cached).
I was able to reproduce the problem in Visual C++ 2005. In Visual C++ 2008 and 2010, the string is correctly truncated (bytes contains 1234\0) and -1 is returned as expected.
|
2,738,435 | 2,738,576 | Using numeric_limits::max() in constant expressions | I would like to define inside a class a constant which value is the maximum possible int. Something like this:
class A
{
...
static const int ERROR_VALUE = std::numeric_limits<int>::max();
...
}
This declaration fails to compile with the following message:
numeric.cpp:8: error: 'std::numeric_limits::max()' cannot appear in a constant-expression
numeric.cpp:8: error: a function call cannot appear in a constant-expression
I understand why this doesn't work, but two things look weird to me:
It seems to me a natural decision to use the value in constant expressions. Why did the language designers decide to make max() a function thus not allowing this usage?
The spec claims in 18.2.1 that
For all members declared static const in the numeric_limits template, specializations shall define these values in such a way that they are usable as integral constant expressions.
Doesn't it mean that I should be able to use it in my scenario and doesn't it contradict the error message?
Thank you.
| While the current standard lacks support here, for integral types Boost.IntegerTraits gives you the compile time constants const_min and const_max.
The problem arises from §9.4.2/4:
If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions.
Note that it adds:
The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.
As others already mentioned numeric_limits min() and max() simply aren't integral constant expressions, i.e. compile time constants.
|
2,738,521 | 2,738,539 | Function that copies into byte vector reverses values | Hey, I've written a function to copy any variable type into a byte vector, however whenever I insert something it gets inserted in reverse.
Here's the code.
template <class Type>
void Packet::copyToByte(Type input, vector<uint8_t>&output)
{
copy((uint8_t*) &input, ((uint8_t*) &input) + sizeof(Type), back_inserter(output));
}
Now whenever I add for example a uint16_t with the value 0x2f1f it gets inserted as 1f 2f instead of the expected 2f 1f.
What am I doing wrong here ?
Regards, Xeross
| If you are on a little-endian machine (e.g., an x86), the bytes will appear reversed (i.e., the lower order bytes will appear before the higher order bytes).
If you really want to reverse the order of the bytes, you can use std::reverse.
|
2,738,669 | 2,747,440 | Getting the System tick count with basic C++? | I essentially want to reconstruct the getTickCount() windows function so I can use it in basic C++ without any non standard libraries or even the STL. (So it complies with the libraries supplied with the Android NDK)
I have looked at
clock()
localtime
time
But I'm still unsure whether it is possible to replicate the getTickCount windows function with the time library.
Can anyone point me in the right direction as to how to do this or even if its possible?
An overview of what I want to do:
I want to be able to calculate how long an application has been "doing" a certain function.
So for example I want to be able to calculate how long the application has been trying to register with a server
I am trying to port it from windows to run on the linux based Android, here is the windows code:
int TimeoutTimer::GetSpentTime() const
{
if (m_On)
{
if (m_Freq>1)
{
unsigned int now;
QueryPerformanceCounter((int*)&now);
return (int)((1000*(now-m_Start))/m_Freq);
}
else
{
return (GetTickCount()-(int)m_Start);
}
}
return -1;
}
| On Android NDK you can use the POSIX clock_gettime() call, which is part of libc. This function is where various Android timer calls end up.
For example, java.lang.System.nanoTime() is implemented with:
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
This example uses the monotonic clock, which is what you want when computing durations. Unlike the wall clock (available through gettimeofday()), it won't skip forward or backward when the device's clock is changed by the network provider.
The Linux man page for clock_gettime() describes the other clocks that may be available, such as the per-thread elapsed CPU time.
|
2,738,760 | 2,738,888 | gcc problem with explicit template instantiation? | It is my understanding that either a declaration or typedef of a specialization ought to cause a template class to be instantiated, but this does not appear to be happening with gcc. E.g. I have a template class, template class Foo {};
I write
class Foo<double>;
or
typedef Foo<double> DoubleFoo;
but after compilation the symbol table of the resulting object file does not contain the members of Foo.
If I create an instance:
Foo<double> aFoo;
then of course the symbols are all generated.
Has anyone else experienced this and/or have an explanation?
| The syntax for explicit instantiation is
template class Foo<double>;
See C++03 §14.7.2.
Hoping the functions get generated and linked, but not stripped after creating, but not using, an instance (the most minimal implicit instantiation), is quite a gamble.
|
2,738,840 | 2,738,931 | npruntime example plugin (c++) of NPAPI fails to run on mac OSX 10.5 | I have compiled Mozilla NPAPI plugin example npruntime on Mac OSX 10.5.
It give me a libnprt.dylib
I am bundling this dylib with proper plist.
On loading the plugin, NP_GetMIMEDescription() is getting called (i am logging this), but its not going inside NP_GetEntryPoints().
How a part of code is getting loaded and a part not?
Can you suggest me of any other documentation or example code?
Any light on "How to make an NPAPI plugin for Mac"?
Advance thanks
-Parimal Das
| Solving your problem with the npruntime sample is a bit hard with the details given. I suggest checking out WebKits examples from their repository. Mac-wise Mozillas samples are somewhat outdated.
To spare yourself from implementing it all, you can also take a look at:
QtBrowserPlugin
FireBreath (Cocoa support is work-in-progress though at the moment)
If you haven't found it already you might also find this NPAPI plugin introduction helpful.
|
2,738,868 | 2,738,958 | Variable Argument list with no named argument? | Is it possible to have a function with variable arguments and no named argument?
For example:
SomeLogClass("Log Message Here %d").Log(5);
SomeLogClass("Log Message Here %d").Error(5);
| Take a look at QString's arg methods. Those seem to be something you're looking for.
You can definitely roll your own, although implementation might turn out to be not really trivial, especially if you would like it to support printf format specifiers. If printf style is not necessary, chaining a replace_all kind of calls sounds doable.
|
2,738,896 | 2,739,188 | What is a truly empty std::vector in C++? | I've got a two vectors in class A that contain other class objects B and C. I know exactly how many elements these vectors are supposed to hold at maximum. In the initializer list of class A's constructor, I initialize these vectors to their max sizes (constants).
If I understand this correctly, I now have a vector of objects of class B that have been initialized using their default constructor. Right? When I wrote this code, I thought this was the only way to deal with things. However, I've since learned about std::vector.reserve() and I'd like to achieve something different.
I'd like to allocate memory for these vectors to grow as large as possible because adding to them is controlled by user-input, so I don't want frequent resizings. However, I iterate through this vector many, many times per second and I only currently work on objects I've flagged as "active". To have to check a boolean member of class B/C on every iteration is silly. I don't want these objects to even BE there for my iterators to see when I run through this list.
Is reserving the max space ahead of time and using push_back to add a new object to the vector a solution to this?
| A vector has capacity and it has size. The capacity is the number of elements for which memory has been allocated. Size is the number of elements which are actually in the vector. A vector is empty when its size is 0. So, size() returns 0 and empty() returns true. That says nothing about the capacity of the vector at that point (that would depend on things like the number of insertions and erasures that have been done to the vector since it was created). capacity() will tell you the current capacity - that is the number of elements that the vector can hold before it will have to reallocate its internal storage in order to hold more.
So, when you construct a vector, it has a certain size and a certain capacity. A default-constructed vector will have a size of zero and an implementation-defined capacity. You can insert elements into the vector freely without worrying about whether the vector is large enough - up to max_size() - max_size() being the maximum capacity/size that a vector can have on that system (typically large enough not to worry about). Each time that you insert an item into the vector, if it has sufficient capacity, then no memory-allocation is going to be allocated to the vector. However, if inserting that element would exceed the capacity of the vector, then the vector's memory is internally re-allocated so that it has enough capacity to hold the new element as well as an implementation-defined number of new elements (typically, the vector will probably double in capacity) and that element is inserted into the vector. This happens without you having to worry about increasing the vector's capacity. And it happens in constant amortized time, so you don't generally need to worry about it being a performance problem.
If you do find that you're adding to a vector often enough that many reallocations occur, and it's a performance problem, then you can call reserve() which will set the capacity to at least the given value. Typically, you'd do this when you have a very good idea of how many elements your vector is likely to hold. However, unless you know that it's going to a performance issue, then it's probably a bad idea. It's just going to complicate your code. And constant amortized time will generally be good enough to avoid performance issues.
You can also construct a vector with a given number of default-constructed elements as you mentioned, but unless you really want those elements, then that would be a bad idea. vector is supposed to make it so that you don't have to worry about reallocating the container when you insert elements into it (like you would have to with an array), and default-constructing elements in it for the purposes of allocating memory is defeating that. If you really want to do that, use reserve(). But again, don't bother with reserve() unless you're certain that it's going to improve performance. And as was pointed out in another answer, if you're inserting elements into the vector based on user input, then odds are that the time cost of the I/O will far exceed the time cost in reallocating memory for the vector on those relatively rare occasions when it runs out of capacity.
Capacity-related functions:
capacity() // Returns the number of elements that the vector can hold
reserve() // Sets the minimum capacity of the vector.
Size-related functions:
clear() // Removes all elements from the vector.
empty() // Returns true if the vector has no elements.
resize() // Changes the size of the vector.
size() // Returns the number of items in the vector.
|
2,738,967 | 2,738,999 | Vector clear vs. resize | I read on the Internet that if you are clearing a std::vector repetitively (in a tight loop), it might be better to use resize(0) instead of clear(), as it may be faster. I am not sure about this. Does anyone have a definitive answer to this?
| I assume you mean resize(0) instead of setsize, and calling that instead of clear(), and that you're talking about std::vector. IIRC a recent answer discussed this (can't find the link), and on modern STL implementations, clear() is likely identical to resize(0).
Previously clearing a vector might have freed all its memory (ie. its capacity also falls to zero), causing reallocations when you start adding elements again, in contrast to resize(0) keeping the capacity so there are fewer reallocations. However, I think in modern STL libraries there is no difference. If you're using an old STL implementation, or you're just paranoid, resize(0) might be faster.
|
2,738,985 | 2,739,016 | Using member variables inherited from a templated base class (C++) | I'm trying to use member variables of a templated base class in a derived class, as in this example:
template <class dtype>
struct A {
int x;
};
template <class dtype>
struct B : public A<dtype> {
void test() {
int id1 = this->x; // always works
int id2 = A<dtype>::x; // always works
int id3 = B::x; // always works
int id4 = x; // fails in gcc & clang, works in icc and xlc
}
};
gcc and clang are both very picky about using this variable, and require either an explicit scope or the explicit use of "this". With some other compilers (xlc and icc), things work as I would expect. Is this a case of xlc and icc allowing code that's not standard, or a bug in gcc and clang?
| You are probably compiling in non-strict mode in icc. Anyway, since x is unqualified, it shall not be looked up in any base classes that depend on the template parameters. So in your code, there is no place where x is found, and your code is invalid.
The other names are looked up using another form of lookup (class member access lookup, and qualified lookup). Both of those forms will look into dependent base classes if they can (i.e if they are dependent, and are thus looked up when instantiating the template when dtype is known - all your other names are dependent on template parameters).
Even GCC in their latest versions don't implement that correctly, and some dependent names still resolve against dependent bases during unqualified lookup.
|
2,739,049 | 2,739,156 | c++ inline functions | i'm confused about how to do inline functions in C++....
lets say this function. how would it be turned to an inline function
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
| As others have said, you can use the inline keyword to tell the compiler you want your function inlined. But the inline keyword is just a compiler hint. The compiler can and will chose to ignore your request if it wants or needs to.
An alternative is to make your function a function template, which will often be blown out inline:
template<class Val>
Val maximum( Val x, Val y, Val z )
{
Val max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
|
2,739,146 | 2,739,194 | C++ OOP: Which functions to put into the class? | Assume I have a class a:
class a
{
public:
void load_data( );
private:
void check_data( );
void work_data( );
void analyze_data( );
}
Those functions all do something with the class or one of its members.
However this function:
bool validate_something( myType myData )
{
if ( myData.blah > 0 && myData.blah < 100 )
{
return true;
}
return false;
}
Is related to the class and will only be called by it, so it won't be needed anywhere else
Doesn't do anything with the class or its members - just a small "utility" function
Where to put validate_something? Inside or outside the class?
| Make it a private static class member. I used to tend to make these non-class members and put them in an nameless namespace in the implementation file, but it seems that they almost always do end up needing to be class members (or need to be moved elsewhere - perhaps to a validation library, in your example), as the code changes, so now I almost always make them static members.
Please notice the use of "almost" as a qualifier throughout this answer :-)
|
2,739,191 | 2,739,314 | implement SIMD in C++ | I'm working on a bit of code and I'm trying to optimize it as much as possible, basically get it running under a certain time limit.
The following makes the call...
static affinity_partitioner ap;
parallel_for(blocked_range<size_t>(0, T), LoopBody(score), ap);
... and the following is what is executed.
void operator()(const blocked_range<size_t> &r) const {
int temp;
int i;
int j;
size_t k;
size_t begin = r.begin();
size_t end = r.end();
for(k = begin; k != end; ++k) { // for each trainee
temp = 0;
for(i = 0; i < N; ++i) { // for each sample
int trr = trRating[k][i];
int ei = E[i];
for(j = 0; j < ei; ++j) { // for each expert
temp += delta(i, trr, exRating[j][i]);
}
}
myscore[k] = temp;
}
}
I'm using Intel's TBB to optimize this. But I've also been reading about SIMD and SSE2 and things along that nature. So my question is, how do I store the variables (i,j,k) in registers so that they can be accessed faster by the CPU? I think the answer has to do with implementing SSE2 or some variation of it, but I have no idea how to do that. Any ideas?
Edit: This will be run on a Linux box, but using Intel's compiler I believe. If it helps, I have to run the following commands before I do anything to make sure the compiler works... source /opt/intel/Compiler/11.1/064/bin/intel64/iccvars_intel64.csh; source /opt/intel/tbb/2.2/bin/intel64/tbbvars.csh ... and then to compile I do: icc -ltbb test.cxx -o test
If there's no easy way to implement SSE2, any advice on how to further optimize the code?
Thanks,
Hristo
| Your question represents some confusion on what is going on. The i,j,k variables are almost certainly held in registers already, assuming you are compiling with optimizations on (which you should do - add "-O2" to your icc invocation).
You can use an asm block, but an easier method considering you're already using ICC is to use the SSE intrinsics. Intel's documentation for them is here - http://www.intel.com/software/products/compilers/clin/docs/ug_cpp/comm1019.htm
It looks like you can SIMD-ize the top-level loop, though it's going to depend greatly on what your delta function is.
|
2,739,236 | 2,739,283 | C++ from SpeakHere in iPhone app | I've made a template app where I've grabbed the recording part of the SpeakHere example and removed the file handling part, but I'm struggeling to get the C++ part of the app working right. As soon as it enters the C++ class, it gets syntax errors. If I don't import the header files from C++ (and then of course don't use the code) into my Objective C classes, all works fine. I cannot see the difference between how I'm doing it and the example is doing it. Can you see the difference?
I've posted the entire code here: http://github.com/niklassaers/testFFT
The build errors I get are:
testFFT/CAStreamBasicDescription.h:91:0 testFFT/CAStreamBasicDescription.h:91: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'CAStreamBasicDescription'
testFFT/CAStreamBasicDescription.h:298:0 testFFT/CAStreamBasicDescription.h:298: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
testFFT/CAStreamBasicDescription.h:299:0 testFFT/CAStreamBasicDescription.h:299: error: expected '=', ',', ';', 'asm' or '__attribute__' before '==' token
testFFT/CAStreamBasicDescription.h:301:0 testFFT/CAStreamBasicDescription.h:301: error: expected '=', ',', ';', 'asm' or '__attribute__' before '!=' token
testFFT/CAStreamBasicDescription.h:302:0 testFFT/CAStreamBasicDescription.h:302: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<=' token
testFFT/CAStreamBasicDescription.h:303:0 testFFT/CAStreamBasicDescription.h:303: error: expected '=', ',', ';', 'asm' or '__attribute__' before '>=' token
testFFT/CAStreamBasicDescription.h:304:0 testFFT/CAStreamBasicDescription.h:304: error: expected '=', ',', ';', 'asm' or '__attribute__' before '>' token
testFFT/CAStreamBasicDescription.h:307:0 testFFT/CAStreamBasicDescription.h:307: error: expected ';', ',' or ')' before '&' token
testFFT/CAXException.h:65:0 testFFT/CAXException.h:65: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'CAX4CCString'
testFFT/CAXException.h:87:0 testFFT/CAXException.h:87: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'CAXException'
testFFT/AQRecorder.h:59:0 testFFT/AQRecorder.h:59: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'AQRecorder'
testFFT/RecorderLink.h:57:0 testFFT/RecorderLink.h:57: error: expected specifier-qualifier-list before 'AQRecorder'
testFFT/RecorderLink.h:62:0 testFFT/RecorderLink.h:62: error: expected specifier-qualifier-list before 'AQRecorder'
Any idea what's going on here?
Cheers
Nik
| You are indirectly including the C++ headers into plain Objective-C code (.m) - that won't work, you have to use Objective-C++ (.mm) all the way or encapsulate the C++ classes in Objective-C classes using opaque pointers.
One problematic chain:
Classes/MainViewController.m, plain Objective-C, includes
RecorderLink.h, includes
AQRecorder.h, which is C++
|
2,739,251 | 2,739,264 | Reversing a for loop... want to print numbers in reverse | How would I change this loop to print prime number in reverse... starting from the biggest one first
int main(){
bool prime;
for( int i=3; i<=10000; i++){
prime = true;
for(int n=2; n<=i-1; n++){
if( i%n == 0){
prime = false;
}
}
if(prime){
cout << i << " ";
}
}
return 0;
}
| You can reverse the for loop as follows:
for( int i=10000; i>=3; i--) {
That being said - you can also simplify this. You only need to check until you reach the square root of the number. Also make sure that, when you find that a number isn't prime, you break out immediately:
int main() {
bool prime;
for( int i=10000; i>=3; i--) {
prime = true;
int max = sqrt(i)+1; // Don't check beyond this...
for(int n=2; n<=max; n++)
{
if( i%n == 0){
prime = false;
break; // This prevents you from continually checking!
}
}
if(prime){
cout << i << " ";
}
}
return 0;
}
|
2,739,354 | 2,743,627 | segfault on vector<struct> | I created a struct to hold some data and then declared a vector to hold that struct.
But when I do a push_back I get damn segfault and I have no idea why!
My struct is defines as:
typedef struct Group
{
int codigo;
string name;
int deleted;
int printers;
int subpage;
/*included this when it started segfaulting*/
Group(){ name.reserve(MAX_PRODUCT_LONG_NAME); }
~Group(){ name.clear(); }
Group(const Group &b)
{
codigo = b.codigo;
name = b.name;
deleted = b.deleted;
printers = b.printers;
subpage = b.subpage;
}
/*end of new stuff*/
};
Originally, the struct didn't have the copy, constructor or destructor. I added them latter when I read this post below.
Seg fault after is item pushed onto STL container
but the end result is the same.
There is one this that is bothering me as hell! When I first push some data into the vector, everything goes fine. Later on in the code when I try to push some more data into the vector, my app just segfaults!
The vector is declared
vector<Group> Groups
and is a global variable to the file where I am using it. No externs anywhere else, etc...
I can trace the error to:
_M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage- this->_M_impl._M_start);
in vector.tcc when I finish adding/copying the last element to the vector....
As far as I can tell. I shouldn't be needing anything to do with a copy constructor as a shallow copy should be enough for this. I'm not even allocating any space (but I did a reserve for the string to try out).
I have no idea what the problem is!
I'm running this code on OpenSuse 10.2 with gcc 4.1.2
I'm not really to eager to upgrade gcc because of backward compatibility issues...
This code worked "perfectly" on my windows machine. I compiled it with gcc 3.4.5 mingw without any problems...
help!
--- ... ---
:::EDIT:::
I push data
Group tmp_grp;
(...)
tmp_grp.name = "Nova ";
tmp_grp.codigo=GetGroupnextcode();
tmp_grp.deleted=0;
tmp_grp.printers=0;
tmp_grp.subpage=0;
Groups.push_back(tmp_grp);
| Well...
valgrind to the rescue! What called out to me in the valgrind log was this piece.
Invalid write of size 4
==4639== at 0x805BDC0: ChangeGroups() (articles.cpp:405)
==4639== by 0x80AC008: GeneralConfigChange() (config.cpp:4474)
==4639== by 0x80EE28C: teste() (main.cpp:2259)
==4639== by 0x80EEBB3: main (main.cpp:2516)
At this point in the file I was doing this
Groups[oldselected].subpage=SL.selected_code();
and what if oldselected was outside the bounds of the vector?
In this case what was happening was that oldselected could be -1... and although this wasn't crashing at this point, it was writing something somewhere else...
I should probably start using the at() operator and check for the exception or just check if "oldselected" is >0 and < Groups.size() [preferred solution].
So kudos to John and Josh for reminding me of valgrind.
I've used it before, but never needed to do anything t significant with it (fortunately :D).
It's interesting that in windows I don't get this segfault. The problem was the same... I guess that it has something to do with memory management and the compiler... it really eludes me.
Thanks everyone for the input ;)
Cheers
|
2,739,464 | 2,739,472 | Segmentation fault C++ in recursive function | Why do I get a segmentation fault in my recursive function. It happens every time i call it when a value greater than 4 as a parameter
#include <iostream>
#include <limits>
using namespace std;
int printSeries(int n){
if(n==1){
return 1;
}
else if( n==2){
return 2;
}
else if( n==3){
return 3;
}
else if( n==4){
return printSeries(1) + printSeries(2) + printSeries(3);
}
else{
return printSeries(n-3) + printSeries((n-2) + printSeries(n-1));
}
}
int main(){
//double infinity = numeric_limits<double>::max();
for(int i=1; i<=10; i++){
cout << printSeries(i) << endl;
}
return 0;
}
This works fine, but i'm not sure that returns the correct result:
return printSeries(n-3) + printSeries(n-2) + printSeries(n-1);
| return printSeries(n-3) + printSeries( (n-2) + printSeries(n-1) );
// ^^^^^^^^^^^^^^^^^^^^^^^^
Incorrect nesting of parenthesis causes infinite recursion, which leads to stack overflow (segfault).
Consider when n = 4,
f(4) = 1 + f(2 + f(3))
= 1 + f(2 + 3)
= 1 + f(5)
= 1 + [ f(2) + f(3 + f(4)) ]
= ...
|
2,739,572 | 2,739,820 | C++ UTF-8 output with ICU | I'm struggling to get started with the C++ ICU library. I have tried to get the simplest example to work, but even that has failed. I would just like to output a UTF-8 string and then go from there.
Here is what I have:
#include <unicode/unistr.h>
#include <unicode/ustream.h>
#include <iostream>
int main()
{
UnicodeString s = UNICODE_STRING_SIMPLE("привет");
std::cout << s << std::endl;
return 0;
}
Here is the output:
$ g++ -I/sw/include -licucore -Wall -Werror -o icu_test main.cpp
$ ./icu_test
пÑивеÑ
My terminal and font support UTF-8 and I regularly use the terminal with UTF-8. My source code is in UTF-8.
I think that perhaps I somehow need to set the output stream to UTF-8 because ICU stores strings as UTF-16, but I'm really not sure and I would have thought that the operators provided by ustream.h would do that anyway.
Any help would be appreciated, thank you.
| Your program will work if you just change the initializer to:
UnicodeString s("привет");
The macro you were using is only for strings that contain "invariant characters", i.e., only latin letters, digits, and some punctuation.
As was said before, input/output codepages are tricky. You said:
My terminal and font support UTF-8 and
I regularly use the terminal with
UTF-8. My source code is in UTF-8.
That may be true, but ICU doesn't know that's true. The process codepage might be different (let's say iso-8859-1), and the output codepage may be different (let's say shift-jis). Then, the program wouldn't work. But, the invariant characters using the API UNICODE_STRING_SIMPLE would still work.
Hope this helps.
srl, icu dev
|
2,739,773 | 2,739,789 | error LNK2001: unresolved external symbol _D3DX10CreateTextureFromFileW@24 | I am trying to call a direct X funciton but I get the following error
error LNK2001: unresolved external symbol _D3DX10CreateTextureFromFileW@24
I understand that possibly there maybe a linker issue. But I am not sure where. I inluded both d3dx10.h and the d3d10.h. I also included the d3d10.lib file. Plus, the intellisense picks up on the method as well. below is my code. The method is D3DX10CreateTextureFromFile
bool MyGame::InitDirect3D()
{
if(!DX3dApp::InitDirect3D())
{
return false;
}
ID3D10Resource* pD3D10Resource = NULL;
HRESULT hr = D3DX10CreateTextureFromFile(mpD3DDevice,
L"C:\\delete.jpg",
NULL,
NULL,
&pD3D10Resource,
NULL);
if(FAILED(hr))
{
return false;
}
return true;
}
| Is the appropriate DirectX library (or libraries) configured inthe project or makefile (or whatever build system is being used)?
For this particular function , it's D3DX10.lib.
|
2,739,905 | 2,746,909 | Better way to write an object generator for an RAII template class? | I would like to write an object generator for a templated RAII class -- basically a function template to construct an object using type deduction of parameters so the types don't have to be specified explicitly.
The problem I foresee is that the helper function that takes care of type deduction for me is going to return the object by value, which will (**) result in a premature call to the RAII destructor when the copy is made. Perhaps C++0x move semantics could help but that's not an option for me.
Anyone seen this problem before and have a good solution?
This is what I have:
template<typename T, typename U, typename V>
class FooAdder
{
private:
typedef OtherThing<T, U, V> Thing;
Thing &thing_;
int a_;
// many other members
public:
FooAdder(Thing &thing, int a);
~FooAdder();
FooAdder &foo(T t, U u);
FooAdder &bar(V v);
};
The gist is that OtherThing has a horrible interface, and FooAdder is supposed to make it easier to use. The intended use is roughly like this:
FooAdder(myThing, 2)
.foo(3, 4)
.foo(5, 6)
.bar(7)
.foo(8, 9);
The FooAdder constructor initializes some internal data structures. The foo and bar methods populate those data structures. The ~FooAdder dtor wraps things up and calls a method on thing_, taking care of all the nastiness.
That would work fine if FooAdder wasn't a template. But since it is, I would need to put the types in, more like this:
FooAdder<Abc, Def, Ghi>(myThing, 2) ...
That's annoying, because the types can be inferred based on myThing. So I would prefer to create a templated object generator, similar to std::make_pair, that will do the type deduction for me. Something like this:
template<typename T, typename U, typename V>
FooAdder<T, U, V>
AddFoo(OtherThing<T, U, V> &thing, int a)
{
return FooAdder<T, U, V>(thing, a);
}
That seems problematic: because it returns by value, the stack temporary object will (**) be destructed, which will cause the RAII dtor to run prematurely.
** - if RVO is not implemented. Most compilers do, but it is not required, and can be turned off in gcc using -fno-elide-constructors.
| It seems pretty easy. The questioner himself proposed a nice solution, but he can just use a usual copy constructor with a const-reference parameter. Here is what i proposed in comments:
template<typename T, typename U, typename V>
class FooAdder
{
private:
mutable bool dismiss;
typedef OtherThing<T, U, V> Thing;
Thing &thing_;
int a_;
// many other members
public:
FooAdder(Thing &thing, int a);
FooAdder(FooAdder const&o);
~FooAdder();
FooAdder &foo(T t, U u);
FooAdder &bar(V v);
};
FooAdder::FooAdder(Thing &thing, int a)
:thing_(thing), a_(a), dismiss(false)
{ }
FooAdder::FooAdder(FooAdder const& o)
:dismiss(false), thing_(o.thing_), a_(o.a_)
{ o.dismiss = true; }
FooAdder::~FooAdder() {
if(!dismiss) { /* wrap up and call */ }
}
It Just Works.
template<typename T, typename U, typename V>
FooAdder<T, U, V>
AddFoo(OtherThing<T, U, V> &thing, int a)
{
return FooAdder<T, U, V>(thing, a);
}
int main() {
AddFoo(myThing, 2)
.foo(3, 4)
.foo(5, 6)
.bar(7)
.foo(8, 9);
}
No need for complex templates or smart pointers.
|
2,740,002 | 2,740,101 | How does server management software work? | How does server management software work?
I was reading about this software, and I found that they can monitor CPU speed/temperature.
How can one do this in C++?
| Traditionally, motherboards come with device drivers that provide functionality to query the temp sensors and other motherboard parameters. These drivers can be accessed by other programs. For example, vendors like ASUS have rich GUIs that can present this info (by querying the driver) or background programs that can give you an alert when this crosses a threshold (by occasionally querying the driver). You could write something similar yourself, including server management software.
The main problem is that in a heterogeneous environment you could end up with different motherboards and thus different drivers. Some operating systems provide an abstraction layer for this functionality, so they can implement things like power management. I would also assume that modern motherboards have a more unified way of accessing this sort of information.
This is really not about C/C++, except that it is generally easier to access drivers from C/C++ than it is from languages like Java, C# or Python. In these cases, it is sometimes worth checking if there is a command-line based program on the motherboard CD that queries the driver, and then shell out, execute this program, and parse the returned string.
|
2,740,020 | 2,740,178 | C++ STL: Array vs Vector: Raw element accessing performance | I'm building an interpreter and as I'm aiming for raw speed this time, every clock cycle matters for me in this (raw) case.
Do you have any experience or information what of the both is faster: Vector or Array?
All what matters is the speed I can access an element (opcode receiving), I don't care about inserting, allocation, sorting, etc.
I'm going to lean myself out of the window now and say:
Arrays are at least a bit faster than vectors in terms of accessing an element i.
It seems really logical for me. With vectors you have all those security and controlling overhead which doesn't exist for arrays.
(Why) Am I wrong?
No, I can't ignore the performance difference - even if it is so small - I have already optimized and minimized every other part of the VM which executes the opcodes :)
| Element access time in a typical implementation of a std::vector is the same as element access time in an ordinary array available through a pointer object (i.e. a run-time pointer value)
std::vector<int> v;
int *pa;
...
v[i];
pa[i];
// Both have the same access time
However, the access time to an element of an array available as an array object is better than both of the above accesses (equivalent to access through a compile-time pointer value)
int a[100];
...
a[i];
// Faster than both of the above
For example, a typical read access to an int array available through a run-time pointer value will look as follows in the compiled code on x86 platform
// pa[i]
mov ecx, pa // read pointer value from memory
mov eax, i
mov <result>, dword ptr [ecx + eax * 4]
Access to vector element will look pretty much the same.
A typical access to a local int array available as an array object will look as follows
// a[i]
mov eax, i
mov <result>, dword ptr [esp + <offset constant> + eax * 4]
A typical access to a global int array available as an array object will look as follows
// a[i]
mov eax, i
mov <result>, dword ptr [<absolute address constant> + eax * 4]
The difference in performance arises from that extra mov instruction in the first variant, which has to make an extra memory access.
However, the difference is negligible. And it is easily optimized to the point of being exactly the same in multiple-access context (by loading the target address in a register).
So the statement about "arrays being a bit faster" is correct in narrow case when the array is accessible directly through the array object, not through a pointer object. But the practical value of that difference is virtually nothing.
|
2,740,029 | 2,740,046 | Reading data from a socket | I am having issues reading data from a socket. Supposedly, there is a server socket that is waiting for clients to connect. When I write a client to connect() to the server socket/port, it appears that I am connected. But when I try to read() data that the server is supposedly writing on the socket, the read() function hangs until the server app is stopped.
Why would a read() call ever hang if the socket is connected? I believe that I am not ever really connected to the socket/port but I can't prove it, b/c the connect() call did not return an error. The read() call is not returning an error either, it is just never returning at all.
| Read is blocking until is receives some I/O (or an error).
|
2,740,164 | 2,740,236 | How to Embed/Link binary data into a Windows module | So I have a Visual Studio 2008 project which has a large amount of binary data that it is currently referencing. I would like to package the binary data much like you can do with C# by adding it as a "resource" and compiling it as a DLL.
Lets say all my data has an extension of ".data" and is currently being read from the visual studio project.
Is there a way that you can compile or link the data into the .dll which it is calling?
I've looked at some of the google link for this and so far I haven't come up with anything - the only possible solution I've come up with is to use something like ResGen to create a .resources file and then link it using AssemblyLinker with /Embed or /Link flags. I dont think it'd work properly though because I dont have text files to create the .resources files, but rather binary files themselves.
Any advice?
|
Right click the resource script (.rc file)
Choose Import
http://msdn.microsoft.com/en-us/library/saced6x2.aspx
You can embed any "custom" file you want, as well as things like .bmps and stuff VisualStudio "knows" how to edit. Then you can access them with your framework's resource functions like FindResource LoadResource etc...
If you don't have a resource script.
Click Project
Add New Item
Resource Script
http://msdn.microsoft.com/en-us/library/sxdy04be(v=VS.71).aspx
|
2,740,431 | 2,740,970 | How can I store an inventory-like list of numbers? | I've got a list of number that I need to keep track of. The numbers are loosely related, but represent distinctly different items. I'd like to keep a list of the numbers but be able to refer to them by name so that I can call them and use them where needed easily. Kind of like an inventory listing, where the numbers all refer to a part ID and I'd like to call them idPart1, idPart2, idPart3 so their purpose is easily identifiable when they are used.
What would be the best way to do this?
1)Define a structure. Say, Inventory. A number of int members will be included, part1, part2 etc. To use, an instance of the structure will be created, values assigned to the members, and the numbers will be used by saying struct.member as needed.
2)Define an enumeration. Use part1, part2 as the enum literals. Store the actual values in a vector or list, each one at the index corresponding to the value of the number's name within the enum. Use the enum literals to retrieve the values, list[enumLit].
3)Something completely different
There's nothing else I need to do with the numbers - just look them up every once in a while. Since there's no processing, I kind of think a new class for them is overkill, but I'm willing to be convinced otherwise.
Any suggestions?
| Let me try to rephrase what you're trying to do here. You want developers who use your code to be able to refer to a pre-defined set of numeric values:
using intuitive names
that will be validated at compile time
and that the IDE will recognize for the sake of code completion.
If the values will not change at run-time, and they are integer values, you can use an enum as Mark Ransom showed.
If the values will not change at run-time, and they are non-integer values, you can use either #define or const variables:
#define PART1 1.3
#define PART2 "1233-456"
or
namespace PartNumbers
{
const double Part1 = 1.3;
const char* Part2 = "123-456"
}
If the values may change at run-time, you can use either of the two options you identified. Both of these options have the drawback of requiring an object to be instantiated which holds the current part number values. The other options are simpler to implement and don't require any run-time lookup. Everything is resolved at compile time.
All of these options require users of your code to recompile if they are to access new part types. Your first option may require existing code to be recompiled when new part types are added, even if the existing code doesn't access them; it's more prone to memory layout changes.
|
2,740,573 | 2,740,976 | How to share classes between DLLs | I have an unmanaged Win32 C++ application that uses multiple C++ DLLs. The DLLs each need to use class Foo - definition and implementation.
Where do Foo.h and Foo.cpp live so that the DLLs link and don't end up duplicating code in memory?
Is this a reasonable thing to do?
[Edit]
There is a lot of good info in all the answers and comments below - not just the one I've marked as the answer. Thanks for everyone's input.
| Providing functionality in the form of classes via a DLL is itself fine. You need to be careful that you seperate the interrface from the implementation, however. How careful depends on how your DLL will be used. For toy projects or utilities that remain internal, you may not need to even think about it. For DLLs that will be used by multiple clients under who-knows-which compiler, you need to be very careful.
Consider:
class MyGizmo
{
public:
std::string get_name() const;
private:
std::string name_;
};
If MyGizmo is going to be used by 3rd parties, this class will cause you no end of headaches. Obviously, the private member variables are a problem, but the return type for get_name() is just as much of a problem. The reason is because std::string's implementation details are part of it's definition. The Standard dictates a minimum functionality set for std::string, but compiler writers are free to implement that however they choose. One might have a function named realloc() to handle the internal reallocation, while another may have a function named buy_node() or something. Same is true with data members. One implementation may use 3 size_t's and a char*, while another might use std::vector. The point is your compiler might think std::string is n bytes and has such-and-so members, while another compiler (or even another patch level of the same compiler) might think it looks totally different.
One solution to this is to use interfaces. In your DLL's public header, you declare an abstract class representing the useful facilities your DLL provides, and a means to create the class, such as:
DLL.H :
class MyGizmo
{
public:
static MyGizmo* Create();
virtual void get_name(char* buffer_alloc_by_caller, size_t size_of_buffer) const = 0;
virtual ~MyGizmo();
private:
MyGizmo(); // nobody can create this except myself
};
...and then in your DLL's internals, you define a class that actually implements MyGizmo:
mygizmo.cpp :
class MyConcreteGizmo : public MyGizmo
{
public:
void get_name(char* buf, size_t sz) const { /*...*/ }
~MyGizmo() { /*...*/ }
private:
std::string name_;
};
MyGizmo* MyGizmo::Create()
{
return new MyConcreteGizmo;
}
This might seem like a pain and, well, it is. If your DLL is going to be only used internally by only one compiler, there may be no reason to go to the trouble. But if your DLL is going to be used my multiple compilers internally, or by external clients, doing this saves major headaches down the road.
|
2,740,712 | 2,740,728 | How safe and reliable are C++ String Literals? | So, I'm wanting to get a better grasp on how string literals in C++ work. I'm mostly concerned with situations where you're assigning the address of a string literal to a pointer, and passing it around. For example:
char* advice = "Don't stick your hands in the toaster.";
Now lets say I just pass this string around by copying pointers for the duration of the program. Sure, it's probably not a good idea, but I'm curious what would actually be going on behind the scenes.
For another example, let's say we make a function that returns a string literal:
char* foo()
{
// function does does stuff
return "Yikes!"; // somebody's feeble attempt at an error message
}
Now lets say this function is called very often, and the string literal is only used about half the time it's called:
// situation #1: it's just randomly called without heed to the return value
foo();
// situation #2: the returned string is kept and used for who knows how long
char* retVal = foo();
In the first situation, what's actually happening? Is the string just created but not used, and never deallocated?
In the second situation, is the string going to be maintained as long as the user finds need for it? What happens when it isn't needed anymore... will that memory be freed up then (assuming nothing points to that space anymore)?
Don't get me wrong, I'm not planning on using string literals like this. I'm planning on using a container to keep my strings in check (probably std::string). I'm mostly just wanting to know if these situations could cause problems either for memory management or corrupted data.
| String-literals have the type const char[N] (where N is the length + 1) and are statically allocated. You need not worry about memory issues; if a string is used in your program it is all handled for you, and resides somewhere in program memory (usually read-only).
That is, these are "the same":
static const char str[] = "a string";
"a string"
When you point to a string literal, you are pointing to the first character at the array. In fact, because the type is const char[], it's only safe to point to it via const char*. The conversion from string literal to char* is deprecated, and unsafe.
// the "same"
static const char str[] = "a string";
const char* strPtr = str; // decays
const char* s1 = "a string";
char* s2 = "a string"; // allowed, implicit const_cast
*s1 = 'A'; // not allowed, it's const
*s2 = 'B'; // allowed, it's not const (but leads to undefined behavior)
|
2,740,715 | 2,740,721 | what is the reason for the difference between setprecision (12) and setprecision (012) for example,in c++? | In c++ when you write setprecision (12) for example, 12 is in the base of 10 but when you write it like setprecision (012) it is an octal number,why?
| Because constants with leading zeros (other than leading 0x) are always octal:
An octal integer literal (base eight)
begins with the digit 0 and consists
of a sequence of octal digits.
C++ draft standard (n1905) §2.13.1
It has nothing at all to do with setprecision.
|
2,740,822 | 2,836,393 | Is it possible to use boost::bind to effectively concatenate functions? | Assume that I have a boost::function of with an arbitrary signature called type CallbackType.
Is it possible to use boost::bind to compose a function that takes the same arguments as the CallbackType but calls the two functors in succession?
I'm open to any potential solution, but here's a...
...Hypothetical example using some magic template:
Template<typename CallbackType>
class MyClass
{
public:
CallbackType doBoth;
MyClass( CallbackType callback )
{
doBoth = bind( magic<CallbackType>,
protect( bind(&MyClass::alert, this) ),
protect( callback ) );
}
void alert()
{
cout << "It has been called\n";
}
};
void doIt( int a, int b, int c)
{
cout << "Doing it!" << a << b << c << "\n";
}
int main()
{
typedef boost::function<void (int, int, int)> CallbackType;
MyClass<CallbackType> object( boost::bind(doIt) );
object.doBoth();
return 0;
}
| Boost already provides a way to create a sequence of bound functions. Use Lambda's comma operator.
using namespace boost::lambda;
MyClass mc;
CallbackType object = (bind(&MyClass::alert, mc), bind(doIt, _1, _2, _3));
object(1, 2, 3);
That will create a new functor, object. When you invoke that functor with three arguments, it will in turn call mc.alert() before passing those arguments to doIt. The parentheses are important.
For my example above to work, you'd need alert to be a const function. If it needs to be non-const, then either pass a pointer to mc, or wrap it with boost::ref(mc). And you'll need to use Boost.Lambda's bind rather than Boost.Bind's; the latter isn't compatible with Lambda's function-combining operators (comma, in particular).
|
2,740,939 | 2,740,955 | Malloc function in C++ | I am transitioning to C++ from C. In C++, is there any use for the malloc function? Or can I just declare it with the "new" keyword. For example:
class Node
{
...
}
...
Node *node1 = malloc(sizeof(Node)); //malloc
Node *node2 = new Node; //new
Which one should I use?
| Use new. You shouldn't need to use malloc in a C++ program, unless it is interacting with some C code or you have some reason to manage memory in a special way.
Your example of node = malloc(sizeof(Node)) is a bad idea, because the constructor of Node (if any exists) would not be called, and a subsequent delete node; would have undefined results.
If you need a buffer of bytes, rather than an object, you'll generally want to do something like this:
char *buffer = new char[1024];
or, preferably, something like this:
std::vector<char> buffer(1024);
Note that for the second example (using std::vector<>), there is no need to delete the object; its memory will automatically be freed when it goes out of scope. You should strive to avoid both new and malloc in C++ programs, instead using objects that automatically manage their own memory.
|
2,741,059 | 2,741,068 | Are Bitsets actually Bools? | In C++, are bitsets actually a set of bools? Doesn't this defeat the purpose of using a BitSet because bools are 32 bits (I think...)?
| They represent a collection of bool's, but those values are really stored as bits in an unsigned long.
The size of a bool is not necessary any number of bits, neither is an unsigned long. (Though the minimum number of bits for any data type is 8, and for an unsigned long it must be at least 32.)
|
2,741,370 | 2,741,392 | C++ Boost bind value type | I look in documentation and source code but cannot figure out how to get return value type of boost bind functor.
I am trying to accomplish following:
35 template<typename T,size_t N, class F>
36 boost::array<typename F::value_type, N> make_array(T (&input)[N], F unary) {
37 boost::array<typename F::value_type, N> array;
38 std::transform(input, input + N, array.begin(), unary);
39 return array;
40 }
where F can be bind functor. the above does not work because functor does not have value_type. for that matter, is there standard interface for unary/binary functor as far as return value.
solution: it should be result_type. also equivalent defined are argument_type and first/second_argument_type for binary functions
Thanks
| Doh. nevermind, it's result_type rather than value_type. should i delete this question?
|
2,741,422 | 2,741,468 | How can I avoid explicitly declaring directory paths in C or C++ #include directives? | I am making a simulator and have written lots of files and headers. The problem is whenever I include a file I give the relative path of the particular file. For example a typical code in my application would begin like
#ifndef AI_H
#define AI_H
#include <cstdlib>
#include "../world/world.h"
#include "pathPlan.h"
#include "skills/tryskill.h"
#include "../info/condition.h"
#include "dataStructures/destination.h"
#include "../params/gamePlay.h"
#include "../modules/controlModule.h"
class ai
{
public:
etc etc
I want to avoid using the relative paths. For example I want to directly include "tryskill.h" and "destination.h" without giving the absolute paths. That way I wont need to bother if I change the location of any particular file. I am using Ubuntu 9.10. Any help would be highly appreciated.
| Really it all depends on your include path, different compilers might call it different things but in gcc
-Idir Append directory dir to the list of directories searched for include files.
So in your example you would specify ../world etc... in the list of directories in -I
|
2,741,522 | 2,741,541 | How do you mentally handle going from writing managed to non-managed code? | ~80% of the code I write is in C#. The other ~20% is in C++. Whenever I have to switch from C# to C++, it takes me quite a while to mentally "shift gears" to thinking in C++. I make simple mistakes using pointers and memory allocation that I would not have made when I was in university. After the adjustment period, I am fine and writing in native code comes naturally.
Is this normal? Does anyone else experience something similar and if so, what do you do to cut down on the time this wastes?
Edit: I'm not saying that I cannot work with memory allocation and pointers. I comfortably use them often in my C++ code. Just not immediately after working in C# for long periods of time.
| I have the same problem. I use completely different color schemes for Visual Studio (dark-on-light for C++; light-on-dark for C# and VB).
Seems to help my brain ease the switch.
|
2,741,744 | 2,743,535 | qt drop event get widget | I'm trying to, inside a dropevent method, find out which widget was just dropped. I tried looking at the docs, but they only have commands for images and text. How do I access both the item just dropped and which widget it was dropped on?(this is drag and drop inside of a QTreeWidget)
| By default, Qt is limited to darg & drop text and images but this behaviour can be extended by adding new MIME Type.
You can find an interesting example of drag & drop using alternate data type at http://doc.trolltech.com/4.6/draganddrop-fridgemagnets.html. This example can be extended to support drag & drop of widgets.
You can find the QModelIndex of the item receiving the drop by giving the QDropEvent::pos() parameter to the QAbstractItemView::indexAt() method of the QTreeView. This gives you the opportunity to find the actual widget if that is what you want.
|
2,741,787 | 2,741,810 | Warning: cast increases required alignment | I'm recently working on this platform for which a legacy codebase issues a large number of "cast increases required alignment to N" warnings, where N is the size of the target of the cast.
struct Message
{
int32_t id;
int32_t type;
int8_t data[16];
};
int32_t GetMessageInt(const Message& m)
{
return *reinterpret_cast<int32_t*>(&data[0]);
}
Hopefully it's obvious that a "real" implementation would be a bit more complex, but the basic point is that I've got data coming from somewhere, I know that it's aligned (because I need the id and type to be aligned), and yet I get the message that the cast is increasing the alignment, in the example case, to 4.
Now I know that I can suppress the warning with an argument to the compiler, and I know that I can cast the bit inside the parentheses to void* first, but I don't really want to go through every bit of code that needs this sort of manipulation (there's a lot because we load a lot of data off of disk, and that data comes in as char buffers so that we can easily pointer-advance), but can anyone give me any other thoughts on this problem? I mean, to me it seems like such an important and common option that you wouldn't want to warn, and if there is actually the possibility of doing it wrong then suppressing the warning isn't going to help. Finally, can't the compiler know as I do how the object in question is actually aligned in the structure, so it should be able to not worry about the alignment on that particular object unless it got bumped a byte or two?
| One possible alternative might be:
int32_t GetMessageInt(const Message& m)
{
int32_t value;
memcpy(&value, &(data[0]), sizeof(int32_t));
return value;
}
For x86 architecture, the alignment isn't going to matter that much, it's more a performance issue that isn't really relevant for the code you have provided. For other architectures (eg MIPS) misaligned accesses cause CPU exceptions.
OK, here's another alternative:
struct Message
{
int32_t id;
int32_t type;
union
{
int8_t data[16];
int32_t data_as_int32[16 * sizeof(int8_t) / sizeof(int32_t)];
// Others as required
};
};
int32_t GetMessageInt(const Message& m)
{
return m.data_as_int32[0];
}
Here's variation on the above that includes the suggestions from cpstubing06:
template <size_t N>
struct Message
{
int32_t id;
int32_t type;
union
{
int8_t data[N];
int32_t data_as_int32[N * sizeof(int8_t) / sizeof(int32_t)];
// Others as required
};
static_assert((N * sizeof(int8_t) % sizeof(int32_t)) == 0,
"N is not a multiple of sizeof(int32_t)");
};
int32_t GetMessageInt(const Message<16>& m)
{
return m.data_as_int32[0];
}
// Runtime size checks
template <size_t N>
void CheckSize()
{
assert(sizeof(Message<N>) == N * sizeof(int8_t) + 2 * sizeof(int32_t));
}
void CheckSizes()
{
CheckSize<8>();
CheckSize<16>();
// Others as required
}
|
2,741,790 | 2,741,853 | C++ and preprocessor macro gotcha | Can you figure out what is wrong with the statement below?
GCC error states:
'type name' declared as function returning array
#define MACRO(a) (a)[1]
class index {
public:
typedef int index_type[2];
const index_type& operator[](int i) const;
};
int k = 0;
int i = MACRO(index()[k]);
btw: I know what is wrong, I thought it was amusing thing to share. Many thanks to litb, his explanation of previous gotcha helped to solve this error pretty quickly.
| In the expanded line:
int i = (index()[k])[1];
(index()[k]) is interpreted as a cast expression, declaring a function that returns an array of length k of index. At least, that's what it looks like is happening. How gcc is manages to validly interpret the [1] as an expression, I'm not sure.
|
2,741,840 | 2,741,867 | Dev-C++ Run Program in Background without GUI | I recently began learning C++ in order to reach people w/o .net. I need to run my program in the background(without any visual indication to the user so no window or cmd). I know there a various methods to do this In C#, but I don't know how to do this in C++ (specifically Dev-C++). Any help is greatly appreciated.
| First of all, you shouldn't be using Dev-C++. If you really don't want to use Visual Studio (why not? it's free!) then Code::Blocks or Eclipse or something is a better choice. Dev-C++ hasn't been updated in like 5 years...
The ways of creating background processes in C++ is basically the same as in C#, you just don't get the enormous class library that C# has which handles most of the work for you.
Your main choices are windows services, or creating a regular windows application and simply not displaying any windows... which one you choose depends on your specific requirements (do you want it run even when no one is logged in, or do you want it associated with a logged-in user, etc)
|
2,741,846 | 2,741,852 | How to sort an array or ArrayList<Point> ASC first by x and then by y? | I just want to use Collections.sort or Arrays.sort to sort a list of points (class Point) by x first and then by y.
I have a class Ponto that implements Comparable like this:
public int compareTo(Ponto obj) {
Ponto tmp = obj;
if (this.x < tmp.x) {
return -1;
} else if (this.x > tmp.x) {
return 1;
}
return 0;
}
but now I want to sort by y too after x.
How can I do that by modifying the above code? Or is that a better and "clean" way to do this?
I also use to pass this code to C++, in which I've created a structure called Point with a equivalent comparable method.
| Replace return 0 by the same comparison algo on this.y and obj.y.
By the way, reassigning to tmp is unnecessary here. The optimized picture can look like:
public int compareTo(Ponto other) {
if (this.x == other.x) {
return (this.y < other.y) ? -1 : ((this.y == other.y) ? 0 : 1);
} else {
return (this.x < other.x) ? -1 : 1;
}
}
|
2,741,986 | 2,742,159 | Indentation control while developing a small python like language | I'm developing a small python like language using flex, byacc (for lexical and parsing) and C++, but i have a few questions regarding scope control.
just as python it uses white spaces (or tabs) for indentation, not only that but i want to implement index breaking like for instance if you type "break 2" inside a while loop that's inside another while loop it would not only break from the last one but from the first loop as well (hence the number 2 after break) and so on.
example:
while 1
while 1
break 2
'hello world'!! #will never reach this. "!!" outputs with a newline
end
'hello world again'!! #also will never reach this. again "!!" used for cout
end
#after break 2 it would jump right here
but since I don't have an "anti" tab character to check when a scope ends (like C for example i would just use the '}' char) i was wondering if this method would the the best:
I would define a global variable, like "int tabIndex" on my yacc file that i would access in my lex file using extern. then every time i find a tab character on my lex file i would increment that variable by 1. when parsing on my yacc file if i find a "break" keyword i would decrement by the amount typed after it from the tabIndex variable, and when i reach and EOF after compiling and i get a tabIndex != 0 i would output compilation error.
now the problem is, whats the best way to see if the indentation got reduced, should i read \b (backspace) chars from lex and then reduce the tabIndex variable (when the user doesn't use break)?
another method to achieve this?
also just another small question, i want every executable to have its starting point on the function called start() should i hardcode this onto my yacc file?
sorry for the long question any help is greatly appreciated. also if someone can provide an yacc file for python would be nice as a guideline (tried looking on Google and had no luck).
thanks in advance.
| I am currently implementing a programming language rather similar to this (including the multilevel break oddly enough). My solution was to have the tokenizer emit indent and dedent tokens based on indentation. Eg:
while 1: # colons help :)
print('foo')
break 1
becomes:
["while", "1", ":",
indent,
"print", "(", "'foo'", ")",
"break", "1",
dedent]
It makes the tokenizer's handling of '\n' somewhat complicated though. Also, i wrote the tokenizer and parser from scratch, so i'm not sure whether this is feasable in lex and yacc.
Edit:
Semi-working pseudocode example:
level = 0
levels = []
for c = getc():
if c=='\n':
emit('\n')
n = 0
while (c=getc())==' ':
n += 1
if n > level:
emit(indent)
push(levels,n)
while n < level:
emit(dedent)
level = pop(levels)
if level < n:
error tokenize
# fall through
emit(c) #lazy example
|
2,742,084 | 2,742,091 | const CFoo &bar() const | I have a property of a class, for example, const CFoo &bar() const, what does it mean?
| The method bar returns a reference to a const CFoo (that's the const CFoo & part before bar), and calling this method does not modify any variables that are not marked as mutable (that's the const after the parentheses).
See also the C++ FAQ Lite entries What does "Fred const& X" mean? and What is a "const member function"?.
|
2,742,295 | 2,742,306 | issue with OOP Class Definitions | I work for my homework in C++ and i have some problems with multiply definitions.
My graph class ;
class Graph{
private:
string name; //Graph name
fstream* graphFile; //Graph's file
protected:
string opBuf; //Operations buffer
int containsNode(string); //Query if a node is present
Node* nodes; //Nodes in the graph
int nofNodes; //Number of nodes in the graph
public:
static int nOfGraphs; //Number of graphs produced
Graph(); //Constructors and destructor
Graph(int);
Graph(string);
Graph(const Graph &);
~Graph();
string getGraphName(); //Get graph name
bool addNode(string); //add a node to the graph
bool deleteNode(string); //delete a node from the graph
bool addEdge(string,string); //add an edge to the graph
bool deleteEdge(string,string); //delete an edge from the graph
void intersect(const Graph&); //intersect the graph with the <par>
void unite(const Graph&); //intersect the graph with the <par>
string toString(); //get string representation of the graph
void acceptTraverse(BreadthFirst*);
void acceptTraverse(DepthFirst *);
};
and my traversal class;
class Traversal {
public:
string *visitedNodes;
virtual string traverse (const Graph & );
};
class BreadthFirst : public Traversal {
public :
BreadthFirst();
string traverse();
};
class DepthFirst : public Traversal {
public :
DepthFirst();
string traverse();
};
My problem is in traversal class , i need to declare Graph class at the same time , in graph class i need traversal class to declare.
I have big problems with declerations :) Could you please help me ?
| No you don't need the definition of the classes. You just need to give the hint to the compiler that Graph and Traversal are classes. So use forward declartion like class BreadthFirst; in the definition of Graph (i..e just above class Graph{....}). Similarly use class Graph; before the definition of Traversal class.
|
2,742,299 | 2,742,339 | How to get all n sets of three consecutives elements in an array or arraylist with a for statement? | I'm trying to do a convex hull approach and the little problem is that I need to get all sets of three consecutive vertices, like this:
private void isConvexHull(Ponto[] points) {
Arrays.sort(points);
for (int i = 0; i <points.length; i++) {
isClockWise(points[i],points[i+1],points[i+2]);
}
//...
}
I always do something that I don't consider clean code. Could please help me find one or more ways to this? I want it to be circular, i.e., if my fisrt point of the a set is the last element in the array, the 2nd element will be the 3rd in the list and the 3rd in that set will be the the 2nd element in the list, and so on. They must be consecutive, that's all.
| The remainder "trick"
You can use the % "trick" (% is the remainder operator JLS 15.17.3) for circular indexing. Here I will illustrate the general idea using a String instead.
String s = "ABCDE";
final int L = s.length();
for (int i = 0; i < L; i++) {
System.out.format("%c%c%c ",
s.charAt(i),
s.charAt((i + 1) % L),
s.charAt((i + 2) % L)
);
} // prints "ABC BCD CDE DEA EAB "
An Iterator approach
If you're doing this triplet processing often, though, it will be a better overall design to have an Iterator<PointTriplet> or something similar.
Here's a prototype to illustrate the idea:
import java.util.*;
public class CircSubArray {
static <T> Iterator<T[]> circularIterator(final T[] arr, final int K) {
return new Iterator<T[]>() {
int index = 0;
final int L = arr.length;
T[] sub = Arrays.copyOf(arr, K); // let it do the dirty work!
@Override public boolean hasNext() {
return index < L;
}
@Override public T[] next() {
for (int i = 0; i < K; i++) {
sub[i] = arr[(index + i) % L];
}
index++;
return sub; // we always overwrite; no need to .clone()
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
String[] arr = { "s1", "s2", "s3", "s4", "s5", "s6" };
Iterator<String[]> iter = circularIterator(arr, 4);
while (iter.hasNext()) {
System.out.println(Arrays.toString(iter.next()));
}
}
}
This prints:
[s1, s2, s3, s4]
[s2, s3, s4, s5]
[s3, s4, s5, s6]
[s4, s5, s6, s1]
[s5, s6, s1, s2]
[s6, s1, s2, s3]
A List-based solution
As Effective Java 2nd Edition says, Item 25: Prefer lists to arrays. Here's a solution that redundantly stores the first K-1 elements at the end of the List, and then simply uses subList to get K elements at a time.
String[] arr = { "s1", "s2", "s3", "s4", "s5", "s6" };
final int L = arr.length;
final int K = 3;
List<String> list = new ArrayList<String>(Arrays.asList(arr));
list.addAll(list.subList(0, K-1));
for (int i = 0; i < L; i++) {
System.out.println(list.subList(i, i + K));
}
This prints:
[s1, s2, s3]
[s2, s3, s4]
[s3, s4, s5]
[s4, s5, s6]
[s5, s6, s1]
[s6, s1, s2]
Since subList is a view, this does not have to do the O(K) shifting that the array-based solution does. This also shows the expressiveness of List over arrays.
|
2,742,371 | 2,748,434 | Visual Studio 2010 - Export (Project) Template menu option grayed out | In Visual Studio, I want to make a simple C++ project and export it out as a template, so I can use the template to start new projects to save me time. But the Export Template menu option is always grayed out. I've not once been able to click it.
Anyone know why? Anyone know how to accomplish what I need (besides the obvious "make a copy of an existing project in explorer")?
It seems like project templates should be a no-brainer feature for VS.
This seems to be the case for Visual Studio 2005, 2010 (I probably 2008 as well I haven't checked).
| You can use the Visual C++ wizard architecture, which is designed for easy extensibility and customization. You can create a wizard using the Visual C++ Custom Wizard. After you create your wizard, you can configure it to generate the starter files you need for your projects.
For more information how to do this please refer to the following location:
http://msdn.microsoft.com/en-us/library/bhceedxx(v=VS.80).aspx
Noticed that normal project template and VC++ project template are different
Let me know if you have any problems...
s
|
2,742,381 | 2,742,413 | Getting a seg fault, having trouble with classes and variables | Ok, so I'm still learning the ropes of C++ here so I apologize if this is a simple mistake.
I have this class:
class RunFrame : public wxFrame {
public:
RunFrame();
void OnKey(wxKeyEvent& keyEvent);
private:
// Configuration variables.
const wxString *title;
const wxPoint *origin;
const wxSize *size;
const wxColour *background;
const wxColour *foreground;
const wxString *placeholder;
// Control variables.
wxTextCtrl *command;
// Event table.
DECLARE_EVENT_TABLE()
};
...then in the OnKey method I have this code:
void RunFrame::OnKey(wxKeyEvent& keyEvent) {
// Take the key and process it.
if(WXK_RETURN == keyEvent.GetKeyCode()) {
bool empty = command -> IsEmpty();
}
// Propogate the event through.
keyEvent.Skip();
}
...but my program keeps seg faulting when it reaches the line where I attempt to call the IsEmpty method from the command variable. My question is, "Why?" In the constructor of the RunFrame class I can seemingly call methods for the command variable in the same way I'm doing so in the OnKey method...and it compiles correctly, it just seg faults on me when it attempts to execute that line.
Here is the code for the constructor if necessary:
RunFrame::RunFrame() :
wxFrame(NULL, wxID_ANY, wxT("DEFAULT"), wxDefaultPosition, wxDefaultSize, wxBORDER_NONE) {
// Create the styling constants.
title = new wxString(wxT("RUN"));
origin = new wxPoint(0, 0);
size = new wxSize(250, 25);
background = new wxColour(33, 33, 33);
foreground = new wxColour(255, 255, 255);
placeholder = new wxString(wxT("command"));
// Set the styling for the frame.
this -> SetTitle(*title);
this -> SetSize(*size);
// Create the panel and attach the TextControl to it.
wxPanel *panel = new wxPanel(this, wxID_ANY, *origin, *size, wxBORDER_NONE);
// Create the text control and attach it to the panel.
command = new wxTextCtrl(panel, wxID_ANY, *placeholder, *origin, *size);
// Set the styling for the text control.
command -> SetBackgroundColour(*background);
command -> SetForegroundColour(*foreground);
// Connect the key event to the text control.
command -> Connect(wxEVT_CHAR, wxKeyEventHandler(RunFrame::OnKey));
// Set the focus to the command box.
command -> SetFocus();
}
Thanks in advance for any help you can give!
Regards,
celestialorb
| You are catching the event in an object other than the RunFrame object. Probably it's being caught in the base-object of type wxFrame. Use the runtime command wxEvtHandler::Bind<>() to bind the event, rather than an event table, and it should become clear what's happening.
To verify that this is the problem, compare the address of your RunFrame object to the "this" pointer in the OnKey method. Betcha they are different.
UPDATE: Show us your event table definition. That's where the problem is.
UPDATE 2: I've got to leave you with it. Maybe this will be clearer: Your event handler is defined as belonging to RunFrame. The event table is (I think) binding the event to a different object. The effect is that RunFrame::OnKey is being called not with the this-pointer for your RunFrame object, but some other object, probably of a different type. Good luck. Gotta go.
|
2,742,447 | 2,742,477 | Split string "A10" into char 'A' and int 10 | Given a string consisting of a single character followed by a number (one or two digits), I would like to split it into a character and an integer. What is the easiest way to accomplish this?
My thoughts so far:
I can easily grab the character like so:
string mystring = "A10";
char mychar = mystring[0];
The hard part seems to be grabbing the one or two digit number that follows.
| You can make use of the operator[], substr, c_str and atoi as:
string s = "A10";
char c = s[0]; // c is now 'A'
int n = atoi((s.substr(1,2)).c_str()); // n is now 10
EDIT:
The above will also work if s="A1". This is because if the 2nd argument to substr makes the substring to span past the end of the string content, only those characters until the end of the string are used.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.