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
7,820,618
7,820,999
Does overloading the comma operator *really* affect the order of evaluation of its operands?
The comma operator guarantees left-to-right evaluation order. [n3290: 5.18/1]: The comma operator groups left-to-right. expression: assignment-expression expression , assignment-expression A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded value expressio...
I only have the 03 standard to hand, but in it 5/3 says "Clause 5 defines the effects of operators when applied to types for which they have not been overloaded." So all of clause 5, including 5.18/1, only applies to the built-in operators and not to any overloaded function. (A compliant compiler could always evaluate ...
7,820,653
7,820,855
pthread_create parameter function pointer
I am trying to create a thread in the following code but the pointer to a function parameter of the pthread_create method call is just not letting me compile my code. Please let me know what I am doing wrong and how can I fix it in the following code: #include "RobotNodes.cpp" int main(int argc, char** argv){ int i,...
There seems to be a non-static member function in the class RobotNodes and you seem to think that the type of member function is void (*)(). If so, then you are wrong. The type of non-static member functon and free function are not same, even if they have exactly same signature! So I would suggest you to define a sta...
7,820,753
7,820,839
Converting ruby hash into c++ map
Is there a way to convert a hash made in ruby to a C++ map? I've tried printing the hash into a file, but am unaware of how to read it into a C++ map. The hash is printed in the following way: stringA => 123 234 345 456 567 stringB => 12 54 103 313 567 2340 ... The amount of numbers varies for each associated str...
Just use plain-Jane formatted input: #include <unordered_map> #include <fstream> #include <sstream> #include <string> #include <vector> std::ifstream infile("thefile.txt"); std::string line; std::unordered_map<std::string, std::vector<int>> v; while (std::getline(infile, line) { std::string key, sep; int n; s...
7,820,926
7,821,488
Convert an MFC CString to an unsigned integer
I am trying to convert a CString to an unsigned int. I have looked up and got results for conversion to unsigned long but couldn't find anything for int as such. I know this is simple, but its kind of confusing me a bit. Any suggestions? Need something like this: CString abc; unsigned int xyz; xyz = (unsigned int)abc;...
Use _tcstoul to get unsigned long value from string and then cast the value to unsigned int.
7,820,981
7,824,998
Can std::forward_list members be implemented as static?
std::forward_list provides insert_after and erase_after members which may not need to actually access the std::forward_list object. Therefore they can be implemented as static member functions and be called without a list object — useful for an object that wants to delete itself from a list, which is a very common use....
The standard says you can get away with it if no one can tell the difference. And you are correct that one can not legally create a PTMF into forward_list, so you're safe that way. The danger of custom allocators has already been pointed out. But even for std::allocator<T> there is a danger that someone could special...
7,821,233
7,821,298
Compiler error while passing function objects
Say you would like to make iterative modifications to the elements of a container object and do something with the elements at each iteration. The code I came up with to do something like this: #include <vector> #include <iostream> template <class InputIterator, class Operation, class Callback> void transformAndTraver...
These are declarations of functions: addTwoFnObject<vec_iter> addtwo(); plotFnObject<vec_iter> plot(); These are local variable instantiations: addTwoFnObject<vec_iter> addtwo; plotFnObject<vec_iter> plot; You need to lose the extra parens at the end, otherwise the compiler complains that here you are trying to call ...
7,821,276
7,821,379
Multiple files and Object Oriented Programming
In my application, I use multiple files, each file contains a class, is it a good idea to gather all C++ files (implementation of all classes) in one file and gather all headers in another file, or this is not good for some reason but code organizing ?
Keeping declarations and definitions organized in to separate but related translation units can help to decrease compilation times. And don't disregard the value of keeping things organized for humans too! Software can consist of many thousand different objects, functions, and other parts. Keep it as simple as possibl...
7,821,315
7,821,482
When should I prefer non-member non-friend functions to member functions?
Meyers mentioned in his book Effective C++ that in certain scenarios non-member non-friend functions are better encapsulated than member functions. Example: // Web browser allows to clear something class WebBrowser { public: ... void clearCache(); void clearHistory(); void removeCookies(); ... }; Many users ...
More generally, what are the rules of when to use which? Here is what Scott Meyer's rules are (source): Scott has an interesting article in print which advocates that non-member non-friend functions improve encapsulation for classes. He uses the following algorithm to determine where a function f gets placed: ...
7,821,316
7,831,377
swig mysql: undefined symbol: mysql_init'
I am trying to create a swig package for python that offers mysql connectivity. But when I try to import the package in python I get the following error: -> _mod = imp.load_module('_IMysqlConnection', fp, pathname, description) (Pdb) s ImportError: './_IMysqlConnection.so: undefined symbol: mysql_init' I am creating t...
Solved: I was missing mysql_config --cflags mysql_config --libs while creating the shared library _IMysqlConnection.so g++ -shared CMysqlConnection_wrap.o CMysqlConnection.o -o _CMysqlConnection.so mysql_config --cflags mysql_config --libs Above command linked mysql library to the shared library _IMysqlConnection.so an...
7,821,514
7,822,392
Multiple Blob Tracking
I would like to track some traffic signs from a video. I found a nice way to solve the problem here: Link My question now is: How should I handle the case of new incoming blobs? I mean for a Blob one could define a search-region, but maybe in the next frame there is also a second thing that appears? How should I handle...
from what I understand from the paper you provide, this system is already made to track several signs at a time, appearing and disappearing. See the end of §2 : the latest tracked blobs are stored in a temporary memory. Blobs in frame (t+1) are matched with those in the temporary memory (...) thus, when a sign disappe...
7,822,509
7,823,768
MPI how to send and receive unknown datatypes
We have developed an algorithm library in C++ which allows the user to implement his own datatypes for sharing data between individual algorithms (also implemented by the user). This works fine, but we want to provide parallelization at library level. The individual algorithms should be executed in parallel on differe...
Yes, you can do this with MPI, but no, MPI can't do it for you by itself. Whether you're sending this data to another node, or writing it to disk, at some point you need to expressly describe the data structures layout in memory so that it can be serialized. If you pass MPI (or any other communications library) a poi...
7,822,652
7,823,004
Using bind1st for a method that takes argument by reference
I have a struct like this: struct A { void i(int i) {} void s(string const &s) {} }; Now when I try this: bind1st(mem_fun(&A::i), &a)(0); bind1st(mem_fun(&A::s), &a)(""); The first line compiles OK, but the second generates an error: c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(...
std::bind1st and std::bind2nd don't accept functors which take reference arguments, because they themselves form references to these arguments. You can use pointers for your function inputs instead of references use boost::bind accept the performance cost of copying the string
7,822,908
7,823,037
how to calculate the total memory and CPU usage consumed by an application in c++?
can any one tell me how to calculate the memory and CPU usage consumed by an application while executing.?
Here are some great answers probably you are looking for and , some of them you might ask next.! determine CPU and memory consumption
7,822,928
7,824,755
scanf not taking in long double
i have problem with scanf not reading long double in the code below: (please excuse my poor English) #include <iostream> #include <cstdlib> #include <math.h> using namespace std; int main() { int n; scanf("%d",&n); long double a,b,c,ha,hb,hc,ma,cosa,r,l,res,area; for (int i=0;i<n;i++) { ...
Dev-c++ uses MinGW, which uses the gcc compiler and the Microsoft runtime library. Unfortunately, those components disagree on the underlying type to be used for long double (64 vs. 80 or 96 bits, I think). Windows assumes long double is the same size as double; gcc makes long double bigger. Either choice is valid, b...
7,823,005
7,823,138
HUGE .cpp file better than reading from text file?
Is it a legitimate optimisation to simply create a really HUGE source file which initialises a vector with hundreds of thousands of values manually? rather than parsing a text file with the same values into a vector? Sorry that could probably be worded better. The function that parses the text file in is very slow due ...
6 minutes vs 6 seconds!! must be something wrong with your C++ code. Optimize it using good old methods before you revert to such an extreme "optimization" mentioned in your post. Also know that reading from file would allow you to change the vector contents without changing the source code. If you do it the way you me...
7,823,142
7,823,265
Virtual Drive Mapped to Program
Would it be possible to create a program (.NET preferably) to create a virtual drive letter, but when it is read, written to, or browsed an independent program deals with what is returned? Although you could do it by mapping a drive to a TCP server, webDAV or something like that, I'm wondering if it could be done with ...
What you're talking about is a storage device driver, which is how programs such as Daemon Tools and TrueCrypt accomplish such "virtual" drives. You may not have to delve into the kernel to accomplish this, though. Microsoft supply a Windows User-Mode Driver Framework, which is designed to simplify the development of c...
7,823,262
7,824,014
Where can one find a profiler for reducing binary size on MSVC++/Windows?
I've got a lot of users who use dial up. Plus I'm paying for bandwidth. I'm interested in working on getting my app smaller to help on both these concerns; it sits at about 200k right now but it would be nice if it was in the 100-150k range. However, I have no idea what constructs and locations in my binary are using ...
Visual Studio has an option to generate a map file which will show you the addresses assigned to each part of your program. In the project properties, Linker->Debugging->Generate Map File.
7,823,314
7,823,425
Strange things in C/C++ code (ISO C++ forbids declaration of 'xxx' with no type)
I am a C/C++ newbie, so this might be a dumb question, I have the following problem, I have a method in a c++ lib which is exported using extern 'C' and it is being called by another method from a different c file. So, I needed some structures in the c++ code, so the "smart" thing to do seemed to be simply add the st...
The compiler thinks that "someclassname" is a variable name. You wrote something like Employee* newguy = foo(); And the compiler thinks you gave the name of an undeclared variable, Employee, complained about that, complained that a * doesn't go after a variable name, and so on. Go look at where you think you're explai...
7,823,628
7,823,669
C++ / Template / Explicit init of template type?
Assume the following dummy template: template < class DataType > class Dummy { public: void init( ) { m_data = DataType( 0 ); } private: DataType m_data; }; Calling init will init the internal data. This does work fine when DataType is a standard data type (e.g. int or float). When DataType is...
In your example I guess you meant: DataType( 0 ); Not: Data ( 0 ); In any case, try: m_data = DataType(); That will call the default constructor for a class type, or will zero-init for a built-in type.
7,823,732
7,823,783
C++ do/while loop with two different conditions
I want the do while loop to check to see if the entered input is R OR P. I think it is checking for both and when I get to that part when I run, it pauses for a minute and then I get "CPU Limit Exceeded (core dumped). On another related note, am I in danger of breaking something? /**************************************...
The correct syntax is: while (servcode != 'R' && servcode != 'P' && i < 3) Note the expanded comparison and the removal of the semicolon at the end: (servcode != 'R', 'P') is valid C++ but doesn't do what you're expecting it to do; the semicolon makes the statement into a loop with an empty body, so it continues exec...
7,823,797
7,823,852
Windows GDI Context - Displaying Bitmaps
I want to catch a Desktop frame and store it in a HBITMAP struct. Then, after creating a proper memory device context out of my application main window's device context, I would select the HBITMAP into it and the use StretchBlt to display the bitmap. But this doesn't work as expected, because it just shows a black fram...
The source dc of your StretchBlt operation is mem_hdc, which has a compatible uninitialized bitmap. That's why you get a black frame. If you want to capture the desktop contents, you have to first copy it to the bitmap in your mem_hdc. Just after SelectObject do: BitBlt( mem_hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, ...
7,823,845
7,823,872
Disable compiler-generated copy-assignment operator
When I'm writing a class (say class nocopy), is it possible to prevent the existence of the copy operator entirely? If I don't define one, and somebody else writes something like nocopy A; nocopy B; A = B; the compiler will auto-generate a definition. If I define one myself, I will prevent the compiler from auto-gener...
You just declare a copy constructor with private access specifier and not even define it. Anyone trying to use it will get an compile error since it is declared private. If someone uses it even indirectly, you will get a link error. You can't do anything more than that in C++03. However, In C++11 you can Explicitly ...
7,823,990
7,839,129
What are the advantages of boost::noncopyable
To prevent copying a class, you can very easily declare a private copy constructor / assignment operators. But you can also inherit boost::noncopyable. What are the advantages / disadvantages of using boost in this case?
Summarizing what others have said: Advantages of boost::noncopyable over private copy methods: It is more explicit and descriptive in the intent. Using private copy functions is an idiom that takes longer to spot than noncopyable. It is less code / less typing / less clutter / less room for error (the easiest would be...
7,824,097
7,824,193
Wrap STL vector and change behavior of its iterator
There is such code: #include <iostream> #include <vector> template <class T> class A{ public: class iterator : public std::vector<T>::iterator{ public: T& operator*(){ ?? } }; iterator begin(){ return v.begin(); // error } iterator end(){ return...
Wrapping stdlib iterators is done best with iterator adaptors. This task is far from trivial and there is the Boost.Iterator library to simplify the task. Maybe one of the provided iterators already solves your problem. If you are going to write this on your own (I really don't recommend this), you should implement you...
7,824,264
7,824,415
Why does operator delete's signature take two parameters?
I've been reading about overloading new and delete (and related topics like placement new/delete). One thing that is confusing me thus far is that operator delete's standard signature is (at class-scope): void operator delete(void *rawMemory, std::size_t size) throw(); Delete is called like this: MyClass* ptr = new M...
Short Answer: new and delete operators are overloaded at class scope for optimizing allocation for objects of specific class. But there can be special scenarios due to certain beasts like Inheritance which may lead to allocation requests for more than the class size itself,Since the very purpose of new and delete overl...
7,824,282
7,825,237
How do I debug Java code running inside a JVM hosted by my C++ application?
I have a C++ application that uses the Java Native Interface and creates a JVM in order to execute Java code. How can I debug this Java code while it is being executed within my C++ application? I have all the relevant Java source code, and I'd like to set breakpoints and watch object data within Eclipse. I've heard of...
This EclipseZone article is a few years old but I think the basic workflow is the same. Enable remote debugging when starting your JVM within JNI (using the JavaVMInitArgs.JavaVMOption array, see the spec on JNI_CreateJavaVM). You should then be able to follow the EclipseZone steps using localhost as your remote site.
7,824,396
7,824,473
Overloading operator<< for a private enum
My class has a private enum whose members are being used to index an array of strings, the output of which is written to an output stream. private: enum supportedMessageTypes(CRITICAL = 0, WARNING, INFORMATION); string messages[3]; //meanwhile, inside the constructor, messages[3] = {"Critical error message", ...
This isn't possible. You want to accept an argument of type supportedMessageTypes, so it must be visible. There's no way around it. Also, a friend function wouldn't be bad here; this is one of the intented scenarios for friendship.
7,824,443
7,824,517
valid variable capture from lambda
I'm wondering if the following style of capture by reference is valid: struct Foo { Foo( boost::function<void()> v); int get() const; }; int main() { Foo instance( [&]() -> void { int value = instance.get(); .... } ); As you see, i'm capturing a reference to an object being constructed when the lambda is passed. ...
The lambda is not executed until you execute it by writing v() in the Foo constructor. And if you do that, then it is same as if you call the function get() directly from the constructor, which is alright, if get is not a virtual function and you have implemented get in such way that it can be called from the construct...
7,824,476
7,824,709
Issue writing an Algorithm with Vectors
-(void)userShow{ vector<CGPoint>::iterator it; vector<CGPoint>* xp = x.graphPoints; vector<CGPoint>* yp = y.graphPoints; xVal = new vector<double>(); yVal = new vector<double>(); xyVal = new vector<double>(); xxVal = new vector<double>(); value = new vector<double>(); c = new vector<...
There are some mysteries in your code, but something like this hopefully gets you started. I removed the use of pointers-to-vector and put some comments in line to explain my changes. void userShow() { // I assume that x.graphPoints is just some `std::vector<CGPoint>` and you just want to use it locally // if...
7,824,625
7,825,380
in the code (.c file) how I can find the linux distribution name version
I'd like to know in the code (.c file) how I can find the linux distribution name version (like ubuntu 10.0.4, or centOS 5.5...)? The c function that I'm looking for should be like the uname() system call used in (.c files) to get kernel version. it will be appreciated that the function is working for all linux distrib...
Is it acceptable to run some shell commands? $ /usr/bin/lsb_release -r Release: 11.04 $ /usr/bin/lsb_release -d Description: Ubuntu 11.04 $ /usr/bin/lsb_release -rd Description: Ubuntu 11.04 Release: 11.04
7,824,646
7,866,403
How to stop propagating declarations through hierarchical includes?
Whenever I make a .h header file, a question comes to my mind: "How to stop propagating declarations through hierarchical includes?" Assume there are these below files: foo.h #ifndef FOO_H #define FOO_H typedef int foo_t; inline int foo() { return 1; } class foo_c {}; #endif /* FOO_H */ bar.h #ifndef BAR_H #defin...
In C++ and C, "to stop propagating declarations" you need to remove them from public interface, period. Move them to implementation. Or to "less public" interface. Compilation time is one of goals. Others are portability, maintenability. Also this is directly related with loose coupling. The most popular C++ technique...
7,824,731
7,824,780
Which OS to use to build For XP and Win7
I have a software which has to be deployed in Windows Xp and Windows 7 32 bit versions. Is it Ok to build the software in Win XP for for both platforms? or Should I build in Xp for deploying in Xp and build in Win7 for deploying in Win7? The software is developed in C++
Yes you can build on any (modern) windows version for deployment on any other. But you probably want to test on both!
7,824,803
7,825,933
thread safe data exchange between threads/shared memory in C++ on linux
I got a "bit" confused: In production we have two processes communicating via shared memory, a part of data exchange is a long and a bool. The access to this data is not synchronized. It's been working fine for a long time and still is. I know modifying a value is not atomic, but considering that these values are modif...
Basically you're asking "why do I see no difference in behavior/performance between s2++; and __sync_add_and_fetch(&s2, 1); Well, if you go and look at the actual code generated by the compiler in these two cases, you will see that there IS a difference -- the s2++ version will have a simple INC instruction (or possi...
7,824,922
7,825,059
Screen capture program on Mac OS X Lion, preferable portable on other OS
I need to develop a screen capture program that runs on Mac OS X Lion. I tried to make a screenshot using mono and GTK#, but the screenshot is black Gdk.Window window = Gdk.Global.DefaultRootWindow; if (window!=null) { Gdk.Pixbuf pixBuf = new Gdk.Pixbuf(Gdk.Colorspace.Rgb, false, 8, ...
For Java, see Robot.createScreenCapture(Rectangle). Note though, that Robot commonly also produces a black screen image for apps. that take direct control of the screen area (e.g. many games).
7,825,491
7,825,699
How to serialize QSound?
I'm looking for a way to store some *.wav sounds persistently. In my application I'm already serializing several things into a little binary database using boost. Now I'm trying to store QSounds in this database, too, which if obviously not working. I don't want to deliver the wav-files to the exe, but rather have them...
QSound is a simple class for playing sound, not for "sound objects" (a little unfortunate naming in my opinion). You can use Qt resources to store your files inside your exe.
7,825,618
7,825,674
Accessing a static array in class by using overloaded operator ()
I'm new here so I hope I will write understandable question. My problem is, how to access a static array in class by using overloaded operator (). Main.cpp: class SomeClass { public: static const int a[2][2]; const int& operator() (int x, int y) const; }; Just under it, I define the array a: const int SomeCla...
You need to instantiate an object of your class to access its members. Try using cout << SomeClass()(1, 1) << endl; instead, instantiating a temporary and using it's operator().
7,825,784
7,825,868
How to access a map within a map in C++ ..? Performance issue?
typedef map<int, string> iMap; typedef map<double, innerMap> OutMap; OutMap mx; map<double, iMap >::iterator it_out; map<int, string>::iterator it_i; for ( it_out=mx.begin() ; it_out != mx.end(); it_out++ ) { cout << "\n\nNew element\n" << (*it_out).first << endl; for( it_i=(*it_out).second.begin(); it_i != (*...
It cannot be improved further, except that You can use pre-increment instead of post-increment, i.e ++it_out instead of it_out++. You can use '\n' instead of endl in the cout. Using '\n' would improve the performance of output operation by reasonable margin, because endl first puts '\n' in the output buffer, and then...
7,825,793
7,826,045
What's better solution to separate user input by space in C++?
I'm reading C++ Primer and working on its exercise. It want me to get user's input and separate by space ' '. So I come up with 2 solution. First solution: vector<string> vector1; string input; string temp = ""; // temperary hold each word value in input. string x1 = ""; char x2 = 'b'; x1 += x2; cout << x1 << endl;...
I would write this: std::vector<std::string> data; std::copy(std::istream_iterator< std::string>(std::cin), std::istream_iterator< std::string>(), std::back_inserter(data)); It is almost same as @K-ballo's answer, except that I let std::copy read directly from input stream (i.e std::cin) rather t...
7,825,849
7,825,897
How can I use a managed DLL without loading the CLR?
If I have a managed DLL and an unmanaged Explorer extension, is it possible to load the managed DLL somehow without pulling the CLR into Explorer's process space? I understand that writing a managed Explorer extension is a no-no as it loads the CLR into Explorer and causes issues with any other plugins/extensions that ...
Not an ideal answer, but a route you could consider nonetheless. Write an unmanaged proxy and call into a managed code service using named pipes / other IPC. It is a bit tacky and smells but if you are stuck..
7,826,092
7,841,740
Gio::OutputStream to a String or std::ostream
I am using the library libvtemm, which has a function write_contents. It takes an internal buffer and outputs it to a Glib::RefPtr<Gio::OutputStream> object. I have been trying to find a way to convert the contents of the Gio::OutputStream into a std::string or something similar so that I can play with and move aroun...
For those of you who are looking for an answer, here is what I have come up with to read the console buffer into a std::string. // Create a mock stream just for this example Glib::RefPtr<Gio::MemoryOutputStream> bufStream = Gio::MemoryOutputStream::create(NULL, 0, &realloc, &free); // Create the stringstream to use ...
7,826,175
7,857,697
MFC multithreading: AfxBeginThread vs Boost.Thread?
I have an MFC application to which I want to incorporate multi-threading. Originally I was thinking of using Boost.Thread because of the general ease of development with boost. However, I'm wondering if there are any gotchas and if I should use AfxBeginThread to be safe in an MFC context?
I found this Microsoft article: Multithreading: Programming Tips. It says: Accessing MFC Objects from Non-MFC Threads If you have a multithreaded application that creates a thread in a way other than using a CWinThread object, you cannot access other MFC objects from that thread. In other words, if you want to ac...
7,826,193
7,826,333
SDL C++ ttf linker errors
I'm using CodeBlocks and trying to link SDL_ttf when compiling my program. I have followed thus instructions: Add "-lSDL_ttf" in the linker command line Put SDL_ttf.dll in library directory Put SDL_ttf.h in include file directory And I have this error when compiling: ld.exe||cannot find -lSDL_ttf| ||=== Build finish...
You also need the .lib file to link against. Put the .lib file in your library directory; you may also need to add that directory to your linker's search path with the -L <path> option.
7,826,239
34,561,915
Does cmake use convention over configuration?
Maven is said to employ a form of Convention over Configuration. I don't want to draw any wrong comparisons but as far as I understand cmake can fill a similar roll for a C++ project as maven can for a Java project. So, does cmake have some Conventions over Configuration, or is each project configured uniquely? (Wrt. f...
After experiencing the elegance of Maven 3, I also looked for a convention over configuration C maven style system. ... I also checked out CMAKE, after creating a skeleton a few things stood out. CMAKE is sometimes declarative, sometimes procedural, and your always going to end up with an ugly mix. AKA, it's ANT fo...
7,826,354
7,838,040
Best way for OpenCV type independent image access?
I am writing a function that takes a OpenCV Mat structure and does some processing. The problem is that OpenCV doesn't seem to have a type independent way for accessing the strucutre so I have to do something like this. int myfunc(cv::Mat& im, int iRow, int iCol) { int iResult = 0; if (im.type()==CV_16U) iResu...
It's because you generally require high performance in image processing and so need different algorithms for 8bit, 16bit or double image types. You can do it all with templated types but that's often just a less readable way of having a switch statement. ps if you do care about performance you shouldn't be using the .a...
7,826,396
7,868,784
Write binary data in QT '\n' 0x10->0x0d,0x010
I work on project that involved writing binary data, I use QString for storing line and then save it on hard by Qfile data.append(QChar(10)); and I set encoding to "ISO-8859-1", anyway when the data equal to 10 I as showed above, the saved data is 0x0d,0x0a I find the problem source ,10='\n' and Qt change it to '\n\...
I found the reason, because the QFile object that I had created is in Text mode so when QFile want to write file it changes /n to /r/n the code below is the previous code that have problem in binary because of existence of QIODevice::Text QFile myfile; myfile.setFileName("build/Data.bin"); if(!myfile.open(QIODevice::Wr...
7,826,507
7,833,213
Interfacing Ada with an asynchronous interface in C++
I have this task of designing a new interface for a distributed application (multiple processes running on a single computer, not physically distributed - yet) which is comprised of many graphical panel modules written in C++/OpenGL and a single module written in Ada. The modules share information on the form of parame...
Not sure what the semantics of Get() are. Does it wait for new data? return the last data received? (in which case, what happens if no data has been received yet?) Assuming a callback scheme and Ada 2005, you might for a start consider a spec like generic type T is private; package Interfacing is -- 'put' not sh...
7,826,687
7,826,832
Empty Object or Class/Empty Type using Templates
I have written a program that has a class with a constructor and destructor written with couts and cins. The class contains a run() function which I am using as my menu. From the menu, I want to have the user select the option to 1. Test the constructor (creates an instance from the class) and 2. Test the destructor (e...
Make run() a free function, like this: template <class T> class MyT { public: MyT(const T& v) : val_(v) {} const T& get() const {return val_;} private: T val_; }; int run() { int opt; cout << " 1) Create\n 2)Destroy\n"; cin >> opt; cin.ignore(); return opt; }...
7,826,715
7,854,596
Why am I failing to capture the "this" pointer by a lambda?
Consider the following code: class A { public: void foo() { auto functor = [this]() { A * a = this; auto functor = [a]() // The compiler won't accept "this" instead of "a" { a->bar(); }; ...
This appears to be a compiler bug in VS2010. I was able to make it work by letting the inner lambda implicitly capture this: class A { public: void foo() { auto functor = [this]() { auto functor = [=]() { bar(); }; }; } void b...
7,826,749
7,832,818
How to have dynamic scene update in libqglviewer
I'm using libqglviewer for a project, I read input from a motion capture device through USB and display this as a human in the viewer. I draw the opengl things in the draw() method of the viewer, it works fine. However, when the motion controllers change, I actually get new position values and i draw these in the vie...
It looks like you just need to post an updateGL right after you get the new position values. QGLWidget::updateGL() void QGLWidget::updateGL () [virtual slot] Updates the widget by calling glDraw(). For painting in 2D the function is called update. Also, don't call it from inside your draw method (see updateG...
7,826,985
7,827,179
Printing a pointer-to-member-field
I was debugging some code involving pointers to member fields, and i decided to print them out to see their values. I had a function returning a pointer to member: #include <stdio.h> struct test {int x, y, z;}; typedef int test::*ptr_to_member; ptr_to_member select(int what) { switch (what) { case 0: return &te...
Member pointers aren't ordinary pointers. The overloads you expect for << aren't in fact there. If you don't mind some type punning, you can hack something up to print the actual values: int main() { ptr_to_member a = select(0), b = select(1); std::cout << *reinterpret_cast<uint32_t*>(&a) << " and " << ...
7,827,092
7,827,112
I have no idea what is this(C++ linker error)
getting this 1>main_display.obj : error LNK2005: "struct ALLEGRO_DISPLAY * main_display" (?main_display@@3PAUALLEGRO_DISPLAY@@A) already defined in event_queue.obj 1>main.obj : error LNK2005: "struct ALLEGRO_DISPLAY * main_display" (?main_display@@3PAUALLEGRO_DISPLAY@@A) already defined in event_queue.obj 1>main.obj : ...
Looks like those structures are defined in a header file. Then they're #included into multiple translation units. You need to make it such that there's only one definition of the particular item. Given that these are global variables, the way you generally do that is declaring them by marking them extern in the header,...
7,827,121
7,827,563
What stable c++11 feature can be used safely
What are the C++11 features that have got enough mature that I can start using safely in my projects. I am talking about GCC mainly I rarely need Visual Studio. and I obviously don't want to include a feature in my code that requires a rewrite after few months. and should I even start using these features in this very ...
The C++11 standard is finally done and published, so there won't be any more changes. Implementations still lag behind a little and may implement slightly older versions of C++0x, but you probably won't notice much difference when they are updated. C++11 isn't perfectly backwards compatible, so the first thing you shou...
7,827,316
7,828,303
Read raw 3D texture and slice cube
Reading a raw 3d (256x256x256 cells) texture (8bit) using the following: f = fopen(file, "rb"); if (f == NULL) return; int size = width * height * depth; data = new unsigned char[size*3]; fread(data, 3, size, f); image = reinterpret_cast<rgb *>(data); fclose(f); where image rgba is typedef unsigned char byte; typ...
It's just a 3D array. Pick two axes to scan in the standard 2D access pattern and vary the third to change slices: for( unsigned int slice = 0; i < numSlices; ++i ) { for( unsigned int x = 0; x < xSize; ++x ) { for( unsigned int y = 0; y < ySize; ++y ) { // XY slice outp...
7,827,414
7,827,495
Strange behavior of 'this' with inheritance
I'm having trouble understanding the value of this in the following example: struct A { int i; void bar() { cout << this << endl; } }; struct B : public A { virtual void foo() = 0; }; struct C : public B { void foo() { printf("hello world!\n"); } }; int main (int argc, const char* argv[]) { C*...
But it refers to differnt things. void bar() { cout << this << endl; } Here this has a type A*. It points to the part of the object that is A. out << c << endl; Here c is a C* and points to the part of the object that is C. If the A object lines up exactly with the C object the pointers are the same. If they do...
7,827,504
7,827,569
c++ delete pointer issue, can still access data
I don't really understand why are those pointer accessible ... any help appreciated #include <iostream> class Wicked{ public: Wicked() {}; virtual ~Wicked() {}; int a; int b; }; class Test { public: Test() {}; virtual ~Test() {}; int c; Wicked * TestFunc() { Wicked * z;...
Deleting a pointer doesn't zero out any memory because to do so would take CPU cycles and that's not what C++ is about. What you have there is a dangling pointer, and potentially a subtle error. Code like this can sometimes work for years only to crash at some point in the future when some minor change is made somewh...
7,827,582
7,828,306
How do you change the minimum size of a QTableWidget?
I am embedding some QTableWidget(s) recursively inside of each other. The final GUI will have 4 to a couple thousand squares. Here is an example screenshot only showing 16 squares.: Because there are so many squares (thousands) that need to be displayed I need the minimum size of each square to be something like 5x5 p...
On my WindowsXP, I can't shrink most programs lower than 148x96. It might have absolutely nothing to do with your Widgets. Test with 256+ squares, and tell us how big each square is. Windows (and whatever it is you're using) have this limitation to guarantee the users are able to see the bottons on the top, a few lette...
7,827,628
7,854,444
How does the GPL affect macros stored in user data?
I'm considering writing a program in C++ which will embed a Python interpreter for executing macros created by users. Suppose that I'm intending to release my program under the GPLv3. What is not clear to me is what impact this has on the macros and data created by the users of my program. Do any of the requirements of...
No the macros don't become GPL derived works anymore than a 'C' program written on a GPL linux system or with a GPL gcc compiler become GPL. Including library functions is a little more complicated. If you wrote those library functions then you can let the user do what they want with them. If they are part of the GIMP/...
7,827,714
7,827,740
How does the first star in this program get printed?
Im trying to figure out how the first star in this program gets printed. When the loop that controls the stars is first encountered the value of stars should be 1 due to the initialization withing the loop, the value of light should be zero because it was assigned zero in the declaration of light. The condition to prin...
It's printing it on the second iteration. When light is equal to 2, it will print 1 star.
7,827,758
7,828,138
Linking to cocoa libraries with CMake (C++ intermixed with Objective-C)
I'm working on adding cross platform clipboard support to my gui api. I managed to get it working on Windows nicely, now I'm on to OSX. I've gotten the functions working like I want them, but the file is .mm . Therefore when people compile the OSX version of my gui, they now need to link against the cocoa library. Does...
There are some compiler switches which you pass to gcc or to clang to enable compilation of Objective C or Objective C++ applications: gcc -ObjC MySourceFile.m gcc -ObjC++ MySourceFile.mm clang -ObjC MySourceFile.m clang -ObjC++ MySourceFile.mm You specify which the minimum version of MacOSX on which your app can r...
7,827,829
7,829,288
Read from a file C++
Hi I want to read data from a VTK file into my C++ program. Here is how my files will typically look. POINTS 2 double 1 2 3 4 POINT_DATA 2 SCALARS pressure double LOOKUP_TABLE default 5 6 SCALARS density double LOOKUP_TABLE default 7 8 I want to put the numerical data highlighted in bold into my C++ program but I don...
You can use the ignore function to throw away lines of text that are not numbers. Use cin >> x to read a value x from the input file. If that fails, the failbit is set in the input stream, which you must clear. Then, ignore the whole line. std::vector<int> data; while (!cin.eof()) { int x; if (cin >> x) { ...
7,827,904
7,827,983
Can someone explain what is a HelperClass and what does in Java or in C++?
I want to know what the HelperClass used for. Can someone please explain it with examples? Thank You
A helper class (in Java, at least) is usually just a static utility class with a variety of methods. In general, a single helper class deals with related functionality, like Apache Commons' StringUtils class, that has a bunch if static methods that operate on strings. In Java, these types of classes often exist to wrap...
7,827,938
7,828,049
_Dist_type not declared in this scope
I've been tasked with getting some old code working. It's dated from 2006 and I believe it was written in visual studio. I get this error when compiling with g++ 4.5.2 using ming32 on a windows machine and I get the same error compiling with g++ 4.1.2 on a unix machine(not sure what flavor) "_Dist_type was not declared...
_Dist_type is an internal implementation detail used by Visual Studio's standard library. Names starting with an underscore followed by an uppercase letter are reserved by the implementation and must never be called directly from user code. You'll have to figure out what that function does and duplicate the functionali...
7,828,006
7,828,061
C++ Dynamic 2D-Array with pointers(Matrix)
everyone: Im creating a program that is able to create Matrices and and perform various operations on them for a course at school. They require us to overload the operators with with the appropriate Matrix Operations. I am having a hard time with the following function: typedef double matrixType; using namespace std;...
Given your implementation, it should be if (B.a[row][col] != a[row][col]) BTW: You should read this page if you plan to implement your own matrix class.
7,828,136
7,828,626
Visual C++ LNK2019 error
Using Microsoft Visual C++ I am trying to compile the file "test.cc" which is part of a small package available for free download at http://sourceforge.net/projects/clippoly/files/ The file test.cc appears as follows: // nclip: a polygon clip library // Copyright (C) 1993 University of Twente // klamer@mi.e...
It looks as though you have told the compiler where the header files are, but not told the linker where it can find the library that contains the Poly class. I don't have Visual Studio in front of me so the following route through the interface might not be spot on, but from memory you need to add the library (.lib) t...
7,828,145
7,828,252
Memory Allocation for Derived C++ classes
I am working on designing a small system and am wondering about a nuance of how memory is allocated for derived classes. If I have two classes class foo { public: int a; Foo(): a(0) {}; }; class bar : public foo { public: int b; Bar() : Foo() , b(0) {} }; and then do something like this in another method Bar* purple ...
new Bar is just one contiguous allocation, as is new Bar[n]. It may help to think of like this: Bar* purple = new Bar(); is similar to: Bar* purple = (Bar*)malloc(sizeof(Bar)); Behind the scenes, the constructor is also called, and in some cases the allocation may be greater than sizeof(Bar); new[] is a common case w...
7,828,398
7,828,425
Get more than one value out of an function
Possible Duplicate: Returning multiple values from a C++ function /************************************************/ /* Name: premserv */ /* Description: Calculations for premium serv */ /* Parameters: N/A */ /* Return Value: premserv ...
You could use references. float premserv (int& daymin, int& nightmin) { float daytotal = 0; //Var for day total float nighttotal = 0; //Var for night total float premserv = 0; //Var for premium service cost cout << "\n" << "Please enter the number of minutes used durring the day (6AM - 6P...
7,828,447
7,828,629
Why is it better to explicitly manage matrices in OpenGL?
Recently I've been messing around a fair amount with OpenGL, and I have come across the split between allowing OpenGL to manage the view/model/projection matrices or managing them yourself, either with your own matrix implementation or a library such as GLM. I've seen that a lot of large projects have their own camera ...
(As an aside, OpenGL ES 2 has no transform management facility, so in some cases you have no choice.) More on point, I've found managing matrices via OpenGL's built-in matrix stacks to be a real pain at times, forcing me to push and pop rather copiously in the more intricate portions of my rendering code, even reorderi...
7,828,702
7,829,168
UUID into unsigned int
Is there anywhere to compress/convert/encode/encrypt a UUID into an unsigned int? I read UUID's from a sql table, the history is ugly and i can not change... I have only an unsigned int to store it in. This is C++ in case that makes a difference Any thoughts on this? Thanks Reza
Use a CRC32 of the UUID (I assume you mean 32-bit integer). There's obviously the potential for collisions, but if there's a collision it should be rare enough you can just fix it manually. Note that if this is MS SQL Server, you can use the CHECKSUM function to do a crc32 hash on the server to update your table.
7,828,864
7,829,017
Pthread Passing Function to Pool
I am working on creating a threadpool from scratch as part of an assignment and am able to create the thread pool and then pass each created thread a function that constantly loops. My question is how can I accept the input and pass it to an already executing pthread. After figuring this out I will add mutexes to lock ...
The best pattern that I can think of is to use some sort of queue to pass messages to the thread-pool. These messages may contain functions to be run as well as some control messages for shutting down the thread-pool. As you already have guessed, the queue will have to be thread safe. A simple approach for the queue is...
7,828,960
7,829,003
Memory corruption in a small ref-counted buffer class
I have a simple reference counted class that holds a memory buffer. It looks like this: #include <algorithm> template<typename T> struct buffer { // create a buffer of length n buffer(unsigned n) : rc(*(new unsigned(1))), data(new T[n]) { } buffer(const buffer<T> & rhs) : rc(++rhs.rc), data(rhs.data) { } ...
One problem is that when you swap(rc, rhs.rc); you're actually swapping the contents of the recounts, not the references. Imagine you have this situation: When you swap(rc, rhs.rc);, the references to the refcounts will remain the same, and the counts themselves will swap. This is what you get after the two swaps: Th...
7,829,018
7,829,166
Can we rely on the reduce-capacity trick?
Is it actually guaranteed anywhere that the following reduce-capacity trick will "work"? int main() { std::string s = "lololololol"; s = ""; // capacity still non-zero string(s).swap(s); // ? } It doesn't seem to "work" for me (in that the capacity remains non-zero), and I ...
I've always been taught that there is no guaranteed standard way to lower the capacity. All methods have been (and still are) implementation defined. § 23.2.1\8 says: The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invo...
7,829,094
7,829,155
Having problem understanding following C++ code. (seekp)
#include<stdio.h> #include<fstream.h> class Test { char name[10]; int data; public: void getData() { cin>>name; cin>>data; } void display() { cout<<name<<data; } void modify() { cin>>name; ...
Its because your program is reading the data from t1, reading the data from t2, modifying t2, and then writing over the contents of t2. When the fp2 is first opened, the file looks like this (^ represents the current position of the file pointer): +-----------+-----------+-----------+-----------+ | t1 data | t2 data...
7,829,129
7,839,972
How to access different members of class by using Traits pattern
I have a class that holds several vectors of objects: struct ComponentA { public: methodA1(); float data1; ... }; struct ComponentB { ... }; struct ComponentC { ... }; struct ComponentD { ... }; class Assembly { vector<ComponentA> As; vector<ComponentB> Bs; vector<ComponentC> Cs; vec...
Traits aren't going to do what you want here. C++ lacks the introspection support needed to say, "Get me the first member of class X that is of type Y." Also, traits are intended for "tell me more about type X" kinds of operations. Template specialization can be used for this, but they'll be a lot of work: template<cla...
7,829,283
7,829,420
What's the difference between the _T("...") and _RT("...") macros?
I'm sure this question has been asked before, but I can't get the text searched for. If anyone can explain them, refer me to an article, or give me the correct search query I would appreciate it. Thanks.
This is just a hunch but looking at the Wikipedia C++11 Page for String Literals, and mixing it with what we know of the _T macro, it makes sense that the _RT macro could be about making _T based raw string literals. You would have to take a look at the macro itself to see what it does. As the _T macro prepends L to th...
7,829,300
7,829,488
Getting the size of a micro SD card via C++
I am looking for some function that will return the total capacity of a micro SD card mounted to /dev/sdb. I do not care so much about free space I care about total capacity of the drive. I need a reliable and accurate function. If there is none in existence how would I go about creating one? Thanks!
strace for blockdev tells me you could use: #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/fs.h> int main() { unsigned long long size; int fd = open("/dev/sdx", O_RDONLY); ioctl(fd, BLKGETSIZE64, &size); std::cout << size << ...
7,829,427
7,829,449
C++ memory management clarification
I'm new to c++. I've got a Rectangle class. When I create a Rectangle object like this: Rectangle R1(10,10,90,20); Does R1 sit on the heap or stack? If I were to create it using the new operator, would only then it be on the heap? (In general what would be the correct way to create an object in c++?) To my understan...
Rectangle R1(10,10,90,20); This creates a variable with "automatic" duration. It is automatically destroyed when the code flow exits the scope. If it's not in a function, that means when the execution of your code completes. Usually (but not always) it sits on some sort of stack. Rectangle* R = new Rectangle(1,1,1,...
7,829,495
7,829,520
Operator overload = and const reference
I'm trying to construct a class for colors in C++, this is not an homework is just that I'm still struggling with references and const. --Color.h class Color{ private: double r; double g; double b; double a; public: //constructor, getters and setters... Color& operator =(Color& other_color); //(...
passing 'const Color' as 'this' argument of 'float Color::get_r()' discards qualifiers This means you have to take it further. get_r is probably declared as float get_r() and to make it work (const-correctly), you should make it float get_r() const second what would happen if I don't declare other_color as const? ...
7,829,646
7,829,665
Object factory in C instead of C++
I am converting a bunch of code from C++ in to C. Is there an equivalent pattern in C for a Object factory? Consider the following source code. Based on a parameters (int type) the ObjectFactory() function should return a void pointer to an struct of a pedicure type. How can I instantiate the struct in a way that I c...
How about using malloc: case 5: return malloc(sizeof(struct CPlaces)); No need for the break if you already return. If you like, you can add some initialization before returning. The caller will have to know the actual type so she can cast the pointer back to the correct type. This will probably amount to a duplicate ...
7,829,713
7,831,145
Parameters to improve a music frequency analyzer
I'm using a FFT on audio data to output an analyzer, like you'd see in Winamp or Windows Media Player. However the output doesn't look that great. I'm plotting using a logarithmic scale and I average the linear results from the FFT into the corresponding logarithmic bins. As an example, I'm using bins like: 16k,8k,4k,...
With an FFT of 1100 points, you probably aren't able to capture the low frequencies with a lot of frequency resolution. Think about it, 30 Hz corresponds to a period of 33ms, which at 32kHz is roughly 1000 samples. So you'll only be able to capture about 1 period in this time. Thus, you'll need a longer FFT window...
7,829,838
7,829,863
dll function name is same with already existing MFC function
I am not very familiar with C++ and here I am confronted with an error which I couldn't find answer from web. I am trying to compile an example code which imports functions from a dll. I am using VS 2010 Professional. The problem is I get an error message saying: error C2660: 'CDialog::Initialize': function does not t...
Specify the correct function to be called with Namespace::Initialize() or Class::Initialize(), or just ::Initialize() if the function is not a member of any namespace or class.
7,829,854
43,998,815
How to store a bit-array in C++?
What's the best way to store a bit array in C++ (no Boost, just standard containers), representing, for example, a volume allocation bitmap? I thought std::vector<bool> was a great idea, but apparently it's Evil and deprecated, so is there a better choice? Also: If I have a byte array in memory, how would I go about co...
Just posting this 6 years later for posterity: like one of the commenters said, I came to the conclusion that it's perfectly fine to use std::vector<bool> as its own specialized type. The only thing you need to be careful of is not to treat it like a standard bool container, since it isn't.
7,829,897
7,829,988
segmentation fault c++
I'm getting a segmentation fault and I have no idea how to debug it! It occurs after the creation of the MyString array i.e. the array created without any issue. void ConcatTest() { cout << "\n----- Testing concatentation on MyStrings\n"; const MyString s[] = {MyString("outrageous"), MyString("mil...
You attempt to delete str1.pString about half way through your + method. but str1 is passed as a const MyString, which points to a static string in the program. You cannot deallocate this! most likely this is the cause. You should not modify either str1 or str2 in your operator. If I have understood your prog correct...
7,829,921
7,830,003
Does MPI drop or delay messages?
I asked the same question here, but I think it was too long so I'll try again in a shorter way: I've got a C++ program using the latest OpenMPI on a Rocks cluster under a master/slave setup. The slaves perform a task and then report data to the master using the blocking MPI_SEND / MPI_RECV calls (through Boost MPI), w...
As far as I see this results from the recv in the while loop in the master node. ... while (1) { // Receive results from slave. stat = world.recv(MPI_ANY_SOURCE,MPI_ANY_TAG); ... When there is a message from one slave the master cannot get any messages until the code inside while loop is finished (which tak...
7,830,054
7,831,708
How to draw a point (on mouseclick) on a QGraphicsScene?
I have the following code to set up a QGraphicsScene. I wish to click on the scene and draw a point at the location I've clicked. How could I do this? This is my current code: MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QGraphicsScene *s...
UPDATE: There is a new class called QGraphicsSceneMouseEvent that makes this a little easier. I just finished an example using it here: https://stackoverflow.com/a/26903599/999943 It differs with the answer below in that it subclasses QGraphicsScene, not QGraphicsView, and it uses mouseEvent->scenePos() so there isn't...
7,830,243
7,934,377
pthread sleep function, cpu consumption
On behalf, sorry for my far from perfect English. I've recently wrote my self a demon for Linux (to be exact OpenWRT router) in C++ and i came to problem. Well there are few threads there, one for each opened TCP connection, main thread waiting for new TCP connections and, as I call it, commander thread to check for st...
I've I have resolved it other way. #include <sys/time.h> #define CLOCK_US_IN_SECOND 1000000 static long myclock() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * CLOCK_US_IN_SECOND) + tv.tv_usec; } void *MainThread(void* arg) { Commander* commander = (Commander*)arg; pthread_detac...
7,830,245
7,830,271
How to serialize a (nested) map to a variable using boost?
I have a map declared inside a class as follows: class Example { public: Example() { std::map< std::string, std::string > map_data; map_data["LOCATION"] = "USA"; map_data["WEBSITE"] = "http://www.google.com/"; custom_map["nickb"] = map_data; }...
It looks like you have two completely separate stringstream objects: one of which receives the data, and a second (with no underlying string data) from which you attempt to restore the data. A stringstream isn't data storage anyway; a string is - in much the same way that an fstream writes to a file on disk which is th...
7,830,428
17,603,295
C++ Templates and Emacs: Customizing Indentation
As far as I know in emacs, there is no way of customizing the indentation level of the closing '>' character of a template list in C++. Currently my emacs indentation scheme does this: template < typename T1, typename T2, typename T3 > class X; What I want is something like this: template < typenam...
The best solution that I have found is writing a custom (and relatively straightforward) indentation function. The Code (defun c++-template-args-cont (langelem) "Control indentation of template parameters handling the special case of '>'. Possible Values: 0 : The first non-ws character is '>'. Line it up under 'templ...
7,830,496
7,830,840
Conversion of C++ code from Linux to Windows
I am new to C++ , I have a program in C++ written for Linux. I'm trying to convert it to Windows. The code I have is: struct Timer { struct tms t[2]; void STARTTIME (void) { times(t); } void STOPTIME(void) { times(t+1); } double USERTIME(void) { return ((...
Here is a drop-in replacement that returns the user time, rather than the elapsed time: #include <windows.h> struct Timer { ULONGLONG t[2]; void STARTTIME (void) { t[0] = getCurrentUserTime(); } void STOPTIME(void) { t[1] = getCurrentUserTime(); } double USERTIME(...
7,830,545
7,830,573
(C++) Best way to serialize my database of customer?
I'm currently doing a program for a Notary for storing his customers informations, and here's my concern: XML + Serialisation usage vs Vector (of Objects) + Serialisation usage vs SQL Databases. Using Qt, I would like to know which would be the best for storing clients, searching and modifying the clients? I have a lot...
Personally, I'd go with an SQLite database. XML is great for interchange between programs or storage, but not the most efficient for searching. Vector serialization is not so easily documented. SQLite is well-known, embedded (no separate process needed), easy to search, and efficient for speed. I would consider that th...
7,830,592
7,830,670
Does Pro*C/C++ support "describe [schema.]object" statements?
I can't prepare this statement in my Pro*C code. When I running this statement I get this error: SQLERROR: ORA CODE: -900 MSG: ORA-00900: invalid SQL statement Is there a way to exec this statement with EXEC SQL?
No, you can't do that because describe is a SQL*Plus command (under the covers it queries the data dictionary). If you need to actually describe a table, in order to programmatically interpret columns and datatypes of a columns, you'll need to do dynamic SQL method 4. See this link for a good description: http://downlo...
7,830,601
7,830,614
Redundant #include in C/C++?
Suppose now I have three source files: ClassA.hpp, ClassB.hpp, and ClassC.hpp. ClassB inherits from ClassA, and ClassC inherits from ClassB. So, in ClassB.hpp, I wrote #include "ClassA.hpp". Then, in ClassC.hpp, besides including ClassB.hpp, shall I also include ClassA.hpp? When writing Makefiles, should I make a Class...
Does ClassC.hpp require the contents of ClassA.hpp, disregarding ClassB.hpp for the time being? If so, then yes, you should include it and not rely on a round-about accidental include that could change. Checking that and setting up the proper includes should be relatively simple. Relying on another file or behavior tha...
7,830,639
7,830,678
Class member privacy and headers in C++
So I'm making a class to define a character in D&D. The way I thought setting up the class was that public members are defined in the header and private in the .cpp so they're not revealed to the outside right? How do you do this? Currently it looks like this and I'm sure it's wrong. character.h: namespace d20 { cl...
Just put private members in the same header file. Class definition cannot be spread across different files by design. Why do you want prevent those private members from being seen by clients in the first place? Being private, they cannot be accessed directly anyway. Edit: Those private members are implementation detail...
7,830,794
7,830,823
Accessing template friend function of class in main.
I am having a hard time finding a simple solution to this. I am implementing an expression tree using the following classes, I declare a friend function of class Tree. My problem comes when I try to get it started in main. template<class object> class Tree; template<class object> Tree<object>::expTree(Tree<object> *&T)...
template<class object> Tree<object>::expTree(Tree<object> *&T); // ERROR //^^^^^^^^^^^^^^ cause of the error This function template is actually a free function, and will be a friend of the class Tree. So it should be written as: template<class object> expTree(Tree<object> *&T); That is, remove ...
7,830,918
7,830,965
c++ Better way to assign a derived class to a base class
This seems like a silly question but I want to be able to instantiate a derived class and assign it to a base class in one line: class A { }; class B : public A { }; // i can do this A *base; B derived; base = &derived; // i'd like to do something like this A *base; base = &B(); // produces a warning: taking address ...
I want to be able to instantiate a derived class and assign it to a base class in one line An object instantiated within a single line (without using the new operator) will last only until the end of the expression that evaluates it. So by the point you have the address, the temporary does no longer exist. I'm tryin...
7,830,925
7,830,948
Serialization of class object
class MyClass { public: MyClass(int X= 0; int Y= 0) { /*...*/ } private: int x; int y; }; I'm trying to avoid the overhead of using boost::serialization library for this simple class. so, is it valid to do something like this: MyClass Obj(43, 64); char *c = (char*)&Obj; // ok? // write to file
Casting your object as a pointer won't do what you want. It's valid to cast its address to a pointer to char: (char*)&Obj or better yet reinterpret_cast<char*>( &Obj );. Actually accessing that pointer to store the raw data and later load from it its not guaranteed to work by the standard. The memory layout of complex ...
7,830,929
7,830,983
Reading only SPECIFIC range of lines in a text file C++
Hi I have a text file which contains some numerical data. Of that text file ONLY the lines 14 to 100 have to be read into my C++ program. Each of these lines contain three numbers corresponding to x,y,z coordinates of a point. Thus, coordinates are given for 87 points in all. I want to put these numbers into the arra...
Read line by line, for most flexibility in your format: #include <fstream> #include <sstream> #include <string> std::ifstream infile("thefile.txt"); std::string line; unsigned int count = 0; while (std::getline(infile, line)) { ++count; if (count > 100) { break; } // done if (count < 14) { continue; } // t...
7,830,957
7,831,063
How to pass a scanf string to a global character array through pass-by-address in C++?
Let me make this clear right away, this is for a college class. I cannot use C++ libraries, only standard C libraries. Do not suggest that I use C++ strings or cin/cout because that will not help me for this assignment. My issue: I have global character arrays in the main function. I need to pass strings to the global ...
scanf("%s", &arr); // <---------- the problem function (input < 20 chars) should be scanf("%s", arr); // <---------- the problem function (input < 20 chars) The perils of using the C io functions!
7,831,275
7,831,284
Compiling C++ code makes the system hang
When I try to compile this file by issuing the command, "g++ qr.cpp -o qr" The system hangs. I haven't seen this kind of an error anywhere else. #include<iostream> using namespace std; bool win[1000000001]; bool know[1000000001]; int sixes[] = {6, 36, 216, 1296, 7776, 46656, 279936, 1679616, 10077696, 60466176, 3627...
Do you realize how big these are? bool win[1000000001]; bool know[1000000001]; Those are at least 1GB each!!! You're gonna want to allocate them dynamically...
7,831,426
7,831,729
hoare partition code does not work
following code for partition #include<iostream> using namespace std; #define maxn 10000 int x[maxn]; void partition(int x[],int p,int r){ int y=x[p]; int i=p-1; int j=r+1; while(i<j){ do{ j=j-1; } while( x[j]>y); do { i=i+1; } while(x[j]<y); if (i<j){ int s=x[i];x[i...
I don`t really what are you trying but may be second while comparison: while(x[j]<y) must be changed by while(x[i]<y)
7,831,535
7,831,779
Writing a C program that takes user input and is supposed to locate the inputted file?
I am supposed to use a for loop for use input -Not sure why a for loop? I mean all this program does is keep on asking the user to input a filename, a starting seek adds and the # of bytes to read off. For example, the input should look like: %myprog Enter filename:datafile Start seek:0 Bytes to read:65 My block ...
The for loop is the universal looping construct in C. The following loops are equivalent. FOR LOOP int n; for(n = 0; n < 10; n++) { foo(n); } WHILE LOOP int n; n = 0; while(n < 10) { foo(n) n++; } Assuming you know this, you could write the following rather obtuse code, although it might be frowned upon: #inc...