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,799,243 | 2,799,296 | Segmentation Fault in prime number sieve | when I run this program while inputting a number greater than 46348, I get a segmentation fault. For any values below it, the program works perfectly. I am using CodeBlocks 8.02 on Ubuntu 10.04 64-bit.
The code is as follows:
int main()
{
int number = 46348;
vector<bool> sieve(number+1,false);
vector<int> primes;
sieve[0] = true;
sieve[1] = true;
for(int i = 2; i <= number; i++)
{
if(sieve[i]==false)
{
primes.push_back(i);
int temp = i*i;
while(temp <= number)
{
sieve[temp] = true;
temp = temp + i;
}
}
}
for(int i = 0; i < primes.size(); i++)
cout << primes[i] << " ";
return 0;
}
| Assuming you are on a common architecture, the problem is that the i*i calculation overflows. The result can not be stored in a signed 32 bit integer. You can try adding cout << temp << endl; after this calculation. In the end it will print:
2144523481
2146190929
2147117569
-2146737495
Segmentation fault
For the future, you will want to run your code in a debugger. It lets you spot these things more easily. I suspect CodeBlocks offers a graphical debugger. (Otherwise, make sure to compile with -ggdb and run your program with gdb)
Since you are on a 64 bit platform, you might want to use 64 bits unsigned integers to get a greater range. unsigned long long (C99, C++0x) is a good way to ask for "the biggest int you've got, that's reasonably cheap". (Even though one long long might span two registers, as is the case with a 64 bit datatype on IA32)
Alternatively, you can add a check to automatically verify that number < sqrt(numeric_limits<int>::max()) before entering the loop.
|
2,799,412 | 2,802,312 | How to use QMetaMethod with QObject::connect | I have two instances of QObject subclasses and two QMetaMethod instances of signal in one of objects and slot in another object. I want to connect this signal and slot with each other.
I've looked through the qobject.h file and find that SIGNAL() and SLOT() macro are just add "1" or "2" character to the beginning of method signature so it looks like it should be possible to add the same character to the beginning of string returned by QMetaMethod::signature() but this approach depends on some undocumented internals of toolkit and may be broken at any time by a new version of Qt.
Does anybody know reliable way to connect signals and slots through their QMetaMethod reflection representation?
Edited:
I've created suggestion in Qt issue tracker:
https://bugreports.qt.io/browse/QTBUG-10637
If anybody also interested in this feature you can vote for this ticket there.
| It looks like there is no way to make it work without relying on internal implementation. If I were you, I'd submit feature request to Qt bug tracker, write a code that mimics current behavior SIGNAL/SLOT macros and add unit test that will fail when SIGNAL/SLOT behavior changes.
There might be a simpler solution to the problem you're trying to solve: describe what exactly are you trying to do without any implementation details.
|
2,799,620 | 2,799,676 | windows keydown listeners in C | I am having a very hard time finding resources that talk about the windows message system. Mainly the keydown constant variables. I need to know what const varibles I need to listen for all keypress especially the arrow keys for C
| There is a winuser.h header file found in your SDK's installation which lists all the VK_ (Virtual Keys) which are key codes that you require, specifically VK_UP, VK_RIGHT, VK_LEFT and VK_DOWN for the up/right/left/down cursor keys respectively.
|
2,799,682 | 2,799,693 | C++ includes with and without .h |
Possible Duplicate:
What is the difference between using #include<filename> and #include<filename.h> in c++
I've never noticed it making any difference whether or not I include the .h at the end of an include, so I've always ignored the meaning, but I've just noticed in a particular program of mine, I get the error "memcpy was not declared in this scope" if I include "string", but not if I include "string.h".
First of all, I was wondering the specific cause of this, but also generally the difference between the two. At the same time, if someone could explain the difference between includes in angular brackets and those in quotation marks, It'd be much appreciated.
| <string> is the C++ standard library string header file containing std::string and its friends. <string.h> is a different header, from the C standard library, which has functions for manipulating C strings (null-terminated strings) and other related functions.
The two are entirely different and unrelated. In C++ (as in C), a header file can have any extension. The C++ standard library headers have no extension; the C standard library headers have a .h extension. .hpp or .hxx are also common.
|
2,799,684 | 2,799,708 | x86-64 long double precision | What is the actual precision of long double on Intel 64-bit platforms?
is it 80 bits padded to 128 or actual 128 bit?
if former, besides going gmp, is there another option to achieve true 128 precision?
| x86-64 precision is the same as regular x86. Extended double is 80 bits, using the x87 ISA, with 6 padding bytes added. There is no 128-bit FP hardware.
A software implementation of quad or extended quad precision might benefit from the x86-64 64x64 => 128 integer multiply instruction, though.
|
2,799,739 | 2,799,748 | Load XML from string in libxml++ in C++ | Does anyone familiar with libxml++ know if it's possible to load the XML document from a string instead of a file? Alternately, if it can load a document directly from a web page, that would do.
Thanks
| It sounds like you are looking for either xmlpp::Parser::parse_memory or xmlpp::DomParser::parse_memory.
Each of those classes also have a parse_stream method which take a std::istream if that is more convenient.
|
2,799,789 | 2,799,804 | What C++ library do I need to get this program to compile | When I try to compile my program I get these errors:
btio.c:19: error: ‘O_RDWR’ was not declared in this scope
btio.c:19: error: ‘open’ was not declared in this scope
btio.c: In function ‘short int create_tree()’:
btio.c:56: error: ‘creat’ was not declared in this scope
btio.c: In function ‘short int create_tree(int, int)’:
btio.c:71: error: ‘creat’ was not declared in this scope
what library do I need to include to fix these errors?
| You want:
#include <fcntl.h> /* For O_RDWR */
#include <unistd.h> /* For open(), creat() */
Also, note that, as @R Samuel Klatchko writes, these are not "libraries". What #include does is inserts a file into your code verbatim. It just so happens that the standard header fcntl.h will have a line like:
#define O_RDWR <some value here>
And unistd.h will have lines like:
int open(const char *, int, ...);
int creat(const char *, mode_t);
In other words, function prototypes, which informs the compiler that this function exists somewhere and optionally what its parameters look like.
The later linking step will then look for these functions in libraries; that is where the term "library" comes in. Most typically these functions will exist in a library called libc.so. You can think of your compiler inserting the flag -lc (link to libc) on your behalf.
Also, these are not "C++" but rather POSIX.
|
2,799,876 | 2,799,903 | Is compiler able to do a procedural integration of functions imported from dll? | I know, that modern compilers can do procedural integration not only with functions defined inline, but also with functions residing in object files. But is this also true when you compile your program against shared library (especially dll)? Roughly speaking: will function code be copied into executable from dll, if that's desirable?
| No, because the compiler does not have the code that makes up those functions.
On Windows, when you link against a dynamic library, you usually include a header and link against an import library, which simply contains the code to load the dynamic library and obtain pointers to the functions that you call (technically, you don't need the import library; you can also manually call LoadLibrary() and friends).
Since the compiler never sees the code in the dynamic library itself, it certainly can't perform inline expansion on the code.
|
2,799,966 | 2,800,029 | How to traverse a Btree? | I have a Btree and I'm trying to figure out how traverse it so that the keys are displayed ascending order.
All I can figure out is that this can be done with a recursive function.
What's the pseudo-code to do it?
| Assuming you have a definition like:
template <class T>
class btree_node
{
btree_node **child; // an array of child nodes
T **element; // the elements in this node
unsigned int child_count; // the number of children
// the number of elements is 1 less then child_count
};
Then you'll need do something like this:
void btree_inorder(node):
for (int i = 0; i < node.child_count; ++i)
{
btree_inorder(node.child[i]);
handle_element(node.element[i]);
}
btree_inorder(node.child[node.child_count-1]);
|
2,799,972 | 2,799,990 | Canny edge detection - grayscale images always coming up as 3-channel, unusable? | I am working through the book "Learning OpenCV" from the O'Reilly series and am trying to perform a canny edge detection sample.
Any grayscale image I choose seems to come up as having 3 channels, and to the best of my knowledge, canny only works with single channel images, so this always fails. I am even using the images provided by OpenCV.
Here is my code..
IplImage* doCanny(IplImage* in, double lowThresh, double highThresh, double aperture)
{
if(in->nChannels != 1)
return(0); //canny only handles gray scale images
IplImage* out = cvCreateImage(cvSize(in->width, in->height), IPL_DEPTH_8U, 1);
cvCanny(in, out, lowThresh, highThresh, aperture);
return(out);
};
IplImage* img = cvLoadImage("someGrayscaleImage.jpg");
IplImage* out = doCanny(img, 10, 100, 3);
Why might this always give me 3-channel images? How can I solve this?
| You can use this method with another parameter
IplImage* cvLoadImage(const char* filename, int iscolor=CV_LOAD_IMAGE_COLOR)
#define CV_LOAD_IMAGE_COLOR 1
#define CV_LOAD_IMAGE_GRAYSCALE 0
#define CV_LOAD_IMAGE_UNCHANGED -1
The default parameter is load image with color. What you have to do is to load it with grayscale
Here is an example
cvLoadImage("yourimage.jpg", CV_LOAD_IMAGE_GRAYSCALE);
Here is the detail explanation for that method. You can look at here for more details:
Open CV 2.0 References
scolor – Specific color type of the loaded image: if $ > 0 $, the loaded image is forced to be a 3-channel color image; if 0, the loaded image is forced to be grayscale; if $ < 0 $, the loaded image will be loaded as is (note that in the current implementation the alpha channel, if any, is stripped from the output image, e.g. 4-channel RGBA image will be loaded as RGB).
|
2,800,064 | 2,800,070 | singly linked list in the C++ standard library or other widely-used libraries? | Seems that there is only doubly linked list (but no singly linked list) in the C++ standard library, right? Is there any widely-used C++ libraries with singly linked list?
| There is slist, which is an SGI extension (__gnu_cxx::slist)
#include <iostream>
#include <iterator>
#include <ext/slist>
int main(int argc, char** argv) {
__gnu_cxx::slist<int> sl;
sl.push_front(1);
sl.push_front(2);
sl.push_front(0);
std::copy(sl.begin(), sl.end(), // The output is 0 2 1
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
|
2,800,138 | 2,800,312 | Mac laptop usage and development discussion? | I bought a new Mac book (MacBook Pro), and I am previously using Windows. I use this MacBook for personal (e.g. instant messaging, document, browsing the web) and development (writing C++ and Java code) purpose. Any recommended discussion group or forums (or I can directly ask here in StackOverflow)? I am a newbie.
| Yes, you may be interested in my Development Environment Setup guides. I currently develop on Mac OS X 10.6 Snow Leopard. My recommendation is to install Xcode and MacPorts. I tend to edit everything using Xcode, and I use MacPorts to install pretty much all the various libraries (except Qt, for which it is more sensible to downlod the precompiled Cocoa 32-bit and 64-bit binaries). In terms of developing such that things also work on Linux, as long as you conform to the Single UNIX Specification (i.e. use the authoritative manual pages at the link instead of Mac OS X's man pages) and, other than that, you rely only on cross-platform libraries, then you should be fine. That said, it is reasonable to install a copy of VirtualBox and setup an image of Ubuntu in it for verifying that your code compiles and runs under Linux.
|
2,800,143 | 2,800,160 | Why does the answer print out twice? | I made a program that returns the product abc where a,b,c are pythagorean triples and add up to 1000. The program does output the correct answer but does it twice. I was curious as to why this is so. After playing around with it a bit I found out that it prints out when a = 200 b = 375 c = 425. And once again when a = 375 b = 200 c = 425.
bool isPythagTriple(int a, int b, int c);
int main()
{
for(int a = 1; a < 1000; a++)
{
for(int b = 1; b < 1000; b++)
{
for(int c = 1; c < 1000; c++)
{
if( ((a+b+c)==1000) && isPythagTriple(a,b,c) )
{
cout << a*b*c << " ";
break;
}
}
}
}
return 0;
}
bool isPythagTriple(int a, int b, int c)
{
if( (a*a)+(b*b)-(c*c) == 0 )
return true;
else
return false;
}
| Break, in this case, will only break out of the c loop, not the b and a ones.
A quick fix is to ensure you don't get repeats by starting each variable greater than or equal to the previous (so b is never less than a and c is never less than b).
In addition, you can actually get rid of the c loop altogether since there's only one value of c that is valid for a given a,b pair (unless a + b + c > 1000 in which case there are none). I would try something like:
for (int a = 1; a < 1000; a++) {
for (int b = a; b < 1000; b++) {
int c = 1000 - a - b;
if (c >= b) {
if (isPythagTriple (a,b,c)) {
cout << a << " " << b << " " << c << " " << a*b*c << std::endl;
}
}
}
}
The overall effect of that is to reduce the total loop count from a billion (short scale) to about half a million hence reducing it by about 99.95% - that should be a tiny bit faster :-)
And potentially making it faster with Jerry Coffin's suggestion as well (and an inline suggestion to the compiler), a full program:
#include <iostream>
inline bool isPythagTriple(int a, int b, int c) {
return a * a + b * b == c * c;
}
int main() {
for(int a = 1; a < 1000; a++) {
for(int b = a; b < 1000; b++) {
int c = 1000 - a - b;
if (c >= b) {
if (isPythagTriple(a,b,c)) {
std::cout << a << " " << b << " " << c << " "
<< a*b*c << std::endl;
}
}
}
}
return 0;
}
which takes 0.004 seconds on average (system + user) on my box, with the original taking about 2.772 seconds on average (ten samples each). Not that it really matters unless you're running it many, many times, of course.
The output of that code is, as expected:
200 375 425 31875000
|
2,800,250 | 2,800,357 | Sum of all primes under 2 million | I made a program that returns the sum of all primes under 2 million. I really have no idea what's going on with this one, I get 142891895587 as my answer when the correct answer is 142913828922. It seems like its missing a few primes in there. I'm pretty sure the getPrime function works as it is supposed to. I used it a couple times before and worked correctly than. The code is as follows:
vector<int> getPrimes(int number);
int main()
{
unsigned long int sum = 0;
vector<int> primes = getPrimes(2000000);
for(int i = 0; i < primes.size(); i++)
{
sum += primes[i];
}
cout << sum;
return 0;
}
vector<int> getPrimes(int number)
{
vector<bool> sieve(number+1,false);
vector<int> primes;
sieve[0] = true;
sieve[1] = true;
for(int i = 2; i <= number; i++)
{
if(sieve[i]==false)
{
primes.push_back(i);
unsigned long int temp = i*i;
while(temp <= number)
{
sieve[temp] = true;
temp = temp + i;
}
}
}
return primes;
}
| The expression i*i overflows because i is an int. It is truncated before being assigned to temp. To avoid the overflow, cast it: static_cast<unsigned long>( i ) * i.
Even better, terminate iteration before that condition occurs: for(int i = 2; i*i <= number; i++).
Tested fixed.
Incidentally, you're kinda (un)lucky that this doesn't produce extra primes as well as missing some: the int value is signed, and could be negative upon overflow, and by my reading of §4.7/2, that would cause the inner loop to skip.
|
2,800,297 | 2,805,470 | Design patterns commonly used for RTOS (VXworks) | Can anyone help me on design patterns commonly used for RTOS?
In VXworks, which pattern is more preferable?
| Can we ignore the second sentence in your question? It is meaningless, and perhaps points to a misunderstanding of design patterns. The first part is interesting however. That said, I would generalise it to cover real-time systems rather than RTOS.
Many of the most familiar patterns are mechanistic, but in real-time systems higher-level architectural patterns are also important.
Bruce Powell Douglass is probably the foremost author on the subject of patterns for real time systems. If you want a flavour of what he has to say on the subject then read this article on Embedded.com (it is part three of a series of three; be sure to read the first two as well, since they also touch on the subject, (1) (2)). You could also do worst than to visit Embedded.com and enter "design patterns" into the search box, there are a number of articles on specific patterns and general articles on the subject.
While I think you are being far to specific in requesting patterns for "RTOS(VxWorks)", patterns I have used specifically with VxWorks are the Facade and Adapter patterns. Partly to provide an OO API, and also to provide a level of RTOS agnostic abstraction. The resulting classes were then implemented for Segger emBOS (to allow us to run a smaller, lower cost, royalty free RTOS), and both Windows and Linux to allow test, debug and simulation of the code in a richer environment with more powerful tools.
A non-exhaustive list of many patterns is provided on Wikipedia, many of which will be applicable to real-time systems. The listed concurrency patterns are most obviously relevant.
|
2,800,642 | 2,800,654 | Interop c# using a "long" from c++ | On my System:
sizeof(long) in c++ is 4 aka 32bits
sizeof(long) in c# is 8 aka 64 bits
So in my Interop method declarations I've been substituting c++ longs with c# int's however I get the feeling this isn't safe?
Why is a long the same size as an int in c++? And long long is 64bits? What's next a long long long long??
| Best thing to do assuming you have a recent C library is to include <stdint.h> and use uint64_t, int64_t, uint32_t, int32_t. This will works regardless of model of the underlying platform.
But if you are curious, the underlying issue is that different systems use different models. On 32 bit systems, both Posix and Windows use ILP32, which means an integer, long and point are all 32 bits long.
For 64 bits, Posix and Windows use different models.
Posix usually uses LP64 which means 32 bit integers, 64 bit longs and 64 bit pointers.
Windows uses LLP64 which means 32 bit integers and longs, 64 bit long longs and 64 bit pointers.
|
2,801,034 | 2,801,058 | Using C++ to find out how many lines are in a text file | My C++ program needs to know how many lines are in a certain text file. I could do it with getline() and a while-loop, but is there a better way?
| No.
Not unless your operating system's filesystem keeps track of the number of lines, which your system almost certainly doesn't as it's been a looong time since I've seen that.
|
2,801,097 | 2,801,314 | Where to add an overloaded operator for the tr1::array? | Since I need to add an operator& for the std::tr1::array<bool, N> I wrote the following lines
template<std::size_t N>
std::tr1::array<bool, N>
operator& (const std::tr1::array<bool, N>& a,
const std::tr1::array<bool, N>& b)
{
std::tr1::array<bool, N> result;
std::transform(a.begin(), a.end(), b.begin(), result.begin(),
std::logical_and<bool>());
return result;
}
Now I don't know in which namespace I've to put this function. I considered the std namespace as a restricted area. Only total specialization and overloaded function templates are allowed to be added by the user. Putting it into the global namespace isn't "allowed" either in order to prevent pollution of the global namespace and clashes with other declarations. And finally putting this function into the namespace of the project doesn't work since the compiler won't find it there.
What had I best do? I don't want to write a new array class putted into the project namespace. Because in this case the compiler would find the right namespace via argument dependent name lookup. Or is this the only possible way because writing a new operator for existing classes means extending their interfaces and this isn't allowed either for standard classes?
| I fully support GMan and sbk who told you to use a named function instead of an operator. Contrary to popular believe, overloading operators is always almost wrong, because it almost never adds clarity to the code. There are surprisingly few exceptions. Among them are the stream input and output operators as well as the arithmetical operators should you implement a number-like type. (And just how likely is that outside of a book teaching you operator overloading?) Note that some people frown upon the std lib overloading + (and +=, of course) for std::string for the same reason (and others, like that a+b==b+a holds for numbers, but not for strings) - and IMO they do have a point.
Anyway if one wanted to do this despite all advice:
When you try to invoke the operator, the compiler tries to find it in the namespace it was invoked in, all enclosing namespaces, and the namespaces of all the arguments. (The latter is called argument-dependent lookup or Koenig lookup.) The namespace of the argument is std, which you must not add an overload to. So that leaves the namespace the operator is invoked in and its enclosing namespaces - including the global namespace, which encloses all others - to put the operator in.
So if you want to implement it despite all warnings, put it in the namespace where it is used in. If it is used in several namespaces, put it into the one that encloses all these. If that's the global namespace, so be it.
Oh, and did I mention you should not implement this as an overloaded operator?
|
2,801,315 | 2,801,605 | Disable debug output in libxml2 and xmlsec | In my software, I use libxml2 and xmlsec to manipulate (obviously) XML data structures. I mainly use XSD schema validation and so far, it works well.
When the data structure input by the client doesn't match the XSD schema, libxml2 (or xmlsec) output some debug strings to the console.
Here is an example:
Entity: line 1: parser error : Start tag expected, '<' not found
DUMMY<?xml
^
While those strings are useful for debugging purposes, I don't want them to appear and polute the console output in the released software. So far, I couldn't find an official way of doing this.
Do you know how to suppress the debug output or (even better) to redirect it to a custom function ?
Many thanks.
| I would investigate the xmlSetGenericErrorFunc() and xmlThrDefSetGenericErrorFunc() functions, they seem right. The documentation is .. sparse, though.
Here is some Python code that seems to use these functions to disable error messages, the relevant lines look like this:
# dummy function: no debug output at all
cdef void _nullGenericErrorFunc(void* ctxt, char* msg, ...) nogil:
pass
# setup for global log:
cdef void _initThreadLogging():
# disable generic error lines from libxml2
xmlerror.xmlThrDefSetGenericErrorFunc(NULL, _nullGenericErrorFunc)
xmlerror.xmlSetGenericErrorFunc(NULL, _nullGenericErrorFunc)
|
2,801,426 | 2,806,541 | How do I know if a boost thread is done? | I am using boost::thread to process messages in a queue.
When a first message comes I start a message processing thread.
When a second message comes I check if the message processing thread is done.
if it is done I start a new one
if it is not done I don nothing.
How do I know if the thread is done ? I tried with joinable() but it is not working, as when the thread is done, it is still joinable.
I also tried to interrupt the process at once, and add an interruption point at the end of my thread, but it did not work.
Thanks
EDIT :
I would like to have my thread sleep for an undetermined time, and wake up when a signal is triggered.
The mean to do it is boost::condition_variable
| Spawning a new thread for each incoming message is very inefficient. You should check out the Thread pool pattern.
EDIT:
Sorry, jules, I misread your question. I recommend you take a look at the producer-consumer pattern. Check out this article on how to roll your own blocking queue using boost condition variables. Intel's Thread Building Blocks also has a blocking queue implementation.
Check out this SO question about existing lock-free queue implementations.
Hope this helps.
|
2,801,484 | 2,801,586 | weighted RNG speed problem in C++ | Edit: to clarify, the problem is with the second algorithm.
I have a bit of C++ code that samples cards from a 52 card deck, which works just fine:
void sample_allcards(int table[5], int holes[], int players) {
int temp[5 + 2 * players];
bool try_again;
int c, n, i;
for (i = 0; i < 5 + 2 * players; i++) {
try_again = true;
while (try_again == true) {
try_again = false;
c = fast_rand52();
// reject collisions
for (n = 0; n < i + 1; n++) {
try_again = (temp[n] == c) || try_again;
}
temp[i] = c;
}
}
copy_cards(table, temp, 5);
copy_cards(holes, temp + 5, 2 * players);
}
I am implementing code to sample the hole cards according to a known distribution (stored as a 2d table). My code for this looks like:
void sample_allcards_weighted(double weights[][HOLE_CARDS], int table[5], int holes[], int players) {
// weights are distribution over hole cards
int temp[5 + 2 * players];
int n, i;
// table cards
for (i = 0; i < 5; i++) {
bool try_again = true;
while (try_again == true) {
try_again = false;
int c = fast_rand52();
// reject collisions
for (n = 0; n < i + 1; n++) {
try_again = (temp[n] == c) || try_again;
}
temp[i] = c;
}
}
for (int player = 0; player < players; player++) {
// hole cards according to distribution
i = 5 + 2 * player;
bool try_again = true;
while (try_again == true) {
try_again = false;
// weighted-sample c1 and c2 at once
// h is a number < 1325
int h = weighted_randi(&weights[player][0], HOLE_CARDS);
// i2h uses h and sets temp[i] to the 2 cards implied by h
i2h(&temp[i], h);
// reject collisions
for (n = 0; n < i; n++) {
try_again = (temp[n] == temp[i]) || (temp[n] == temp[i+1]) || try_again;
}
}
}
copy_cards(table, temp, 5);
copy_cards(holes, temp + 5, 2 * players);
}
My problem? The weighted sampling algorithm is a factor of 10 slower. Speed is very important for my application.
Is there a way to improve the speed of my algorithm to something more reasonable? Am I doing something wrong in my implementation?
Thanks.
edit: I was asked about this function, which I should have posted, since it is key
inline int weighted_randi(double *w, int num_choices) {
double r = fast_randd();
double threshold = 0;
int n;
for (n = 0; n < num_choices; n++) {
threshold += *w;
if (r <= threshold) return n;
w++;
}
// shouldn't get this far
cerr << n << "\t" << threshold << "\t" << r << endl;
assert(n < num_choices);
return -1;
}
...and i2h() is basically just an array lookup.
| Your reject collisions are turning an O(n) algorithm into (I think) an O(n^2) operation.
There are two ways to select cards from a deck: shuffle and pop, or pick sets until the elements of the set are unique; you are doing the latter which requires a considerable amount of backtracking.
I didn't look at the details of the code, just a quick scan.
|
2,801,532 | 2,801,717 | make include directive and dependency generation with -MM | I want a build rule to be triggered by an include directive if the target of the include is out of date or doesn't exist.
Currently the makefile looks like this:
program_NAME := wget++
program_H_SRCS := $(wildcard *.h)
program_CXX_SRCS := $(wildcard *.cpp)
program_CXX_OBJS := ${program_CXX_SRCS:.cpp=.o}
program_OBJS := $(program_CXX_OBJS)
DEPS = make.deps
.PHONY: all clean distclean
all: $(program_NAME) $(DEPS)
$(program_NAME): $(program_OBJS)
$(LINK.cc) $(program_OBJS) -o $(program_NAME)
clean:
@- $(RM) $(program_NAME)
@- $(RM) $(program_OBJS)
@- $(RM) make.deps
distclean: clean
make.deps: $(program_CXX_SRCS) $(program_H_SRCS)
$(CXX) $(CPPFLAGS) -MM $(program_CXX_SRCS) > make.deps
include $(DEPS)
The problem is that it seems like the include directive is executing before the rule to build make.deps which effectively means that make is either getting no dependency list if make.deps doesn't exist or always getting the make.deps from the previous build and not the current one.
For example:
$ make clean
$ make
makefile:32: make.deps: No such file or directory
g++ -MM addrCache.cpp connCache.cpp httpClient.cpp wget++.cpp > make.deps
g++ -c -o addrCache.o addrCache.cpp
g++ -c -o connCache.o connCache.cpp
g++ -c -o httpClient.o httpClient.cpp
g++ -c -o wget++.o wget++.cpp
g++ addrCache.o connCache.o httpClient.o wget++.o -o wget++
Edit
I read the docs for the include directive, and it sounds like if the include target doesn't exist it will continue processing the parent makefile try and build the target, but it's not completely clear to me how this works:
If an included makefile cannot be
found in any of these directories, a
warning message is generated, but it
is not an immediately fatal error;
processing of the makefile containing
the include continues. Once it has
finished reading makefiles, make will
try to remake any that are out of date
or don't exist. See section How
Makefiles Are Remade. Only after it
has tried to find a way to remake a
makefile and failed, will make
diagnose the missing makefile as a
fatal error.
ANSWER
This is a modification of the answer I accepted. The one thing missing was that the dependency files also depend on the sources, and won't get regenerated unless they are added to the deps files which are being included:
%.d: $(program_CXX_SRCS)
@ $(CXX) $(CPPFLAGS) -MM $*.cpp | sed -e 's@^\(.*\)\.o:@\1.d \1.o:@' > $@
sed adds the name of the .d file to the beginning of each dependency line like so:
foo.d foo.o: foo.cpp foo.h bar.h baz.h
I got the idea from this amazing paper on the dangers of recursive make:
Recursive Make Considered Harmful
I also add the following to the makefile:
clean_list += ${program_SRCS:.c=.d}
# At the end of the makefile
# Include the list of dependancies generated for each object file
# unless make was called with target clean
ifneq "$(MAKECMDGOALS)" "clean"
-include ${program_SRCS:.c=.d}
endif
| You are relying on an implicit rule to compile your .cpp files. You have to redefine it to use the -MM and -MF flags that will create the dependency file.
%.o: %.cpp
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ -MM -MF $@.d
Then, you have to include these dependencies files in the Makefile, using -include that will not error when the dependencies files do not exist yet (on the first time, or after a clean).
program_DEPS := $(program_OBJS:.o=.o.d)
-include $(program_DEPS)
And remember to add the rm command for the dependencies files in the clean rule.
|
2,801,666 | 47,693,140 | Wrapping different versions of static library in dynamic libraries | In my project there is a dependency on a static library (just called libsomething from now on) from a 3rd party. Recently, libsomething has become available in another version. My task is to provide my software with support for the old and the new version. Only one version of libsomething is used at run-time at any given time, but which version this is should be configurable between program runs.
I am using MSVC2005 on WinXP, a secondary objective is to become prepared to switch over to Linux and GCC.
Since both versions of libsomething are using the same symbols, linking them both into my executable is out of the question as the symbols of both versions are going to clash all over at link-time.
While I could create two executables (one linking against the old version, the other one using the new version), I cannot implement a decision on which executable to call in the final deployment environment (legacy reasons).
I came up with the idea of creating a dynamic library wrapper for each version of libsomething and linking them at run-time depending on some config file. With MSCV, this would mean going down the road of using LoadLibrary(), GetProcAddress(), etc., while on Linux I would have to use dlopen() and dlsym().
I understand that using libtool (i.e., libtldl) is wrapping this platform-dependency for using shared libraries. Is this an appropriate path to follow? Are there better (or, at least, different) ways? Do alternatives for libtldl exist as open-source?
| It has been few years now but I'd like to mention another solution for completeness. Instead of manual dlopen and dlsym you could generate simple stubs for all necessary functions and on first call (or at program startup) decide which library version is needed, load it and resolve the addresses.
You could write a script specifically tailored for your project or use Implib.so tool:
# This will generate mylib.so.init.c and mylib.so.tramp.S
# which implement stubs. These need to be linked to your
# executable.
$ implib-gen.py mylib.so
Implib.so is Linux-only atm but should be easily adaptable to Windows.
|
2,801,691 | 2,801,695 | a nicer way to create structs in a loop | I haven't coded in C++ in ages. And recently, I'm trying to work on something
involving structs. Like this
typedef struct{
int x;
int y;
} Point;
Then in a loop, I'm trying to create new structs and put pointers to them them in a list.
Point* p;
int i, j;
while (condition){
// compute values for i and j with some function...
p = new Point;
p* = {i, j}; //initialize my struct.
list.append(p); //append this pointer to my list.
}
Now, my question is it possible to simplify this? I mean, the pointer
variable *p outside of the loop and calling p = new Point inside the loop.
Isn't there a better/nicer syntax for this?
| Sure:
Point * p = new Point;
You should probably also give your Point class a constructor:
struct Point { // note no need for typedef
int x;
int y;
Point( int ax, int ay ) : x( ax ), y( ay ) {}
};
so that you can say:
Point * p = new Point( i, j );
You may also want to make your list a list of Point values, rather than pointers, in which case you can avoid using dynamic allocation with new - always something to be avoided wherever possible in C++.
|
2,801,739 | 2,801,749 | calling a function from static function | how can i call a function which computes with input parameters from an another static function.
say,
class X
{
static void xyz();
static int pqr(int, int);
};
void X::xyz()
{
...pqr(10,20);
}
int X::pqr(int t1, int t2)
{
return t1*t2;
}
| You have to call instance methods off an instance of the class. Otherwise, just call it off the class.
X::pqr(10, 20)
|
2,801,859 | 2,801,872 | How would I convert decimal into binary? | All I really know is PHP and I used the decbin function etc, It was fairly easy to do. In this C++ program I want to do the same thing, just a simple number or string how would I do this?
| A simple function could be defined such as this:
void binary(int decimal) {
int remainder;
if(decimal <= 1) {
std::cout << decimal;
return;
}
remainder = decimal % 2;
binary(decimal >> 1);
std::cout << remainder;
}
Although there are many other resources on the web on how to do this..
A noteworthy question for efficiency of it here, as you may want more than just that:
Efficiently convert between Hex, Binary, and Decimal in C/C++
|
2,801,938 | 2,802,525 | GCC ABI compatibility | As far as I've understood, it is not possible to link libraries that use different versions of GCC's Application Binary Interface (ABI). Are there ABI changes to every version of GCC? Is it possible to link a library built with 4.3.1 if I use, say, GCC 4.3.2? Is there a matrix of some sort that lists all the ways I can combine GCC versions?
| The official ABI page points to an ABIcheck. This tool may do, what you want.
|
2,801,959 | 2,802,379 | Making only one column of a QTreeWidgetItem editable | I have a QTreeWidgetItem with two columns of data, is there any way to make only the second column editable? When I do the following:
QTreeWidgetItem* item = new QTreeWidgetItem();
item->setFlags(item->flags() | Qt::ItemIsEditable);
all columns become editable.
| Looks like you will have to forgo using QTreeWidget and QTreeWidgetItem and go with QTreeView and QAbstractItemModel. The "Widget" classes are convenience classes that are concrete implementations of the more abstract but more flexible versions. QAbstractItemModel has a call flags(QModelIndex index) where you would return the appropriate value for your column.
|
2,802,147 | 2,802,177 | C++ Programming in Linux Platform | I am a software engineer and i work in VC++, C++ in WIndows OS.
Are there any major differences when it comes to coding in C++ in Linux environment.
Or is it just some adjustments that we have to make when we need to code in C++ in Linux.
| It would depend on the types of projects you've worked on and what native windows APIs you made use of. For example if you used the native Windows API for everything, you're going to have a pretty big task ahead of you, it'd be worth making your project(s) work nicely with Wine instead.
In the Linux environment you have the man pages, quite detailed documentation of almost everything :). As mentioned above, look at POSIX, and while I recommend Qt - it provides a LOT of abstractions for things you might want to learn to do the Linux way (eg sockets, filesystem...)
|
2,802,188 | 2,802,196 | File count in a directory using C++ | How do I get the total number of files in a directory by using C++ standard library?
| You can't. The closest you are going to be able to get is to use something like Boost.Filesystem
EDIT: It is possible with C++17 using the STL's filesystem library
|
2,802,197 | 2,803,533 | C++ hash table implementation with collision handling | What is a good C++ library for hash tables / hash maps similar to what java offers. I have worked with Google Sparsehash, but it has no support for collisions.
| In addition to those mentioned in other answers, you could try MCT's closed_hash_map or linked_hash_map. It is internally similar to Google SparseHash, but doesn't restrict values used and has some other functional advantages.
I'm not sure I understand what you mean by "no support for collisions", though. Both Google SparseHash and similarly implemented MCT of course handle collisions fine, though differently than Java's HashMap.
|
2,802,302 | 2,802,327 | Simple OOP-related question | This question came to my mind quite a few times.
Let my explain my question through an example.
Say I've got two classes:
1- Grid.
2- Cell.
Now the location of the cell 'should' be stored in the grid class, not in the cell class itself. Say that the cell wanted to get its location through a method in the grid.
How can it do that? Keep in mind that the cell was created/initialised by the Grid class.
What good OO approach to solve this problem?
Thank you
| I don't think that's a good design. If the cell needs to know its location, it should hold it itself and provide methods for the grid to access it.
|
2,802,393 | 2,802,565 | Why does gdb show two different returns? | Last week I was a debugging a code and a weird situation came up: gdb passes through two different return clauses. I made a simple example that illustrates the situation:
#include <iostream>
using namespace std;
int test() {
string a = "asd";
string b = "asd";
while (true) {
if (a == b) {
return 0;
}
}
return -1;
}
int main() {
int result = test();
cout << "result: " << result << endl;
}
When debugging the code I got:
(gdb) b main
Breakpoint 1 at 0x1d4c: file example.cpp, line 19.
(gdb) r
Starting program: /Users/yuppienet/temp/a.out
Reading symbols for shared libraries +++. done
Breakpoint 1, main () at example.cpp:19
19 int result = test();
(gdb) s
test () at example.cpp:7
7 string a = "asd";
(gdb) n
8 string b = "asd";
(gdb) n
11 if (a == b) {
(gdb) n
12 return 0;
(gdb) n
15 return -1;
(gdb) n
16 }
(gdb) n
main () at example.cpp:20
20 cout << "result: " << result << endl;
(gdb) n
result: 0
21 }
(gdb) n
0x00001ab2 in start ()
I noted that even if gdb shows line 15, the return value is 0 (the finish command confirms this as well).
So the question is: why does gdb show line 15: return -1, even if the function is not really returning this value?
Thanks!
Edit:
I forgot to mention that I compiled with the following line:
g++ -Wall -pedantic -g -pg example.cpp
| I suspect you're seeing the function epilogue. Your two strings have destructors, which are being implicitly called on return. Check out what the disassembly says to be sure, but I suspect that both return statements are mapping to something along the lines of:
stash return_value;
goto epilogue;
and correspondingly:
epilogue:
destroy a; // on the stack, so destructor will be called
destroy b;
really_return(stashed value);
The epilogue appears to come from line 15 as a side-effect of how g++ does line numbering - a fairly simple format, really just a list of tags of the form "address X comes from line number Y" - and so it's reporting 15 as the closest match. Confusing in this case, but correct a lot of the time.
|
2,802,418 | 2,802,438 | '+=' : pointer on left; needs integral value on right | I am confused. I can not use this on a float? Must it be a integer? I try to define that as a point but I guess I can not convert float to float *
//global definition
float g_posX = 0.0f;
&g_posX -= 3.03f;
| You probably simply want to do this:
float g_posX = 0.0f;
g_posX -= 3.03f;
What your code tries to do is take the address of g_posX and subtract 3.03f from the address. That does not work, for two reasons:
The address is not an lvalue: it cannot be assigned to. Assigning to an address would be meaningless. What would it do, move the variable around in memory?
Pointer arithmetic can only be done using integers. Fractional addresses do not exist.
|
2,802,584 | 2,802,611 | passing a float as a pointer to a matrix | Honestly, I couldnt think of a better title for this issue because I am having 2 problems and I don't know the cause.
The first problem I have is this
//global declaration
float g_posX = 0.0f;
.............
//if keydown happens
g_posX += 0.03f;
&m_mtxView._41 = g_posX;
I get this error
cannot convert from 'float' to 'float *'
So I assume that the matrix only accepts pointers. So i change the varible to this....
//global declaration
float *g_posX = 0.0f;
.............
//if keydown happens
g_posX += 0.03f;
&m_mtxView._41 = &g_posX;
and I get this error
cannot convert from 'float' to 'float *'
which is pretty much saying that I can not declare g_posX as a pointer.
honestly, I don't know what to do.
| 1.)
m_mtxView._41 = g_posX;
2.)
Update: this piece of code is quite unnecessary, although it shows how to use a pointer allocated on the heap.
float* g_posX = new float; // declare a pointer to the address of a new float
*g_posX = 0.0f; // set the value of what it points to, to 0.0This
m_mtxView._41 = *g_posX; // set the value of m_mtxView._41 to the value of g_posX
delete g_posX; // free the memory that posX allocates.
Hint: Read "*****" as "value of" and "&" as "address of"
|
2,802,953 | 2,802,984 | How do shared pointers work? | How do shared pointers know how many pointers point to that object? (shared_ptr, in this case)
| Basically, shared_ptr has two pointers: a pointer to the shared object and a pointer to a struct containing two reference counts: one for "strong references," or references that have ownership, and one for "weak references," or references that don't have ownership.
When you copy a shared_ptr, the copy constructor increments the strong reference count. When you destroy a shared_ptr, the destructor decrements the strong reference count and tests whether the reference count is zero; if it is, the destructor deletes the shared object because no shared_ptrs point to it anymore.
The weak reference count is used to support weak_ptr; basically, any time a weak_ptr is created from the shared_ptr, the weak reference count is incremented, and any time one is destroyed the weak reference count is decremented. As long as either the strong reference count or the weak reference count is greater than zero, the reference count struct will not be destroyed.
Effectively, as long as the strong reference count is greater than zero, the shared object will not be deleted. As long as the strong reference count or the weak reference count is not zero, the reference count struct will not be deleted.
|
2,802,960 | 2,803,621 | What is a QT Plugin? | What is a QT Plugin? What are differences between a qt plugin and a custom made qt library?
Thanks.
| AFAIK Qt plugins are implemented as shared libraries (.so on Unix/Linux and DLLs on Windows). The differences between them are the same as with plugins and libraries in general.
What this means is that, a plug-in architecture is independent of the linking method.
They tend to be thought of as plug-in/dynamic linking and non-plug-in/static linking.
A core application specifies an interface and data exchange contract (i.e. an API) through which separate modules can interact with the application and expose functionality through the application. Just shipping new modules in DLLs does not address the need of a way for the application itself to discover these DLLs and to know how to execute the logic within. This is the essence of a plugin architecture. In general, DLL's expose only a list of procedures or functions. Variables, classes, objects inside the dll are not directly accessible to outside processes. Writing a plugin involves moving most or all of the relevant code into the DLL, where all variables and objects can be directly referenced.
Something like Eclipse, wherein you place you plugin in a pre-defined directory and the next time you click on some Menu you see new entries. All this without restarting your app or running a new version of the exe.
|
2,803,071 | 2,803,150 | C++ sort array of strings | I am trying to sort an array of strings, but it's not sorting anything.... what am I doing wrong?
string namesS[MAX_NAMES];
int compare (const void * a, const void * b){
return ( *(char*)a - *(char*)b );
}
void sortNames(){
qsort(namesS, MAX_NAMES, sizeof(string), compare);
}
| This is C++, not C. Sorting an array of strings is easy.
#include <string>
#include <vector>
#include <algorithm>
std::vector<std::string> stringarray;
std::sort(stringarray.begin(), stringarray.end());
|
2,803,258 | 2,803,303 | How to initialise a struct-type in the initialisation list? | How can I initilise a structure in the constructor list?
Say:
struct St{int x, y};
class Foo
{
public:
Foo(int a = 0, int b = 0) : /*here initilise st_foo out of a and b*/
{}
private:
const St st_foo;
};
| You need to provide a constructor for struct St that takes 2 int parameters and assigns them to x and y. Then invoke it in your Foo initialization list.
Remember: structs are the same thing as classes except default visibility rules (for structs, default is public.
|
2,803,304 | 2,803,445 | advance mathematics c++ libraries | what popular advance mathematics libraries for c++ are present out there, so that they can be used as a 1 stop solution and avoiding reinventing the wheel ?
| Check out GNU Scientific Library -- it's in C, but I use it all the time to avoid re-writing the Numerical Recipes code.
|
2,803,403 | 2,803,512 | C++ stream as a parameter when overloading operator<< | I'm trying to write my own logging class and use it as a stream:
logger L;
L << "whatever" << std::endl;
This is the code I started with:
#include <iostream>
using namespace std;
class logger{
public:
template <typename T>
friend logger& operator <<(logger& log, const T& value);
};
template <typename T>
logger& operator <<(logger& log, T const & value) {
// Here I'd output the values to a file and stdout, etc.
cout << value;
return log;
}
int main(int argc, char *argv[])
{
logger L;
L << "hello" << '\n' ; // This works
L << "bye" << "alo" << endl; // This doesn't work
return 0;
}
But I was getting an error when trying to compile, saying that there was no definition for operator<< (when using std::endl):
pruebaLog.cpp:31: error: no match for ‘operator<<’ in ‘operator<< [with T = char [4]](((logger&)((logger*)operator<< [with T = char [4]](((logger&)(& L)), ((const char (&)[4])"bye")))), ((const char (&)[4])"alo")) << std::endl’
So, I've been trying to overload operator<< to accept this kind of streams, but it's driving me mad. I don't know how to do it. I've been loking at, for instance, the definition of std::endl at the ostream header file and written a function with this header:
logger& operator <<(logger& log, const basic_ostream<char,char_traits<char> >& (*s)(basic_ostream<char,char_traits<char> >&))
But no luck. I've tried the same using templates instead of directly using char, and also tried simply using "const ostream& os", and nothing.
Another thing that bugs me is that, in the error output, the first argument for operator<< changes, sometimes it's a reference to a pointer, sometimes looks like a double reference...
| endl is a strange beast. It isn't a constant value. It's actually, of all things, a function. You need a special override to handle the application of endl:
logger& operator<< (logger& log, ostream& (*pf) (ostream&))
{
cout << pf;
return log;
}
This accepts insertion of a function that takes an ostream reference and returns an ostream reference. That's what endl is.
Edit: In response to FranticPedantic's interesting question of "why can't the compiler deduce this automatically?". The reason is that if you delve yet deeper, endl is actually itself a template function. It's defined as:
template <class charT, class traits>
basic_ostream<charT,traits>& endl ( basic_ostream<charT,traits>& os );
That is, it can take any sort of ostream as its input and output. So the problem isn't that the compiler can't deduce that T const & could be a function pointer, but that it can't figure out which endl you meant to pass in. The templated version of operator<< presented in the question would accept a pointer to any function as its second argument, but at the same time, the endl template represents an infinite set of potential functions, so the compiler can't do anything meaningful there.
Providing the special overload of the operator<< whose second argument matches a specific instantiation of the endl template allows the call to resolve.
|
2,803,502 | 2,803,610 | C++ Detecting ENTER key pressed by user | I have a loop where I ask the user to enter a name. I need to stop when the user presses the ENTER key..... or when 20 names have been entered. However my method doesn't stop when the user presses the ENTER key
//loop until ENTER key is entered or 20 elements have been added
bool stop = false;
int ind = 0;
while( !stop || ind >= 20 ){
cout << "Enter name #" << (ind+1) << ":";
string temp;
getline(cin, temp);
int enterKey = atoi(temp.c_str());
if(enterKey == '\n'){
stop = true;
}
else{
names[ind] = temp;
}
ind++;
}
| You convert the read string to an integer with atoi:
int enterKey = atoi(temp.c_str());
If temp is a string like "1234" this will set enterKey to 1234. Then you compare enterKey to the ASCII value of \n. This is most probably not doing anything useful.
Also std::getline just read the characters up to, but not including, the next '\n'. If a user just presses enter without typing any other characters, std::getline will return an empty string. If a string is empty can be easily tested with its empty() method:
getline(cin, temp);
if (temp.empty()) {
stop = true;
}
|
2,803,910 | 2,804,018 | C++ Beginner - Trouble using classes inside of classes | I am working on a college project, where I have to implement a simple Scrabble game.
I have a player class (containing a Score and the player's hand, in the form of a std::string, and a score class (containing a name and numeric (int) score).
One of Player's member-functions is Score getScore(), which returns a Score object for that player. However, I get the following error on compile time:
player.h(27) : error C2146: syntax error : missing ';' before identifier 'getScore'
player.h(27) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
player.h(27) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
player.h(27) : warning C4183: 'getScore': missing return type; assumed to be a member function returning 'int'
player.h(35) : error C2146: syntax error : missing ';' before identifier '_score'
player.h(35) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
player.h(35) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Here's lines 27 and 35, respectively:
Score getScore(); //defined as public
(...)
Score _score; //defined as private
I get that the compiler is having trouble recognizing Score as a valid type... But why? I have correctly included Score.h at the beginning of player.h:
#include "Score.h"
#include "Deck.h"
#include <string>
I have a default constructor for Score defined in Score.h:
Score(); //score.h
//score.cpp
Score::Score()
{
_name = "";
_points = 0;
}
Any input would be appreciated!
Thanks for your time,
Francisco
EDIT:
As requested, score.h and player.h:
http://pastebin.com/3JzXP36i
http://pastebin.com/y7sGVZ4A
| You've got a circular inclusion problem - relatively easy to fix in this case.
Remove the #include "Player.h" from Score.h.
See this question for an explanation and discussion of what you'd need to do if Score actually used Player.
As for the compiler errors you're getting, that's how Microsoft's compiler reports the use of undefined types -you should learn to mentally translate them all into "Type used in declaration not defined".
|
2,804,089 | 2,805,729 | printf("... %c ...",'\0') and family - what will happen? | How will various functions that take printf format string behave upon encountering the %c format given value of \0/NULL?
How should they behave? Is it safe? Is it defined? Is it compiler-specific?
e.g. sprintf() - will it crop the result string at the NULL? What length will it return?
Will printf() output the whole format string or just up to the new NULL?
Will va_args + vsprintf/vprintf be affected somehow? If so, how?
Do I risk memory leaks or other problems if I e.g. shoot this NULL at a point in std::string.c_str()?
What are the best ways to avoid this caveat (sanitize input?)
| What happens when you output a NUL depends on the output device.
It is a non printing character, i.e. isprint('\0') == 0; so when output to a display device, it has no visible affect. If redirected to a file however (or if calling fprintf()), it will insert a NUL (zero byte) into the file; the meaning of that will depend on how the file is used.
When output to a C string, it will be interpreted as a string terminator by standard string handling functions, although any other subsequent format specifiers will still result in data being placed in the buffer after the NUL, which will be invisible to standard string handling functions. This may still be useful if ultimately the array is not to be interpreted as a C string.
Do I risk memory leaks or other problems if I e.g. shoot this NULL at a point in std::string.c_str()?
It is entirely unclear what you mean by that, but if you are suggesting using the pointer returned by std::string.c_str() as the buffer for sprintf(); don't! c_str() returns a const char*, modifying the string through such a pointer is undefined. That however is a different problem, and not at all related to inserting a NUL into a string.
What are the best ways to avoid this caveat (sanitize input?)
I am struggling to think of a circumstance where you could "accidentally" write such code, so why would you need to guard against it!? Do you have a particular circumstance in mind? Even though I find it implausible, and probably unnecessary, what is so hard about:
if( c != 0 )
{
printf( "%c", c ) ;
}
or perhaps more usefully (since there are other characters you might want to avoid in the output)
if( isgraph(c) || isspace(c) )
{
printf( "%c", c ) ;
}
which will output only visible characters and whitespace (space, '\t','\f','\v','\n','\r').
Note that you might also consider isprint() rather than isgraph(c) || isspace(c), but that excludes '\t','\f','\v','\n' and '\r'
|
2,804,115 | 2,805,489 | How to connect focus event from QLineEdit? | I have to connect focus event from some QLineEdit element (ui->lineEdit) to the method focus(). How can I do this?
| There is no signal emitted when a QLineEdit gets the focus. So the notion of connecting a method to the focus event is not directly appropriate.
If you want to have a focused signal, you will have to derive the QLineEdit class. Here is a sample of how this can be achieved.
In the myLineEdit.h file you have:
class MyLineEdit : public QLineEdit
{
Q_OBJECT
public:
MyLineEdit(QWidget *parent = 0);
~MyLineEdit();
signals:
void focussed(bool hasFocus);
protected:
virtual void focusInEvent(QFocusEvent *e);
virtual void focusOutEvent(QFocusEvent *e);
};
In the myLineEdit.cpp file you have :
MyLineEdit::MyLineEdit(QWidget *parent)
: QLineEdit(parent)
{}
MyLineEdit::~MyLineEdit()
{}
void MyLineEdit::focusInEvent(QFocusEvent *e)
{
QLineEdit::focusInEvent(e);
emit(focussed(true));
}
void MyLineEdit::focusOutEvent(QFocusEvent *e)
{
QLineEdit::focusOutEvent(e);
emit(focussed(false));
}
You can now connect the MyLineEdit::focussed() signal to your focus() method (slot).
|
2,804,194 | 2,804,233 | How do I retrieve program output in Python? | I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to:
$version = `java -version`;
How would I go about getting the same end result in Python? Does the above line retrieve standard error (equivalent to C++ std::cerr) and standard log (std::clog) output as well? If not, how can I retrieve those output streams as well?
Thanks,
Geoff
| For python 2.5: sadly, no. You need to use subprocess:
import subprocess
proc = subprocess.Popen(['java', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
Docs are at http://docs.python.org/library/subprocess.html
|
2,804,261 | 2,804,312 | How do I create a C++ console/terminal project in XCode? | I am using MacBook Pro Mac OS 10.5 with related version of XCode. I am new to this development environment. I want to develop C++ code for a console/terminal-based application using XCode on Mac OS 10.5, but I did not figure out how to create such type of project using XCode. Could anyone briefly describe the steps or refer me to some related tutorials?
| File->New project
Then from the list on the left "Command line utility", and on the right "C++ tool".
|
2,804,320 | 2,804,457 | Linked list issue with insert | The problem appears with the insert function that I wrote.
3 conditions must work, I tested b/w 1 and 2, b/w 2 and 3 and as last element, they worked.
EDIT;
It was my own problem. I did not realize I put MAXINPUT = 3 (instead of 4). I do appreciate all the efforts to help me becoming a better programmer, using more advance and more concise features of C++.
Basically, the problem has been solved.
Efficiency is not my concern here (not yet). Please guide me through this debug process.
Thank you very much.
#include<iostream>
#include<string>
using namespace std;
struct List // we create a structure called List
{
string name;
string tele;
List *nextAddr;
};
void populate(List *);
void display(List *);
void insert(List *);
int main()
{
const int MAXINPUT = 3;
char ans;
List * data, * current, * point; // create two pointers
data = new List;
current = data;
for (int i = 0; i < (MAXINPUT - 1); i++)
{
populate(current);
current->nextAddr = new List;
current = current->nextAddr;
}
// last record we want to do it sepeartely
populate(current);
current->nextAddr = NULL;
cout << "The current list consists of the following data records: " << endl;
display(data);
// now ask whether user wants to insert new record or not
cout << "Do you want to add a new record (Y/N)?";
cin >> ans;
if (ans == 'Y' || ans == 'y')
{
/*
To insert b/w first and second, use point as parameter
between second and third uses point->nextAddr
between third and fourth uses point->nextAddr->nextAddr
and insert as last element, uses current instead
*/
point = data;
insert(());
display(data);
}
return 0;
}
void populate(List *data)
{
cout << "Enter a name: ";
cin >> data->name;
cout << "Enter a phone number: ";
cin >> data->tele;
return;
}
void display(List *content)
{
while (content != NULL)
{
cout << content->name << " " << content->tele;
content = content->nextAddr;
cout << endl; // we skip to next line
}
return;
}
void insert(List *last)
{
List * temp = last->nextAddr; //save the next address to temp
last->nextAddr = new List; // now modify the address pointed to new allocation
last = last->nextAddr;
populate(last);
last->nextAddr = temp; // now link all three together, eg 1-NEW-2
return;
}
| Your code works fine on my machine (once the insert(()) statement is "filled in" properly as explained in the code comment). The insertion works in all positions.
Something else, though: I initially had a look at your insert function. I thought I'd give you a hint on how to make it a little shorter and easier to understand what's going on:
void insert(List *last)
{
// create a new item and populate it:
List* new_item = new List;
populate(new_item);
// insert it between 'last' and the item succeeding 'last':
new_item->nextAddr = last->nextAddr;
last->nextAddr = new_item;
}
This would be preferable because it first creates a new, separate item, prepare it for insertion, and only then, when this has worked successfully, will the function "mess" with the linked list. That is, the linked list is not affected except in the very last statement, making your function "safer". Contrast this with your version of insert, where you mix code for constructing the new item with the actual insertion. If something goes wrong inside this function, chances are far higher that the linked list is messed up, too.
(What's still missing btw. is a initial check whether the passed argument last is actually valid, ie. not a null pointer.)
P.S.: Of course you could just use a standard C++ std::list container instead of building your own linked list, but seeing that you tagged your question beginner, I assume you want to learn how it actually works.
|
2,804,426 | 2,804,621 | How do I increase the stack size for executables built with scons on Solaris? | I am working with scons and am trying to compile a program that require bigger stack size but I dont know how to extend the stack size. This is on a solaris machine, and we use scons to compile our projects.
Anyone know how to do this ?
| In the shell (ksh example) prior to executing your program you can use ulimit -s <size in kbytes>. You may need elevated privileges to change it.
You can also use setrlimit programmatically but from the man page it won't adjust the currently running process so it's probably not helpful for your needs.
Also consider what about your program needs the larger stack size. Is there a way you can change your design to be more stack friendly? The Solaris default seems to be 10M which is a fairly large stack.
|
2,804,473 | 2,804,564 | Having issues with initializing character array | Ok, this is for homework about hashtables, but this is the simple stuff I thought I was able to do from earlier classes, and I'm tearing my hair out. The professor is not being responsive enough, so I thought I'd try here.
We have a hashtable of stock objects.The stock objects are created like so:
stock("IBM", "International Business Machines", 2573, date(date::MAY, 23, 1967))
my constructor looks like:
stock::stock(char const * const symbol, char const * const name, int sharePrice, date priceDate): m_symbol(NULL), m_name(NULL), sharePrice(sharePrice), dateOfPrice(priceDate)
{
setSymbol(symbol);
setName(name);
}
and setSymbol looks like this: (setName is indentical):
void stock::setSymbol(const char* symbol)
{
if (m_symbol)
delete [] m_symbol;
m_symbol = new char[strlen(symbol)+1];
strcpy(m_symbol,symbol);
}
and it refuses to allocate on the line
m_symbol = new char[strlen(symbol)+1];
with a std::bad_alloc. name and symbol are declared
char * m_name;
char * m_symbol;
It's definitely strlen() that is going astray. And it doesn't seem to happen every time.
cout << symbol << strlen(symbol);
returns IBM correctly, then crashes
| As this is tagged C++ can you use std::string instead of doing all the pointer maintenance yourself on char*?
std::string name;
std::string symbol
Then setSymbol becomes easy:
void stock::setSymbol(const char* symbol)
{
this->symbol = symbol;
}
|
2,804,556 | 2,804,672 | How to detect the language of MS Excel | I'm trying to figure out a way of detecting the language of an installed version of Excel (ideally from C++). I need this to resolve an issue with computers on which the language of Excel differs from the Windows language (see this problem).
| Using automation, the applications LanguageSettings object gives you that:
Application.LanguageSettings.LanguageID(msoLanguageIDUI)
|
2,804,641 | 2,851,477 | Pretty printing boost::unordered_map on gdb | recently I've started to use the excellent boost::unordered_map on my system, but got one drawback: I couldn't figure how to inspect its contents. Printing it on gdb gives me a table_ and a buckets_, but haven't found where are the items. Anyone has a clue about this?
| For the ones that wanted a printer, I've managed to create one. Here is Code:
class BoostUnorderedMapPrinter:
"prints a boost::unordered_map"
class _iterator:
def __init__ (self, fields):
type_1 = fields.val.type.template_argument(0)
type_2 = fields.val.type.template_argument(1)
self.buckets = fields.val['table_']['buckets_']
self.bucket_count = fields.val['table_']['bucket_count_']
self.current_bucket = 0
pair = "std::pair<%s const, %s>" % (type_1, type_2)
self.pair_pointer = gdb.lookup_type(pair).pointer()
self.base_pointer = gdb.lookup_type("boost::unordered_detail::value_base< %s >" % pair).pointer()
self.node_pointer = gdb.lookup_type("boost::unordered_detail::hash_node<std::allocator< %s >, boost::unordered_detail::ungrouped>" % pair).pointer()
self.node = self.buckets[self.current_bucket]['next_']
def __iter__(self):
return self
def next(self):
while not self.node:
self.current_bucket = self.current_bucket + 1
if self.current_bucket >= self.bucket_count:
raise StopIteration
self.node = self.buckets[self.current_bucket]['next_']
iterator = self.node.cast(self.node_pointer).cast(self.base_pointer).cast(self.pair_pointer).dereference()
self.node = self.node['next_']
return ('%s' % iterator['first'], iterator['second'])
def __init__(self, val):
self.val = val
def children(self):
return self._iterator(self)
def to_string(self):
return "boost::unordered_map"
|
2,804,743 | 2,804,860 | How i can display image in symbian c++ | Hi i'm new in symbian c++ and sdk 5th, I use carbide c++ how i can display some image? (.bmp extension for example)
| Perhaps have a look into the DrawBitmap and BitBit functions.
|
2,804,880 | 2,804,895 | In C++, what is the scope resolution ("order of precedence") for shadowed variable names? | In C++, what is the scope resolution ("order of precedence") for shadowed variable names? I can't seem to find a concise answer online.
For example:
#include <iostream>
int shadowed = 1;
struct Foo
{
Foo() : shadowed(2) {}
void bar(int shadowed = 3)
{
std::cout << shadowed << std::endl;
// What does this output?
{
int shadowed = 4;
std::cout << shadowed << std::endl;
// What does this output?
}
}
int shadowed;
};
int main()
{
Foo().bar();
}
I can't think of any other scopes where a variable might conflict. Please let me know if I missed one.
What is the order of priority for all four shadow variables when inside the bar member function?
| Your first example outputs 3. Your second outputs 4.
The general rule of thumb is that lookup proceeds from the "most local" to the "least local" variable. Therefore, precedence here is block -> local -> class -> global.
You can also access each most versions of the shadowed variable explicitly:
// See http://ideone.com/p8Ud5n
#include <iostream>
int shadowed = 1;
struct Foo
{
int shadowed;
Foo() : shadowed(2) {}
void bar(int shadowed = 3);
};
void Foo::bar(int shadowed)
{
std::cout << ::shadowed << std::endl; //Prints 1
std::cout << this->shadowed << std::endl; //Prints 2
std::cout << shadowed << std::endl; //Prints 3
{
int shadowed = 4;
std::cout << ::shadowed << std::endl; //Prints 1
std::cout << this->shadowed << std::endl; //Prints 2
//It is not possible to print the argument version of shadowed
//here.
std::cout << shadowed << std::endl; //Prints 4
}
}
int main()
{
Foo().bar();
}
|
2,804,893 | 2,805,812 | C++ DLL Export: Decorated/Mangled names | Created basic C++ DLL and exported names using Module Definition file (MyDLL.def).
After compilation I check the exported function names using dumpbin.exe
I expect to see:
SomeFunction
but I see this instead:
SomeFunction = SomeFunction@@@23mangledstuff#@@@@
Why?
The exported function appears undecorated (especially compared to not using the Module Def file), but what's up with the other stuff?
If I use dumpbin.exe against a DLL from any commercial application, you get the clean:
SomeFunction
and nothing else...
I also tried removing the Module Definition and exporting the names using the "C" style of export, namely:
extern "C" void __declspec(dllexport) SomeFunction();
(Simply using "extern "C" did not create an exported function)
However, this still creates the same output, namely:
SomeFunction = SomeFunction@@@23mangledstuff#@@@@
I also tried the #define dllexport __declspec(dllexport) option and created a LIB with no problem. However, I don't want to have to provide a LIB file to people using the DLL in their C# application.
It's a plain vanilla C++ DLL (unmanaged code), compiled with C++ nothing but a simple header and code. Without Module Def I get mangled exported functions (I can create a static library and use the LIB no problem. I'm trying to avoid that). If I use extern "C" __declspec(dllexport) OR a Module Definition I get what appears to be an undecorated function name... the only problem is that it is followed by an "=" and what looks like a decorated version of the function. I want to get rid of the stuff after the "=" - or at least understand why it is there.
As it stands, I'm pretty certain that I can call the function from C# using a P/Invoke... I just want to avoid that junk at the end of the "=".
I'm open to suggestions on how to change the project/compiler settings, but I just used the standard Visual Studio DLL template - nothing special.
| You can get what you want by turning off debug info generation. Project + Properties, Linker, Debugging, Generate Debug Info = No.
Naturally, you only want to do this for the Release build. Where the option is already set that way.
|
2,805,029 | 2,805,066 | Overview look of header inclusions | When a project grows it becomes hard to get an overview of header inclusion. I've noticed our object files have grown rather large and so I'm thinking there's a lot to be won by rearranging dependencies. This is where the problem begin, I know of no convenient way to actually get an overview on what headers actually get included for a specific source file. There's the possibility of outputting the pre-processed source files, that however creates huge files with loads of irrelevant information. I'm thinking there must be a tool for this, but I can't seem to find any. I'm on windows, so in case anyone know of a good tool / way to actually do this for windows I'd be eternally grateful.
| Visual C++ has the /showIncludes switch, which causes the compiler to output a message when an include is encountered.
|
2,805,215 | 2,805,243 | What header file is where the boost library define its own primitive data type? | Recently, I try to use the boost::spirit::qi binary endian parser to parse some binary data depends on the endianness of the Platform. There is a simple example, like following:
Using declarations and variables:
using boost::spirit::qi::little_word;
using boost::spirit::qi::little_dword;
using boost::spirit::qi::little_qword;
boost::uint16_t us;
boost::uint32_t ui;
boost::uint64_t ul;
Basic usage of the little endian binary parsers:
test_parser_attr("\x01\x02", little_word, us); assert(us == 0x0201);
test_parser_attr("\x01\x02\x03\x04", little_dword, ui); assert(ui == 0x04030201);
test_parser_attr("\x01\x02\x03\x04\x05\x06\x07\x08", little_qword, ul);
assert(ul == 0x0807060504030201LL);
test_parser("\x01\x02", little_word(0x0201));
test_parser("\x01\x02\x03\x04", little_dword(0x04030201));
test_parser("\x01\x02\x03\x04\x05\x06\x07\x08",
little_qword(0x0807060504030201LL));
It works very well. But my questions come, why do we need use some data types like boost::uint16_t, boost::uint32_t here? Can I use unsigned long or unsigned int here?
And if I want to parse double or float data type, what boost data type should I use? And please tell me where is boost define the above these types?
| Types like uint16_t or uint32_t exist so that you can declare a variable to have a specific bit width. You can't do this with normal types like "long" because they are different sizes on different architectures and/or implementations. The afore mentioned types are normally derived by through preprocessor calculations resulting in typedefs to the implementation/architectural specific type to get that specific size.
|
2,805,270 | 2,805,452 | "Invalid Handle Object" when plotting 2 figures Matlab | I'm having a difficult time understanding the paradigm of Matlab classes vs compared to c++. I wrote code the other day, and I thought it should work. It did not... until I added
<handle
after the classdef.
So I have two classes, landmarks and robot, both are called from within the simulation class. This is the main loop of obj.simulation.animate() and it works, until I try to plot two things at once.
DATA.path is a record of all the places a robot has been on the map, and it's updated every time the position is updated.
When I try to plot it, by uncommenting the two marked lines below, I get this error:
??? Error using ==> set
Invalid handle object.
Error in ==> simulation>simulation.animate at 45
set(l.lm,'XData',obj.landmarks.apparentPositions(:,1),'YData',obj.landmarks.apparentPositions(:,2));
%INITIALIZE GLOBALS
global DATA XX
XX = [obj.robot.x ; obj.robot.y];
DATA.i=1;
DATA.path = XX;
%Setup Plots
fig=figure;
xlabel('meters'), ylabel('meters')
set(fig, 'name', 'Phil''s AWESOME 80''s Robot Simulator')
xymax = obj.landmarks.mapSize*3;
xymin = -(obj.landmarks.mapSize*3);
l.lm=scatter([0],[0],'b+');
%"UNCOMMENT ME"l.pth= plot(0,0,'k.','markersize',2,'erasemode','background'); % vehicle path
axis([xymin xymax xymin xymax]);
%Simulation Loop
for n = 1:720,
%Calculate and Set Heading/Location
XX = [obj.robot.x;obj.robot.y];
store_data(XX);
if n == 120,
DATA.path
end
%Update Position
headingChange = navigate(n);
obj.robot.updatePosition(headingChange);
obj.landmarks.updatePerspective(obj.robot.heading, obj.robot.x, obj.robot.y);
%Animate
%"UNCOMMENT ME" set(l.pth, 'xdata', DATA.path(1,1:DATA.i), 'ydata', DATA.path(2,1:DATA.i));
set(l.lm,'XData',obj.landmarks.apparentPositions(:,1),'YData',obj.landmarks.apparentPositions(:,2));
rectangle('Position',[-2,-2,4,4]);
drawnow
This is the classdef for landmarks
classdef landmarks <handle
properties
fixedPositions; %# positions in a fixed coordinate system. [ x, y ]
mapSize; %Map Size. Value is side of square
x;
y;
heading;
headingChange;
end
properties (Dependent)
apparentPositions
end
methods
function obj = landmarks(mapSize, numberOfTrees)
obj.mapSize = mapSize;
obj.fixedPositions = obj.mapSize * rand([numberOfTrees, 2]) .* sign(rand([numberOfTrees, 2]) - 0.5);
end
function apparent = get.apparentPositions(obj)
currentPosition = [obj.x ; obj.y];
apparent = bsxfun(@minus,(obj.fixedPositions)',currentPosition)';
apparent = ([cosd(obj.heading) -sind(obj.heading) ; sind(obj.heading) cosd(obj.heading)] * (apparent)')';
end
function updatePerspective(obj,tempHeading,tempX,tempY)
obj.heading = tempHeading;
obj.x = tempX;
obj.y = tempY;
end
end
end
To me, this is how I understand things. I created a figure l.lm that has about 100 xy points. I can rotate this figure by using
set(l.lm,'XData',obj.landmarks.apparentPositions(:,1),'YData',obj.landmarks.apparentPositions(:,2));
When I do that, things work. When I try to plot a second group of XY points, stored in DATA.path, it craps out and I can't figure out why.
I need to plot the robots path, stored in DATA.path, AND the landmarks positions. Ideas on how to do that?
Jonas:
I'm not saying you're wrong, because I don't know the answer, but I have code from another application that plots this way without calling axes('NextPlot','add');
if dtsum==0 & ~isempty(z) % plots related to observations
set(h.xf, 'xdata', XX(4:2:end), 'ydata', XX(5:2:end))
plines= make_laser_lines (z,XX(1:3));
set(h.obs, 'xdata', plines(1,:), 'ydata', plines(2,:))
pfcov= make_feature_covariance_ellipses(XX,PX);
set(h.fcov, 'xdata', pfcov(1,:), 'ydata', pfcov(2,:))
end
drawnow
The above works on the other code, but not mine. I'll try implementing your suggestion and let you know.
| When you call plot multiple times on the same figure, the previous plot is by default erased, and the handle to the previous plot points to nothing. Thus the error.
To fix this, you need to set the NextPlot property of the axes to add. You can do this by calling hold on (that's what you'd do if you were plotting from command line), or you can write
fig=figure;
%# create a set of axes where additional plots will be added on top of each other
%# without erasing
axes('NextPlot','add');
If you want, you can store the axes handle as well, and use plot(ah,x,y,...) to make sure that you plot into the right set of axes and not somewhere strange if you happen to click on a different figure window between the time the figure is opened and the plot command is issued.
|
2,805,457 | 2,805,479 | C++ : Swapping template class elements of different types? | template< class T1, class T2 >
class Pair {
T1 first;
T2 second;
};
I'm being asked to write a swap() method so that the first element becomes the second and the second the first. I have:
Pair<T2,T1> swap() {
return Pair<T2,T1>(second, first);
}
But this returns a new object rather than swapping, where I think it needs to be a void method that changes its own data members. Is this possible to do since T1 and T2 are potentially different class types? In other words I can't simply set temp=first, first=second, second=temp because it would try to convert them to different types. I'm not sure why you would potentially want to have a template object that changes order of its types as it seems that would cause confusion but that appears to be what I'm being asked to do.
Edit: Thank you all for answering! Pretty much as I thought, swapping in place obviously does not make any sense, the request for the swap() function was quite ambiguous.
| You cannot swap in-place, since T1 and T2 need not be of the same type. Pair<T1,T2> is a different type than Pair<T2,T1>. You have to return an object of a different type than the original one, so that has to be a new object.
What I'd do is this:
template< class T1, class T2 >
Pair<T2,T1> swap(const Pair<T1,T2>& pair) {
return Pair<T2,T1>(pair.second, pair.first);
}
(There's no reason to make this a member of your Pair template.)
You could, however, add an overload for when T1 and T2 are of the same type:
template< class T >
Pair<T,T>& swap(Pair<T,T>& pair) {
using std::swap;
swap(pair.first, pair.second);
return pair;
}
But this, as Dennis mentioned in his comment, might be indeed very confusing.
Another idea is to define a converting constructor for your Pair template, so that implicitly convertible types can be swapped:
template< class T1, class T2 >
class Pair {
T1 first;
T2 second;
template< class A1, class A2 >
Pair(const A1& a1, const A2& a2) : first(a1), second (a2) {}
};
Then you can swap like this:
Pair<int,double> p1(42,47.11);
Pair<double,int> p2(p1.second,p1.first);
But note that this also supports other, probably unwanted implicit conversions:
Pair<char,float> p3(p1.second, p1.first); // narrowing!
|
2,805,542 | 2,805,685 | Installing a cpp library on linux | I'm trying to install a library (libspopc), but, when I run the make command, I get the errors:
strip libspopc.a libspopc.so
strip: 'libspopc.a': No such file
strip: 'libspopc.so': No such file
make: *** [install] Error
Working under the assumption that every version of the library I've tried isn't actually missing two of its files, what could cause this? I am running it as su, as instructed, if it's relevant.
| While this question is only remotely related to programming (seems more like something for superuser.com), on linux you should whenever you can use the package manager of your system. In most cases, it let's you fetch the files as binaries (thus avoiding possible compilation frustrations), keeps your system clean and is (most importantly for me) easy to remove again. Oh yeah, and it helps you keep the library up to date.
Try looking in your package manager! If it's a fairly popular library, it's probably in your package manager's repositiories!
At least I know it's in mine!
$ bauerbill --aur -Ss libspopc
AUR/libspopc 0.9-1
A simple pop3 mail client library
|
2,805,698 | 2,805,806 | Do While loop breaks after incorrect input? | I am trying to have a loop continue to prompt the user for an option. When I get a string of characters instead of an int, the program loops indefinitely. I have tried setting the variable result to NULL, clearing the input stream, and have enclosed in try{}catch blocks (not in this example). Can anyone explain to me why this is?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int menu(string question, vector<string> options)
{
int result;
cout << question << endl;
for(int i = 0; i < options.size(); i++)
{
cout << '[' << i << ']' << options[i] << endl;
}
bool ans = false;
do
{
cin >> result;
cin.ignore(1000, 10);
if (result < options.size() )
{
ans = true;
}
else
{
cout << "You must enter a valid option." << endl;
result = NULL;
ans = false;
}
}
while(!ans);
return result;
}
int main()
{
string menuQuestion = "Welcome to my game. What would you like to do?";
vector<string> mainMenu;
mainMenu.push_back("Play Game");
mainMenu.push_back("Load Game");
mainMenu.push_back("About");
mainMenu.push_back("Exit");
int result = menu(menuQuestion, mainMenu);
cout << "You entered: " << result << endl;
return 0;
}
| It looks like there is a random element here, since result is not initialized.
In any case, test cin directly
if ( cin && result < options.size() )
and reset it upon invalid input so it will again perform I/O operations
result = 0; // inappropriate to initialize an integer with NULL
cin.clear(); // reset cin to work again
cin.ignore(1000, '\n'); // use \n instead of ASCII code
|
2,805,744 | 2,805,823 | CreateTimerQueue for linux | Anyone know if there is any function similar to CreateTimerQueue on linux? Or do I have to make my own.
| You want to use timer_gettime and timer_settime. Lookup the page on timer_create to get a nice example
|
2,805,802 | 2,805,839 | boost.threads Singleton initialization | Is there preferred way to initialize (lazily) singleton data when using multiple threads from boost.threads?
Thanks.
| Check out the call_once free function in Boost.Thread.
|
2,805,841 | 2,805,891 | Implementing PyMyType_Check methods with Python C API? | All the Python-provided types have a check method (i.e., PyList_Check) that allows you to check if an arbitrary PyObject* is actually a specific type.
How can I implement this for my own types? I haven't found anything good online for this, though it seems like a pretty normal thing to want to do.
Also, maybe I'm just terrible at looking through large source trees, but I cannot for the life of me find the implementation of PyList_Check or any of it's companions in the Python (2.5) source.
| That's because they're macros that use deep magic. Save yourself a bit of headache and use PyObject_IsInstance() instead.
|
2,805,896 | 2,806,384 | What alignment does HeapAlloc use | I'm developing a general purpose library which uses Win32's HeapAlloc
MSDN doesn't mention alignment guarantees for Win32's HeapAlloc, but I really need to know what alignment it uses, so I can avoid excessive padding.
On my machine (vista, x86), all allocations are aligned at 8 bytes. Is this true for other platforms as well?
| The HeapAlloc function does not specify the alignment guarantees in the MSDN page, but I'm inclined to think that it should have the same guarantees of GlobalAlloc, which is guaranteed to return memory 8-byte aligned (although relying on undocumented features is evil); after all, it's explicitly said that Global/LocalAlloc are just wrappers around HeapAlloc (although they may discard the first n bytes to get aligned memory - but I think that it's very unlikely).
If you really want to be sure, just use GlobalAlloc, or even VirtualAlloc, whose granularity is the page granularity, which is usually 4 KB (IIRC), but in this case for small allocations you'll waste a lot of memory.
By the way, if you use C++ new operator, you are guaranteed to get memory aligned correctly for the type you specified: this could be the way to go.
|
2,806,046 | 2,862,380 | Linking LLVM JIT Code to Static LLVM Libraries? | I'm in the process of implementing a cross-platform (Mac OS X, Windows, and Linux) application which will do lots of CPU intensive analysis of financial data. The bulk of the analysis engine will be written in C++ for speed reasons, with a user-accessible scripting engine interfacing with the C++ testing engine. I want to write several scripting front-ends over time to emulate other popular software with existing large user bases. The first front will be a VisualBasic-like scripting language.
I'm thinking that LLVM would be perfect for my needs. Performance is very important because of the sheer amount of data; it can take hours or days to run a single run of tests to get an answer. I believe that using LLVM will also allow me to use a single back-end solution while I implement different front-ends for different flavors of the scripting language over time.
The testing engine itself will be separated from the interface and testing will even take place in a separate process with progress and results being reported to the testing management interface. Tests will consist of scripting code integrated with the testing engine code.
In a previous implementation of a similar commercial testing system I wrote, I built a fast interpreter which easily interfaced with the testing library because it was written in C++ and linked directly to the testing engine library. Callbacks from scripting code to testing library objects involved translating between the formats with significant overhead.
I'm imagining that with LLVM, I could implement the callbacks into C++ directly so that I could make the scripting code work almost as if it had been written in C++. Likewise, if all the code was compiled to LLVM byte-code format, it seems like the LLVM optimizers could optimize across the boundaries between the scripting language and the testing engine code that was written in C++.
I don't want to have to compile the testing engine every time. Ideally, I'd like to JIT compile only the scripting code. For small tests, I'd skip some optimization passes, while for large tests, I'd perform full optimizations during the link.
So is this possible? Can I precompile the testing engine to a .o object file or .a library file and then link in the scripting code using the JIT?
Finally, ideally, I'd like to have the scripting code implement specific methods as subclasses for a specific C++ class. So the C++ testing engine would only see C++ objects while the JIT setup code compiled scripting code that implemented some of the methods for the objects. It seems that if I used the right name mangling algorithm it would be relatively easy to set up the LLVM generation for the scripting language to look like a C++ method call which could then be linked into the testing engine.
Thus the linking stage would go in two directions, calls from the scripting language into the testing engine objects to retrieve pricing information and test state information and calls from the testing engine of methods of some particular C++ objects where the code was supplied not from C++ but from the scripting language.
In summary:
1) Can I link in precompiled (either .bc, .o, or .a) files as part of the JIT compilation, code-generation process?
2) Can I link in code using the process in 1) above in such a way that I am able to create code that acts as if it was all written in C++?
|
Yes we can! Depending on the version of LLVM you use there are different API calls. you will need llvm::getBitcodeModuleProvider on 2.5.
The easiest way to call C++ functions is to create a function (llvm::Function::Create) using the flag llvm::Function::ExternalLinkage and then addGlobalMapping to make it point to your C++ function.
|
2,806,104 | 2,806,146 | Does fwrite buffer the output? | In C++, there is an std::fwrite() which writes a buffer to a file on disk.
Can you please tell me if there is any buffer inside that fwrite implementation?
i.e. if I call fwrite() multiple times (say 10 times), does it actually invoke file I/O 10 different times?
I am asking this for Ubuntu 10.04 environment.
| Yes, it is buffered. The size of the buffer is defined by BUFSIZ. (Thanks @ladenedge.) Ten sufficiently large operations will result in ten system calls.
You are also allowed to set your own buffer using std::setbuf and std::setvbuf.
The functions in cstdio are inherited from C. The preferred interface in C++ is fstream and filebuf.
|
2,806,160 | 2,806,205 | How do I determine which C/C++ compiler to use? | I am trying to figure out which C/C++ compiler to use. I found this list of C/C++ compilers at Wikipedia:
http://en.wikipedia.org/wiki/List_of_compilers#C.2FC.2B.2B_compilers
I am fairly certain that I want to go with an open source compiler. I feel that if it is open source then it will be a more complete compiler since many programmer perspectives are used to make it better. Please tell me if you disagree.
I should mention that I plan on learning C/C++ mainly to program 2D/3D game applications that will be compatible with Windows, Linux, MAC and iPhone operating systems. I am currently using Windows Vista x64 OS.
| First of all, IMHO as a beginner your development environment (IDE) matters a lot more than the compiler.
I think that people place too much emphasis on compiler choice early on. While it is not Java, C++ is meant to be portable.
If the program you're writing only works with specific compilers, you're probably doing the wrong thing or can work a little on making it more portable.
If you get to a point where compiler choice makes a significant performance impact for you, then you've already perfected everything else in your program and you're in a good state and you are also quite advanced in your abilities. We used to teach the differences between compilers at fairly advanced stages in the CS curriculum.
If you use a UNIX based machine (Linux, Mac, actual Linux), then pretty much GNU (g++) is the way to go and is fairly much standard. If it's good enough to compile your OS, it's probably good enough for you. On a mac you can use XCode as your IDE, and it interfaces well with g++. On Linux some people prefer command line tools, though you might like the Eclipse C++ support, it is much better today than it was 3-4 years ago.
Things on Windows are trickier. If you can afford it, have access to, or are eligible for one of the free editions (e.g., via a school), I think the Microsoft Visual C++ Environments (or whatever they are called now) are pretty good for learning and they are used in production. I think there's actually a lightweight visual studio now with an emphasis on C++ that could be a good start. If you don't, you can probably find a distribution of Eclipse that is specific for C++ and includes an implementation of the GNU compilers.
|
2,806,370 | 2,806,411 | C++ std::vector insert segfault | I am writing a test program to understand vector's better. In one of the scenarios, I am trying to insert a value into the vector at a specified position. The code compiles clean. However, on execution, it is throwing a Segmentation Fault from the v8.insert(..) line (see code below). I am confused. Can somebody point me to what is wrong in my code?
#define UNIT_TEST(x) assert(x)
#define ENSURE(x) assert(x)
#include <vector>
typedef std::vector< int > intVector;
typedef std::vector< int >::iterator intVectorIterator;
typedef std::vector< int >::const_iterator intVectorConstIterator;
intVectorIterator find( intVector v, int key );
void test_insert();
intVectorIterator
find( intVector v, int key )
{
for( intVectorIterator it = v.begin(); it != v.end(); ++it )
{
if( *it == key )
{
return it;
}
}
return v.end();
}
void
test_insert()
{
const int values[] = {10, 20, 30, 40, 50};
const size_t valuesLength = sizeof( values ) / sizeof( values[ 0 ] );
size_t index = 0;
const int insertValue = 5;
intVector v8;
for( index = 0; index < valuesLength; ++index )
{
v8.push_back( values[ index ] );
}
ENSURE( v8.size() == valuesLength );
for( index = 0; index < valuesLength; ++index )
{
printf( "index = %u\n", index );
intVectorIterator it = find( v8, values[ index ] );
ENSURE( it != v8.end() );
ENSURE( *it == values[ index ] );
// intVectorIterator itToInsertedItem =
v8.insert( it, insertValue ); // line 51
// UNIT_TEST( *itToInsertedItem == insertValue );
}
}
int main()
{
test_insert();
return 0;
}
$ ./a.out
index = 0
Segmentation Fault (core dumped)
(gdb) bt
#0 0xff3a03ec in memmove () from /platform/SUNW,T5140/lib/libc_psr.so.1
#1 0x00012064 in std::__copy_move_backward<false, true, std::random_access_iterator_tag>::__copy_move_b<int> (__first=0x23e48, __last=0x23450, __result=0x23454)
at /local/gcc/4.4.1/lib/gcc/sparc-sun-solaris2.10/4.4.1/../../../../include/c++/4.4.1/bits/stl_algobase.h:575
#2 0x00011f08 in std::__copy_move_backward_a<false, int*, int*> (__first=0x23e48, __last=0x23450, __result=0x23454)
at /local/gcc/4.4.1/lib/gcc/sparc-sun-solaris2.10/4.4.1/../../../../include/c++/4.4.1/bits/stl_algobase.h:595
#3 0x00011d00 in std::__copy_move_backward_a2<false, int*, int*> (__first=0x23e48, __last=0x23450, __result=0x23454)
at /local/gcc/4.4.1/lib/gcc/sparc-sun-solaris2.10/4.4.1/../../../../include/c++/4.4.1/bits/stl_algobase.h:605
#4 0x000119b8 in std::copy_backward<int*, int*> (__first=0x23e48, __last=0x23450, __result=0x23454) at /local/gcc/4.4.1/lib/gcc/sparc-sun-solaris2.10/4.4.1/../../../../include/c++/4.4.1/bits/stl_algobase.h:640
#5 0x000113ac in std::vector<int, std::allocator<int> >::_M_insert_aux (this=0xffbfeba0, __position=..., __x=@0xffbfebac)
at /local/gcc/4.4.1/lib/gcc/sparc-sun-solaris2.10/4.4.1/../../../../include/c++/4.4.1/bits/vector.tcc:308
#6 0x00011120 in std::vector<int, std::allocator<int> >::insert (this=0xffbfeba0, __position=..., __x=@0xffbfebac)
at /local/gcc/4.4.1/lib/gcc/sparc-sun-solaris2.10/4.4.1/../../../../include/c++/4.4.1/bits/vector.tcc:126
#7 0x00010bc0 in test_insert () at vector_insert_test.cpp:51
#8 0x00010c48 in main () at vector_insert_test.cpp:58
(gdb) q
| You're passing v8 by value to your find function. The iterator returned thus points into the copy of the vector, which is out of scope after the find call returns. Try passing by (const) reference, or better yet, just use std::find.
|
2,806,769 | 2,806,809 | Esoteric C++ operators | What is the purpose of the following esoteric C++ operators?
Pointer to member
::*
Bind pointer to member by pointer
->*
Bind pointer to member by reference
.*
(reference)
| A pointer to a member allows you to have a pointer that is relative to a specific class.
So, let's say you have a contact class with multiple phone numbers.
class contact
{
phonenumber office;
phonenumber home;
phonenumber cell;
};
The idea is if you have an algorithm that needs to use a phone number but the decision of which phone number should be done outside the algorithm, pointers to member solve the problem:
void robocall(phonenumber contact::*number, ...);
Now the caller of robocall can decide which type of phonenumber to use:
robocall(&contact::home, ...); // call home numbers
robocall(&contact::office, ...); // call office number
.* and ->* come into play once you have a pointer. So inside robocall, you would do:
contact c = ...;
c.*number; // gets the appropriate phone number of the object
or:
contact *pc = ...;
pc->*number;
|
2,806,801 | 2,806,838 | Do bit operations cause programs to run slower? | I'm dealing with a problem which needs to work with a lot of data. Currently its values are represented as an unsigned int. I know that real values do not exceed a limit of 1000.
Questions
I can use unsigned short to store it. An upside to this is that it'll use less storage space to store the value. Will performance suffer?
If I decided to store data as short but all the calling functions use int, it's recognized that I need to convert between these datatypes when storing or extracting values. Will performance suffer? Will the loss in performance be dramatic?
If I decided to not use short but just 10 bits packed into an array of unsigned int. What will happen in this case comparing with previous ones?
| This all depends on architecture. Bit-fields are generally slower, but if you are able to to significantly cut down memory usage with them, you can even gain in performance due to better CPU caching and similar things. Likewise with short (though it is not dramatic in any case).
The best way is to make your source code able to switch representation easily (at compilation time, of course). Then you will be able to test and profile different implementations in your specific circumstances just by, say, changing one #define.
Also, don't forget about premature optimization rule. Make it work first. If it turns out to be slow/not fast enough, only then try to speed up.
|
2,806,922 | 2,807,047 | MySQL, C++: Retrieving auto-increment ID | I have a table with an auto-incrementing ID. After inserting a new row, I would like to retrieve the new ID.
I found an article that used the MySQL function LAST_INSERT_ID(). The article says to create a new query and submit it.
I'm using MySQL Connector C++, Windows XP and Vista, and Visual Studio 9.
Here are my questions:
Is there an API, for the connector,
that will fetch the ID out of the
record?
Does the result set, after an
insert/append, contain the new ID?
The LAST_INSERT_ID is MySQL
specific. Is there an SQL
standard method for obtaining the new ID?
|
It doesn't look like it - in the C API, you have mysql_insert_id() for this, but it doesn't appear to be used in the C++ connector, nor does it appear to implement the getGeneratedKeys method from the JDBC API (However, I don't use this connector myself, so I may be missing something obvious...).
No, there is no result set from an INSERT.
No. Supposedly, DB2 is the only one that follows what the SQL standard says about auto-generated keys; everyone else does it differently (from both the standard and from each other).
|
2,806,939 | 2,807,506 | visual c++ 2010 link against older runtime? | Sorry if this has been asked.
Just like I can select in C# project that I want it to build for .NET 2.0 runtime, is it possible for native c++ project to be built against older CRT, let's say one from visual studio 2005?
I would like this because I have external SDK that was build with VS2005, but I'd like to use newer IDE.
| You can build against 2005 and 2008 (think also 2003) as long as they are installed along side vis 2010.
You will need to change The platform Tool set for each project to reflect the one you want to build against (properties -> general -> platform toolset) with v100 being 2010, v90 2008, v80 2005 and so on
|
2,806,957 | 2,813,379 | insufficient buffer when call DocumentProperties, also, global unlock wouldn't unlock | please see comments inline
bool res = false;
DWORD dwNeeded = DocumentPropertiesW(NULL, m_currPrinterHandle, (LPWSTR) m_currPrinterName.c_str(), NULL, NULL, 0);
if (m_devmode_buf)
{
GlobalFree(m_devmode_buf);
}
m_devmode_buf = GlobalAlloc(GPTR, dwNeeded);
GetLastError(); // = 0;
if (m_devmode_buf)
{
LPDEVMODEW devmode_buf = (LPDEVMODEW) GlobalLock(m_devmode_buf);
GetLastError(); // = 0
if (devmode_buf)
{
if (devmode_buf)
{
lala = DocumentPropertiesW(NULL, m_currPrinterHandle, (LPWSTR) m_currPrinterName.c_str(), devmode_buf, NULL, DM_OUT_BUFFER);
if (lala == IDOK)
{
res = true;
}
GetLastError(); // = 122. insufficient buffer here. why????
}
UInt32 res1 = GlobalUnlock(m_devmode_buf); // res1 is 1. should be 0
res2 = GetLastError(); // = 0
if (!(res1 == 0 && (res2 == ERROR_NOT_LOCKED || res2 == NO_ERROR)))
{
//res = false;
}
}
}
| If the second call to DocumentProperties() is returning 1 (i.e. IDOK) then it is not failing, thus the value of GetLastError() is meaningless. It is probably an expected condition that is raised and handled inside of DocumentProperties(). The convention of using GetLastError() is that you only set it on failure; you don't usually clear it on success. It is up to the documentation of each individual function to explain how errors are returned. The documentation for DocumentProperties() doesn't even mention GetLastError(), so checking it at all might be meaningless (though usually it is safe to assume that all Win32 functions return errors via GetLastError()).
|
2,807,013 | 2,807,086 | buffer size for socket connection in c++ | I'm trying to build a basic POP3 mail client in C/++, but I've run into a bit of an issue. Since you have to define the buffer size when building the program, but a message can be arbitrarily large, how do you, say, get the mail server to send it to you in parts? And if this isn't the correct means of solving the problem, what is?
And while I'm here, can anyone confirm for me that RFC 2822 is still the current document defining email layout?
Thanks
| Since most email is done using TCP/IP, you can read one byte at a time if you really want to. The underlying implementation will buffer the stream for you. It is received approximately 1,400 bytes at a time off of the network. Generally, I using either std::vector<char> or std::string as a buffer and read one byte at a time and push_back on to the buffer in a select() loop with a short timeout.
I can't remember if POP includes a maximum line length or not. If it does, then you can use that as your buffer size and call reserve() on the vector. That will minimize memory reallocations and copies that might otherwise occur.
As for which standard is most recent, https://www.rfc-editor.org/rfc/rfc2822 says that it was obsoleted by https://www.rfc-editor.org/rfc/rfc5322. I usually check https://www.rfc-editor.org/rfc/rfcXXXX where XXXX is the RFC number. If it is obsolete, then there is a link to the most appropriate RFC at the top.
And as a final mention, don't build a POP client for deployment without a good reason too. There are a lot of gotcha's buried in the various RFCs. It is a really good learning experience though.
|
2,807,048 | 2,807,063 | C++ vector of strings, pointers to functions, and the resulting frustration | So I am a first year computer science student, for on of my final projects, I need to write a program that takes a vector of strings, and applies various functions to these. Unfortunately, I am really confused on how to use pointer to pass the vector from function to function. Below is some sample code to give an idea of what I am talking about. I also get an error message when I try to deference any pointer.
thanks.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
using namespace std;
vector<string>::pointer function_1(vector<string>::pointer ptr);
void function_2(vector<string>::pointer ptr);
int main()
{
vector<string>::pointer ptr;
vector<string> svector;
ptr = &svector[0];
function_1(ptr);
function_2(ptr);
}
vector<string>::pointer function_1(vector<string>::pointer ptr)
{
string line;
for(int i = 0; i < 10; i++)
{
cout << "enter some input ! \n"; // i need to be able to pass a reference of the vector
getline(cin, line); // through various functions, and have the results
*ptr.pushback(line); // reflectedin main(). But I cannot use member functions
} // of vector with a deferenced pointer.
return(ptr);
}
void function_2(vector<string>::pointer ptr)
{
for(int i = 0; i < 10; i++)
{
cout << *ptr[i] << endl;
}
}
| std::vector<T>::pointer is not std::vector<T>*, it is T*.
Don't worry about using pointers; just use references, e.g.,
void function_1(std::vector<string>& vec) { /* ... */ }
function_2, which does not modify the vector, should take a const reference:
void function_2(const std::vector<string>& vec) { /* ... */ }
|
2,807,055 | 2,986,029 | Reading from serial port with Boost Asio | I'm want to check for incoming data packages on the serial port, using boost.asio. Each data packet will start with a header that is one byte long, and will specify what type of the message has been sent. Each different type of message has its own length. The function I want to write should listen for new incoming messages continually, and when it finds one it should read it, and call some other function to parse it. My current code is as follows:
void check_for_incoming_messages()
{
boost::asio::streambuf response;
boost::system::error_code error;
std::string s1, s2;
if (boost::asio::read(port, response, boost::asio::transfer_at_least(0), error)) {
s1 = streambuf_to_string(response);
int msg_code = s1[0];
if (msg_code < 0 || msg_code >= NUM_MESSAGES) {
// Handle error, invalid message header
}
if (boost::asio::read(port, response, boost::asio::transfer_at_least(message_lengths[msg_code]-s1.length()), error)) {
s2 = streambuf_to_string(response);
// Handle the content of s1 and s2
}
else if (error != boost::asio::error::eof) {
throw boost::system::system_error(error);
}
}
else if (error != boost::asio::error::eof) {
throw boost::system::system_error(error);
}
}
Is boost::asio::streambuf the right tool to use? And how do I extract the data from it so I can parse the message? I also want to know if I need to have a separate thread which only calls this function, so that it gets called more often. Should I be worried about losing data between two calls to the function because of high traffic and serial port's buffer running out? I'm using Qt's libraries for GUI and I don't really know how much time it takes to process all the events.
Edit: The interesting question is: how can I check if there is any incoming data at the serial port? If there is no incoming data, I don't want the function to block...
| This article is helpful in understanding how ASIO can be used asynchronously with serial ports:
https://gist.github.com/kaliatech/427d57cb1a8e9a8815894413be337cf9
UPDATE (2019-03):
The original article I had linked to is no longer available and is difficult to find even in Internet Archive. (Here is a snapshot.). There are now newer articles on using ASIO for serial I/O found easily by searching, but this older article is still very useful. I'm putting it in a public gist so that it doesn't get lost:
https://gist.github.com/kaliatech/427d57cb1a8e9a8815894413be337cf9
The code described in the article appears to have been copied here:
https://github.com/fedetft/serial-port
The author seems to have updated it for C++11. I believe the article was
originally written by fede.tft.
|
2,807,095 | 2,807,111 | C++: calling member functions within constructor? | The following code raises a runtime error:
#include <iostream>
#include <iterator>
#include <ext/slist>
class IntList : public __gnu_cxx::slist<int> {
public:
IntList() { tail_ = begin(); } // seems that there is a problem here
void append(const int node) { tail_ = insert_after(tail_, node); }
private:
iterator tail_;
};
int main() {
IntList list;
list.append(1);
list.append(2);
list.append(3);
for (IntList::iterator i = list.begin(); i != list.end(); ++i) {
std::cout << *i << " ";
}
return 0;
}
Seems that the problem is in the constructor IntList(). Is it because it calls the member function begin()?
| Looks like You are inserting after end();
In the body of the constructor
IntList() { tail_ = begin(); }
the base class is constructed and it's members can be called, but for an empty list, it should return end();
|
2,807,138 | 2,807,166 | can I access a struct inside of a struct without using the dot operator? | I have 2 structures that have 90% of their fields the same. I want to group those fields in a structure but I do not want to use the dot operator to access them. The reason is I already coded with the first structure and have just created the second one.
before:
typedef struct{
int a;
int b;
int c;
object1 name;
} str1;
typedef struct{
int a;
int b;
int c;
object2 name;
} str2;
now I would create a third struct:
typedef struct{
int a;
int b;
int c;
} str3;
and would change the str1 and atr2 to this:
typedef struct{
str3 str;
object1 name;
} str1;
typedef struct {
str3 str;
object2 name;
} str2;
Finally I would like to be able to access a,b and c by doing:
str1 myStruct;
myStruct.a;
myStruct.b;
myStruct.c;
and not:
myStruct.str.a;
myStruct.str.b;
myStruct.str.c;
Is there a way to do such a thing. The reason for doing this is I want keep the integrety of the data if chnges to the struct were to occur and to not repeat myself and not have to change my existing code and not have fields nested too deeply.
RESOLVED: thx for all your answers. The final way of doing it so that I could use auto-completion also was the following:
struct str11
{
int a;
int b;
int c;
};
typedef struct str22 : public str11
{
QString name;
}hi;
| Yes. Rather using a C-style of inheritance, using C++ style:
struct str3{
int a;
int b;
int c;
};
struct str2 : public str3{
object2 name;
};
|
2,807,293 | 2,807,302 | Resolving ambiguous this pointer in C++ | I'm trying to derive a new class from an old one. The base class declaration looks like this:
class Driver : public Plugin, public CmdObject
{
protected:
Driver();
public:
static Driver* GetInstance();
virtual Engine& GetEngine();
public:
// Plugin methods...
virtual bool InitPlugin (Mgr* pMgr);
virtual bool Open();
virtual bool Close();
// CmdObject
virtual bool ExecObjCmd(uint16 cmdID, uint16 nbParams, CommandParam *pParams, CmdChannelError& error);
Mgr *m_pMgr;
protected:
Services *m_pServices;
Engine m_Engine;
};
Its constructor looks like this:
Driver::Driver() :
YCmdObject("Driver", (CmdObjectType)100, true),
m_Engine("MyEngine")
{
Services *m_pServices = NULL;
Mgr *m_pMgr = NULL;
}
So when I created my derived class, I first tried to simply inherit from the base class:
class NewDriver : public Driver
and copy the constructor:
NewDriver::NewDriver() :
CmdObject("NewDriver", (EYCmdObjectType)100, true),
m_Engine("MyNewEngine")
{
Services *m_pServices = NULL;
Mgr *m_pMgr = NULL;
}
The compiler (VisualDSP++ 5.0 from Analog Devices) didn't like this:
".\NewDriver.cpp", line 10: cc0293: error: indirect nonvirtual base
class is not allowed
CmdObject("NewDriver", (EYCmdObjectType)100, true),
That made sense, so I decided to directly inherit from Plugin and CmdObject. To avoid multiple inheritance ambiguity problems (so I thought), I used virtual inheritance:
class NewDriver : public Driver, public virtual Plugin, public virtual CmdObject
But then, in the implementation of a virtual method in NewDriver, I tried to call the Mgr::RegisterPlugin method that takes a Plugin*, and I got this:
".\NewDriver.cpp", line 89: cc0286: error: base class "Plugin" is
ambiguous
if (!m_pMgr->RegisterPlugin(this))
How is the this pointer ambiguous, and how do I resolve it?
Thanks,
--Paul
| If you derive from Driver, you don't have to call the constructors of Drivers bases explicitly:
class NewDriver : public Driver { /* ... */ };
NewDriver::NewDriver() : Driver() {}
The constructor of Driver then initializes its own bases, you don't have to and shouldn't do that directly.
If it should behave differently, let it take parameters:
class Driver : /* ... */ {
public:
Driver(const std::string& name /* , ... */)
: CmdObject(name /* , ... */)
{}
// ...
};
NewDriver::NewDriver() : Driver("NewDriver" /* , ... */) {}
|
2,807,492 | 2,807,501 | Can I prevent future developers from making an object constructable? | you have a class A, where you set ctor to be private, so a client can't call
"A a;"
to create obj on stack.
But someday another developer add a new ctor:
"A(int)"
and try to call "A a(1);" inside main(). So this will create a obj on stack. How do you prevent that?
| Nothing you can do to C++ source code can constrain the future behavior of other people with permission to modify the C++ source code. That other developer could delete the string 'private:' just as easily as they could add a public constructor with another signature. All you can do is carefully comment the reasons why this class shouldn't ever be allocated directly, and expect other developers to read and pay attention.
|
2,807,786 | 2,807,788 | where is std::cout windows in MacBook Pro? | I am using MacBook Pro Mac OS 10.5 with related version of XCode. I am new to this development environment. I am developing C++ console/terminal applications (File->New project, then from the list on the left "Command line utility", and on the right "C++ tool".).
When statement like std::cout executes, I think the output should be on the console/terminal/command line, but I can not find such output from XCode IDE. Appreciate if anyone could tell me how to find output of std::cout from XCode IDE?
thanks in advance,
George
| Choose Run => Console or press shift-command-R.
|
2,808,030 | 2,808,041 | subscript operator on pointers | If I have a pointer to an object that has an overloaded subscript operator ([]) why can't I do this:
MyClass *a = new MyClass();
a[1];
but have to do this instead:
MyClass *a = new MyClass();
(*a)[1];
| It's because you can't overload operators for a pointer type; you can only overload an operator where at least one of the parameters (operands) is of class type or enumeration type.
Thus, if you have a pointer to an object of some class type that overloads the subscript operator, you have to dereference that pointer in order to call its overloaded subscript operator.
In your example, a has type MyClass*; this is a pointer type, so the built-in operator[] for pointers is used. When you dereference the pointer and obtain a MyClass, you have a class-type object, so the overloaded operator[] is used.
|
2,808,216 | 2,808,241 | passing a class method as opposed to a function in std::sort | Within a class, I am trying to sort a vector, by passing a method of the same class. But it gives errors at the time of compilation. Can anyone tell what the problem is? Thank you!
it gives the following error:
argument of type bool (Sorter::)(D&, D&)' does not matchbool (Sorter::*)(D&, D&)'
I have also tried using sortBynumber(D const& d1, D const& d2)
#include<vector>
#include<stdio.h>
#include<iostream>
#include<algorithm>
class D {
public:
int getNumber();
D(int val);
~D(){};
private:
int num;
};
D::D(int val){
num = val;
};
int D::getNumber(){
return num;
};
class Sorter {
public:
void doSorting();
bool sortByNumber(D& d1, D& d2);
std::vector<D> vec_D;
Sorter();
~Sorter(){};
private:
int num;
};
Sorter::Sorter(){
int i;
for ( i = 0; i < 10; i++){
vec_D.push_back(D(i));
}
};
bool Sorter::sortByNumber(D& d1, D& d2){
return d1.getNumber() < d2.getNumber();
};
void Sorter::doSorting(){
std::sort(vec_D.begin(), vec_D.end(), this->sortByNumber);
};
int main(){
Sorter s;
s.doSorting();
std::cout << "\nPress RETURN to continue...";
std::cin.get();
return 0;
}
| Make Sorter::sortByNumber static. Since it doesn't reference any object members, you won't need to change anything else.
class Sorter {
public:
static bool sortByNumber(const D& d1, const D& d2);
...
};
// Note out-of-class definition does not repeat static
bool Sorter::sortByNumber(const D& d1, const D& d2)
{
...
}
You should also use const references as sortByNumber should not be modifying the objects.
|
2,808,324 | 2,808,340 | What trick does Java use to avoid spaces in >>? | In the Java Generic Book, while contrasting the difference between C++ Templates and Java Generic says:
In C++, a problem arises because >>
without the space denotes the
right-shift operator. Java fixes the
problem by a trick in the grammar.)
What is this trick?
| This is actually being fixed in C++ in the next version. There really isn't much of a trick; if you encounter >> while in the process of parsing a generic or template where instead you expected >, then you already have enough information to generate an error message. And, if you have enough information to generate an error message, you also have enough information to interpret >> as two separate tokens: > followed by >.
|
2,808,437 | 2,808,638 | how to implement a sparse_vector class | I am implementing a templated sparse_vector class. It's like a vector, but it only stores elements that are different from their default constructed value.
So, sparse_vector would store the lazily-sorted index-value pairs for all indices whose value is not T().
I am basing my implementation on existing sparse vectors in numeric libraries-- though mine will handle non-numeric types T as well. I looked at boost::numeric::ublas::coordinate_vector and eigen::SparseVector.
Both store:
size_t* indices_; // a dynamic array
T* values_; // a dynamic array
int size_;
int capacity_;
Why don't they simply use
vector<pair<size_t, T>> data_;
My main question is what are the pros and cons of both systems, and which is ultimately better?
The vector of pairs manages size_ and capacity_ for you, and simplifies the accompanying iterator classes; it also has one memory block instead of two, so it incurs half the reallocations, and might have better locality of reference.
The other solution might search more quickly since the cache lines fill up with only index data during a search. There might also be some alignment advantages if T is an 8-byte type?
It seems to me that vector of pairs is the better solution, yet both containers chose the other solution. Why?
| Effectively, it seems that they reinvented the wheel (so to speak).
I would personally consider 2 libraries for your need:
Loki, for Loki::AssocVector -> the interface of a map implemented over a vector (which is what you wish to do)
Boost.Iterator, for its iterator_adaptor class. Makes it very easy to implement a new container by Composition.
As a remark, I would note that you may wish to be a little more generic that values different from the T() because this impose T to be DefaultConstructible. You could provide a constructor which takes a T const&. When writing a generic container it is good to try and reduce the necessary requirements as much as possible (as long as it does not hurt performance).
Also, I would remind you that the idea of using a vector for storage is very good for a little number of values, but you might wish to change the underlying container toward a classic map or unordered_map if the number of values grows. It could be worth profiling/timing. Note that the STL offer this ability with the Container Adapters like stack, even though it could make implementation slightly harder.
Have fun.
|
2,808,617 | 2,808,734 | Difference between Locks, Mutex and Critical Sections | There is an existing question regarding difference between Mutex and Critical section but it does not deal with Locks also.
So i want to know whether Critical sections can be used for thread synchronisation between processes.
Also what is meant by signalled states and non-signalled states
| In Windows critical sections are (mostly) implemented in user mode, and a mutex will switch context to kernel mode (which is slow). If a thread terminates while owning a mutex, the mutex is said to be abandoned. The state of the mutex is set to signaled, and the next waiting thread gets ownership. In the same situation with a critical section all other threads will remain blocked. Critical sections cannot be named so you cannot use them to synchronize several processes.
|
2,808,960 | 2,809,619 | C++ imitating ls like commands | How to implement the ls "filename_[0-5][3-4]?" like class? The result I would like to store in the vector.
Currently I am using system() which is calling ls, but this is not portable under MS.
thanks,
Arman.
| The following program lists files in the current directory whose name matches the regular expression filename_[0-5][34]:
#include <boost/filesystem.hpp>
#include <boost/regex.hpp> // also functional,iostream,iterator,string
namespace bfs = boost::filesystem;
struct match : public std::unary_function<bfs::directory_entry,bool> {
bool operator()(const bfs::directory_entry& d) const {
const std::string pat("filename_[0-5][34]");
std::string fn(d.filename());
return boost::regex_match(fn.begin(), fn.end(), boost::regex(pat));
}
};
int main(int argc, char* argv[])
{
transform_if(bfs::directory_iterator("."), bfs::directory_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"),
match(),
mem_fun_ref(&bfs::directory_entry::filename));
return 0;
}
I omitted the definition of transform_if() for brevity. It isn't a standard function but it should be straightforward to implement.
|
2,809,014 | 2,809,038 | Why does this C++ code-snippet segmentation fault? | #include <iostream>
using namespace std;
int recur(int x) {
1 and recur(--x);
cout << x;
return x;
}
int main() {
recur(10);
return 0;
}
| 1 and recur(--x);
is equivalent to
recur(--x);
Clearly you are making infinite recursive calls which leads to stack overflow followed by segmentation fault.
I guess you meant
x and recur(--x);
which makes the recursive call only when x is non-zero.
|
2,809,127 | 2,812,847 | How do I connect from an XPCOM object to a GStreamer plugin in a Songbird addon? | I am writing a Songbird addon, with three parts: XUL (javascript), a GStreamer filter and an XPCOM addon.
I am interested in accessing the GStreamer layer from my XPCOM component. If anyone knows any resources on how to do that I'd be grateful.
Specifically, I need documentation or examples on accessing the GStreamer functionality from within my addon (building a GST pipeline and running a file through it, from my XPCOM component (C++).
Thanks :)
| A few months ago I created a XULRunner application for recording live camera and audio streams. It was based on GStreamer via an XPCOM component. I got my inspiration from the GStreamer code.
However, you want to access the GStreamer functionality from Songbird. I'm not familiar with that route. If I were you I would start with looking at the addons-api documentation.
If StackOverflow isn't very responsive you can always try the songbird-dev mailing list, or the irc channel: irc://irc.mozilla.org/#songbird.
HTH
|
2,809,167 | 2,809,203 | c++ static int in a class - compile time error | I want to have a simple class i can call to get a unique number whilst the program is running - i can do the below with a dynamic allocation, and then just delete when not needed, but i still wanted to get a static version too.
Strangely, the code below (which is seemingly straightforward) throws some strange comiple errors (appended below).
Any ideas whats going on ? is this an incorrect use of static ?
class Id_gen {
private:
//adding static here stops the code from compiling:
static int curr_id;
public:
Id_gen() {curr_id = 1; cout<<"debug:constructed"; }
int get_id() {curr_id++; return curr_id; };
};
int main () {
Id_gen bGen;
cout << bGen.get_id() <<endl;
return 0;
}
running g++ (linux 64):
c++2.cpp:(.text._ZN6Id_genC1Ev[Id_gen::Id_gen()]+0xe): undefined reference to `Id_gen::curr_id'
/tmp/cc766N6p.o: In function `Id_gen::get_id()':
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0xa): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x13): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x19): undefined reference to `Id_gen::curr_id'
| Add the initialization/definition of the static member as:
int Id_gen::curr_id = 0;
after the class definition.
EDIT: As mentioned in the comment by @sbi : Initialization is optional, the linker requires the definition only.
|
2,809,309 | 2,812,260 | Can I use the [] operator in C++ to create virtual arrays | I have a large code base, originally C ported to C++ many years ago, that is operating on a number of large arrays of spatial data. These arrays contain structs representing point and triangle entities that represent surface models. I need to refactor the code such that the specific way these entities are stored internally varies for specific scenarios. For example if the points lie on a regular flat grid, I don't need to store the X and Y coordinates, as they can be calculated on the fly, as can the triangles. Similarly, I want to take advantage of out of core tools such as STXXL for storage. The simplest way of doing this is replacing array access with put and get type functions, e.g.
point[i].x = XV;
becomes
Point p = GetPoint(i);
p.x = XV;
PutPoint(i,p);
As you can imagine, this is a very tedious refactor on a large code base, prone to all sorts of errors en route. What I'd like to do is write a class that mimics the array by overloading the [] operator. As the arrays already live on the heap, and move around with reallocs, the code already assumes that references into the array such as
point *p = point + i;
may not be used. Is this class feasible to write? For example writing the methods below in terms of the [] operator;
void MyClass::PutPoint(int Index, Point p)
{
if (m_StorageStrategy == RegularGrid)
{
int xoffs,yoffs;
ComputeGridFromIndex(Index,xoffs,yoffs);
StoreGridPoint(xoffs,yoffs,p.z);
} else
m_PointArray[Index] = p;
}
}
Point MyClass::GetPoint(int Index)
{
if (m_StorageStrategy == RegularGrid)
{
int xoffs,yoffs;
ComputeGridFromIndex(Index,xoffs,yoffs);
return GetGridPoint(xoffs,yoffs); // GetGridPoint returns Point
} else
return m_PointArray[Index];
}
}
My concern is that all the array classes I've seen tend to pass by reference, whereas I think I'll have to pass structs by value. I think it should work put other than performance, can anyone see any major pitfalls with this approach. n.b. the reason I have to pass by value is to get
point[a].z = point[b].z + point[c].z
to work correctly where the underlying storage type varies.
| After reading the above answers, I decided that Pete's answer with two versions of operator[] was the best way forward. To handle the morphing between types at run-time I created a new array template class that took four parameters as follows;
template<class TYPE, class ARG_TYPE,class BASE_TYPE, class BASE_ARG_TYPE>
class CMorphArray
{
int GetSize() { return m_BaseData.GetSize(); }
BOOL IsEmpty() { return m_BaseData.IsEmpty(); }
// Accessing elements
const TYPE& GetAt(int nIndex) const;
TYPE& GetAt(int nIndex);
void SetAt(int nIndex, ARG_TYPE newElement);
const TYPE& ElementAt(int nIndex) const;
TYPE& ElementAt(int nIndex);
// Potentially growing the array
int Add(ARG_TYPE newElement);
// overloaded operator helpers
const TYPE& operator[](int nIndex) const;
TYPE& operator[](int nIndex);
CBigArray<BASE_TYPE, BASE_ARG_TYPE> m_BaseData;
private:
CBigArray<TYPE, ARG_TYPE> m_RefCache;
CBigArray<int, int&> m_RefIndex;
CBigArray<int, int&> m_CacheIndex;
virtual void Convert(BASE_TYPE,ARG_TYPE) = 0;
virtual void Convert(TYPE,BASE_ARG_TYPE) = 0;
void InitCache();
TYPE& GetCachedElement(int nIndex);
};
The main data storage is in m_BaseData which is the data in its native format, which can vary in type as discussed. m_RefCache is secondary array to cache of elements in the expected format, and the GetCachedElement function uses the virtual Convert functions to translate the data as it is moved in and out of the cache. The cache needs to be at least as big as the number of simultaneous references that can be active at any one time, but in my case will probably benefit from being bigger as it reduces the number of conversions required. While Alsk's cursor implementation probably would have worked well, the solution given requires fewer object copies and temporary variables, and ought to afford slightly better performance which is important in this case.
Apologies to all you STL fans for the older MFC look and feel; the rest of the project is MFC so it makes more sense in this case. The CBigArray was the result of a related stack overflow question that became the basis of my large array handling. I hope to finish the implementation today and test tomorrow. If it all goes belly up on me, I'll edit this post accoringly.
|
2,809,329 | 2,809,364 | Smart pointer class predeclaration | I have a header file:
class A
{
public:
DeviceProxyPtr GetDeviceProxy();
};
DeviceProxyPtr is defined in a different header file like this:
typedef SmartPtrC<DeviceProxyC> DeviceProxyPtr;
I don't want to include DeviceProxyPtr definition header.
If a return type was DeviceProxy* I could simply use predeclaration class DeviceProxy.
Is there any way to do the same with my smart pointer class?
| The fact that it's a concrete return type makes no difference. You can forward-declare return types.
However, in this case, it's not a class, but a typedef. You couldn't use class DeviceProxy, even if it was a pointer.
Mind you, all hope is not lost. The point of forward declarations is to avoid dragging in too much code and slowing down the compiler. The standard iostream library has exactly the same problem. For instance, istream isn't actually a class, but a typedef of a basic_istream instantiation. The standard library solves this by providing an <iosfwd> header that forward-declares the basic_istream class template and then uses it to declare the istream typedef. Thus, classes that interact with the iostream need only #include <iosfwd> in the header file, and then #include <iostream> in the implementation file.
|
2,809,330 | 2,809,405 | XCode C++ source code print issue on Mac | I am using MacBook Pro Mac OS 10.5 with related version of XCode. I am new to this development environment. I am developing C++ console/terminal applications (File->New project, then from the list on the left "Command line utility", and on the right "C++ tool".).
For C++ source code file, I want to print source file content with line number. Any ideas how to do this?
thanks in advance,
George
| I found this article A Recipe to Pretty-Print Your iPhone Source in Xcode it uses enscript which is installed by Apple for Xcode on Snow Leopard so no need for macports etc.
You can get linenumbers by passing -C as an argument to the enscript executable called in the shell script
|
2,809,559 | 2,809,602 | Using a SOCKS proxy from C++ | How I can use a SOCKS proxy from my C++ socket program?
| Your question is a bit vague, but I'll try to answer it anyway.
If found these links that might help you:
A C++ socket library - Includes an sample of a Web Proxy
Another C++ socket library - Includes also an example of Proxy
Using the SOCKS RFC and the cited links, you might be able to create a SOCKS proxy.
I don't like posting links as an answer but since you don't clearly state what you want to achieve, I can't really be more accurate...
|
2,809,637 | 2,809,701 | Auto tester/debugger for g++? | I just finished a project for my cryptography class and it all seems to go well (mostly). Because the key is generated randomly, I wanted to ensure it would work for all keys. Anyway, I ran it a bunch of times and hit a segfault at around the 30th run. I haven't been able to reproduce this segfault in gdb. Does gdb have a command, or is there some other method to continue running the program and then break when it segfaults so I can check the stack?
| Place the loop inside your program so you only have to run it in the debugger once.
|
2,809,968 | 2,810,040 | how to call a function to refresh GUI | I am refactoring some code to decouple GUI from some state.
#include <StateObject>
Class GUI{
...
StateObject A;
void doSomething() { A->hullaballoo();}
**void ReFreshMyGui() { //take state A and redraw }**
};
State object is being shared by multiple classes to update the state but this Gui Object specializes in displaying the state. So I would like to call the Refresh function via StateObject whenever its modified.
I am not sure how or if signals will provide the solution. Any hints?
| In order to decouple GUI and Data you could use the MVC pattern. This means your GUI should register to your model's (data) object(s) and whenever the data changes the GUI will be notified and it will be the GUI to redraw itself.
But careful, the model should not have the notion of a concrete GUI, instead the GUI should implement an observer interface containing a method (e.g. void Update()) that will be called whenever changes occur (notification handler).
Just look for the MVC-pattern on google. You'll find thousands of useful tutorials.
You may also take in consideration the MVP and the MVVM patterns.
Example:
class Observer
{
virtual void Update(void* data) = 0;
}
class GUI : public Observer
{
public:
virtual void Update(void* data)
{
//Redraw method and some other things you may
//want to do with the new data
}
}
class Model
{
private:
int m_iData;
List<Observer> observers;
public:
void SetData(int iData)
{
m_iData = iData;
for(int i = 0; i < observers.Length; i++)
{
observers[i].Update(NULL);
}
}
}
|
2,810,118 | 2,813,596 | How to tell the MinGW linker not to export all symbols? | I'm building a Windows dynamic library using the MinGW toolchain.
To build this library I'm statically linking to other 2 which offer an API and I have a .def file where I wrote the only symbol I want to be exported in my library.
The problem is that GCC is exporting all of the symbols including the ones from the libraries I'm linking to. Is there anyway to tell the linker just to export the symbols in the def file?
I know there is the option --export-all-symbols but there seems not to be the opposite to it.
Right now the last line of the build script has this structure:
g++ -shared CXXFLAGS DEFINES INCLUDES -o library.dll library.cpp DEF_FILE \
OBJECT_FILES LIBS -Wl,--enable-stdcall-fixup
EDIT: In the docs about the linker it says that --export-all-symbols is the default behavior and that it's disabled when you don't use that option explicitly if you provide a def file, except when it doesn't; the symbols in 3rd party libs are being exported anyway.
EDIT: Adding the option --exclude-libs LIBS or –exclude-symbols SYMBOLS doesn't prevent the symbols from the libraries from being exported.
| You can use dllwrap if your distribution of binutils (either native or cross compiling) provides it.
It can produce DLLs using the interface in a DEF file (under the hood it calls gcc, ld and dlltool to do so). The difference between using this and passing a DEF file to GCC directly is that the definitions in the file are treated differently.
For example, if you have a symbol rename in the export file:
_SomeFuntion = _SomeFunction@12
GCC will create 2 exports, one by the name of _SomeFunction and the other one with the decorated name while dllwrap will only export _SomeFuntion. So if you only add to the DEF file the symbols you want to be exported you will end up only with them in the library.
dllwrap by default uses the C compiler driver since it has no way of knowing otherwise. As you're linking C++ code, you have to use the option --driver-name c++ to set the driver. If you happen to have the MinGW executables with a prefix you have to include it too in the driver name (e.g. i686-mingw32-c++ instead of c++) and you may need to use the option --dlltool-name too.
Try using these two lines instead of the one you posted:
g++ -c CXXFLAGS DEFINES INCLUDES -o library.o library.cpp
dllwrap -o library.dll --driver-name c++ --def DEF_FILE OBJECT_FILES LIBS -Wl,--enable-stdcall-fixup
The first one generates an object file from the code of library.cpp and the second one assembles the dynamic library. The OBJECT_FILES thing (which I assume to be other object files you generated previously) should have library.o there too.
That said, I have to tell you dllwrap was already deprecated in 2006 and there is no documentation on it in the official binutils package; to get some info you may call it with --help as usual. It can generate an import library in case you need it too.
|
2,810,151 | 2,810,509 | #include - brackets vs quotes in XCode? | In MSVC++ #include files are searched for differently depending on whether the file is enclosed in "" or <>. The quoted form searches first in the local folder, then in /I specified locations, The angle bracket form avoids the local folder.
This means, in MSVC++, its possible to have header files with the same name as runtime and SDK headers.
So, for example, I need to wrap up the windows sdk windows.h file to undefine some macro's that cause trouble. With MSVS I can just add a (optional) windows.h file to my project as long as I include it using the quoted form :-
// some .cpp file
#include "windows.h" // will include my local windows.h file
And in my windows.h, I can pull in the real one using the angle bracket form:
// my windows.h
#include <windows.h> // will load the real one
#undef ConflictingSymbol
Trying this trick with GCC in XCode didn't work. angle bracket #includes in system header files in fact are finding my header files with similar names in my local folder structure.
The MSVC system means its quite safe to have a "String.h" header file in my own folder structre. On XCode this seems to be a major no no.
Is there some way to control this search path behaviour in XCode to be more like MSVC's? Or do I just have to avoid naming any of my headers anything that might possibly conflict with a system header. Writing cross platform code and using lots of frameworks means the possibility of incidental conflicts seems large.
| You should be able to do the same with gcc (I don't know how much xcode wraps things and prevent access to some features). There is a bunch of options controlling the search path (see http://gcc.gnu.org/onlinedocs/gcc-4.5.0/cpp/Search-Path.html and http://gcc.gnu.org/onlinedocs/gcc-4.5.0/cpp/Invocation.html and look for -iquote). Calling gcc with -v will give you the path specifying where the two differs.
|
2,810,212 | 2,811,322 | Custom PreviewPane - Works in Windows7, not in Vista | I've written an explorer extension to display my custom file format in the Preview Pane. This works fine in Windows 7, but doesn't seem to work in Vista. The same DLL handles both thumbnails and the preview pane. The thumbnails side of things work in both Vista and Windows7.
Adding logs to my code, Vistas only calling my DllGetClassObject function for the thumbnail class, not the preview handler class.
Is there anything obvious that Vista does differently to Windows7 when calling COM DLLs?
Here's the values I'm adding to the registry:
HKEY_CLASSES_ROOT\\.<myext>\\(default) = "<myext>.Thumbnail.Handler.1"
HKEY_CLASSES_ROOT\\<myext>.Thumbnail.Handler.1\\ShellEx\\{8895b1c6-b41f-4c1c-a562-0d564250836f}\\(default) = "<myguid>"
HKEY_CLASSES_ROOT\\CLSID\\<myguid>\\(default) = "<myext> Preview Handler"
HKEY_CLASSES_ROOT\\CLSID\\<myguid>\\DisplayName = "@ExplorerPreviewHandler.dll,-101"
HKEY_CLASSES_ROOT\\CLSID\\<myguid>\\Icon = "@ExplorerPreviewHandler.dll,201"
HKEY_CLASSES_ROOT\\CLSID\\<myguid>\\AppID = "{6d2b5079-2f0b-48dd-ab7f-97cec514d30b}"
HKEY_CLASSES_ROOT\\CLSID\\<myguid>\\InProcServer32\\(default) = "<path to my dll>"
HKEY_CLASSES_ROOT\\CLSID\\<myguid>\\InProcServer32\\ThreadingModel = "Apartment"
HKEY_CLASSES_ROOT\\CLSID\\<myguid>\\InProcServer32\\ProgID = "<myext>.Thumbnail.Handler.1"
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\PreviewHandlers\\<myguid> = "<myext> Preview Handler"},
Given that my DllGetClassObject isn't being called, I presume the problem must be something to do with what I'm setting in the registry? I know the DLL exports are okay, as it works for the thumbnails in both Vista and Win7, and works for the preview pane in Windows7.
DLL is x64, as are both my Vista and Win7 OSs. DLL is written in C++ without ATL.
Thankyou for any help with this,
Dan.
| The reg looks okayish, only the default progid is missing. Win7 does have documented alternate behavior for the location of the PreviewHandlers key. Unfortunately the SDK docs don't say what Vista requires. A Vista time magazine article uses HKLM instead of HKCU. I bet that's it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.