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,391,104
2,391,128
Are the subscripts for three-dimensional arrays strictly defined?
Let's say I declare this: int [a][b][c]; Does a stand for the level/page, b the row and c the column? Or can it be anything I want it to be i.e. a stands for column, b stands for page, and c stands for row (since data is just data and a cube can be abstracted any way)?
Anything you want in any order you want, the designations row and column are just convention. The layout in memory will be http://en.wikipedia.org/wiki/Row-major_order in C++, That part can't be changed. How you iterate through the elements will have an impact on performance in many cases. You want to change the rightmost index in your innermost loop to move through memory sequentially.
2,391,233
2,391,240
return type of the constructor in C++
I know that there is no return type of the constructors in C++ However, the code below compiles right. What is returned by the constructor in the code below? class A{ public: A() {} } A a = A(); //what is returned by A() here, why? Is there any conflict here?
Nothing is returned from the constructor. The syntax A() is not a constructor call, it creates a temporary object of type A (and calls the constructor in the process). You can't call a constructor directly, constructors are called as a part of object construction. In your code, during the construction of the temporary the default constructor (the one you defined) is called. Then, during the construction of a, the copy constructor (generated automatically by the compiler) is called with the temporary as an argument. As Greg correctly points out, in some circumstances (including this one), the compiler is allowed to avoid the copy-construction and default-construct a (the copy-constructor must be accessible however). I know of no compiler that wouldn't perform such optimization.
2,391,294
2,391,306
Are functions defined in headers guaranteed to be inlined?
If I define a non-member function in a header, will it always be inlined by the compiler, or does the compiler choose based on its heuristics? I know that __inline is just a hint, is it the same with functions in headers?
Remember that including something from a header is no different than just typing it directly in the source file. So being in a header makes no difference as far as the compiler is concerned; it never knew it was there. So when you define a function in a header file, and you include that header file in a file, it's like you just typed the function straight into the file. So now the question is, "does the compiler choose to inline things based on heuristics?" The answer is "it depends on the compiler". The standard makes no guarantees about what gets inlined or not. That said, any modern compiler will be extremely intelligent about what it inlines, likely with heuristics. However, we come to an interesting point. Imagine you have a function in a header and you include that header in multiple source files. You will then have multiple definitions of the function, across translation units, and this violates the one-definition rule. Ergo, you will get compile errors. (The linker error is usually something along the lines of: "Error, function x already defined in y") What you can do is use the inline keyword and you no longer violate the ODR. By the way __inline is non-standard. Contrary to your post, it's usually a compiler extension which forces inlining, not hints it. inline is the standard keyword, which was originally intended to hint at inlining. Like you say, most modern compilers completely ignore it in that regard and it's only purpose nowadays is to give things internal linkage.
2,391,334
2,391,353
How do i begin writing a windows shell extension?
I'm looking at writing a shell extension so when a file is clicked an action can be performed against it. (Like any other context menu :)) What is the minimum i need to insert a new Menu Item in the Context menu and perform an action against one or more files. A comparative example would be that i selected 10 files and Send to Zip. I read that writing some unmanaged code is required but my knowledge of c++ unmanaged code is about zero so i want to do as little as possible to get the Menu item in the Windows Context Menu (File > Right Click). After that i want to call a C# console app to do the main processing, so is it possible to call a c# console app from unmanaged code? Also, what type of visual studio project would i need to create the Windows Shell program? Which project type do i choose from: Win32 Console App MFC Application Win32 Project ATL Project MFC DLL CLR Console App Class Library Makefile Project MFC ActiveX Control Windows Forms Control Library Cheers
This MSDN article will get you started. Your approach of spawning a process (written in managed code) to do the actual work of the shell extension should be fine. I'd suggest just passing the selected files as command line parameters via CreateProcess. As to the project type, you'll be wanting to generate a Win32 dynamic link library (DLL). Under 2005, there actually is a Win32 Dll project type. With 2008 (which I infer you're using) you should create a Win32 project, then select DLL as the application type in the resulting wizard.
2,391,458
2,391,623
Map file with GCC on OSX
I am using GCC on Mac OSX. I am trying to get GCC to create a map(or listing) file of all the symbols in the project so it contains the addresses at which they are mapped. I read in the GCC manual that a way of generating such map files is to pass system specific flags to the GCC linker using -Xlinker option. But I cannot find what the option itself is. Does anyone know if this is possible with using GCC on OSX?
The ld option is -map. With -Xlinker you would write: gcc -Xlinker -map -Xlinker /path/to/map ... You can also write this more concisely with -Wl: gcc -Wl,-map,/path/to/map ...
2,391,471
2,391,481
Why does this code not compile correctly?
I just found my code like this does not compile right? Is there any compiler-provided constructor here? class A { private: A(const A& n); }; int main() { A a; } The error is test.cpp:18: error: no matching function for call to ‘A::A()’ test.cpp:11: note: candidates are: A::A(const A&) I am using g++ under Ubuntu 8.04
The compiler will provide for you the default constructor A() if and only if there are no user-defined constructors, and the copy constructor A(A const &) unless you provide either of the four possible copy constructors A(A cv &), where cv is any combination of const and volatile. In your case, you've declared your own copy constructor, which means that the compiler will provide neither of the above. The line A a; needs an accessible default constructor to compile.
2,391,476
2,391,650
problem with dead keys (acute, diaeresis, etc) c++
I'm currently writing my own virtual keyboard for linux using the X11 lib and i just can't find the way to simulate a KeyPress event of any dead keys. I'd tried , for example, to write "á" using the asigned macro, which is XK_aacute, and nothing happens. later i'd tried to send XK_acute (the acute accent macro) and then XK_a, and again, nothing happens :( In the KDE virtual Keyboard "Kvkbd" it's possible to do this, so i downloaded the source code, but it only supports the english keyboard layout Here is my test code: #include <X11/Xlib.h> #include <X11/keysym.h> #include <X11/extensions/XTest.h> #include <iostream> int main(){ Display *display; unsigned int keycode; unsigned int keycode1; display = XOpenDisplay(NULL); keycode = XKeysymToKeycode(display, XK_aacute); XTestFakeKeyEvent(display, keycode, True, 0); XTestFakeKeyEvent(display, keycode, False, 0); keycode1 = XKeysymToKeycode(display, XK_acute); XTestFakeKeyEvent(display, keycode1, True, 0); keycode = XKeysymToKeycode(display, XK_a); XTestFakeKeyEvent(display, keycode, True, 0); XTestFakeKeyEvent(display, keycode, False, 0); XTestFakeKeyEvent(display, keycode1, False, 0); keycode = XKeysymToKeycode(display, XK_D); XTestFakeKeyEvent(display, keycode, True, 0); XTestFakeKeyEvent(display, keycode, False, 0); XFlush(display); } Any help or idea will be much apreciated
i just figured out ¬¬ #include <X11/extensions/XTest.h> #include <X11/keysym.h> #include <X11/Xlib.h> #include <iostream> int main(){ Display *display; unsigned int keycode; unsigned int keycode1; display = XOpenDisplay(NULL); keycode1 = XKeysymToKeycode(display, XK_dead_acute); XTestFakeKeyEvent(display, keycode1, true, 0); keycode = XKeysymToKeycode(display, XK_A); XTestFakeKeyEvent(display, keycode, true, 0); XTestFakeKeyEvent(display, keycode, false, 0); XTestFakeKeyEvent(display, keycode1, false, 0); XFlush(display); } i was using the wrong macro
2,391,483
2,391,487
Quick question: Where is the C++ compiler located in Windows?
For some MATLAB code that I want to make executable, I need the location to a compiler in Windows. I have Visual Studio installed, so would I be able to reference the compiler that that uses? If so, how can I find it? Thanks.
Run the "Visual Studio Command Prompt", and you'll have the environment setup for compilation.
2,391,679
2,391,781
Why do we need virtual functions in C++?
I'm learning C++ and I'm just getting into virtual functions. From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived classes. But earlier in the book, when learning about basic inheritance, I was able to override base functions in derived classes without using virtual. So what am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly. I just can't find a straightforward answer online.
Without "virtual" you get "early binding". Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through. With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object - what it was originally constructed as. This is not necessarily what you'd think based on the type of the pointer that points to that object. class Base { public: void Method1 () { std::cout << "Base::Method1" << std::endl; } virtual void Method2 () { std::cout << "Base::Method2" << std::endl; } }; class Derived : public Base { public: void Method1 () { std::cout << "Derived::Method1" << std::endl; } void Method2 () { std::cout << "Derived::Method2" << std::endl; } }; Base* basePtr = new Derived (); // Note - constructed as Derived, but pointer stored as Base* basePtr->Method1 (); // Prints "Base::Method1" basePtr->Method2 (); // Prints "Derived::Method2" EDIT - see this question. Also - this tutorial covers early and late binding in C++.
2,391,823
2,398,307
C++ code snippet for a new baby greeting card
A friend of mine sent me this code snippet to celebrate his new baby birth: void new_baby_name() { father_surname++; } The snippet is from his point of view, he is the father and the new baby get the surname from him. I answered with this: class father_name {}; class mother_name {}; class new_baby_name: public father_name, public mother_name {}; But I'm not fully satisfied of my answer...
The correct reply is: Sleep(0);
2,392,178
2,392,188
extracting numbers and characters from a string, which doesn't follow a specific format? (postfix calculator)
I'm having trouble separating numbers and characters from my input string. The purpose of my program is to add,subtract,multiply and divide in postfix so i cant predict the input form as it can be anything from 2 2 3 + * (answer being 10) to 2 2 + 3 * (answer being 12). So i cant use sscanf to extract the numbers and the operator character without having a specific format to the input string. What should i do here?
Well, to process postfix you're going to want to implement a stack, so you should push each number onto a stack as you get it, each operator pops two off the stack and pushes the result back.
2,392,232
2,396,530
Displaying a pop-up notification window
How do you create a window that pops up from system tray notification area vertically upwards and displays a message? for example - In MSN, it displays it when someone gets online/offline.
Create a window with the look you want, and call AnimateWindow to get the pop-in effect. AnimateWindow doesn't really like windows with anything except a simple border.
2,392,308
2,392,319
C++ vector of char array
I am trying to write a program that has a vector of char arrays and am have some problems. char test [] = { 'a', 'b', 'c', 'd', 'e' }; vector<char[]> v; v.push_back(test); Sorry this has to be a char array because I need to be able to generate lists of chars as I am trying to get an output something like. a a a b a c a d a e b a b c Can anyone point me in the right direction? Thanks
You cannot store arrays in vectors (or in any other standard library container). The things that standard library containers store must be copyable and assignable, and arrays are neither of these. If you really need to put an array in a vector (and you probably don't - using a vector of vectors or a vector of strings is more likely what you need), then you can wrap the array in a struct: struct S { char a[10]; }; and then create a vector of structs: vector <S> v; S s; s.a[0] = 'x'; v.push_back( s );
2,392,318
2,394,541
Copy constructor and dynamic allocation
I would like to ask you how to write a copy constructor (and operator = ) for the following classes. Class Node stores coordinates x,y of each node and pointer to another node. class Node { private: double x, y; Node *n; public: Node (double xx, double yy, Node *nn) : x(xx), y(yy), n(nn) {} void setNode (Node *nn) : n(nn) {} ... }; Class NodesList (inherited from std:: vector) stores all dynamically allocated Nodes class NodesList : public std::vector<Node *> {} The main program: int main() { Node *n1 = new Node(5,10,NULL); Node *n2 = new Node(10,10,NULL); Node *n3 = new Node(20,10,NULL); n1->setNode(n2); n2->setNode(n3); n3->setNode(n2); NodesList nl1; nl1.push_back(n1); nl1.push_back(n2); nl1.push_back(n3); //Copy contructor is used, how to write NodesList nl2(nl1); //OPerator = is used, how to write? NodesList nl3 = nl1; } I do not want to create a shallow copy of each node but a deep copy of each node. Could I ask you for a sample code with copy constructor? Each node can be pointed more than once. Let us have such situation, when 3 nodes n[1], n[2], n[3] are stored in the NodesList nl1: n[1] points to n[2] n[2] points to n[3] n[3] points to n[2] A] Our copy constructor process the node n[1]. It creates a new object n[1]_new represented by the copy of the old object n[1]_old. The node n[2] pointed from n[1]_old still does not exist, so n[2]_new must be also created... The pointer from n1_new to n2_new is set. B] Then second point n[2] is processed. It can not be created twice, n[2]_new was created in A]. But pointed node n[3] does not exist, so the new object n[3]_new as a copy of an old object n[3]_old is created. The pointer from n2_new to n3_new is set. C] Node n[3]_new has already been created and n[2]_new. The pointer from n3_new to n2_new is set and no other object will be created... So the copy constructor should check whether the object has been created in the past or has not... Some reference counting could be helpful...
Perform a shallow copy in NodeList::NodeList(const NodeList&) and you don't have to worry about cycles breaking the copy operation. Disclaimer: the following is untested, incomplete and may have bugs. class NodeList { private: typedef std::vector<Node*> Delegate; Delegate nodes; public: NodeList(int capacity=16) : nodes() { nodes.reserve(capacity); } NodeList(const NodeList& from); virtual ~NodeList(); NodeList& operator=(const NodeList& from); /* delegated stuff */ typedef Delegate::size_type size_type; typedef Delegate::reference reference; typedef Delegate::const_reference const_reference; typedef Delegate::iterator iterator; typedef Delegate::const_iterator const_iterator; size_type size() const { return nodes.size(); } iterator begin() { return nodes.begin(); } const_iterator begin() const { return nodes.begin(); } iterator end() { return nodes.end(); } const_iterator end() const { return nodes.end(); } // ... }; NodeList::NodeList(const NodeList& from) : nodes(from.size()), flags(NodeList::owner) { std::map<Node*, Node*> replacement; Delegate::const_iterator pfrom; Delegate::iterator pto; // shallow copy nodes for (pfrom=from.begin(), pto=nodes.begin(); pfrom != from.end(); ++pfrom, ++pto) { replacement[*pfrom] = *pto = new Node(**pfrom); } // then fix nodes' nodes for (pto = nodes.begin(); pto != nodes.end(); ++pto) { (*pto)->setNode(replacement[(*pto)->getNode()]); } } NodeList::operator=(const NodeList&) can use the copy-swap idiom, the same as Tronic's Node::operator=(const Node&). This design has a potential memory leak in that a copied NodeList is (initally) the only place that references its nodes. If a temporary NodeList goes out of scope, a poor implementation will leak the Nodes the list contained. One solution is to proclaim that NodeLists own Nodes. As long as you don't add a Node to more than one NodeList (via NodeList::push_back, NodeList::operator[] &c), NodeList's methods can delete nodes when necessary (e.g. in NodeList::~NodeList, NodeList::pop_back). NodeList::~NodeList() { Delegate::iterator pnode; for (pnode = nodes.begin(); pnode != nodes.end(); ++pnode) { delete *pnode; } } void NodeList::pop_back() { delete nodes.back(); nodes.pop_back(); } Another solution is to use smart pointers, rather than Node*. NodeList should store shared pointers. Node::n should be a weak pointer to prevent ownership cycles.
2,392,397
2,392,483
going through a string of characters and extracting the numbers?
Given a string of characters, how can I go through it and assign all the numbers within that string into an integer variable, leaving out all other characters? I want to do this task when there is a string of characters already read in through gets(), not when the input is read.
unsigned int get_num(const char* s) { unsigned int value = 0; for (; *s; ++s) { if (isdigit(*s)) { value *= 10; value += (*s - '0'); } } return value; } Edit: Here is a safer version of the function. It returns 0 if s is NULL or cannot be converted to a numeric value at all. It return UINT_MAX if the string represents a value larger than UINT_MAX. #include <limits.h> unsigned int safe_get_num(const char* s) { unsigned int limit = UINT_MAX / 10; unsigned int value = 0; if (!s) { return 0; } for (; *s; ++s) { if (value < limit) { if (isdigit(*s)) { value *= 10; value += (*s - '0'); } } else { return UINT_MAX; } } return value; }
2,392,408
2,392,411
What is significance/use of doing void(param); at the start of function?
I was just going thro' source code of Yahoo's Trafic Server It is written in C++. In almost all methods (from one of modules), they do void(param) on each param that function receive. (Eg below) Can someone explain what this could be for ? int some_method_name(caddr_t addr, size_t len, caddr_t end, int flags) { (void) end; (void) addr; (void) len; (void) end; (void) flags; ...... .... } PS: For actual source code, please see methods from http://github.com/apache/trafficserver/blob/trunk/iocore/eventsystem/SocketManager.cc
This suppresses the "unused argument" warnings. Those statements do nothing, but count as using the argument.
2,392,485
2,392,544
algorithm for nth_element
I have recently found out that there exists a method called nth_element in the STL. To quote the description: Nth_element is similar to partial_sort, in that it partially orders a range of elements: it arranges the range [first, last) such that the element pointed to by the iterator nth is the same as the element that would be in that position if the entire range [first, last) had been sorted. Additionally, none of the elements in the range [nth, last) is less than any of the elements in the range [first, nth). It claims to have O(n) complexity on average. How does the algorithm work? I could not find any explanation for it.
It's called a selection algorithm and wikipedia has a decent page on it: http://en.wikipedia.org/wiki/Selection_algorithm Also read about order statistics: http://en.wikipedia.org/wiki/Order_statistic
2,392,515
2,407,544
GCC/VS2008: Different behaviour of function call when templated base class is derived from itself
The following code works with Visual Studio 2008 but not with GCC/G++ 4.3.4 20090804. Which behaviour is - according to the C++ standard - correct? template <int N> struct A : A<N-1> {}; template <> struct A<0> {}; struct B : A<1> {}; template <int N> void Func(const A<N> &a) {} int main() { A<1> a; //is derived from A<0> Func(a); //vs2008: ok, g++: ok //Comeau: ok B b; //is derived from A<1> Func(b); //vs2008: ok, g++: error, no matching function for call to Func(B&) //Comeau: error: no instance of function template "Func" matches the // argument list. The argument types that you used are: (B). return 0; } If I overload Func() with void Func(const A<0> &a) { std::cout << '0'; } void Func(const A<1> &a) { std::cout << '1'; } always the latter one is called (as expected). So I would also expect the templated function to be called with N=1 because A<1> is direct base of B. Is this assumption really wrong?
After some digging through N3035, I found this in section 14.9.2.1.4: If P is a class and P has the form simple-template-id, then the transformed A can be a derived class of the deduced A. Likewise, if P is a pointer to a class of the form simple-template-id, the transformed A can be a pointer to a derived class pointed to by the deduced A. However in 14.9.2.1.5, it says: These alternatives are considered only if type deduction would otherwise fail. If they yield more than one possible deduced A, the type deduction fails. Which is the case: both A<1> and A<0> are considered base classes for B. I guess this means a no for Visual Studio (at least, if the current standard says the same: exercise for the reader).
2,392,584
2,392,611
In c++, how to create a conversion from T to T*?
In preparing to a OOP exam, I enjoyed seeing g++ compile the following code (without an instantiation) even though it appeared to make no sense: template<class T> void f() { T t = "a"; t += 5.6; t->b(); T* p = t; p = p*(t/"string"); } I then set out on a challenge to make this instantiate and compile. I created the following class: class A { public: A(const char* s) {} void operator+=(double d) {} A operator/(char* str) {return A("");} A* operator->() {return this;} A* operator=(A& a) {return &a;} void b() {} }; A* operator*(A* a, A b) {return new A("");} which allowed almost all of the template to work, except the line T* p = t; My question is, what operator or constructor will make this line work? Currently it gives me "error: cannot convert ‘A’ to ‘A*’ in initialization"
That is a completely meaningless line. But to make it compilable, you can provide the conversion operator: operator A* () { return 0; } Hope you realize how evil this is.
2,392,655
2,392,693
What are the signs of crosses initialization?
Consider the following code: #include <iostream> using namespace std; int main() { int x, y, i; cin >> x >> y >> i; switch(i) { case 1: // int r = x + y; -- OK int r = 1; // Failed to Compile cout << r; break; case 2: r = x - y; cout << r; break; }; } G++ complains crosses initialization of 'int r'. My questions are: What is crosses initialization? Why do the first initializer x + y pass the compilation, but the latter failed? What are the problems of so-called crosses initialization? I know I should use brackets to specify the scope of r, but I want to know why, for example why non-POD could not be defined in a multi-case switch statement.
The version with int r = x + y; won't compile either. The problem is that it is possible for r to come to scope without its initializer being executed. The code would compile fine if you removed the initializer completely (i.e. the line would read int r;). The best thing you can do is to limit the scope of the variable. That way you'll satisfy both the compiler and the reader. switch(i) { case 1: { int r = 1; cout << r; } break; case 2: { int r = x - y; cout << r; } break; }; The Standard says (6.7/3): It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).
2,392,660
2,392,682
How to compute number of seconds since the beginning of this day?
I want to get the number of seconds since midnight. Here is my first guess: time_t current; time(&current); struct tm dateDetails; ACE_OS::localtime_r(&current, &dateDetails); // Get the current session start time const time_t yearToTime = dateDetails.tm_year - 70; // year to 1900 converted into year to 1970 const time_t ydayToTime = dateDetails.tm_yday; const time_t midnightTime = (yearToTime * 365 * 24 * 60 * 60) + (ydayToTime* 24 * 60 * 60); StartTime_ = static_cast<long>(current - midnightTime);
You can use standard C API: Get current time with time(). Convert it to struct tm with gmtime_r() or localtime_r(). Set its tm_sec, tm_min, tm_hour to zero. Convert it back to time_t with mktime(). Find the difference between the original time_t value and the new one. Example: #include <time.h> #include <stdio.h> time_t day_seconds() { time_t t1, t2; struct tm tms; time(&t1); localtime_r(&t1, &tms); tms.tm_hour = 0; tms.tm_min = 0; tms.tm_sec = 0; t2 = mktime(&tms); return t1 - t2; } int main() { printf("seconds since the beginning of the day: %lu\n", day_seconds()); return 0; }
2,392,689
2,392,729
How can we find second maximum from array efficiently?
Is it possible to find the second maximum number from an array of integers by traversing the array only once? As an example, I have a array of five integers from which I want to find second maximum number. Here is an attempt I gave in the interview: #define MIN -1 int main() { int max=MIN,second_max=MIN; int arr[6]={0,1,2,3,4,5}; for(int i=0;i<5;i++){ cout<<"::"<<arr[i]; } for(int i=0;i<5;i++){ if(arr[i]>max){ second_max=max; max=arr[i]; } } cout<<endl<<"Second Max:"<<second_max; int i; cin>>i; return 0; } The interviewer, however, came up with the test case int arr[6]={5,4,3,2,1,0};, which prevents it from going to the if condition the second time. I said to the interviewer that the only way would be to parse the array two times (two for loops). Does anybody have a better solution?
Your initialization of max and second_max to -1 is flawed. What if the array has values like {-2,-3,-4}? What you can do instead is to take the first 2 elements of the array (assuming the array has at least 2 elements), compare them, assign the smaller one to second_max and the larger one to max: if(arr[0] > arr[1]) { second_max = arr[1]; max = arr[0]; } else { second_max = arr[0]; max = arr[1]; } Then start comparing from the 3rd element and update max and/or second_max as needed: for(int i = 2; i < arr_len; i++){ // use >= n not just > as max and second_max can hav same value. Ex:{1,2,3,3} if(arr[i] >= max){ second_max=max; max=arr[i]; } else if(arr[i] > second_max){ second_max=arr[i]; } }
2,392,714
2,392,725
Adding a struct to std::list
struct Group { Group(string _N, set <string> M_) {Name = N_; Member = M_} string Name; set <string> Members; }; int main() { list <Group> GroupList; set <string> Members; //collect the members from a file and add to set GroupList.pushback(Group(Name, Members)); } is there a less memory consuming way to the add the members to group instead of passing the whole set to the constructor? Edit: Renamed the variables starting with underscore.
You can pass a reference and then make a copy and use initialisation list, same with the string. Group(const string& n, const set <string>& m) : Name(n), Members(m) {}
2,392,762
2,392,774
Class reference to parent
i'm pretty new at using C++ and I'm actually stopped at a problem. I have some class A,B,C defined as follow (PSEUDOCODE) class A { ... DoSomething(B par1); DoSomething(C par1); ... } class B { A parent; ... } class C { A parent; ... } The problem is : How to make this? If I simply do it (as I've always done in c#) it gives errors. I pretty much understand the reason of this. (A isn't already declared if I add the reference (include) of B and C into its own header) Any way to go around this problem? (Using void* pointer is not the way to go imho)
Forward-declare B and C. This way compiler will know they exist before you reach the definition of class A. class B; class C; // At this point, B and C are incomplete types: // they exist, but their layout is not known. // You can declare them as function parameters, return type // and declare them as pointer and reference variables, but not normal variables. class A { .... } // Followed by the *definition* of B and C. P. S. Plus, one more tip unrelated to the question (seeing how you come from a C# background): it's better to pass by const reference than by value: class A { ... void DoSomething(const B& par1); void DoSomething(const C& par1); ... }
2,392,870
2,392,886
Executing functions depending on a variable's value - C++
I am working on a transliteration tool. I have two modules lexer and translator. Lexer generates tokens out of the input text. Depending on the current language chosen, I have to call appropriate translation routine. I have came up with couple of ideas to do this. First one is to create a base class something called base_translator and provide virtual method (translate()) which every translators has to override. Now create a factory translator_factory and call create() with the language name. This factory will return appropriate instance. But this seems to be over engineering. So I came up with another approach where I have a struct like the following. struct translator { const char* name; void (*fp)(); }; Which just keeps a language name and a function pointer who can process it. Usage will be, static translator translators[] = { {"first", first}, {"second", second} }; const char* language = /* */; for(int i = 0; i < 2; i++) { translator *t = translators + i; if(strcmp(t->name, language) == 0) { t->fp(); break; } } This approach is very simple and easy to maintain. But I wonder, is this the best approach to the problem? Do you have any suggestions to make this better? Any help would be great.
Your second approach might look simpler to you for just two items (well for me it doesn't...), but it is more error-prone and difficult to maintain in the long run. Whenever you add a new language, you need to touch the code in at least two places. (And trust me: even if this seems unlikely to you at the moment, it is almost inevitably going to happen...) If you forget to update your loop boundary, you have a silent bug in your code. Moreover, this implementation is much slower than a polymorphic one: you need to iterate over the array and compare character strings before each call (as opposed to looking up a pointer in the vtable). I would definitely use a factory. Apart from the benefits above, it is a well known design pattern which makes it easier to understand. Thus people coming after you to maintain your code will not curse you that much ;-) Update: A factory can also return a function pointer. In this case I would still use functors internally, because these are full fledged classes with all the benefits listed above. And one more, not explicitly mentioned: they (as real objects) can store state, which plain functions can't. That may make a big difference later, and simplify your design a lot. Of course, once you have the factory interface in place, you can easily change your internal representation of its products from plain functions to functors (and back).
2,392,932
2,393,038
Why does the speed of this SOR solver depend on the input?
Related to my other question, I have now modified the sparse matrix solver to use the SOR (Successive Over-Relaxation) method. The code is now as follows: void SORSolver::step() { float const omega = 1.0f; float const *b = &d_b(1, 1), *w = &d_w(1, 1), *e = &d_e(1, 1), *s = &d_s(1, 1), *n = &d_n(1, 1), *xw = &d_x(0, 1), *xe = &d_x(2, 1), *xs = &d_x(1, 0), *xn = &d_x(1, 2); float *xc = &d_x(1, 1); for (size_t y = 1; y < d_ny - 1; ++y) { for (size_t x = 1; x < d_nx - 1; ++x) { float diff = *b - *xc - *e * *xe - *s * *xs - *n * *xn - *w * *xw; *xc += omega * diff; ++b; ++w; ++e; ++s; ++n; ++xw; ++xe; ++xs; ++xn; ++xc; } b += 2; w += 2; e += 2; s += 2; n += 2; xw += 2; xe += 2; xs += 2; xn += 2; xc += 2; } } Now the weird thing is: if I increase omega (the relaxation factor), the execution speed starts to depend dramatically on the values inside the various arrays! For omega = 1.0f, the execution time is more or less constant. For omega = 1.8, the first time, it will typically take, say, 5 milliseconds to execute this step() 10 times, but this will gradually increase to nearly 100 ms during the simulation. If I set omega = 1.0001f, I see an accordingly slight increase in execution time; the higher omega goes, the faster execution time will increase during the simulation. Since all this is embedded inside the fluid solver, it's hard to come up with a standalone example. But I have saved the initial state and rerun the solver on that state every time step, as well as solving for the actual time step. For the initial state it was fast, for the subsequent time steps incrementally slower. Since all else is equal, that proves that the execution speed of this code is dependent on the values in those six arrays. This is reproducible on Ubuntu with g++, as well as on 64-bit Windows 7 when compiling for 32-bits with VS2008. I heard that NaN and Inf values can be slower for floating point calculations, but no NaNs or Infs are present. Is it possible that the speed of float computations otherwise depends on the values of the input numbers?
The short answer to your last question is "yes" - denormalized (very close to zero) numbers require special handling and can be much slower. My guess is that they're creeping into the simulation as time goes on. See this related SO post: Floating Point Math Execution Time Setting the floating-point control to flush denormals to zero should take care of things with a negligible imapct on the simulation quality.
2,393,053
2,398,901
Performancetest: Flash/AS3 Processing/Java and openFrameworks/C++
I need to compare the performance of AS3, Processing and openFrameworks for my Bachelor thesis. Are there any comparison tables you know of or do I have to do the test myself? How would a good test look like? I'm just focused on graphics so I thought about maybe three different programs, a 2d-graphics app, a typographic-app and a 3d-app. Are there any pitfalls? What's the best way to test the performance? All suggestions are appreciated!
I know in the AS3 world there is a popular performance monitor called stats, you can find it here. Honestly I think you may be comparing apples to oranges. My initial assumption would be that openFrameworks (C++) outperforms Processing (Java) and Processing outperforms AS3 for many of the problems you will be exploring. I am sure there are many Java performance monitors and C++ monitors that you can plug into your Processing and openFramework programs to collect the data you need or you can roll your own. Of course you also need to identify what exactly you will be testing. My initial thought would be to test framerates, memory consumption, CPU utilization, and execution time. Personally I like to develop particle emitters and push my programs to the limit on the number of particles it can process. You will quickly see that Processing and openFramworks kicks AS3's butt with this. Well I hope I helped. Have fun! Nick @ nickgs.com
2,393,163
2,393,170
One question about array without default constructor in C++
From previous post, I learnt that for there are two ways, at least, to declare an array without default constructors. Like this class Foo{ public: Foo(int i) {} }; Foo f[5] = {1,2,3,4,5}; Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)}; I also learnt that the first one will construct the object using the parameter directly and the second copy constructor is used here. However, when I test the code below. I make the copy constructor private. I expect to see the difference of the copy constructor usage. But it is not what I expected. Neither of the two declarations is working. class Foo{ public: Foo(int i) {} private: Foo(const Foo& f) {} }; int main(){ Foo f[5] = {1,2,3,4,5}; Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)}; } Can anybody explain to me why does this happen?
The first won't construct the objects directly. It will first construct a temporary Foo, and then copy the Foo into the element. It's similar to your second way. The difference is that your second way won't work with a explicit copy constructor, while your first will. And conversely, the first will not work with a explicit constructor taking int, while the second will. Stated another way, the first constructor used in the initialization of an element must not be explicit. Notice that neither way needs to copy. But they still need to check whether the copy constructors are accessible. So, they shall behave as-if they would copy, but they don't really need to do the copy.
2,393,225
2,522,715
Where are the static methods in gcc's dump file.c.135r.jump
When I run gcc with the parameter -fdump-rtl-jump, I get a dump file with the name file.c.135r.jump, where I can read some information about the intermediate representation of the methods in my C or C++ file. I just recently discovered, that the static methods of a project are missing in this dump file. Do you know, why they are missing in that representation and if there is a possibility to include the static methods in this file, too. Update (some additional information): The test program, I'm using here, is the Hybrid OpenMP MPI Benchmark. Update2: I just reproduced the problem with a serial application, so it has nothing to do with parallel sections.
My guess is that the static methods are inlined and, since they are static, everything is known about their calls, no out-of-line code of them is emitted. A way to confirm or reject this is to add -fkeep-inline-functions gcc option and then they should appear in the dumps.
2,393,325
2,393,495
Why is protected constructor raising an error this this code?
One question about protected constructor. I learnt that the protected constructor can be used in the derived class. How ever, I found the code below has an error. Why does it happen like this? class A { protected: A(){} }; class B: public A { public: B() { A* f=new A(); // Why it is not working here } };
This has nothing to do with constructors specifically. This is just how protected access works. The way protected access specifier works, it allows the derived class B to access the contents of an object of base class A only when that object of class A is a subobject of class B. That means that the only thing you can do in your code is to access the contents of A through B: you can access the members of A through a pointer of type B * (or a reference of type B &). But you cannot access the same members through a pointer of type A * (or reference A &). Consider the following example class A { protected: int i; }; class B : A { void foo() { i = 0; // OK this->i = 0; // OK B *pb = this; pb->i = 0; // OK A *pa = this; pa->i = 0; // ERROR ((A *) this)->i = 0; // ERROR } }; In the above B::foo, you can access base member A::i by using just plain i syntax. This is equivalent to using this->i syntax. Both will work, because the pointer this has type B *, i.e. you are accessing A::i thorough a pointer of type B *. This is exactly what the protected access specifier is supposed to allow. The access through pb pointer works for the very same reason. However, when you "convert" this pointer to type A *, you can no longer access A::i through that new pointer, even though you are still trying to access they very same member as before. When applied to constructors, the protected access specifier has a very specific effect: a protected constructor can only be used to initialize base-class subobjects. It cannot be used to initialize standalone objects (which is what you were trying to do). In other words, protected constructors are another way to implement the concept of abstract class in C++ (along with pure virtual methods). If the constructors of your class are protected, then your class is effectively abstract. You can't use it to define independent objects "from outside". (Of course, the above does not apply within friends, as well as within the class itself).
2,393,345
2,393,389
How to append text to a text file in C++?
How to append text to a text file in C++? And create a new text file if it does not already exist and append text to it if it does exist.
You need to specify the append open mode like #include <fstream> int main() { std::ofstream outfile; outfile.open("test.txt", std::ios_base::app); // append instead of overwrite outfile << "Data"; return 0; }
2,393,399
2,393,504
HTML to XML conversion with C++
Is there a C++ code or library to convert a HTML document to a XML document? Thanks.
You can take a look at Tidy library Tidy is composed from an HTML parser and an HTML pretty printer. The parser goes to considerable lengths to correct common markup errors. It also provides advice on how to make your pages more accessible to people with disabilities, and can be used to convert HTML content into XML as XHTML. The library is written in C.
2,393,439
2,393,562
Can I overload operators on enum types in C++?
For example, if I have: typedef enum { year, month, day } field_type; inline foo operator *(field_type t,int x) { return foo(f,x); } inline foo operator -(field_type t) { return t*-1; } int operator /(distance const &d,field_type v) { return d.in(v); } Because if I do not define such operators it is actually legal to write day*3 and it would be translated into 6? So is it legal? At least gcc and intel compiler accept this without a warning. Clearification: I do not want default arithmetic operations, I want my own operations that return non-integer type.
Yes, operator overloading can be done on enum and class types. The way you do it is fine, but you should use + to promote the enumeration, instead of *-1 or something (the purpose ultimately is to avoid infinite recursion because -t): inline foo operator -(field_type t) { return -+t; } This will scale well to other operations. + will promote the enumeration to an integer type that can represent its value, and then you can apply - without causing infinite recursion. Notice that your operator* does only allow you to do enum_type * integer, but not the other way around. It may be worth considering the other direction too. Also notice that it's always a bit dangerous to overload operators for operands that builtin-operators already accept (even if only by implicit conversions). Imagine that distance has a converting constructor taking int (as in distance(int)), then given your operator/ the following is ambiguous // ambiguous: operator/(int, int) (built-in) or // operator/(distance const&, field_type) ? 31 / month; For this, maybe it's better to make field_type a real class with the appropriate operators, so that you can exclude any of such implicit conversions from begin on. Another good solution is provided by C++0x's enum class, which provides strong enumerations.
2,393,458
2,393,467
Why does using the same count variable name in nested FOR loops work?
Why does the following not give an error? for (int i=0; i<10; ++i) // outer loop { for (int i=0; i<10;++i) // inner loop { //...do something } //...do something else } The way I understand it, variables in braces ({...}) are in scope only within these braces. But the inner loop is inside the braces of the outer loop. So as soon as I declare int i=0 for the inner loop, shouldn't I get an error about multiple definitions?
You are actually making a new variable with the same name as another variable. Since they are in different scopes this is allowed, and the variable in the inner scope "owns" the name. You will not be able to access the outer-scoped i inside the inner scope. The for loop declaration itself is part of the scope of the for loop, so counts as part of the inner-scope in the case of the second i.
2,393,518
2,393,557
undefined C/C++ symbol as operator
I notice that the character/symbol '`' and '@' is not used as an operator in C/C++, does anyone know the reason or historically why its so? if its really not used, is it safe to define those symbols as another operator/statement using #define?
Normally, #define only accepts valid identifiers in the macro name - so you cannot do: #define @ at #define @(x) [x] Similarly with back-quote. And you didn't mention '$', which is sometimes allowed in identifiers. There might be a compiler-specific extension to allow such mappings, but I wouldn't use it. As to the historical reason for this, there are parts of the ISO 646 character set that are reserved to national implementations for national characters. These reserved portions include the characters that cause trouble, and the trigraphs and digraphs features in Standard C (and hence Standard C++) were added to ISO C in 1989 and 1994 respectively to provide workarounds for the problems. Trigraphs Trigraphs were added during the C89 standardization process to prevent people from, for example, having to see alphabetic characters (in Scandinavian languages) used in their C code (adapted from an example in B Stroustrup, 'Design and Evolution of C++', using a Danish terminal): #include <stdio.h> int main(int argc, char **argvÆÅ) æ if (argc < 1 øø *argvÆ1Å == 'Ø0') return 0; printf("Hello, %sØn", argvÆ1Å); å Or, in the ISO 8859-1 code set (or any of the ISO 8859-x code sets): #include <stdio.h> int main(int argc, char **argv[]) { if (argc < 1 || argv[1] == '\0') return 0; printf("Hello, %s\n", argv[1]); } The trigraphs were introduced to produce a neutral format for the code: ??=include <stdio.h> int main(int argc, char **argv??(??)) ??< if (argc < 1 ??!??! *argv??(1??) == '??/0') return 0; printf("Hello, %s??/n", argv??(1??)); ??> That's not very readable, either, but it is the same for everyone. Trigraph Equivalent to ??/ \ backslash ??< { open brace ??> } close brace ??( [ open square bracket ??) ] close square bracket ??= # hash (pound in American, but a pound is £ in English) ??' ^ caret ??! | pipe ??- ~ tilde The standard says 'there are no other trigraphs'. This is why the escape sequence '\?' is recognized (as a simple question mark - though presumably that is '??/?'). Note that the GNU Compiler Collection (GCC) does not interpret trigraphs unless you hold its hand to the fire (specify '-trigraphs' on the command line). Digraphs The digraphs were added in 1994, and are not as pervasive or intrusive as trigraphs; they only appear outside strings and string literals. The digraphs are: Digraph Equivalent to <: [ :> ] <% { %> } %: # %:%: ## The example using digraphs (and trigraphs): %:include <stdio.h> %:include <iso646.h> int main(int argc, char **argv<::>) <% if (argc < 1 or *argv<:1:> == '??/0') return 0; printf("Hello, %s??/n", argv<:1:>); %> At sign and back quote specifically? If you look at the Wikipedia URL above, you'll see that both '@' and '`' are sometimes replaced by national characters - and hence not good identifiers. An additional reason for not using '@' is that at the time C was introduced, '#" was the default erase character and '@' was the kill (line erase) character for terminals. So, you had to remember to escape them. Since '#' only appeared at the beginning of a line, it wasn't too much of a problem (using '#' and '##' came much, much later - standardization again), but '@' would have wiped out all the preceding typing on the line. And this is the days before 'vi' - 'ed is the the standard Unix editor'.
2,393,527
2,393,575
Python code to parse and inspect c++
Is there a library for Python that will allow me to parse c++ code? For example, let's say I want to parse some c++ code and find the names of all classes and their member functions/variables. I can think of a few ways to hack it together using regular expressions, but if there is an existing library it would be more helpful.
In the past I've used for such purposes gccxml (a C++ parser that emits easily-parseable XML) -- I hacked up my own Python interfaces to it, but now there's a pygccxml which should package that up nicely for you.
2,393,644
2,394,081
Visual studio compiler flag /arch and performance
I just noticed that in our project have left the "Enable Enhanced Instruction Set" flag left unset, probably just an oversight. Before enabling the flag I would like to ask if anyone have seen any real-world performance improvements enabling it ? I guess we will see some improvement our application constantly do floating point based calucations, but its not a major part,.
So in a nutshell: This setting only enables certain intrinsic functions that map directly on SSE instructions. In normal C++ programs you don't use these intrinsic functions, so this setting won't improve performance. If you need more performance, you could try to find a compiler that rewrites your code to use SSE instructions (intel claims its compiler can), but its probably smarter to go for multicore (with openMP or .net 4.0), or use the GPU, which is faster and more flexible than SSE.
2,393,673
2,393,696
C++ and,or,not,xor keywords
Possible Duplicate: The written versions of the logical operators. I notice that C++ define keyword and, or, not, xor, and_eq, or_eq, not_eq and xor_eq as an alternative to &&, ||, !, ^, &=, |=, != and |=. and they're rarely used! What's wrong? Are they not portable?
They come from C AFAIR from times when it was not known what special symbols are on the keyboard. So to have portable language they were defined so anyone can use C even if they used keyboard with no &, |, or ^ (etc.). Nowadays when QWERTY is a standard (with AZWERTY & co. as variations) it is no longer an issue. PS. And of course for obfuscation code competitions ;)
2,393,817
2,394,085
C++: Why isn't operator placement new recognized as an inline friend function in a (template) class in VS2005?
I've inherited a Visual Studio 6.0 project to convert to 2005. It includes this fantastic MyClass class below that client code uses everywhere by invoking placement new on an instance of it (greatly simplified here): #include <new> #include <cstdio> template<class T> class MyClass { public: // This is what the author assumed would be called on placement new. inline friend void* operator new(size_t u_size, MyClass<T>& mc) { printf("MyClass friend placement new\n"); // ... return 0; } // This is just to show koenig lookup works on normal functions. inline friend void hello(MyClass<T>& mc) { printf("Hello called with koenig lookup\n"); // ... } // This was part of the original class, gets called further below. operator unsigned int*() { printf("Converting for default placement new\n"); // ... return 0; } }; /* This gets called in VS2005 if un-commented. template<class T> void* operator new(size_t u_size, MyClass<T>& mc) { printf("MyClass placement new non-friend non-inline\n"); // *** return 0; } */ class DummyClass { int a; }; void testfunction() { MyClass<DummyClass> mc; hello(mc); void* a = new(mc) DummyClass; // Placement new call char c; gets(&c); } When I run "testfunction()" in VS2005, at the placement new call, the operator "inline friend void* operator new(...)" in MyClass never gets called. Instead, "operator unsigned int*()" gets called, the result is cast to void*, and the default placement operator new is invoked instead (so "Converting for default placement new" is displayed). In VS6, the placement new calls "inline friend void* operator new(...)" in MyClass instead (so "CMyClass friend placement new" is displayed), which is what the author intended, but then again VS6 implements inline friends in a weird way. Why doesn't VS2005 recognize the inline friend placement operator new using argument-dependent lookup? It recognizes the hello() function using arguments (so "Hello called with koenig lookup" is displayed), but it doesn't work for placement new. For reference, this seems to happen whether or not MyClass is templated or not (but I left it templated for completeness' sake). Also if you un-comment the non-friend "operator new" outside of MyClass, that one gets called properly in VS2005. What gives? Is there an error in there? Is placement new a special case for argument-dependent lookup? Is VS2005 right or wrong? What would be standard C++ here? For a workaround I was going to use a non-inline friend instead of inline, but that gets ugly with forwards and all, wanted to ask what the deal is here first.
The problem is that the allocation function is looked up in the global scope, it is not looked up using ADL. Since friend functions defined inside a class are hidden from the enclosing scope, the function is not found. 5.3.4/9: If the new-expression begins with a unary :: operator, the allocation function’s name is looked up in the global scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function’s name is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function’s name is looked up in the global scope.
2,393,873
2,393,889
how do i add a int to a string
i have a string and i need to add a number to it i.e a int. like: string number1 = ("dfg"); int number2 = 123; number1 += number2; this is my code: name = root_enter; // pull name from another string. size_t sz; sz = name.size(); //find the size of the string. name.resize (sz + 5, account); // add the account number. cout << name; //test the string. this works... somewhat but i only get the "*name*88888" and... i don't know why. i just need a way to add the value of a int to the end of a string
Use a stringstream. #include <iostream> #include <sstream> using namespace std; int main () { int a = 30; stringstream ss(stringstream::in | stringstream::out); ss << "hello world"; ss << '\n'; ss << a; cout << ss.str() << '\n'; return 0; }
2,393,874
2,393,900
Removing the repeating pattern in C++
I have atleast 16 functions of the following form. bool Node::some_walker( Arg* arg1 ) { if(this == NULL) return false; bool shouldReturn = false; if( this->some_walker_p(arg1, shouldReturn) ) //This line alone varies return true; if( shouldReturn ) // true is already returned return false; return this->std_walker(arg1); } The function some_walker_p is a virtual function and i am not able to templatize it. Is there any solution to avoid this code repetition? Thanks, Gokul.
It depends on whether the arguments to the private functions are similar or not. The following solutions are possible, ranging from simple and limited to complex and generic: Equivalent =< Use member-function-pointer) Same number, different types => Templatize over each argument) Different numbers/types of arguments => se boost::bind and function objects) Thanks for the comments given. At first, I only posted the first solution, but there are (as listed) other situations that need different approaches. Member-function-pointer: bool Node::walker_caller(Arg* arg1, bool (Node::*memfn)(Arg*, bool)) { ... if( (this->*memfn)(arg1, shouldReturn) ) //This line alone varies return true; ... } bool Node::some_walker(Arg* arg1) { return walker_caller(arg1, &Node::some_walker_p); } bool Node::other_walker(Arg* arg1) { return walker_caller(arg1, &Node::other_walker_p); } Sidenote: I usually typedef the mem-fn-ptr to make the syntax more bearable. Templated arguments: I assume you always have two arguments here, but they can have different types. If you have a limited amount of args-numbers (say 1 and 2), you can could implement walker_caller twice, one impl for one-arg and one for two-arg, both templated. template<class A1, class A2) bool Node::walker_caller(A1 arg1, A2 arg2, bool (Node::*memfn)(A1, A2, bool)) { ... if( (this->*memfn)(arg1, arg2, shouldReturn) ) //This line alone varies return true; ... } bool Node::some_walker(Arg* arg, OtherArg* other_arg) { return walker_caller(arg, other_arg, &Node::some_walker_p); } bool Node::other_walker(OtherArg* other_arg, YetAnotherArg* yaa) { return walker_caller(other_arg, yaa, &Node::other_walker_p); } Function objects: If your walkers use widely different number and argument types, you probably want to use boost::bind, and maybe boost::function. (Use of the latter is not required but cuts down on the generated code size...) // faster code, as the function object may be inlined, but // each call instantiates a different walker_caller, so exe might be bigger template<class F> bool Node::walker_caller(const F& fn) { ... if( fn(shouldReturn) ) //This line alone varies return true; ... } // only one implementation, so smaller foot print but // all arguments need to be copied into a function objet // which may be a perf hit if the arguments are big // (this version is good to have when you inherit from Node...) bool Node::walker_caller(const boost::function<bool (bool)>& fn) { ... if( fn(shouldReturn) ) //This line alone varies return true; ... } bool Node::some_walker(Arg* arg1) { return walker_caller(boost::bind(&Node::some_walker_p, this, arg1, _1)); } bool Node::other_walker(Arg* arg1, OtherArg* arg2) { return walker_caller(boost::bind(&Node::some_walker_p, this, arg1, arg2, _1)); }
2,393,888
2,396,704
Possible to create a dual-seekable Boost Iostream using a file_descriptor?
I'm trying to update a random-access binary file using the std::iostream interface with separate get/put positions managed via seekg/seekp. Everything works fine with stringstream, but when I create a file descriptor-based stream using Boost.Iostream (specifically boost::iostreams::stream<boost::iostreams::file_descriptor>), the get/put positions are no longer independent. I gather from the documentation on Modes that what I'm looking for is a "Dual-seekable" stream. The docs show that Mode is a template parameter of stream, "principally for internal use", but this seems to be (no longer?) correct. Instead, the mode (aka category?) is taken directly from the Device: template< typename Device, typename Tr = ..., typename Alloc = ...> struct stream : detail::stream_base<Device, Tr, Alloc> { public: typedef typename char_type_of<Device>::type char_type; struct category : mode_of<Device>::type, closable_tag, detail::stream_traits<Device, Tr>::stream_tag { }; Primary question: Is there some way to get Dual-seekable behavior from a Device such as file_descriptor (which is tagged Seekable but not Dual-seekable)? Secondary question: Are there any general guarantees about the independence of seekg/seekp? I gather from web searches that stringstream seems to be independent, but that fstream may not be. However, I can't find anything authoritative.
If you construct a bidirectional_seekable boost::iostreams::device it will support two separate get/put positions which can be modified with the help of the iostreams::seek function. Roughly, this will look like: struct binary_seekable_device : boost::iostreams::device<boost::iostreams::bidirectional_seekable> { explicit binary_seekable_device(int fd) : fd(fd), pos_read(0), pos_write(0) {} std::streamsize read(char *s, std::streamsize n); std::streamsize write(char const *s, std::streamsize n); std::streampos seek(boost::iostreams::stream_offset off, std::ios::seekdir way, std::ios::openmode which); int fd; std::size_t pos_read; std::size_t pos_write; }; You need to implement your stream logic by filling out the three functions (read, write, seek), see the examples and documentation for details. The important point for you is the parameter std::ios::openmode which giving you a clue which of the positions (read, write, or both) you need to update. Now you use this device while instantiating an boost::iostreams::stream: int fd = open(...); boost::iostream::stream<binary_seekable_device> s(fd); where s is your stream instance you can use to do the require file operations.
2,394,017
2,394,040
Remove comments from C/C++ code
Is there an easy way to remove comments from a C/C++ source file without doing any preprocessing. (ie, I think you can use gcc -E but this will expand macros.) I just want the source code with comments stripped, nothing else should be changed. EDIT: Preference towards an existing tool. I don't want to have to write this myself with regexes, I foresee too many surprises in the code.
Run the following command on your source file: gcc -fpreprocessed -dD -E test.c Thanks to KennyTM for finding the right flags. Here’s the result for completeness: test.c: #define foo bar foo foo foo #ifdef foo #undef foo #define foo baz #endif foo foo /* comments? comments. */ // c++ style comments gcc -fpreprocessed -dD -E test.c: #define foo bar foo foo foo #ifdef foo #undef foo #define foo baz #endif foo foo
2,394,061
2,394,095
STL set not adding properly c++
I am adding musicCD information to a set. I have two different functions for this. The problem is adding the musicians. Its only adding the last musician being passed in like its copying over the first ones. here is the required output to give you an idea of the info. Only ringo starr is adding and not "George Harrison" "John Lennon". -MusicCD- band: Beatles musicians: "George Harrison" "John Lennon" "Ringo Starr" songs: 10 title: Sergeant Pepper's Lonely Hearts Club Band keywords: acid rock, sixties here is main() item = library->addMusicCD("Sergeant Pepper's Lonely Hearts Club Band", "Beatles", 10); if (item != NULL) { library->addKeywordForItem(item, "acid rock"); library->addKeywordForItem(item, "sixties"); library->addBandMember(item, "John Lennon"); library->addBandMember(item, "George Harrison"); library->addBandMember(item, "Ringo Starr"); library->printItem(cout, item); } here is the libray.h file where i am adding the info #include "Library.h" #include "book.h" #include "cd.h" #include "dvd.h" #include <iostream> // general functions ItemSet allBooks; ItemSet allCDS; ItemSet allDVDs; ItemSet* temp; ItemSetMap allBooksByAuthor; ItemSetMap allmoviesByDirector; ItemSetMap allmoviesByActor; ItemSetMap allMusicByBand; ItemSetMap allMusicByMusician; const Item* Library::addMusicCD(const string& title, const string& band, const int nSongs) { ItemSet* obj = new ItemSet(); CD* item = new CD(title,band,nSongs); allCDS.insert(item); obj->insert(item); //allMusicByBand[band] = obj; ItemSetMap::iterator myband = allMusicByBand.find(band); if(myband != allMusicByBand.end()) { myband->second->insert(item); } else{ allMusicByBand.insert(make_pair(band, obj)); } return item; } void Library::addBandMember(const Item* musicCD, const string& member) { ItemSet* obj = new ItemSet(); (((CD*) musicCD)->addBandMember(member)); obj->insert((CD*) musicCD); ItemSetMap::iterator MByMusician = allMusicByMusician.find(member); if(MByMusician != allMusicByMusician.end()) { MByMusician->second->insert((CD*) musicCD); } else { allMusicByMusician.insert(make_pair(member, obj)); } } and here is the cd.cpp class #include "CD.h" using namespace std; CD::CD(const string& theTitle, const string& theBand, const int snumber) : Item(theTitle), band(theBand),number(snumber) { } CD::~CD() { } const string CD::getBand() const { return band; } const string CD::getMusician() const { return musicians; } const int CD::getNumber() const { return number; } void CD::addBandMember(const string &member) { this->musicians = member; } void CD::print(ostream &out) const { out << "-MusicCD-" << endl; out << "band: " << this->getBand() << endl; out << "musicians: " << this->getMusician() << endl; out << "songs: " << this->getNumber() << endl; out << "title: " << this->getTitle() << endl; out << "keywords: " << this->printKeywords(this->getKeywords()) << endl; out << endl; } ostream& operator<<(ostream& out, const CD* cd) { cd->print(out); return out; } finally, here is the cd.h #ifndef CD_H #define CD_H #pragma once #include "item.h" class CD : public Item { public: CD(const string& theTitle, const string& theBand, const int snumber); void addBandMember(const string& member); const int getNumber() const; const string getMusician() const; const string getBand() const; virtual void print(ostream& out) const; ~CD(); private: string band; string musicians; string title; int number; }; ostream& operator<<(ostream& out, const CD* cd); #endif I have to assume my problem lies in the Library::addBandMember function? Keep in mind i cannot change that function in the library class.
Yes. string musicians; This variable stores a single string. Hence, even though the call succeeds for addBandMember it gets overwritten by the next call. Hence, all you are left with is the name of the last added musician -- Ringo in your case. Use a list or vector instead to hold all musicians. vector<string> musicians; and modify addBandMember as: void CD::addBandMember(const string &member) { this->musicians.push_back(member); }
2,394,098
2,403,916
Graph colouring algorithm: typical scheduling problem
I'm training code problems like UvA and I have this one in which I have to, given a set of n exams and k students enrolled in the exams, find whether it is possible to schedule all exams in two time slots. Input Several test cases. Each one starts with a line containing 1 < n < 200 of different examinations to be scheduled. The 2nd line has the number of cases k in which there exist at least 1 student enrolled in 2 examinations. Then, k lines will follow, each containing 2 numbers that specify the pair of examinations for each case above. (An input with n = 0 will means end of the input and is not to be processed). Output: You have to decide whether the examination plan is possible or not for 2 time slots. Example: Input: 3 3 0 1 1 2 2 0 9 8 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 Ouput: NOT POSSIBLE. POSSIBLE. I think the general approach is graph colouring, but I'm really a newb and I may confess that I had some trouble understanding the problem. Anyway, I'm trying to do it and then submit it. Could someone please help me doing some code for this problem? I will have to handle and understand this algo now in order to use it later, over and over. I prefer C or C++, but if you want, Java is fine to me ;) Thanks in advance
I've translated the polygenelubricant's pseudocode to JAVA code, in order to provide a solution for my problem. We have a submission platform (like uva/ACM contests), so I know it passed even in the problem with more and hardest cases. Here it is: import java.util.ArrayList; import java.util.Hashtable; import java.util.Scanner; /** * * @author newba */ public class GraphProblem { class Edge { int v1; int v2; public Edge(int v1, int v2) { this.v1 = v1; this.v2 = v2; } } public GraphProblem () { Scanner cin = new Scanner(System.in); while (cin.hasNext()) { int num_exams = cin.nextInt(); if (num_exams == 0) break; int k = cin.nextInt(); Hashtable<Integer,String> exams = new Hashtable<Integer, String>(); ArrayList<Edge> edges = new ArrayList<Edge>(); for (int i = 0; i < k; i++) { int v1 = cin.nextInt(); int v2 = cin.nextInt(); exams.put(v1,"UNKNOWN"); exams.put(v2,"UNKNOWN"); //add the edge from A->B and B->A edges.add(new Edge(v1, v2)); edges.add(new Edge(v2, v1)); } boolean possible = true; for (Integer key: exams.keySet()){ if (exams.get(key).equals("UNKNOWN")){ if (!colorify(edges, exams,key, "BLACK", "WHITE")){ possible = false; break; } } } if (possible) System.out.println("POSSIBLE."); else System.out.println("NOT POSSIBLE."); } } public boolean colorify (ArrayList<Edge> edges,Hashtable<Integer,String> verticesHash,Integer node, String color1, String color2){ verticesHash.put(node,color1); for (Edge edge : edges){ if (edge.v1 == (int) node) { if (verticesHash.get(edge.v2).equals(color1)){ return false; } if (verticesHash.get(edge.v2).equals("UNKNOWN")){ colorify(edges, verticesHash, edge.v2, color2, color1); } } } return true; } public static void main(String[] args) { new GraphProblem(); } } I didn't optimized yet, I don't have the time right new, but if you want, you/we can discuss it here. Hope you enjoy it! ;)
2,394,170
2,394,193
Searching std::string between a limit
if you know the start and end positions in string from where to begin and end the search. For example - string s = StringStringString |S |t |r |i |n |g |S |t |r |i |n |g |S |t |r |i |n |g 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 How would you find "tr" in the string specifying the the position to begin search is at index 6 and the position to end the search is index 9. I'm trying a set a limit of search so it wouldn't go beyond it.
If you really want to limit the length of the sequence that gets traversed (presumably because the string is very long compared to the interesting region), use std::search and pass it the corresponding iterators into the string.
2,394,402
2,394,463
C/C++: Bitwise operators on dynamically allocated memory
In C/C++, is there an easy way to apply bitwise operators (specifically left/right shifts) to dynamically allocated memory? For example, let's say I did this: unsigned char * bytes=new unsigned char[3]; bytes[0]=1; bytes[1]=1; bytes[2]=1; I would like a way to do this: bytes>>=2; (then the 'bytes' would have the following values): bytes[0]==0 bytes[1]==64 bytes[2]==64 Why the values should be that way: After allocation, the bytes look like this: [00000001][00000001][00000001] But I'm looking to treat the bytes as one long string of bits, like this: [000000010000000100000001] A right shift by two would cause the bits to look like this: [000000000100000001000000] Which finally looks like this when separated back into the 3 bytes (thus the 0, 64, 64): [00000000][01000000][01000000] Any ideas? Should I maybe make a struct/class and overload the appropriate operators? Edit: If so, any tips on how to proceed? Note: I'm looking for a way to implement this myself (with some guidance) as a learning experience.
I'm going to assume you want bits carried from one byte to the next, as John Knoeller suggests. The requirements here are insufficient. You need to specify the order of the bits relative to the order of the bytes - when the least significant bit falls out of one byte, does to go to the next higher or next lower byte. What you are describing, though, used to be very common for graphics programming. You have basically described a monochrome bitmap horizontal scrolling algorithm. Assuming that "right" means higher addresses but less significant bits (ie matching the normal writing conventions for both) a single-bit shift will be something like... void scroll_right (unsigned char* p_Array, int p_Size) { unsigned char orig_l = 0; unsigned char orig_r; unsigned char* dest = p_Array; while (p_Size > 0) { p_Size--; orig_r = *p_Array++; *dest++ = (orig_l << 7) + (orig_r >> 1); orig_l = orig_r; } } Adapting the code for variable shift sizes shouldn't be a big problem. There's obvious opportunities for optimisation (e.g. doing 2, 4 or 8 bytes at a time) but I'll leave that to you. To shift left, though, you should use a separate loop which should start at the highest address and work downwards. If you want to expand "on demand", note that the orig_l variable contains the last byte above. To check for an overflow, check if (orig_l << 7) is non-zero. If your bytes are in an std::vector, inserting at either end should be no problem. EDIT I should have said - optimising to handle 2, 4 or 8 bytes at a time will create alignment issues. When reading 2-byte words from an unaligned char array, for instance, it's best to do the odd byte read first so that later word reads are all at even addresses up until the end of the loop. On x86 this isn't necessary, but it is a lot faster. On some processors it's necessary. Just do a switch based on the base (address & 1), (address & 3) or (address & 7) to handle the first few bytes at the start, before the loop. You also need to special case the trailing bytes after the main loop.
2,394,529
2,394,576
Memory Leaks - STL sets
I am trying to plug up all my memory leaks (which is massive). I am new to STL. I have a class library where I have 3 sets. I am also creating a lot of memory with new in the library class for adding info to the sets... Do I need to deallocate the sets? If so, how? Here is the library.h #pragma once #include <ostream> #include <map> #include <set> #include <string> #include "Item.h" using namespace std; typedef set<Item*> ItemSet; typedef map<string,Item*> ItemMap; typedef map<string,ItemSet*> ItemSetMap; class Library { public: // general functions void addKeywordForItem(const Item* const item, const string& keyword); const ItemSet* itemsForKeyword(const string& keyword) const; void printItem(ostream& out, const Item* const item) const; // book-related functions const Item* addBook(const string& title, const string& author, int const nPages); const ItemSet* booksByAuthor(const string& author) const; const ItemSet* books() const; // music-related functions const Item* addMusicCD(const string& title, const string& band, const int nSongs); void addBandMember(const Item* const musicCD, const string& member); const ItemSet* musicByBand(const string& band) const; const ItemSet* musicByMusician(const string& musician) const; const ItemSet* musicCDs() const; // movie-related functions const Item* addMovieDVD(const string& title, const string& director, const int nScenes); void addCastMember(const Item* const movie, const string& member); const ItemSet* moviesByDirector(const string& director) const; const ItemSet* moviesByActor(const string& actor) const; const ItemSet* movies() const; ~Library(); }; I am not sure what i need to do for the destructor? Library::~Library() { } also, am I de allocating the stringset right? #ifndef CD_H #define CD_H #pragma once #include "item.h" #include <set> typedef set<string> StringSet; class CD : public Item { public: CD(const string& theTitle, const string& theBand, const int snumber); void addBandMember(const string& member); const int getNumber() const; const StringSet* getMusician() const; const string getBand() const; virtual void print(ostream& out) const; string printmusicians(const StringSet* musicians) const; ~CD(); private: string band; StringSet* music; string title; int number; }; ostream& operator<<(ostream& out, const CD* cd); #endif cd.cpp #include "CD.h" using namespace std; CD::CD(const string& theTitle, const string& theBand, const int snumber) : Item(theTitle), band(theBand),number(snumber), music(new StringSet) { } CD::~CD() { delete []music; } in the library class I am creating a lot of memory, but dont the destructor clean that up? example: const Item* Library::addBook(const string& title, const string& author, const int nPages) { ItemSet* obj = new ItemSet(); Book* item = new Book(title,author,nPages); allBooks.insert(item); // add to set of all books obj->insert(item); Note: I do not have a copy constructor. I am not sure if I even need one or how top add one. I dont think my destructors are getting called either..
You need to free the memory for each element of the set. The container will not do that for you, and it shouldn't because it can't know whether it owns that data or not -- it could just be holding pointers to objects owned by something else. This is a generic free function that will deallocate any STL container. template <typename T> void deallocate_container(T& c) { for (typename T::iterator i = c.begin(); i != c.end(); ++i) delete *i; } // Usage set<SomeType*> my_set; deallocate_container(my_set); my_set.clear();
2,394,581
2,394,594
Pure Virtual Class and Collections (vector?)
I'm working on a graphics application that is using virtual classes fairly extensively. It has: A picture class, which is essentially a collection of shapes. A shapes class, which is purely virtual and has a few classes that inherit from it: Circle Polygon Rectangle A Figure shape, which is any graphical figure (also virtual), shape inherits from this. Essentially, my problem comes down to implementing the picture class, which is basically being used to store a collection of shapes. I'm currently using a Vector to store shapes, however, it's apparent that this is the wrong decision since Vector instantiates these shapes, which is not good as they are purely virtual. Below is my current code base (summarized a bit): class Figure { public: ... virtual ~Figure(); ... }; class Shape: public Figure { public: ... virtual ~Shape() {} virtual Shape* clone() const = 0; ... }; class Polygon : public Shape { public: ... virtual Shape* clone() const {return new Polygon(*this);} ... private: std::vector<Point> points; }; class Picture: public Figure { public: ... Picture(Graphics& gd); Picture (const Picture&); ~Picture(); void clear(); void add (const Shape&); ... private: std::vector<Shape> shapes; Graphics* gfx; }; //Picture implementation: ... Picture::Picture(Graphics& gd) { gfx = &gd; } Picture::Picture(const Picture& a) { shapes = a.shapes; } Picture::~Picture() { clear(); } void Picture::clear() { shapes.clear(); } void Picture::add (const Shape& shp) { Shape* nshp = shp.clone(); shapes.push_back(*nshp); } ... The error messages I'm getting are just a bunch of these: picture.cpp:33: instantiated from here /opt/local/bin/../lib/gcc/sparc-sun-solaris2.10/4.4.1/../../../../include/c++/4.4.1/ext/new_allocator.h:105: error: cannot allocate an object of abstract type 'Shape' shape.h:12: note: because the following virtual functions are pure within 'Shape': shape.h:58: note: virtual void Shape::get(std::istream&) shape.h:31: note: virtual void Shape::put(std::ostream&) const shape.h:36: note: virtual void Shape::scale(const Point&, double) shape.h:40: note: virtual void Shape::translate(double, double) shape.h:45: note: virtual void Shape::reflectHorizontally(double) shape.h:49: note: virtual void Shape::reflectVertically(double) shape.h:52: note: virtual RectangularArea Shape::boundingBox() const shape.h:21: note: virtual Shape* Shape::clone() const shape.h:55: note: virtual void Shape::draw(Graphics&) const So what is the ideal way to store these shapes. What kind of collection should I be using to store these things? Thanks
When you need polymorphism, you need to use either pointers or references. Since containers (or arrays) can't store references, you have to use pointers. Essentially change your picture class's vector to: std::vector<Shape*> and appropriately modify the other member functions. The reason why you can't/shouldn't store them as value types is because vector is a homogenous container i.e. it only stores data of one type (and only one type -- subclasses are not allowed!). The reason for this is because the vector stores its data in an array, which needs to know the size of the objects it's storing. If the sizes of these objects are different (which they might be for different shapes) then it can't store them in an array. If you store them as pointers then they all have the same size (sizeof(Shape*)) and also have access to the shape's vtable, which is what allows polymorphic behaviour.
2,394,815
2,394,844
testing a string to see if a number is present and asigning that value to a variable while skipping all the non-numeric values?
given a string say " a 19 b c d 20", how do I test to see if at that particular position on the string there is a number? (not just the character '1' but the whole number '19' and '20'). char s[80]; strcpy(s,"a 19 b c d 20"); int i=0; int num=0; int digit=0; for (i =0;i<strlen(s);i++){ if ((s[i] <= '9') && (s[i] >= '0')){ //how do i test for the whole integer value not just a digit //if number then convert to integer digit = s[i]-48; num = num*10+digit; } if (s[i] == ' '){ break; //is this correct here? do nothing } if (s[i] == 'a'){ //copy into a temp char } }
These are C solutions: Are you just trying to parse the numbers out of the string? Then you can just walk the string using strtol(). long num = 0; char *endptr = NULL; while (*s) { num = strtol(s, &endptr, 10); if (endptr == s) { // Not a number here, move on. s++; continue; } // Found a number and it is in num. Move to next location. s = endptr; // Do something with num. } If you have a specific location and number to check for you can still do something similar. For example: Is '19' at position 10? int pos = 10; int value = 19; if (pos >= strlen(s)) return false; if (value == strtol(s + pos, &endptr, 10) && endptr != s + pos) return true; return false; Are you trying to parse out the numbers without using any library routines? Note: I haven't tested this... int num=0; int sign=1; while (*s) { // This could be done with an if, too. switch (*s) { case '-': sign = -1; case '+': s++; if (*s < '0' || *s > '9') { sign = 1; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // Parse number, start with zero. num = 0; do { num = (num * 10) + (*s - '0'); s++; } while (*s >= '0' && *s <= '9'); num *= sign; // Restore sign, just in case sign = 1; // Do something with num. break; default: // Not a number s++; } }
2,394,869
2,394,913
Where can I find a good quick reference for learning C after years of C++?
I last used C professionally around 1997 IIRC. I've used a lot of C++ since then. Now, I find I need to use some C again. One thing I'm sure of is that I can't just drop the obvious C++ features (e.g. classes) and expect everything to work. There are various less obvious syntax changes. I just don't remember what they are. Is there a good reference for making that transition again, but returning to C? If it explains the changes in C99 (and later?) that's even better.
As dirkgently suggests, Harbison and Steele is a good reference, but I don't find it useful to brush up on. To retrain your mind, I have these suggestions: Reread Kernighan and Ritchie Optional: read Peter van der Linden's superb Expert C Programming: Deep C Secrets. Don't forget libraries! Look at P. J. Plauger's book The Standard C Library, or just go to http://dinkumware.com/ (Plauger's company) and browse their excellent documentation of the C99 libraries. Standard C lacks data-structure libraries. Fortunately there is an excellent, free 3rd-party library that fills several voids: Dave Hanson's C Interfaces and Implementations.
2,394,980
2,394,992
seekg() failing mysteriously
I have a 2884765579 bytes file. This is double checked with this function, that returns that number: size_t GetSize() { const size_t current_position = mFile.tellg(); mFile.seekg(0, std::ios::end); const size_t ret = mFile.tellg(); mFile.seekg(current_position); return ret; } I then do: mFile.seekg(pos, std::ios::beg); // pos = 2883426827, which is < than the file size, 2884765579 This sets the failbit. errno is not changed. What steps can I take to troubleshoot this? I am absolutely sure that: The file size is really 2884765579 pos is really 2884765579 The failbit is not set before .seekg() The failbit is set right after .seekg() and no other calls are made in between The file is opened with the binary flag EDIT: in case someone runs into the same problem.. Use this code I wrote (works on windows only) and many less headaches for you: class BinaryIFile { public: BinaryIFile(const string& path) : mPath(path), mFileSize(0) { mFile = open(path.c_str(), O_RDONLY | O_BINARY); if (mFile == -1) FATAL(format("Cannot open %s: %s") % path.c_str() % strerror(errno)); } ~BinaryIFile() { if (mFile != -1) close(mFile); } string GetPath() const { return mPath; } int64 GetSize() { if (mFileSize) return mFileSize; const int64 current_position = _telli64(mFile); _lseeki64(mFile, 0, SEEK_END); mFileSize = _telli64(mFile); _lseeki64(mFile, current_position, SEEK_SET); return mFileSize; } int64 Read64() { return _Read<int64>(); } int32 Read32() { return _Read<int32>(); } int16 Read16() { return _Read<int16>(); } int8 Read8() { return _Read<int8>(); } float ReadFloat() { return _Read<float>(); } double ReadDouble() { return _Read<double>(); } void Skip(int64 bytes) { _lseeki64(mFile, bytes, SEEK_CUR); } void Seek(int64 pos) { _lseeki64(mFile, pos, SEEK_SET); } int64 Tell() { return _telli64(mFile); } template <class T> T Read() { return _Read<T>(); } void Read(char *to, size_t size) { const int ret = read(mFile, (void *)to, size); if ((int)size != ret) FATAL(format("Read error: attempted to read %d bytes, read() returned %d, errno: %s [we are at offset %d, file size is %d]") % size % ret % strerror(errno) % Tell() % GetSize()); } template <class T> BinaryIFile& operator>>(T& val) { val = _Read<T>(); return *this; } private: const string mPath; int mFile; int64 mFileSize; template <class T> T _Read() { T ret; if (sizeof(ret) != read(mFile, (void *)&ret, sizeof(ret))) FATAL("Read error"); return ret; } };
You can seekg before a given position, so pos is signed. Try it with files of size 0x7fffffff and 0x80ffffff and see if the latter triggers the problem, that's my guess.
2,394,983
2,395,159
Is Unix coded in C or C++ or both?
Many system calls in Unix use overloading and default variables. This concept is absent in C, so Unix is coded in C++ also right?
Unix was first created at Bell Labs in 1969, well before C++ was conceived. (Src: Unix), you can confirm this by reading Lions' Commentary on Unix, or the BSD 4.4-Lite (which is similar to BSD Net/2) which is available in tarball or via cvs (from FreeBSD). Or the archives from The Unix Heritage Society which is from the very old Bell Labs / AT&T versions. Bjarne Stroustrup created C++ in approximately 1983, prior to that he worked on "C with Classes", according to History of C++. Confirmed from Bjarne Stroustrup's FAQ, and the earliest date for C with Classes was 1979. I hope that clarifies the impossibility of the idea that Unix was based upon C++. Note that Object-Oriented languages have been around since 1960s in Simula 67, so don't confuse objects and classes with C++.
2,395,040
2,395,103
How do Clang 'blocks' work?
http://clang.llvm.org/docs/BlockLanguageSpec.txt Looks really cool. However, I don't understand it. I don't see examples it. I don't see examples of ideas hard to express in C++ as is, but trivial to express in blocks. Can anyone enlighten me on this?
Blocks are, essentially, a way to pass code and scope around as data. They're known in some other languages as closures and anonymous functions. Here's an article with more details and code examples.
2,395,158
2,395,187
Linker error: "linker input file unused because linking not done", undefined reference to a function in that file
I'm having trouble with the linking of my files. Basically, my program consists of: The main program, gen1. gen1 - receives input sends to str2value for processing, outputs results str2value, breaks input into tokens using "tokenizer" determines what sort of processing to do to each token, and passes them off to str2num, or str2cmd. It then returns an array of the results. str2num - does some processing str2cmd - ditto author.py - a python script that generates str2cmd.c and str2cmd.h from a header cmdTable.h. I'm pretty sure I have my includes right, I've checked a couple of times. I've also checked that there are no conditions #ifndef wrong in the headers. Here is my Makefile: #CPP = g++ -lserial CPP = g++ -DTESTMODE C= gcc DEFINES = LURC CFLAGS = -Wall -fshort-enums -D$(DEFINES) PROJECTFILES = gen1.cpp str2value.o STR2VALUEFILES = str2value.cpp str2cmd.o str2num.o tokenizer.o str2value.h gen1 : $(PROJECTFILES) $(CPP) $(CFLAGS) -o gen1 $(PROJECTFILES) str2value.o : $(STR2VALUEFILES) # echo "str2value" $(CPP) $(CFLAGS) -c $(STR2VALUEFILES) str2num.o: str2num.cpp str2value.h str2num.hpp $(C) $(CFLAGS) -c $^ tokenizer.o: tokenizer.cpp tokenizer.hpp $(CPP) $(CFLAGS) -c $^ str2cmd.o : authorCMDs.py cmdTable.h python authorCMDs.py cmdTable.h str2cmd #this uses the gcc -E cmdTable.h -DLURC $(C) $(CFLAGS) -c str2cmd.c str2cmd.h #TODO: add a thing that checks str2cmd.h/.c has not been modified by hand .PHONEY: clean clean: rm *.o .PHONEY: all all: clear make clean make Here is the output I recieve from make all: make clean make[1]: Entering directory `/home/frames/LURC/gen1/gen1Source' rm *.o make[1]: Leaving directory `/home/frames/LURC/gen1/gen1Source' make make[1]: Entering directory `/home/frames/LURC/gen1/gen1Source' python authorCMDs.py cmdTable.h str2cmd #this uses the gcc -E cmdTable.h -DLURC str2cmd.c and str2cmd.h, generated from cmdTable.h gcc -Wall -fshort-enums -DLURC -c str2cmd.c str2cmd.h gcc -Wall -fshort-enums -DLURC -c str2num.cpp str2value.h str2num.hpp g++ -DTESTMODE -Wall -fshort-enums -DLURC -c tokenizer.cpp tokenizer.hpp g++ -DTESTMODE -Wall -fshort-enums -DLURC -c str2value.cpp str2cmd.o str2num.o tokenizer.o str2value.h g++: str2cmd.o: linker input file unused because linking not done g++: str2num.o: linker input file unused because linking not done g++: tokenizer.o: linker input file unused because linking not done g++ -DTESTMODE -Wall -fshort-enums -DLURC -o gen1 gen1.cpp str2value.o str2value.o: In function `getValue(char*)': str2value.cpp:(.text+0xbd): undefined reference to `str2cmd(char*)' str2value.cpp:(.text+0x102): undefined reference to `str2num(char*)' str2value.o: In function `getAllValues(char*)': str2value.cpp:(.text+0x164): undefined reference to `tokenizer::tokenizer(char*)' str2value.cpp:(.text+0x177): undefined reference to `tokenizer::getNumTokens(char const*)' str2value.cpp:(.text+0x1a9): undefined reference to `tokenizer::getNextToken(char const*)' str2value.cpp:(.text+0x1e9): undefined reference to `tokenizer::getNumTokens(char const*)' str2value.cpp:(.text+0x201): undefined reference to `tokenizer::~tokenizer()' str2value.cpp:(.text+0x25b): undefined reference to `tokenizer::~tokenizer()' collect2: ld returned 1 exit status make[1]: *** [gen1] Error 1 make[1]: Leaving directory `/home/frames/LURC/gen1/gen1Source' make: *** [all] Error 2 Any suggestions about what this is about? STR2VALUESFILES has all the object files I need, to define the missing functions.
I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that. All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols. Here's a small example (calling g++ explicitly for clarity): PROG ?= myprog OBJS = worker.o main.o all: $(PROG) .cpp.o: g++ -Wall -pedantic -ggdb -O2 -c -o $@ $< $(PROG): $(OBJS) g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS) There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.
2,395,178
2,395,203
Given N points in a 3D space, how to find the smallest sphere that contains these N points?
Given N points in a 3D space, how to find the smallest sphere that contains these N points?
This problem is called minimal enclosing ball problem. (google this term to find tutorials and papers on it). Here's one implementation: http://www.inf.ethz.ch/personal/gaertner/miniball.html in c++. Its 2d case (find a circle to enclose all points in a plane) is a classic example taught in computational geometry course. 3D is just a simple extension to the 2D case. One algorithm for this problem is incremental style. You start with 4 points and they fix a sphere, and when you add 5-th point, there are two cases: the point is in the sphere. no need to update. outside the point. In this case, you need to update your sphere. Then a non-trivial property is that this new point must be on your new sphere! Based on the above observation, your problem gets smaller. Read section 4.7 of this book. It is also available on google book.
2,395,275
2,395,311
How to navigate through a vector using iterators? (C++)
The goal is to access the "nth" element of a vector of strings instead of the [] operator or the "at" method. From what I understand, iterators can be used to navigate through containers, but I've never used iterators before, and what I'm reading is confusing. If anyone could give me some information on how to achieve this, I would appreciate it. Thank you.
You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively. using namespace std; vector<string> myvector; // a vector of stings. // push some strings in the vector. myvector.push_back("a"); myvector.push_back("b"); myvector.push_back("c"); myvector.push_back("d"); vector<string>::iterator it; // declare an iterator to a vector of strings int n = 3; // nth element to be found. int i = 0; // counter. // now start at from the beginning // and keep iterating over the element till you find // nth element...or reach the end of vector. for(it = myvector.begin(); it != myvector.end(); it++,i++ ) { // found nth element..print and break. if(i == n) { cout<< *it << endl; // prints d. break; } } // other easier ways of doing the same. // using operator[] cout<<myvector[n]<<endl; // prints d. // using the at method cout << myvector.at(n) << endl; // prints d.
2,395,300
2,395,317
std string problem with libcurl - c++
I'm pretty new to c++ and I'm using libcurl to make an http request and get back a string with the respond's content. size_t write_to_string(void *ptr, size_t size, size_t count, void *stream) { ((std::string*)stream)->append((char*)ptr, 0, size*count); return size*count; } int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.browsarity.com/"); std::string response; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); res = curl_easy_perform(curl); curl_easy_cleanup(curl); // The "response" variable should now contain the contents of the HTTP response } return 0; } after running the above code (with VS2005) I get this errors: 1>libcpmtd.lib(xdebug.obj) : error LNK2019: unresolved external symbol __malloc_dbg referenced in function "void * __cdecl operator new(unsigned int,struct std::_DebugHeapTag_t const &,char *,int)" (??2@YAPAXIABU_DebugHeapTag_t@std@@PADH@Z) 1>libcpmtd.lib(xdebug.obj) : error LNK2019: unresolved external symbol __free_dbg referenced in function "void __cdecl operator delete(void *,struct std::_DebugHeapTag_t const &,char *,int)" (??3@YAXPAXABU_DebugHeapTag_t@std@@PADH@Z) 1>libcpmtd.lib(stdthrow.obj) : error LNK2019: unresolved external symbol __CrtDbgReportW referenced in function "void __cdecl std::_Debug_message(wchar_t const *,wchar_t const *,unsigned int)" (?_Debug_message@std@@YAXPB_W0I@Z) its seems like its a problem with some libraries and I tried adding "msvcrtd.lib" and I still get the error above with additional new errors. Answer: I changed the Run Time Library from Multi-Threaded (/MT) to Multi-threaded Debug DLL (/MDd).
std::string generally should not be part of a public interface of a library distributed in binary form (object, static lib, or DLL). But libcurl is pretty intelligently designed, probably the std::string support is provided by an include file (that's ok) which converts things to a portable format before calling into the library. I think you just need to be careful to link your debug builds with the debug version of libcurl, and your release builds with the release version. Otherwise part of your program wants msvcrt.lib and part wants msvcrtd.lib, and they conflict if you try to use both at once. EDIT in response to the asker's comment: There's a dropdown combo box in the compile/build toolbar, that lets you select between Debug and Release configurations. Also, the Linker "Additional Inputs" setting in the project properties can have different values for Debug and Release. Probably the debug version should use "libcurld.lib" and the release version "libcurl.lib", but not everyone follows that same convention. If you added the .lib file to your project instead of listing it in the link options, you can still do this by adding both variants and setting "Exclude this file from the build" appropriately. But this looks ugly and will confuse anyone else who works on the project. I would use the Linker options in the project properties.
2,395,501
2,396,064
Passing non-Global C++ objects to Lua functions (Swig)
I am extending an interface with lua, and I've run into a problem in that I would need to pass pointers to objects to the lua code to work upon. These classes will have been wrapped via SWIG, and I could instantiate them via lua using swig, but that would leave me with useless objects. I need to be able to pass a callback object to lua, as well as objects representing things on events. I cannot manually define the callback as global because that would introduce a constraint which is unnacceptable. So for a generic example, given a class C and a function in lua that takes 1 parameter, how do I call that lua function while passing it the C++ pointer of type C?
Aha, answering my own question, but I founds it! http://lua-users.org/lists/lua-l/2007-05/msg00053.html Hello Joey, I do almost all my SWIG-LUA work from the lua side. Swig is really good for just wrappering up a C/C++ library to get it readable by lua. Getting the C++ to talk to lua is fairly easy, but not well documented. You idea of lua_pushlightuserdata(), was close, but not there. You probably want something like this: Foo* p= new Foo(); SWIG_NewPointerObj(L,p,SWIGTYPE_p_Foo,1); lua_setglobal (L, "p"); The SWIG_NewPointerObj() creates a userdata (not a lightuserdata) for the foo object & pushes it to the stack. The last param (in this case 1) is whether you want lua to manage the memory (0 for no, 1 for yes). The SWIG_NewPointerObj() and SWIGTYPE_p_Foo are both found in the wrapping file. Once you have that you should be able to do in lua: print(p) print(swig_type(p)) p:some_function() Let me know if you have any other questions. Regards, Mark
2,395,514
2,395,521
Is wchar_t just a typedef of unsigned short?
for example, does: wchar_t x; translate to: unsigned short x;
In short: in C may be in C++ no. Widely. C defines wchar_t as typedef but in Unix it is generally 4 bytes (so generally not short) and in Windows 2 so it may be short. Under C++ it is unique built-in type like char or int, so you can legally overload void foo(short x) and void foo(wchar_t x)
2,395,552
2,395,568
C++: having trouble linking from command line
Just getting started with C++ here. I am working on OSX with Eclipse CDT. I have a project with some custom classes and two files "Test.hpp" and "Test.cpp" - the later with my main() method that runs some tests that I have defined and implemented in these two files. I can compile and run from Eclipse with no problems, but when I try to compile from the command line with "g++ Test.cpp" I get a lot of linking errors that basically list all the methods defined in or referenced from Test.cpp as undefined symbols. I have compiled a few basic programs (one header file and one implementation file) in similar manner from the command line without any problems, but I can't figure out why this one won't work. Please help! EDIT: It wasn't clear from my wording, but yes I have other source files too. The accepted answer did the trick: "g++ Test.cpp Other1.cpp Other2.cpp". Thank you.
Command 'g++ Test.cpp' does both compilation and linking. If you have many source files, you should link Test.cpp with them too like 'g++ Test.cpp other1.cpp other2.cpp' or just compile all files and link them all together later like 'g++ Test.o other1.o other2.o'.
2,395,613
2,395,626
Question on overloading operator+
Consider the following code: class A { public: A& operator=( const A& ); const A& operator+( const A& ); const A& operator+( int m ); }; int main() { A a; a = ( a + a ) + 5; // error: binary '+' : no operator found which takes a left-hand operand of type 'const A' } Can anyone explain why the above is returned as an error? "( a + a )" calls "const A& operator+( const A& )" and returns a constant reference which is then passed to "const A& operator+( int m )" if I'm not mistaken. How can one fix the above error (without creating a global binary operator+ or a constructor that accepts an int) such that the statement inside main() is allowed?
which is then passed to "const A& operator+( int m )" if I'm not mistaken No. Since the LHS is a const A& and RHS is an int, it will call* [anyType] operator+ (int rhs) const // ^^^^^ note the const here. as you've only provided the non-const version const A& operator+( int m ), the compiler will complain. *: Or operator+(const int& rhs) const or operator+(float rhs) const... The crucial point is that it must be a const method.
2,395,703
2,395,756
Variable sized packet structs with vectors
Lately I've been diving into network programming, and I'm having some difficulty constructing a packet with a variable "data" property. Several prior questions have helped tremendously, but I'm still lacking some implementation details. I'm trying to avoid using variable sized arrays, and just use a vector. But I can't get it to be transmitted correctly, and I believe it's somewhere during serialization. Now for some code. Packet Header class Packet { public: void* Serialize(); bool Deserialize(void *message); unsigned int sender_id; unsigned int sequence_number; std::vector<char> data; }; Packet ImpL typedef struct { unsigned int sender_id; unsigned int sequence_number; std::vector<char> data; } Packet; void* Packet::Serialize(int size) { Packet* p = (Packet *) malloc(8 + 30); p->sender_id = htonl(this->sender_id); p->sequence_number = htonl(this->sequence_number); p->data.assign(size,'&'); //just for testing purposes } bool Packet::Deserialize(void *message) { Packet *s = (Packet*)message; this->sender_id = ntohl(s->sender_id); this->sequence_number = ntohl(s->sequence_number); this->data = s->data; } During execution, I simply create a packet, assign it's members, and send/receive accordingly. The above methods are only responsible for serialization. Unfortunately, the data never gets transferred. Couple of things to point out here. I'm guessing the malloc is wrong, but I'm not sure how else to compute it (i.e. what other value it would be). Other than that, I'm unsure of the proper way to use a vector in this fashion, and would love for someone to show me how (code examples please!) :) Edit: I've awarded the question to the most comprehensive answer regarding the implementation with a vector data property. Appreciate all the responses!
This cast is very dangerous as you have allocated some raw memory and then treated it as an initialized object of a non-POD class type. This is likely to cause a crash at some point. Packet* p = (Packet *) malloc(8 + 30); Looking at your code, I assume that you want to write out a sequence of bytes from the Packet object that the seralize function is called on. In this case you have no need of a second packet object. You can create a vector of bytes of the appropriate size and then copy the data across. e.g. void* Packet::Serialize(int size) { char* raw_data = new char[sizeof sender_id + sizeof sequence_number + data.size()]; char* p = raw_data; unsigned int tmp; tmp = htonl(sender_id); std::memcpy(p, &tmp, sizeof tmp); p += sizeof tmp; tmp = htonl(sequence_number); std::memcpy(p, &tmp, sizeof tmp); p += sizeof tmp; std::copy(data.begin(), data.end(), p); return raw_data; } This may not be exactly what you intended as I'm not sure what the final object of your size parameter is and your interface is potentially unsafe as you return a pointer to raw data that I assume is supposed to be dynamically allocated. It is much safer to use an object that manages the lifetime of dynamically allocated memory then the caller doesn't have to guess whether and how to deallocate the memory. Also the caller has no way of knowing how much memory was allocated. This may not matter for deallocation but presumably if this buffer is to be copied or streamed then this information is needed. It may be better to return a std::vector<char> or to take one by reference, or even make the function a template and use an output iterator.
2,395,949
2,395,990
Copy Directory - Post Build Event
How do I copy some directory from one place to another (not file by file) in post build event (whats the comman line??). im using vs 2005 (c++ project)
The commandline is simply a batch script that is executed upon completion of the build. Therefore, you can just use regular Windows shell commands, such as mkdir, copy, ... To copy whole directories recursively, use xcopy <src> <dest> /E.
2,395,954
2,396,173
C++: building iterator from bits
I have a bitmap and would like to return an iterator of positions of set bits. Right now I just walk the whole bitmap and if bit is set, then I provide next position. I believe this could be done more effectively: for example build statically array for each combination of bits in single byte and return vector of positions. This can't be done for a whole int, because array would be too big. But maybe there are some better solutions? Do you know any smart algorithms for this?
I can suggest several ideas. Turns out modern CPUs have dedicated instructions for finding the next set bit in a 32- or 64-bit word. I like very much your idea of constructing the iterator for the whole bitmap from prepared efficient per-byte mini-iterators, this is really cool and I'm surprised I've never seen it before! If your bitmap is very sparse, you may represent it in some other form, such as a balanced tree, where iteration algorithms are quite well-known. If your bitmap is sparse but with dense regions (that sounds exotic, but I've encountered situations where this was exactly the case), use a balanced tree of small (32-bit or 64-bit) bitmaps and use a combined iteration algorithm for a tree and for bits of a word. To avoid the memory overhead of an explicit tree, use an implicit one, like in the canonical heapsort algorithm. After your bitset is ready and will not be mutated, build a "pyramid" on top of it where level(N+1)[i] = level(N)[2*i] | level(N)[2*i+1]. This will allow you to rapidly skip uninhabited regions of the bitset, and iteration will be done in a fashion similar to iterating over a regular binary tree. You might as well build a pyramid of inhabitance, starting from bytes, etc.: it all depends on how sparse your bitset it. There are well-known bit tricks for finding the number of leading zeros in a word; see, for example, the code of java's standard libraries: You might gain a lot of performance by using a passive iterator instead of an active one, t.i. instead of begin() and operator++(), provide a foreach(F) function for your bitset where F has operator(). If you need passive iteration with premature termination, make F's operator() return a boolean that denotes whether termination is requested. EDIT: I couldn't resist trying out your approach with preparing iterators for bytes. I wrote a code generator into C#2.0 that produces code of the following form: IEnumerable<int> bits(byte[] bytes) { for(int i=0; i<bytes.Length; ++i) { int oi=8*i; switch(bytes[i]) { .... case 74: yield return oi+1; yield return oi+4; yield return oi+6; break; .... } } } I compared its performance for counting bits of a random 50%-filled byte array (10Mb) with the performance of code that does not use iterators at all and consists of two loops: for (int i = 0; i < bytes.Length; ++i) { byte b = bytes[i]; for (int j = 7; j >= 0; --j) { if (((int)b & (1 << j)) != 0) s++; } } The second code snippet is just some 1.66 times faster than the first one (~1.5s vs ~2.5s). I think that sparser bit arrays might even make the first code outperform the second one.
2,395,999
2,396,010
Inserting into a specific part of a string using iterators? (C++)
string str = "one three"; string::iterator it; string add = "two "; Lets say I want to add: "two " right after the space in "one". the space would be str[3] correct? so: in this case, n = 3; for (it=str.begin(); it < str.end(); it++,i++) { if(i == n) { // insert string add at current position break; } // if at correct position } // for *it would allow me to access the character at str[3], but I don't know how I would add in the string from there. Any help is appreciated, thanks. If anything is confusing or unclear please let me know
You can make use of the insert method of the string class. string str = "one three"; string add = "two "; str.insert(4,add); // str is now "one two three"
2,396,019
2,396,028
C++ templates hides parent members
Usually, when A is inheriting from B, all the members of A are automatically visible to B's functions, for example class A { protected: int a; }; class B : public A { int getA() {return a;} //no need to use A::a, it is automatically visible }; However when I'm inheriting with templates, this code becomes illegal (at least in gcc) template<typename T> class A { protected: int a; }; template<typename T> class B : public A<T> { int getA() {return a;} }; templt.cpp: In member function `int B<T>::getA()': templt.cpp:9: error: `a' undeclared (first use this function) templt.cpp:9: error: (Each undeclared identifier is reported only once for each function it appears in.) I must do one of class B : public A<T> { using B::a; int getA() {return a;} }; class B : public A<T> { using A<T>::a; int getA() {return a;} }; class B : public A<T> { int getA() {return B::a;} }; etc. As if the variable a is hidden by another variable of B, in the following case: class HiddenByOverload {void hidden(){}} class HidesByOverload : public HiddenByOverload { void hidden(int i) {} //different signature, now `hidden` is hidden void usehidden() { HiddenByOverload::hidden(); // I must expose it explicitly } } Why is it so? Are there any other ways to prevent C++ from hiding the parent template class' variables? Edit: thanks for everyone for the fascinating discussion. I must admit I didn't follow the argument which quoted paragraphs from the C++ standard. It's hard for me to follow it without reading the actual source. The best thing I can do to summarize the discussion, is quoting a short line from "The Zen of Python": If the implementation is hard to explain, it's (probably) a bad idea.
You can also do class B : public A<T> { int getA() {return this->a;} }; The problem is that the member is in a base, which depends on a template parameter. Normal unqualified lookup is performed at the point of definition, not at the point of instantiation, and therefore it doesn't search dependent bases.
2,396,065
2,396,122
C++ overloading operator comma for variadic arguments
is it possible to construct variadic arguments for function by overloading operator comma of the argument? i want to see an example how to do so.., maybe something like this: template <typename T> class ArgList { public: ArgList(const T& a); ArgList<T>& operator,(const T& a,const T& b); } //declaration void myFunction(ArgList<int> list); //in use: myFunction(1,2,3,4); //or maybe: myFunction(ArgList<int>(1),2,3,4);
It is sort-of possible, but the usage won't look very nice. For exxample: #include <vector> #include <iostream> #include <algorithm> #include <iterator> template <class T> class list_of { std::vector<T> data; public: typedef typename std::vector<T>::const_iterator const_iterator; const_iterator begin() const { return data.begin(); } const_iterator end() const { return data.end(); } list_of& operator, (const T& t) { data.push_back(t); return *this; } }; void print(const list_of<int>& args) { std::copy(args.begin(), args.end(), std::ostream_iterator<int>(std::cout, " ")); } int main() { print( (list_of<int>(), 1, 2, 3, 4, 5) ); } This shortcoming will be fixed in C++0x where you can do: void print(const std::initializer_list<int>& args) { std::copy(args.begin(), args.end(), std::ostream_iterator<int>(std::cout, " ")); } int main() { print( {1, 2, 3, 4, 5} ); } or even with mixed types: template <class T> void print(const T& t) { std::cout << t; } template <class Arg1, class ...ArgN> void print(const Arg1& a1, const ArgN& ...an) { std::cout << a1 << ' '; print(an...); } int main() { print( 1, 2.4, 'u', "hello world" ); }
2,396,087
2,396,170
Direct3D - How do I calculate Roll from View Matrix?
This one has been eating up my entire night, and I'm finally throwing up my hands for some assistance. Basically, it's fairly straightforward to calculate the Pitch and Yaw from the View Matrix right after you do a camera update: D3DXMatrixLookAtLH(&m_View, &sCam.pos, &vLookAt, &sCam.up); pDev->SetTransform(D3DTS_VIEW, &m_View); // Set the camera axes from the view matrix sCam.right.x = m_View._11; sCam.right.y = m_View._21; sCam.right.z = m_View._31; sCam.up.x = m_View._12; sCam.up.y = m_View._22; sCam.up.z = m_View._32; sCam.look.x = m_View._13; sCam.look.y = m_View._23; sCam.look.z = m_View._33; // Calculate yaw and pitch and roll float lookLengthOnXZ = sqrtf( sCam.look.z^2 + sCam.look.x^2 ); fPitch = atan2f( sCam.look.y, lookLengthOnXZ ); fYaw = atan2f( sCam.look.x, sCam.look.z ); So my problem is: there must be some way to obtain the Roll in radians similar to how the Pitch and Yaw are being obtained at the end of the code there. I've tried several dozen algorithms that seemed to make sense to me, but none of them gave quite the desired result. I realize that many developers don't track these values, however I am writing some re-centering routines and setting clipping based on the values, and manual tracking breaks down as you apply mixed rotations to the View Matrix. So, does anyone have the formula for getting the Roll in radians (or degrees, I don't care) from the View Matrix?
It seems the Wikipedia article about Euler angles contains the formula you're lookin for at the end.
2,396,106
2,396,387
Most efficient way to add data to an instance
I have a class, let's say Person, which is managed by another class/module, let's say PersonPool. I have another module in my application, let's say module M, that wants to associate information with a person, in the most efficient way. I considered the following alternatives: Add a data member to Person, which is accessed by the other part of the application. Advantage is that it is probably the fastest way. Disadvantage is that this is quite invasive. Person doesn't need to know anything about this extra data, and if I want to shield this data member from other modules, I need to make it private and make module M a friend, which I don't like. Add a 'generic' property bag to Person, in which other modules can add additional properties. Advantage is that it's not invasive (besides having the property bag), and it's easy to add 'properties' by other modules as well. Disadvantage is that it is much slower than simply getting the value directly from Person. Use a map/hashmap in module M, which maps the Person (pointer, id) to the value we want to store. This looks like the best solution in terms of separation of data, but again is much slower. Give each person a unique number and make sure that no two persons ever get the same number during history (I don't even want to have these persons reuse a number, because then data of an old person may be mixed up with the data of a new person). Then the external module can simply use a vector to map the person's unique number to the specific data. Advantage is that we don't invade the Person class with data it doesn't need to know of (except his unique nubmer), and that we have a quick way of getting the data specifically for module M from the vector. Disadvantage is that the vector may become really big if lots of persons are deleted and created (because we don't want to reuse the unique number). In the last alternative, the problem could be solved by using a sparse vector, but I don't know if there are very efficient implementations of a sparse vector (faster than a map/hashmap). Are there other ways of getting this done? Or is there an efficient sparse vector that might solve the memory problem of the last alternative?
The first and third are reasonably common techniques. The second is how dynamic programming languages such as Python and Javascript implement member data for objects, so do not dismiss it out of hand as impossibly slow. The fourth is in the same ballpark as how relational databases work. It is possible, but difficult, to make relational databases run the like the clappers. In short, you've described 4 widely used techniques. The only way to rule any of them out is with details specific to your problem (required performance, number of Persons, number of properties, number of modules in your code that will want to do this, etc), and corresponding measurements. Another possibility is for module M to define a class which inherits from Person, and adds extra data members. The principle here is that M's idea of a person differs from Person's idea of a person, so describe M's idea as a class. Of course this only works if all other modules operating on the same Person objects are doing so via polymorphism, and furthermore if M can be made responsible for creating the objects (perhaps via dependency injection of a factory). That's quite a big "if". An even bigger one, if nothing other than M needs to do anything life-cycle-ish with the objects, then you may be able to use composition or private inheritance in preference to public inheritance. But none of it is any use if module N is going to create a collection of Persons, and then module M wants to attach extra data to them.
2,396,133
2,396,195
OpenGL multiple texture mapping on a cube using GLUT
Have been trying to figure out how to put a different texture on each side of a cube using OpenGL and GLUT. I can get it to be a simple texture but multiple texture won't. I would put up my code but it is ugly and cluttered right now. If this is pretty easy to do please post some code for me to follow. Thanks!
its NEHE openGL lesson #22 http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=22 , then if you want to have different texture for each face, you can modify the cube rendering part for each face by switching glClientActiveTextureARB(GL_TEXTURE0_ARB); ,or glClientActiveTextureARB(GL_TEXTURE1_ARB); depend on the number of texture you have. for example: ` // Back Face glClientActiveTextureARB(GL_TEXTURE0_ARB); glNormal3f( 0.0f, 0.0f,-1.0f); for (i=4; i<8; i++) { glTexCoord2f(data[5*i],data[5*i+1]); glVertex3f(data[5*i+2],data[5*i+3],data[5*i+4]); } // Top Face glClientActiveTextureARB(GL_TEXTURE1_ARB); glNormal3f( 0.0f, 1.0f, 0.0f); for (i=8; i<12; i++) { glTexCoord2f(data[5*i],data[5*i+1]); glVertex3f(data[5*i+2],data[5*i+3],data[5*i+4]); } ` disclaimer: i never test those codes, its based on my memory, you should check ii'am in doubt whether it was glClientActiveTexture() or glActiveTexture()
2,396,328
2,396,340
Get HModule from inside a DLL
I need to load some resource from my DLL (i need to load them from the DLL code), for doing that I'm using FindResource. To do that i need the HModule of the DLL. How to find that? (I do not know the name (filename) of the DLL (the user can change it))
The first argument to DllMain() is the HMODULE of the DLL.
2,396,370
2,396,420
How to make google-test classes friends with my classes?
I heard there is a possibility to enable google-test TestCase classes friends to my classes, thus enabling tests to access my private/protected members. How to accomplish that?
Try this (straight from Google Test docs...): FRIEND_TEST(TestCaseName, TestName); For example: // foo.h #include <gtest/gtest_prod.h> // Defines FRIEND_TEST. class Foo { ... private: FRIEND_TEST(FooTest, BarReturnsZeroOnNull); int Bar(void* x); }; // foo_test.cc ... TEST(FooTest, BarReturnsZeroOnNull) { Foo foo; EXPECT_EQ(0, foo.Bar(NULL)); // Uses Foo's private member Bar(). }
2,396,430
2,397,588
How to use lock in OpenMP?
I have two pieces of C++ code running on 2 different cores. Both of them write to the same file. How to use OpenMP and make sure there is no crash?
You want the OMP_SET_LOCK/OMP_UNSET_LOCK functions: https://hpc.llnl.gov/tuts/openMP/#OMP_SET_LOCK Basically: omp_lock_t writelock; omp_init_lock(&writelock); #pragma omp parallel for for ( i = 0; i < x; i++ ) { // some stuff omp_set_lock(&writelock); // one thread at a time stuff omp_unset_lock(&writelock); // some stuff } omp_destroy_lock(&writelock); Most locking routines such as pthreads semaphores and sysv semaphores work on that sort of logic, although the specific API calls are different.
2,396,467
2,396,480
Using C Code in C++ Project
I want to use this C code in my C++ project : mysql.c : /* Simple C program that connects to MySQL Database server*/ #include <mysql.h> #include <stdio.h> #include <string.h> main() { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "localhost"; char *user = "root"; char *password = "rebourne"; /* set me first */ char *database = "mydb"; conn = mysql_init(NULL); /* Connect to database */ if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } /* send SQL query */ if (mysql_query(conn, "show tables")) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } res = mysql_use_result(conn); /* output table name */ printf("MySQL Tables in mysql database:\n"); while ((row = mysql_fetch_row(res)) != NULL) printf("%s \n", row[0]); /* close connection */ mysql_free_result(res); mysql_close(conn); } it compiles with gcc : gcc -o output-file $(mysql_config --cflags) mysql.c $(mysql_config --libs) but not with g++ .. What would you do ? edit : The Error is : exit(1); was not declared in this Scope
First things first: it would probably be a lot more helpful if you showed us the compilation errors. That being said, my initial instinct is to suggest: extern "C" { #include <mysql.h> #include <stdio.h> #include <string.h> } This is a guess right now, but without the actual error messages it's the best you're going to get. Oh, and perhaps renaming the file to end in .cpp, .c++ or .C (uppercase) would help.
2,396,548
2,396,827
Appending to boost::filesystem::path
I have a certain boost::filesystem::path in hand and I'd like to append a string (or path) to it. boost::filesystem::path p("c:\\dir"); p.append(".foo"); // should result in p pointing to c:\dir.foo The only overload boost::filesystem::path has of append wants two InputIterators. My solution so far is to do the following: boost::filesystem::path p2(std::string(p.string()).append(".foo")); Am I missing something?
#include <iostream> #include <string> #include <boost/filesystem.hpp> int main() { boost::filesystem::path p (__FILE__); std::string new_filename = p.leaf() + ".foo"; p.remove_leaf() /= new_filename; std::cout << p << '\n'; return 0; } Tested with 1.37, but leaf and remove_leaf are also documented in 1.35. You'll need to test whether the last component of p is a filename first, if it might not be.
2,396,576
2,396,592
How to get the cursor position
I want to know how to get the cursor position on Windows in c++, Reasons: I try to move the mouse position on X Y coordinate with the screen information e.g: i want to set the mouse position in the offset x:576 y:854 on the screen. The only method that I found for do that is: mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE|MOUSEEVENTF_LEFTDOWN,x,y,0,0); Normally the flag MOUSEEVENTF_ABSOLUTE is to do that but it doesn't work, that's why i try to get the absolute position of the mouse and try to calculate that ! Thank you for your answer !
Try GetCursorPos().
2,396,632
2,396,669
How To Shift Array Elements to right and replace the shifted index with string in Visual C++
VISUAL C++ Question Hi, I have array of 3 elements and I want to shift its elements to the right and replace the shifted index cell with "SHIFTED" string and this should loop until all the cells has "SHIFTED" string. For example: int a[x]={0,1,2}; Initial index and elements Order: [0]=0 [1]=1 [2]=2 should become in the: 1st loop: [0]=SHIFTED [1]=0 [2]=1 2nd Loop: [0]=SHIFTED [1]=SHIFTED [2]=0 3rd Loop: [0]=SHIFTED [1]=SHIFTED [2]=SHIFTED I know I can do that with memmove() but I don't want to use any function in it. Would you please help me; here is my work: #include <iostream> #include <string> #include <stdio.h> #include <cstdlib> using namespace std; int const ARRAY_SIZE=3; int main() { int Array[ARRAY_SIZE]; int iniPostion,newPostion; string x="SHIFTED"; for(iniPostion=0; iniPostion<ARRAY_SIZE; iniPostion++) { Array[iniPostion] = iniPostion; cout << "Cell [" << iniPostion << "] Initial Element is: (" << Array[iniPostion] << ")" << endl; } cout << endl; for(newPostion=0; newPostion<ARRAY_SIZE; newPostion++) { Array[newPostion]=newPostion; cout << "Cell [" << newPostion << "] New Element is: ("; if(Array[newPostion-1]<0) { cout << x << ")\n"; } else { cout << Array[newPostion-1] << ")" << endl; } } return 0; }
As Peter mentioned in his answer, you cannot assign a string to a int. I've assumed SHIFTED to be -1. So every time you shift you bring in a -1 in the gap created. You need two loops. The outer loops iterates N (3) times and inner loop starts at the end of the array and copies (n-1)th element to nth position: for(int count = 0;count < N;count++){ for(newPostion=ARRAY_SIZE-1; newPostion > count;newPostion--) Array[newPostion]=Array[newPostion - 1]; // copy Array[newPostion]= -1; // fill the gap. // print. for(iniPostion=0; iniPostion<ARRAY_SIZE; iniPostion++) { cout << "Cell [" << iniPostion << "] Initial Element is: (" << Array[iniPostion] << ")" << endl; } cout<<endl; } Sample run: # g++ a.cpp && ./a.out Cell [0] Initial Element is: (0) Cell [1] Initial Element is: (1) Cell [2] Initial Element is: (2) Cell [0] Initial Element is: (-1) Cell [1] Initial Element is: (0) Cell [2] Initial Element is: (1) Cell [0] Initial Element is: (-1) Cell [1] Initial Element is: (-1) Cell [2] Initial Element is: (0) Cell [0] Initial Element is: (-1) Cell [1] Initial Element is: (-1) Cell [2] Initial Element is: (-1)
2,396,744
2,396,971
QTableView has unwanted checkboxes in every cell
I'm just getting started with Qt programming, and I'm trying to make a simple tabular data layout using a QTableView control with a model class of my own creation inheriting from QAbstractTableModel. For some reason, my table view ends up looking like this: (source: nerdland.net) What in the heck are those things that look like checkboxes (but don't do anything when I click them) in every cell, and how do I make them go away? I haven't changed any of the QTableView properties except for the object's name. If it matters, my model code is dead simple: MyTableModel::MyTableModel(QObject* parent) : QAbstractTableModel(parent) { } MyTableModel::~MyTableModel() { } int MyTableModel::rowCount(const QModelIndex& parent) const { return 1000; } int MyTableModel::columnCount(const QModelIndex& parent) const { return 5; } QVariant MyTableModel::data(const QModelIndex& index, int role) const { return "Foo"; } The dialog UI is built in Qt Designer, and inside the class for the dialog I attach the model to the view like this: MyTableModel testModel = new MyTableModel(this); ui.testTable->setModel(testModel); Other than that I perform no operations on ui.testTable. Using Qt 4.6.
Try changing MyTableModel::data() to the following: QVariant MyTableModel::data(const QModelIndex& index, int role) const { if (role == Qt::DisplayRole) return "foo"; else return QVariant(); } Probably the returned QVariant for role Qt::CheckStateRole was misunderstood by the QTableView.
2,397,005
2,397,483
vertical text won't be bold in win32 GDI c++
I'm trying to draw vertical text in win32 GDI api. I call CreateFont() with 2700 for the angle and 900 for bold. logPxlY = ::GetDeviceCaps (c->_hdc, LOGPIXELSY); _hfont = ::CreateFont (-::MulDiv (point, logPxlY, 72), 0, angle, weight, 0, FALSE, FALSE, FALSE, 0, 0, 0, 0, FIXED_PITCH | FF_MODERN, face); where face is "Courier New", point is 9, angle is 2700 and weight is 900. The text IS rotated correctly, but it's pretty dang faint compared to normal Courier New rendering. Is this since truetype is polishing the normal text real nice and isn't bothering with wierd rotated text or something? Thanks for any insight :)
The font mapper can be a bit strange at times. 700 is bold, 900 is supposed to be "black". However, you probably have a Courier New Bold font file, so it can be used directly, whereas you probably do not have a Courier New Black font file, so it'll be synthesized -- probably from the normal Courier New font instead of from Courier New Bold (not sure why that is, but such is life). If you try running through the possibilities, something like this (MFC code, for the moment, but the idea applies regardless): CFont fonts[num]; pDC->SetBkMode(TRANSPARENT); for (int i=0; i<num; i++) { fonts[i].CreateFont(10, 0, 2700, 0, i*100, 0, 0, 0, DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, OUT_CHARACTER_PRECIS, PROOF_QUALITY, FF_MODERN, L"Courier New"); pDC->SelectObject(fonts+i); pDC->TextOut(20+i*14, 20, L"This is some text"); } What you'll probably see (what I get anyway) looks like this: The 700 weight font is noticeably bolder than the 800 or 900 weight. This is not unique to Courier New either -- for example, the same code with the font name changed to Times New Roman produces output like this: That's a bit closer, but the 700 weight still clearly looks darker than the 800 or 900. I won't bore you with screen shots, but the same effect happens when the text is horizontal. Edit: One other minor detail: though it probably doesn't make any difference, you're currently computing the size of the font a bit incorrectly -- you're using logpixelsy, which makes sense when the font is horizontal. For a vertical font, you should use logpixelsx instead. On a typical screen, those will be identical, but on a printer (for example) they may be substantially different.
2,397,103
2,397,118
I have a text-box and I want to enter a string in language A
I have a text-box, and I want to enter a string in language A and send it to Google Translate. After Google has translated it, I want to take the new string (in language B) (after translation) and store it in some variable. How can I do it?
The basic idea is shown in a simple example of Language Translation like this: google.language.translate("Hello world", "en", "es", function(result) { if(!result.error) { var container = document.getElementById("translation"); container.innerHTML = result.translation; } }); translation is the id of your textbox. In this case where you put the translation result. result is the translation itself. You can assign it to a new variable in any way you want. In the above example you're translating "Hello world" from "en" (English) to "es" (Spanish). The above code is written in JavaScript. Take a look at Google AJAX Language API for more detailed steps.
2,397,297
2,397,593
Iphone, callback and objective c
I am using a c++ library using callback to inform about the progress of an operation. Everything is working fine except this: I need to have a function in my controller to be use as a c++ callback function. I've tried a lot of things but none of them are working. Do you know how we can manage this kind of thing? Thanks :)
You have to define a c++-class in your .h with your callback methods, implementing the c++-interface. This class also keeps a delegate of your objC Class. in your .m File after @end you specify the c++ methods. You may then use the delegate to perform selectors of your objC class in .h @interface YourObjcClass { #ifdef __cplusplus class FooObserver : public YourNS::Interface { public: virtual ~FooObserver() { } YourObjcClass *delegate; }; YourNS::YourCallbackClass *myCallbackClass; #endif in .m #ifdef __cplusplus void FooObserver::callback( args ) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; [delegate performSelectorOnMainThread:@selector(performCallback) withObject:nil waitUntilDone:false]; [pool release]; } #endif
2,397,309
2,397,320
error: '' has not been declared
I'm trying to implement a linked list but get an error when compiling: intSLLst.cpp:38: error: ‘intSLList’ has not been declared intSLList looks like it's been declared to me though so I'm really confused. intSLLst.cpp #include <iostream> #include "intSLLst.h" int intSLList::deleteFromHead(){ } int main(){ } intSLLst.h #ifndef INT_LINKED_LIST #define INT_LINKED_LIST #include <cstddef> class IntSLLNode{ int info; IntSLLNode *next; IntSLLNode(int el, IntSLLNode *ptr = NULL){ info = el; next = ptr; } }; class IntSLList{ public: IntSLList(){ head = tail = NULL; } ~IntSLList(); int isEmpty(); bool isInList(int) const; void addToHead(int); void addToTail(int); int deleteFromHead(); int deleteFromTail(); void deleteNode(int); private: IntSLLNode *head, *tail; }; #endif
You're using a lower case i int intSLList::deleteFromHead(){ } should be int IntSLList::deleteFromHead(){ } Names in c++ are always case sensitive.
2,397,354
2,397,384
How to prevent double inclusion of a .lib when inheriting dependencies?
I'm working to a Visual C++ 2008 project which needs two libraries (A and B), both of them are compiled using a a particular .lib (C). When I compile my project I'm asked for C again, and thus I specify it in the additional libraries. Then everything goes ok until the linking phase, where I get errors for external symbols which are defined more than once. Is there a way to exclude them from the linking? Thank you Tommaso
This sounds like you're adding two different versions of this library (Debug/Release, MT/ST etc.). Otherwise the linker would just ignore the second one.
2,397,578
2,397,637
How to get the Executable name of a window
I try to get the name of executable name of all of my launched windows and my problem is that: I use the method UINT GetWindowModuleFileName( HWND hwnd, LPTSTR lpszFileName, UINT cchFileNameMax); And I don't understand why it doesn't work. Data which I have about a window are: -HWND AND PROCESSID The error is: e.g: HWND: 00170628 ProcessId: 2336 WindowTitle: C:\test.cpp - Notepad++ GetWindowModuleFileName(): C:\test.exe HWND: 00172138 ProcessId: 2543 WindowTitle: Firefox GetWindowModuleFileName(): C:\test.exe HWND: 00120358 ProcessId: 2436 WindowTitle: Mozilla Thunderbird GetWindowModuleFileName(): C:\test.exe Note: test.exe is the name of my executable file, but it is not the fullpath of Notepad++... and it make this for Mozilla Thunderbird too... I don't understand why I use the function like this: char filenameBuffer[4000]; if (GetWindowModuleFileName(hWnd, filenameBuffer, 4000) > 0) { std::cout << "GetWindowModuleFileName(): " << filenameBuffer << std::endl; } Thank you for your response.
The GetWindowModuleFileName function works for windows in the current process only. You have to do the following: Retrieve the window's process with GetWindowThreadProcessId. Open the process with PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights using OpenProcess. Use GetModuleFileNameEx on the process handle. If you really want to obtain the name of the module with which the window is registered (as opposed to the process executable), you can obtain the module handle with GetWindowLongPtr with GWLP_HINSTANCE. The module handle can then be passed to the aforementioned GetModuleFileNameEx. Example: TCHAR buffer[MAX_PATH] = {0}; DWORD dwProcId = 0; GetWindowThreadProcessId(hWnd, &dwProcId); HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ , FALSE, dwProcId); GetModuleFileName((HMODULE)hProc, buffer, MAX_PATH); CloseHandle(hProc);
2,397,728
2,397,738
Variable accessible to all instances of a class
Let's say I have a lookup table which I'd like to make accessible to all instances of Foo. Should I make the table private static? If not, what should I do? Basically I want a way to save just one copy of the table (so it doesn't consume extra memory for each instance of Foo) and have it available privately to all instances of Foo.
That sounds like private static to me.
2,397,745
2,397,837
Iterator from both ends of a Vector
I have a vector of IntRect: vector. How can I iterate from both ends of the list and stop the iterator when the iterator intersects? vector<IntRect>::iterator itr = myVector.begin(); vector<IntRect>::reverse_iterator revItr.rbegin(); for (; /*check itr and revItr does not intersect, and itr and revItr do not end */ ; ++itr, ++revItr) { IntRect r1 = *itr; IntRect r2 = *revItr; // do something with r1 and r2 } Thank you.
if(!myVector.empty()) { for(vector<IntRect>::iterator forwards = myVector.begin(), backwards = myVector.end()-1; forwards < backwards; ++forwards, --backwards) { // do stuff } } I think you need to check empty() with that implementation - suspect that end()-1 isn't defined if the vector is empty. I haven't used it before, but Dinkumware STL at least has operator < defined for vector iterators and it appears to do something sensible. Also note that you need to check <, not just equality - that takes care of the (common) case where your vector has an even number of entries and the two iterators would step past one another.
2,397,894
2,397,933
How to have a policy class implement a virtual function?
I'm trying to design a policy-based class, where a certain interface is implemented by the policy itself, so the class derives from the policy, which itself is a template (I got this kind of thinking from Alexandrescu's book): #include <iostream> #include <vector> class TestInterface { public: virtual void test() = 0; }; class TestImpl1 { public: void test() {std::cerr << "Impl1" << std::endl;} }; template<class TestPolicy> class Foo : public TestInterface, TestPolicy { }; Then, in the main() function, I call test() on (potentially) various different objects that all implement the same interface: int main() { std::vector<TestInterface*> foos; foos.push_back(new Foo<TestImpl1>()); foos[0]->test(); delete foos[0]; return 0; } It doesn't compile, though, because the following virtual functions are pure within ‘Foo<TestImpl1>’: virtual void TestInterface::test() I thought TestInterface::test() is implemented because we derive from TestImpl1?
For this to work the policy class needs to inherit from the interface class: class TestInterface { public: virtual void test() = 0; }; template< class Interface > class TestImpl1 : public Interface { public: void test() {std::cerr << "Impl1" << std::endl;} }; template<class TestPolicy> class Foo : public TestPolicy<TestInterface> { // ... };
2,397,984
4,105,123
Undefined, unspecified and implementation-defined behavior
What is undefined behavior (UB) in C and C++? What about unspecified behavior and implementation-defined behavior? What is the difference between them?
Undefined behavior is one of those aspects of the C and C++ language that can be surprising to programmers coming from other languages (other languages try to hide it better). Basically, it is possible to write C++ programs that do not behave in a predictable way, even though many C++ compilers will not report any errors in the program! Let's look at a classic example: #include <iostream> int main() { char* p = "hello!\n"; // yes I know, deprecated conversion p[0] = 'y'; p[5] = 'w'; std::cout << p; } The variable p points to the string literal "hello!\n", and the two assignments below try to modify that string literal. What does this program do? According to section 2.14.5 paragraph 11 of the C++ standard, it invokes undefined behavior: The effect of attempting to modify a string literal is undefined. I can hear people screaming "But wait, I can compile this no problem and get the output yellow" or "What do you mean undefined, string literals are stored in read-only memory, so the first assignment attempt results in a core dump". This is exactly the problem with undefined behavior. Basically, the standard allows anything to happen once you invoke undefined behavior (even nasal demons). If there is a "correct" behavior according to your mental model of the language, that model is simply wrong; The C++ standard has the only vote, period. Other examples of undefined behavior include accessing an array beyond its bounds, dereferencing the null pointer, accessing objects after their lifetime ended or writing allegedly clever expressions like i++ + ++i. Section 1.9 of the C++ standard also mentions undefined behavior's two less dangerous brothers, unspecified behavior and implementation-defined behavior: The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. Certain aspects and operations of the abstract machine are described in this International Standard as implementation-defined (for example, sizeof(int)). These constitute the parameters of the abstract machine. Each implementation shall include documentation describing its characteristics and behavior in these respects. Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine. Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer). [ Note: this International Standard imposes no requirements on the behavior of programs that contain undefined behavior. —end note ] Specifically, section 1.3.24 states: Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). What can you do to avoid running into undefined behavior? Basically, you have to read good C++ books by authors who know what they're talking about. Avoid internet tutorials. Avoid bullschildt.
2,398,031
2,398,817
Calling handwritten CUDA kernel with thrust
since i needed to sort large arrays of numbers with CUDA, i came along with using thrust. So far, so good...but what when i want to call a "handwritten" kernel, having a thrust::host_vector containing the data? My approach was (backcopy is missing): int CUDA_CountAndAdd_Kernel(thrust::host_vector<float> *samples, thrust::host_vector<int> *counts, int n) { thrust::device_ptr<float> dSamples = thrust::device_malloc<float>(n); thrust::copy(samples->begin(), samples->end(), dSamples); thrust::device_ptr<int> dCounts = thrust::device_malloc<int>(n); thrust::copy(counts->begin(), counts->end(), dCounts); float *dSamples_raw = thrust::raw_pointer_cast(dSamples); int *dCounts_raw = thrust::raw_pointer_cast(dCounts); CUDA_CountAndAdd_Kernel<<<1, n>>>(dSamples_raw, dCounts_raw); thrust::device_free(dCounts); thrust::device_free(dSamples); } The kernel looks like: __global__ void CUDA_CountAndAdd_Kernel_Device(float *samples, int *counts) But compilation fails with: error: argument of type "float **" is incompatible with parameter of type "thrust::host_vector> *" Huh?! I thought i was giving float and int raw-pointers? Or am i missing something?
You are calling the kernel with the name of the function the call is in, not the name of the kernel - hence the parameter mismatch. Change: CUDA_CountAndAdd_Kernel<<<1, n>>>(dSamples_raw, dCounts_raw); to CUDA_CountAndAdd_Kernel_Device<<<1, n>>>(dSamples_raw, dCounts_raw); and see what happens.
2,398,129
2,398,202
Writing to the middle of the file (without overwriting data)
In windows is it possible through an API to write to the middle of a file without overwriting any data and without having to rewrite everything after that? If it's possible then I believe it will obviously fragment the file; how many times can I do it before it becomes a serious problem? If it's not possible what approach/workaround is usually taken? Re-writing everything after the insertion point becomes prohibitive really quickly with big (ie, gigabytes) files. Note: I can't avoid having to write to the middle. Think of the application as a text editor for huge files where the user types stuff and then saves. I also can't split the files in several smaller ones.
I'm unaware of any way to do this if the interim result you need is a flat file that can be used by other applications other than the editor. If you want a flat file to be produced, you will have to update it from the change point to the end of file, since it's really just a sequential file. But the italics are there for good reason. If you can control the file format, you have some options. Some versions of MS Word had a quick-save feature where they didn't rewrite the entire document, rather they appended a delta record to the end of the file. Then, when re-reading the file, it applied all the deltas in order so that what you ended up with was the right file. This obviously won't work if the saved file has to be usable immediately to another application that doesn't understand the file format. What I'm proposing there is to not store the file as text. Use an intermediate form that you can efficiently edit and save, then have a step which converts that to a usable text file infrequently (e.g., on editor exit). That way, the user can save as much as they want but the time-expensive operation won't have as much of an impact. Beyond that, there are some other possibilities. Memory-mapping (rather than loading) the file may provide efficiences which would speed things up. You'd probably still have to rewrite to the end of the file but it would be happening at a lower level in the OS. If the primary reason you want fast save is to start letting the user keep working (rather than having the file available to another application), you could farm the save operation out to a separate thread and return control to the user immediately. Then you would need synchronisation between the two threads to prevent the user modifying data yet to be saved to disk.
2,398,525
2,398,585
Comparing objects with IDispatch to get main frame only (BHO)
I don't know if anyone familiar with BHO (Browser Helper Object), but an expert in c++ can help me too. In my BHO I want to run the OnDocumentComplete() function only on the main frame - the first container and not all the Iframes inside the current page. (an alternative is to put some code only when this is the main frame). I can't find how to track when is it the main frame that being populated. After searching in google I found out that each frame has "IDispatch* pDisp", and I have to compare it with a pointer to the first one. This is the main function: STDMETHODIMP Browsarity::SetSite(IUnknown* pUnkSite) { if (pUnkSite != NULL) { // Cache the pointer to IWebBrowser2. HRESULT hr = pUnkSite->QueryInterface(IID_IWebBrowser2, (void **)&m_spWebBrowser); if (SUCCEEDED(hr)) { // Register to sink events from DWebBrowserEvents2. hr = DispEventAdvise(m_spWebBrowser); if (SUCCEEDED(hr)) { m_fAdvised = TRUE; } } } else { // Unregister event sink. if (m_fAdvised) { DispEventUnadvise(m_spWebBrowser); m_fAdvised = FALSE; } // Release cached pointers and other resources here. m_spWebBrowser.Release(); } // Call base class implementation. return IObjectWithSiteImpl<Browsarity>::SetSite(pUnkSite); } This is where I want to be aware whether its the main window(frame) or not: void STDMETHODCALLTYPE Browsarity::OnDocumentComplete(IDispatch *pDisp, VARIANT *pvarURL) { // as you can see, this function get the IDispatch *pDisp which is unique to every frame. //some code } I asked this question on Microsoft forum and I got an answer without explaining how to actually implement that: http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/7c433bfa-30d7-42db-980a-70e62640184c
What jeffdav suggested is, to test wether the pDisp supports IWebBrowser2 via QueryInterface(), and if so, to check wether it is the same object as the one you stored in SetSite(). The QueryInterface() rules only require that a QI for IUnknown always results in the same pointer value, so you have to additionally QI to IUnknown and compare the resulting pointers. This would lead to something like this in OnDocumentComplete(): IWebBrowser2* pBrowser = 0; IUnknown *pUnk1=0, *pUnk2=0; if( SUCCEEDED(pDisp ->QueryInterface(IID_IWebBrowser2, (void**)&pBrowser)) && SUCCEEDED(pDisp ->QueryInterface(IID_IUnknown, (void**)&pUnk1)) && SUCCEEDED(m_spBrowser->QueryInterface(IID_IUnknown, (void**)&pUnk2)) && (pUnk1 == pUnk2)) { // ... top-level } ... or if you are using ATL (as m_spWebBrowser suggests): CComQIPtr<IWebBrowser2> spBrowser(pDisp); if(spBrowser && spBrowser.IsEqualObject(m_spWebBrowser)) { // ... }
2,398,682
2,398,695
Multiple constructors definitions with same name but different signatures (C++)
With the following code, I keep getting error C2535 when I compile. It's complaining that a member function already defined or declared. Rationnel.h ... class Rationnel { public: Rationnel(int); //Constructor Rationnel(int,int); //Constructor void add(const Rationnel); ... Rationnel.cpp ... //Constructor Rationnel::Rationnel(int n = 1) { numerateur = n; denominateur = 1; } //Constructor Rationnel::Rationnel(int n = 1, int d = 1) { numerateur = n; denominateur = d; } ... Any idea what could be causing the error? Thanks for your time.
If you write Rationnel (5), how do you know which one of the following will be called ? Both can be used so an error occurs. Rationnel::Rationnel(int n = 1) Rationnel::Rationnel(int n = 1, int d = 1)
2,398,992
2,399,005
How to access member with same name in the inheritance
I have a question about how to access the member with the same name with inheritance. For example, class Base { public: int i; }; class Derived1 : public Base { public: int i; // how to access the i in the base class here? }; int main() { Derived1 d; cout<<d.i; //which is it is? //how to access the different i here? }
d.i in your example refers to the i in the derived class. You can refer to the base class i by qualifying it with the base class name: d.Base::i In general, it's a bad idea to have derived classes with members having the same name as members in base classes.
2,399,101
2,399,114
how to use Application window? c++
i have been programming for sometime but all of my programming books have not really showed me how to use the Application window i always use the console window. i was looking at the Application project and i noticed that it has a .cpp file that is the main file but how do work with the window? i have tryed googleing it but i can't find anything really that is usefull, can anyone help ?
There are many many GUI frameworks, so this question has hundreds of possible answers. If you are developing on Windows you have the choice of many frameworks including: Straight Win32 API MFC Qt WinForms (.Net) WPF (.Net) Silverlight (.Net) Depending on what you want to do, and on which platform you will have to select a platform/framework. Once you select a platform/framework you can get a tutorial or buy a book.
2,399,269
2,399,283
Checking for underflow/overflow in C++?
Is there a general way to check for an overflow or an underflow of a given data type (uint32, int etc.)? I am doing something like this: uint32 a,b,c; ... //initialize a,b,c if(b < c) { a -= (c - b) } When I print a after some iterations, it displays a large number like: 4294963846.
To check for over/underflow in arithmetic check the result compared to the original values. uint32 a,b; //assign values uint32 result = a + b; if (result < a) { //Overflow } For your specific the check would be: if (a > (c-b)) { //Underflow }
2,399,330
2,399,346
String vectors not working as expected with newline and iterators? (C++)
I have a text file made of 3 lines: Line 1 Line 3 (Line 1, a blank line, and Line 3) vector<string> text; vector<string>::iterator it; ifstream file("test.txt"); string str; while (getline(file, str)) { if (str.length() == 0) str = "\n"; // since getline discards the newline character, replacing blank strings with newline text.push_back(str); } // while for (it=text.begin(); it < text.end(); it++) cout << (*it); Prints out: Line 1 Line 3 I'm not sure why the string with only a newline was not printed out. Any help would be appreciated. Thanks.
Wasn't? Actually, it was! The reason you have a newline after Line 1 is exactly that empty string with newline in it and nothing else. If not for that second line, you'd see Line 1Line 3 as output. (You said it yourself: getline discards newline characters.) Apparently, the way I understand your intent, you were supposed to implement your output cycle as follows for (it = text.begin(); it < text.end(); it++) cout << *it << endl; That way you add a newline after each string during output. But if so, then you don't need to manually add a \n character to empty strings during reading. In other words, decide what is it you want to do. At this time it is not clear. If you want to restore the discarded newline characters during reading, you have to do it for all lines, not just for empty ones. If you want to add the newline characters during output, you don't need to explictly push them into the read lines at all. In fact, it is a rather strange idea to literally push the newline characters into your strings. What for? Since you already read and store your text line-by-line, the newline characters can be implied. I.e. you can do the printing as I do it above (with endl), and everything will look as expected.
2,399,375
2,399,860
Returning ifstream in a function
Here's probably a very noobish question for you: How (if at all possible) can I return an ifstream from a function? Basically, I need to obtain the filename of a database from the user, and if the database with that filename does not exist, then I need to create that file for the user. I know how to do that, but only by asking the user to restart the program after creating the file. I wanted to avoid that inconvenience for the user if possible, but the function below does not compile in gcc: ifstream getFile() { string fileName; cout << "Please enter in the name of the file you'd like to open: "; cin >> fileName; ifstream first(fileName.c_str()); if(first.fail()) { cout << "File " << fileName << " not found.\n"; first.close(); ofstream second(fileName.c_str()); cout << "File created.\n"; second.close(); ifstream third(fileName.c_str()); return third; //compiler error here } else return first; } EDIT: sorry, forgot to tell you where and what the compiler error was: main.cpp:45: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here EDIT: I changed the function to return a pointer instead as Remus suggested, and changed the line in main() to "ifstream database = *getFile()"; now I get this error again, but this time in the line in main(): main.cpp:27: note: synthesized method ‘std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)’ first required here
bool checkFileExistence(const string& filename) { ifstream f(filename.c_str()); return f.is_open(); } string getFileName() { string filename; cout << "Please enter in the name of the file you'd like to open: "; cin >> filename; return filename; } void getFile(string filename, /*out*/ ifstream& file) { const bool file_exists = checkFileExistence(filename); if (!file_exists) { cout << "File " << filename << " not found." << endl; filename = getFileName(); // poor style to reset input parameter though ofstream dummy(filename.c_str(); if (!dummy.is_open()) { cerr << "Could not create file." << endl; return; } cout << "File created." << endl; } file.open(filename.c_str()); } int main() { // ... ifstream file; getFile("filename.ext", file); if (file.is_open()) { // do any stuff with file } // ... }
2,399,377
2,399,393
Examples for Winsock?
What do you guys recommend for a resource for winsock? I have an assignment that we have only have a few days to do that needs to send a simple packet using UDP (and receive the same type of packet). I am fairly familiar with C# sockets but nothing with C++. Any tips or resources?
Some are as follows: Winsock Programming Winsock Networking Tutorial (C++) WinSock Tutorial
2,399,619
2,399,652
Should a C++ constructor that interfaces with hardware do real work?
Possible Duplicate: How much work should be done in a constructor? I'm strugging with some advice I have in the back of my mind but for which I can't remember the reasoning. I seem to remember at some point reading some advice (can't remember the source) that C++ constructors should not do real work. Rather, they should initialize variables only. The advice went on to explain that real work should be done in some sort of init() method, to be called separately after the instance was created. The situation is I have a class that represents a hardware device. It makes logical sense to me for the constructor to call the routines that query the device in order to build up the instance variables that describe the device. In other words, once new instantiates the object, the developer receives an object which is ready to be used, no separate call to object->init() required. Is there a good reason why constructors shouldn't do real work? Obviously it could slow allocation time, but that wouldn't be any different if calling a separate method immediately after allocation. Just trying to figure out what gotchas I not currently considering that might have lead to such advice.
I remember that Scott Meyers in More Effective C++ recommends against having a superfluous default constructor. In that article, he also touched on using methods liked Init() to 'create' the objects. Basically, you have introduced an extra step which places the responsibility on the client of the class. Also, if you want to create an array of said objects, each of them would have to manually call Init(). You can have an Init function which the constructor can call inside for keeping the code tidy, or for the object to call if you implement a Reset(), but from experiences it is better to delete an object and recreate it rather than try to reset its values to default, unless the objects is created and destroyed many times real-time (say, particle effects). Also, note that constructors can perform initialization lists which normal functions could not. One reasons why one may caution against using constructors to do heavy allocation of resources is because it can be hard to catch exceptions in constructors. However, there are ways around it. Otherwise, I think constructors are meant to do what they are supposed to do - prepare an object for its initial state of execution (important for object creation is resource allocation).