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 |
|---|---|---|---|---|
5,270,546 | 5,270,634 | Qt QLine class extension | I am trying to extend QLine class to include a color attribute. I used QCreator to create the code for the new class QLineColor and I just added the attribute char color=0 in the public data. Here is the code generated by QCreator.
UPDATE: Modified according to response about QObject. but now I am getting some other er... | QLine doesn't derive from QObject. Therefore Q_OBJECT etc. are all undefined.
#include <QLine>
class QLineColor : public QLine
{
QLineColor();
char color;
};
should work.
|
5,270,646 | 5,270,757 | Read 32bit caches in 64bit environment | we have a lot of caches that were built on 32bit machine which we now have to read in 64bit environment.
We get a segmentation fault when we want to open read a cache file.
It will take weeks to reproduce the caches, so i would like to know how still can process our 32bit cache files on 64bit machines.
Here's the code ... | From the line:
long size = this->_size * sizeof(long);
I assume that values points to an array of long. Under most OS excepted Widnows, long are 32 bits in 32 bits build and 64 bits in 64 bits build.
You should read your file as a dump of 32 bits values, int32_t for instance, and then copy it as long. And probably v... |
5,270,780 | 5,270,813 | What does the "::" mean in "::tolower"? | I've seen code like this:
std::string str = "wHatEver";
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
And I have a question: what does mean :: before tolower?
and std::tolower not works, but ::tolower works OK
| Means that it is explicitly using the tolower in the global namespace (which is presumably the stdc lib one).
Example:
void foo() {
// This is your global foo
}
namespace bar {
void foo() {
// This is bar's foo
}
}
using namespace bar;
void test() {
foo(); // Ambiguous - which one is it?
... |
5,271,022 | 5,271,205 | OpenGL How to unit test? | Is there a good way to unit test a function or a class using OpenGL commands?
For c++, I know I could make the class a template and pass a class doing direct opengl calls :
namespace myNamespace
{
struct RealOpenglCall
{
static inline void glVertex2fv( const GLfloat * v)
{ ::glVertex2fv( v ); }
};
template< typena... | Here is a nice trick i learned a while back. You can use regular old #defines to let you mock all kinds of API functions:
#ifdef _test_
#define glVertex3f(x,y,z) (mockGlVertex3f((x),(y),(z)))
...
#endif
With a configured preprocessor. There is no need to change your drawing-functions at all. Further: you can implemen... |
5,271,037 | 5,271,081 | Why do people still use C when they have C++? | My question is this, why do people still use C when they have C++?
I've studied C because it is considered the language on which programmers communicate and is recommended for any programmer to know. I've then passed to C++ and I now think, why do people still use and program in C?
As far as I see, C++ is more powerful... | C is much simpler, and more fun to program in.
But what's more, the compiler is much much easier to write so there are still lots of environments where you can either only get a C compiler or the C++ compiler is far inferior (buggy, slower, generates bloated binaries).
|
5,271,078 | 5,271,145 | Scalable and dynamic graph visualization library in C++ | I am developing a piece of software that makes an intensive use of graphs. I'd like to visualize these graphs (they may become quite large). Is there a good C++ library (or in another language, but with a C++ API) that allows for fast, easy, and scalable visualization of graphs?
I would be interested in features such a... | Do you use Boost.Graph? Then you can write .dot-files with write_graphviz and let GraphViz do the drawing.
|
5,271,109 | 5,271,909 | Passing pointer of calling object (this) as argument to method of another instantiated method in C++ | I'm reviewing some code and I have stumbled many times on examples as described in title. THen this passed object is referenced in calling outside methods from second object, even changed somewhere else and then again used by reference in another methods.
THe weirdest thing is that the second object calls methods from ... |
Perhaps main question should be divided into more: is this usual and practical workaround to pass itself to another object in C++?
It is both usual and practical. Quite often it's the most natural way to achieve something. For example if you want a parent-child navigable from both ends, it's easiest for the parent o... |
5,271,471 | 5,271,706 | Help regarding a core dump problem involving string class | I am performing a code review for resolving a rarely occuring live enviornment problem. It is not reproducible in debug enviornments and hence the only means of investigation is the core dump from live enviornment and through code analysis. Here is the summary of the situation:
The core dump:
(gdb) bt
#0 in strlen (... | The constructor from a const char* does not check for a null pointer, it is up to the caller to check if needed. YOU must know if it is possible or not for the argment to be null.
The other constructor could use string's copy constructor, instead of passing c_str() to it. It both saves you from recalculation the length... |
5,271,478 | 5,271,589 | finding memory leaks in a boost::test::unit_test | This question is a continuation to a previous question on boost::test::unit_test.
I've written a unit test and built the unit test. Here's the build output:
2>------ Build started: Project: UnitTests, Configuration: Debug Win32 ------
2> stdafx.cpp
2> UnitTests.cpp
2> UnitTests.vcxproj -> F:\Src\Crash\trunk\Deb... | Have a look here: http://www.boost.org/doc/libs/1_40_0/libs/test/doc/html/execution-monitor/user-guide.html
You can probably set a command line argument to break at the required allocation ID.
Edit: use --detect_memory_leak on the command line (from here: http://www.boost.org/doc/libs/1_40_0/libs/test/doc/html/utf/use... |
5,271,536 | 5,280,544 | How to switch from VS9 to VS10 for NMake with CMake | On my computer I have both VS9 and VS10 for testing purpose.
When I configure my project with VS9 or VS10 I have no problem with CMake.
Now I want to generate a project with NMake but during the configuration it takes VS9 as default C compiler and CXX compiler and I want VS10.
Anyone has an idea how I can perform such ... | The NMake Makefiles generator uses the environment of your shell. In a normal cmd Window it will fail, and you normally open up the Visual Studio shell for the version you are interested in. You can also run the appropriate vcvars. I am not near a Windows machine right now, but I would check the command prompt you are ... |
5,271,721 | 5,271,754 | How to delete a file for sure under windows (problem with file locks)? | is there a way to delete a file under windows xp, ntfs filesystem even if there is a lock on that file?
Having issues with other processes like e.g. virus scan locking files I want to move/delete.
Thanks for any hints!
| MoveFileEx allows you to pass the MOVEFILE_DELAY_UNTIL_REBOOT which will cause the file to be moved/deleted when you next reboot. Other than that, you'd have to find/kill whichever other process(es) currently have the file locked, which may not be possible, and is almost certainly not desirable behaviour for most progr... |
5,271,840 | 5,271,878 | defining output operator << in C++ for user defined type | struct myVals {
int val1;
int val2;
};
I have static functions
static myVals GetMyVals(void)
{
// Do some calcaulation.
myVals val;
val.val1 = < calculatoin done in previous value is assigned here>;
val.val2 = < calculatoin done in previous value is assigned here>;
... | The signature for this operator is as follows:
std::ostream & operator<<(std::ostream & stream, const myVals & item);
An implementation could look like this:
std::ostream & operator<<(std::ostream & stream, const myVals & item) {
stream << item.val1 << " - " << item.val2;
return stream;
}
|
5,271,885 | 5,274,719 | Will boost::recursive_mutex::scoped_locks destructor reference an unlocked mutex? | After calling unlock() on a boost::recursive_mutex::scoped_lock, will the lock object reference the mutex somehow in its destructor?
The lock still retains a reference to the mutex after the call to unlock (ie. mutex() returns the same pointer). Must release() also be called on the lock in the case where the mutex is d... | Looking at the code for the unique_lock destructor from Boost 1.42:
~unique_lock()
{
if(owns_lock())
{
m->unlock();
}
}
It will only try to dereference its pointer to your (now invalid) mutex if it owns the lock. If you've already called unlock on this scoped_lock th... |
5,271,912 | 5,272,050 | sscanf multivalue n length values? | I have a file which is similar to /etc/passwd (semi-colon separated values), and need to extract all three values per line into variables then compare them to what have been given into the program. Here is my code:
typedef struct _UserModel UserModel;
struct _UserModel {
char username[50];
char email[55... | sscanf is so C'ish.
struct UserModel {
string username;
string email;
string pincode;
};
void get_user(char *username) {
ifstream io("test.txt");
string line;
while (getline(io, line)) {
UserModel tmp;
istringstream str(line);
if (getline(str, tmp.username, ':') && getline(str, tmp.pincode, ':... |
5,271,969 | 5,272,003 | C++ exception for null pointers | I have a little function (in a DLL) which looks like this:
int my_function(const char* const s)
{
try {
return my_object->do_something_with(s);
} catch (exception& e) {
return ERROR_CODE;
}
}
I thought that the try-catch block would prevent anything which might happen inside my_object from ... | It would have worked in Java, because in Java a NullPointerException is thown. In C++, there's no such ubiquitous exception, dereferencing a null pointer will just give a segmentation fault.
Additionally, in C++ there is no enforced exception type hierarchy. An exception of any type may be thrown; exceptions don't ha... |
5,272,270 | 5,272,494 | SDL Image Split screen | Trying to display two images on screen each take up one half of the screen. Here is the code I am using:
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* pScreen = SDL_SetVideoMode(1280,720,16, SDL_FULLSCREEN );
SDL_ShowCursor(SDL_DISABLE);
//load two images
SDL_Surface* pImage1 = IMG_Load("/media/x01.JPG");
SDL_Surface* pImage... | SDL_BlitSurface takes two rectangles, one for the source, and one for the destination.
The source rectangle, which is the second parameter, is what part of the source surface (in this case, your image) to draw.
The destination rectangle, which is the fourth parameter, is where to draw on the destination surface.
You're... |
5,272,370 | 5,272,409 | copying arrays of strings in C++ | I have an array of variables of type string. Something like:
std::string Array1[3] = {"A","B","C"};
I would like to copy the contents of this array into another one:
std::string Array2[3];
At the moment I use a loop to do this. Is there any
simpler/alternative way? Also if I declare and initialise the variable
a... | No, with an array of complex objects you need a loop, or you can wrap the loop with std::copy:
std::string Array1[3] = { "A", "B", "C" };
std::string Array2[3];
std::copy(Array1, Array1 + 3, Array2);
However, I suggest using the more canonical std::vector, which has native assignment (see this SO answer for the ways t... |
5,272,449 | 5,272,492 | Linkage of inline functions | I have 2 files:
1 is main.cpp
#include<iostream>
using namespace std;
int min(int,int);
int abs(int);
int gcd(int,int);
const char *s = "Read Error!!";
int main()
{
cout << "Enter first Value: ";
int i;
cin >> i;
while(!cin)
{
cout << s << endl;
cin >> i;
}
cout << "Enter second Value: ";
i... | abs "works" because it is in the standard C library as a regular function. Your homebrew abs never gets exported from its module because it is inline.
The same happens with min, but that is not available in the standard library, except as a template.
My advice: import <cstdlib> and <algorithm>, and use std::abs and std... |
5,272,670 | 5,383,604 | gmock : Doing custom check that can fail | I am using google mock library in my unit tests, and I am trying to do a custom check that can fail.
Next example demonstrates what I am trying to do :
struct Base
{
};
struct Derived : Base
{
int a;
};
struct MockClass
{
MOCK_METHOD1( Send, void ( Base & ) );
};
Now I would like to check if the fake object got p... | You can define a custom matcher to verify the type and the value of your argument simultaneously:
MATCHER_P(IsDerivedAnEqual, a, "") {
Derived* derived_arg = dynamic_cast<Derived*>(&arg);
return derived_arg != NULL && derived_arg->a == a;
}
EXPECT_CALL(mock_obj, Send(IsDerivedAndEqual(5));
You can also use compos... |
5,273,038 | 5,438,971 | Building boost library | I'm trying to build boost library under Arch Linux
$ uname -a
Linux wincode 2.6.37-ARCH #1 SMP PREEMPT Fri Feb 25 07:53:43 CET 2011 x86_64 AMD Athlon(tm) 64 X2 Dual Core Processor 5200+ AuthenticAMD GNU/Linux
$ python --version
Python 3.2
$ ls /usr/include/python
python2.7/ python3.2mu/
$ ls /usr/lib/python
python... | Quick google search comes up with http://lists.boost.org/boost-build/2006/04/13457.php.
Basically, add your python include directory to the include search paths.
|
5,273,091 | 5,273,432 | c++ cgi app calling other program fails | I develop a c++ CGI program that runs under Windows and Linux.
This program calls another program like this:
system("otherProgram.exe arguments");
I also tried:
spawnl(_P_WAIT, "otherProgram.exe", "argument1", NULL);
This works fine in my debugger and in my Virtual Machine, but on my test server it doesn't work.
The ... | This is likely a permissions issue. By default your CGI application will be run as if by user nobody. The program you want to launch should be executable by "nobody".
|
5,273,144 | 5,273,165 | C++ polymorphism and default argument | I have these classes:
class Base
{
public:
virtual void foo(int x = 0)
{
printf("X = %d", x);
}
};
class Derived : public Base
{
public:
virtual void foo(int x = 1)
{
printf("X = %d", x);
}
};
When I have:
Base* bar = new Derived();
bar->f... | Default arguments are retained even if you override a function! And this behaviour is correct. Let me search the reference from the C++ Standard.
§8.3.6/10 [Default arguments] from the C++ Standard says,
A virtual function call (10.3) uses
the default arguments in the
declaration of the virtual function
determin... |
5,273,423 | 5,273,825 | Catching thread exit in Xcode | I'm trying to resolve a very nasty Heisenbug under Xcode where I have a thread that's doing some background processing by calling into an external library, and at some point it appears that the thread is just disappearing. The code is something like this:
LOG("starting operation");
float progress=0;
while (progress <... | Set a breakpoint in _pthread_exit.
In Xcodes's menu select "Run" —> "Show" —> "Breakpoints"
Double click on the last line in the breakpoints table.
Enter "_pthread_exit".
You might also want to set a breakpoint in pthread_cancel.
|
5,273,505 | 5,273,538 | Should I expose a protected std::vector? | I have a class which I intend for others to inherit from. It has a std::vector which I only want developers to be able to read from, but not modify, my base functions modify it. Should I provide a function that returns a const iterator, or expose the vector as protected.
Thanks
| If you expose the vector as protected, subclasses will be able to modify it. So, you should expose methods that return const iterators.
You can use the Non-Virtual Interface idiom to expose different interfaces for users and subclasses.
|
5,273,716 | 5,273,785 | Am I exposing too many iterators? | My class can have children and so I need to expose iterators. The render class needs to reverse iterate them which is why I have reverse iterators. But is there a way to have less of these because it seems like a lot:
std::vector<AguiWidget*>::iterator getChildBeginIterator();
std::vector<AguiWidget*>::reverse... | Those look fine to me. Or I can't comment more precisely without knowing what exactly you're doing. But one thing you can surely do at any rate: why don't you use typedef? If you use typedef, you can use it outside the class as well, means in the client code, where you would use the class!
For example,
class sample
{
p... |
5,273,793 | 5,273,812 | runtime type and attributes identification in c++ | I have a struct (could be a class) which defined in 'h' file:
struct my_struct {
char * a;
char * b;
char * other_char;
char * hello;
// other 100 chars
// new chars can be added in future
};
I use this struct in my project. So I'm getting every attribute and value of this struct and call funct... | No. C++ does not have reflection, and this requirement indicates a possible poor design.
Variable names are given for convenience at the programming stage, and should not be taken as identifiers for data that exists at run-time.
However, you can create a real string->object mapping with std::map.
|
5,273,798 | 5,274,056 | where can i find online c++ design patterns and exercises? | i need to start refine my memory so i like to practice a bit
do you know good site like : http://www.blackbeltfactory.com for java?
| Here are some that looked promising on a quick perusal (and I'm adding to my own reading queue):
Wikibooks entry on Design Patterns in C++
Similar question answered responses on CodeGuru
C++ FAQ section on some design patterns
C++ headers from Head First Design Patterns to inspect
Have fun! (Sorry - don't know of an... |
5,273,803 | 5,273,877 | Use one class method that implements other class methods as well as its own | I'm Programing in C++, and I have 3 classes that inherit from each other:
Hatchback -> Car -> Vehicle;
I want to print the attributes from each class using a void print() method,
Each class has a Print method that prints its own attributes.
void Vehicle::print()
{
// Vehicle attributes
}
void Car::print()
{
// ... | If you are asking if you can call a base class method from a derived class, then yes, you can:
void Vehicle::print() {
std::cout << "Vehicle attributes" << std::endl;
}
void Car::print() {
Vehicle::print();
std::cout << "Car attributes" << std::endl;
}
|
5,274,025 | 5,274,050 | Doesn't erasing std::list::iterator invalidates the iterator and destroys the object? | Why does the following print 2?
list<int> l;
l.push_back( 1 );
l.push_back( 2 );
l.push_back( 3 );
list<int>::iterator i = l.begin();
i++;
l.erase( i );
cout << *i;
I know what erase returns, but I wonder why this is OK? Or is it undefined, or does it depend on the compiler?
| Yes, it's undefined behaviour. You are dereferencing a kind of wild pointer. You shouldn't use the value of i after erase.
And yes, erase destructs the object pointed to. However, for POD types destruction doesn't do anything.
erase doesn't assign any special "null" value to the iterator being erased, the iterator is j... |
5,274,149 | 5,274,184 | How compile time recursion works? | I found a code here Printing 1 to 1000 without loop or conditionals
Can someone please explain how compile time recursion works, couldn't find it in google
// compile time recursion
template<int N> void f1()
{
f1<N-1>();
cout << N << '\n';
}
template<> void f1<1>()
{
cout << 1 << '\n';
}
int main()... | It repeatedly instantiates the f1<N> template with decreasing values for N (f1<N>() calls f1<N-1> and so on). The explicit specialization for N==1 ends the recursion: as soon as N becomes 1, the compiler will pick the specialized function rather than the templated one.
f1<1000>() causes the compiler to instantiate f1<N... |
5,275,100 | 5,275,191 | Union in c++ are they feasible | Can a union in C++ have a member function? How do union with data members and member functions exist if an object is created?
If I suppose yes, then are they feasible any where. If yes then where?
| 9.5/1
A union can have member functions
(including constructors and
destructors), but not virtual (10.3)
functions. A union shall not have base
classes. A union shall not be used as
a base class. An object of a class
with a non-trivial constructor (12.1),
a non-trivial copy constructor (12.8),
a non-tr... |
5,275,133 | 5,275,403 | File reading trouble? | typedef long int INT;
typedef unsigned char byte;
#define MAX_CITIES (INT)2.7e6
#define MAX_LEN (int)1e6
typedef struct
{
unsigned long start;
unsigned long end;
char *region;
char *city;
char *type;
} ipdb;
ipdb db;
char s[MAX_LEN + 1];
typedef struct
{
unsigned long start;
unsigned lo... | Values of 2^31 and higher are outside the range that atoi can handle and it'll return INT_MAX for them. You could use strtoul instead.
|
5,275,175 | 5,275,228 | Using the type conversion operator | I have a visual studio 2008 C++ application where I need to get information from a function that takes a variably sized buffer. So, I have a class that backs that type with a std::vector and implements a conversion operator to the type I want.
class CMibIpForwardTable
{
public:
operator MIB_IPFORWARDTABLE* ()
... | Just overload operator-> in addition to the conversion operator.
MIB_IPFORWARDTABLE* operator-> () { ... }
const MIB_IPFORWARDTABLE* operator-> () const { ... }
|
5,276,150 | 5,276,440 | Similar Data Algorithm | I have a couple DBs of user information, each one 10k-20k entries, each one from a couple of different sources, and each one constantly growing. I'm looking to create a tool that can within a certain tolerance notice similar emails, or similar names ( first + ' ' + last ). I'm running a MySQL database, and can work wit... | That would depend on your notion of "similarity". If you are looking for the number of characters that must be inserted, deleted or replaced in order to transform one string into another, the algorithm is called Levenshtein distance. Be warned, though, that it is quite slow for long strings (as each comparison uses a n... |
5,276,195 | 5,276,412 | const vs. macro and memory lifespan | I have a huge array that is written literally thanks to a script. It is basically an image file converted to an array.
I could define the body as a macro or put it into a const type in a header. If I did set it as a const, what will be the memory lifespan? Does it last for the entire program? Does it last for as long a... | I'd move the array definition into a source file (probably by itself):
// bitmap.cpp
char const my_bitmap[] = {
0x12, 0x34, 0x56, // lots of data here...
};
Then write a header that just has an extern declaration for it:
//bitmap.h
extern char const my_bitmap[];
This gives all code (that includes the header) acces... |
5,276,686 | 5,276,789 | Merging Ranges In C++ | I have a list of randomly ordered unique closed-end ranges R0...Rn-1 where
Ri = [r1i, r2i] (r1i <= r2i)
Subsequently some of the ranges overlap (partially or completely) and hence require merging.
My question is, what are the best-of-breed algorithms or techniques used for merging such ranges. Examples of such algori... | What you need to do is:
Sort items lexicographically where range key is [r_start,r_end]
Iterate the sorted list and check if current item overlaps with next. If it does extend current item to be r[i].start,r[i+1].end, and goto next item. If it doesn't overlap add current to result list and move to next item.
Here is ... |
5,277,213 | 5,277,226 | Is it okay to use constructors to initialize a 2D Vector as a one-liner in C++? | Is it okay to initialize a 2D vector like this (here all values in a 5x4 2D vectro are initialized to 3)?
std::vector<std::vector<int> > foo(5, std::vector<int>(4, 3));
This seems to behave okay, but everywhere I look on the web people seem to recommend initializing such a vector with for loops and push_back(). I was ... | This is perfectly valid - You'll get a 2D vector ([5, 4] elements) with every element initialized to 3.
For most other cases (where you e.g. want different values in different elements) you cannot use any one-liner - and therefore need loops.
|
5,277,373 | 15,555,645 | How to connect a C++ program to a WCF Service? | In the place I work there are some software written in C# and some written in C++ (the most important ones). Some time ago we decided it would be a good idea to track any possible problem in the software, by sending stack trace and exception information over a web service. So I came with a WCF Service, that gets the in... | Since your WCF service is in C# with .NET, and the only issue is getting the C++ application to be able to talk to it, one way is to follow the advice in REST / SOAP Endpoints for a WCF service and related articles.
Your C# programs continue to have the full SOAP access to your service.
Your C++ programs could do somet... |
5,277,524 | 5,277,718 | Minimal linux that can run Qt GUI application | I'm making a homebrew video-game console (simple low spec pc) that will constantly run one application (game) which will be created with Qt (it's a requirement, preferably with gpu acceleration). So OS should be lightweight to boot as fast as possible and run the game.
How can this be achieved? Are there any linux dist... | http://www.tinycorelinux.com/
a 10 MB Linux distribution. boots within a few seconds.
|
5,277,547 | 5,277,574 | Directly casting from pointer to a template function? | I am trying to take a pointer to an instance of function template and cast it to void*:
#include <stdio.h>
void plainFunction(int *param) {}
template <typename T>
void templateFunction(T *param) {}
int main() {
void *addr1=&plainFunction; //OK
void *addr2=&templateFunction<int>; //Compile error
}
I get the ... | Both are technically wrong: in C++, you can't convert a function pointer to a void*.
Pointer-to-function types (like void (*)(int*) here) are a completely different class of types than pointer-to-object types (like void* here).
Visual C++ allowing the conversion at all (e.g. in void* addr1 = &plainFunction;) is a lan... |
5,277,885 | 5,297,737 | KeyRelease event never sent | I'm having a little problem catching a key released event to stop my character from walking in my game..
i'm trying to do this:
switch (xev.type)
{
case Expose:
{
XGetWindowAttributes(dpy, win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
}
break;
... | This is a common gotcha. If you don't register for specific events (or all), you will not be notified.
All of us, doesn't matter the experience, will fall in this one day... :)
Some usefull links:
XSelectInput @Xorg
XSelectInput @tronche
Anatomy of the most basic Xlib program
|
5,277,944 | 5,357,898 | QGraphicsItem::setTransformOriginPoint bug when trying to scale image | I have created my own class by extending QGraphicsItem and I want to make it so that when someone does a wheel even while over this item, it scales.
This way, i can have multiple items in a scene, and scale each of them in and out as I please.
The problem is, I want the item to scale under the mouse cursor, much like g... | I have achieved similar functionality in my Image-Manipulation application (scaling the view and having the area under my mouse stay in place and visible) but I scale the whole graphics-view not a specific item, so I don't know if this code can solve your problem.
Anyway, this is what I do in the constructor of my subc... |
5,278,048 | 5,278,117 | What should be the arguments/declaration for ofstream in int main in C++? | When I tested ofstream under int main() whose the sole purpose is to output data into a file, then I can compile with no problem. However, when I have other arguments inside int main(...), the following errors come up. How do I declare ofstream in int main(...)?
error: ‘ofstream’ was not declared in this scope
error... | You need to #include <fstream> and qualify ofstream as std::ofstream.
Also note that your signature for main is not allowed by the standard and may or may not cause random unpredictable problems for you.
|
5,278,277 | 5,278,350 | write to ostream inside of function with c++ | consider the following function:
void writer(ofstream &output) {
output << "a string to write" << endl;
}
but when i try to call this, i get an error that '<<' is not defined. how can I fix this?
| Add #include <fstream> or change ofstream to ostream
Most likely you lack an include, so that ofstream is only forward declared.
|
5,278,320 | 5,278,333 | x,y,z to vector offset | I know this may sound stupid but I'm goin crazy with this XD
I'm loading ad image (with ImageMagick) into a 1D vector, so that I have something like:
012345678...
RGBRGBRGB...
Where 0-. Are obviously the indexes of the vector, and R, G, and B are respectively the red byte, green byte, and blue byte.
So I have a WIDTHx... | This expression produces an index to color component z at pixel (x,y):
((y * WIDTH) + x) * 3 + z
Assumptions are:
Data is placed in row-major order.
No padding/alignment bytes are used between rows.
|
5,278,540 | 5,278,595 | modifying 2d array in a function | So I've written a function that turns a 2D array 90 degrees and I've been told on IRC that I can't pass 2D array by reference (for example void test(char A[][10]&)) and that I just should pass my array the usual way, however when I do that, this function doesn't change the actual array. So how do I modify my original a... | A = B ; doesn't copy the elements of array B to A permanently. It's an invalid assignment to change to elements of A permanently. A retains it's original values upon function return. You need to do a member wise copy to permanently copy the elements of B to A.
|
5,278,582 | 5,278,627 | Checking the status of a child process in C++ | I have a program that uses fork() to create a child process. I have seen various examples that use wait() to wait for the child process to end before closing, but I am wondering what I can do to simply check if the file process is still running.
I basically have an infinite loop and I want to do something like:
if(chi... | Use waitpid() with the WNOHANG option.
int status;
pid_t result = waitpid(ChildPID, &status, WNOHANG);
if (result == 0) {
// Child still alive
} else if (result == -1) {
// Error
} else {
// Child exited
}
|
5,278,611 | 5,278,655 | not equal to 0 checks for non null on pointer? | Where p is the name of a pointer, does p != 0 return a bool that is true where p is null (not pointing at anything) ?
| It specifically checks to see, as your title says, if the pointer is non-null, or is not the value 0x00000000. Your pointer might not actually be pointing at anything valid (e.g., could be a trashed pointer that just points to some random point in memory), but after that check you know it is not NULL.
EDIT :
Wording ... |
5,278,904 | 5,279,551 | How can I determine appropriate stack and heap sizes for ARM Cortex, using C++ | The cortex M3 processor startup file allows you to specify the amount of RAM dedicated to the stack and the heap. For a c++ code base, is there a general rule of thumb or perhaps some more explicit way to determine the values for the stack and heap sizes? For example, would you count the number and size of unique obj... |
The cortex M3 processor startup file
allows you to specify the amount of
RAM dedicated to the stack and the
heap.
That is not a feature of the Cortex-M3, but rather the start-up code provided by your development toolchain. It is the way the Keil ARM-MDK default start-up files for M3 work. It is slightly unusu... |
5,278,978 | 5,279,028 | C++: general thoughts about overloading operator new | Have you overloaded operator new in C++?
If yes, why?
An interview question, for which I humbly request some of your thoughts.
| We had an embedded system where new was only rarely allowed, and the memory could never be deleted, as we had to prove a maximum heap usage for reliability reasons.
We had a third party library developer who didn't like those rules, so they overloaded new and delete to work against a chunk of memory we allocated just f... |
5,279,042 | 5,279,060 | placement new VS explicit constructor call in C++ | recently I have come across these two ways of creating an object in a specific place in memory:
1.
void* mem = malloc(sizeof(T));
T* obj = new(mem) T();
2.
T* obj = (T*)malloc(sizeof(T));
*obj = T();
The second way is a bit shorter...are there other differences?
Regards
Mateusz
| The second way is wrong, the first is right.
You're invoking the assignment operator on a T instance containg garbage data. The assignment operator expects the instance to have been initialized correctly - It could e.g. delete member variables before assigning, which would cause all sorts of funny crashes. See e.g:
str... |
5,279,043 | 5,279,269 | What are problems with shallow copy? | This is an interview question I saw from here:
http://www.careercup.com/question?id=1707701
Want to know more about this .thanks
| Shallow copy causes a problem (primarily) when you have "remote ownership". The most common form is a pointer to data that's owned by the object so when the object is destroyed the data it owns gets destroyed as well. One place many people run into this is the inevitable string class:
// warning: bad code. Do *not* us... |
5,279,188 | 5,279,229 | Porting c++ to python code | I want to convert this C++ code to Python v2:
static unsigned char asConvCode[3] = {0xFC, 0xCF, 0xAB};
void asConv(char* str, int size)
{
int i = 0;
for (i = 0; n< size; n++)
{
str[i] ^= asConvCode[n % 3];
}
}
tried to make like that:
def asConv(self, data):
asConvCode= [0xFC, 0xCF, 0xAB]... | In Python, characters in strings are simply strings of length 1, not integers. So you must use this:
data[i] = chr(ord(data[i]) ^ asConvCode[i % 3])
Also, as I wrote in a comment, your return data is at the wrong indentation level, and will cause your function to return after processing the first character.
|
5,279,280 | 5,279,310 | Making threads in C++ vs. Two Separate Programs? | I'm making an application that receives user input while it is searching for the requested info in C++. Would it be better just to run two different applications in Windows Explorer? Would it be faster?
| The answer depends on several factors, such as how much time does all this process take, and how much information should the two processes share between them.
If this is a matter of seconds, and there is a data structure shared between the two parts of your application, I don't see any point in separating them into dis... |
5,279,443 | 5,279,615 | CUDA and C++ for host and device code | I started to integrate CUDA into my C++ applications weeks ago. I've been doing my own research about integrating CUDA and C++. However, I still feel uncomfortable about this topic.
Can somebody help me to clarify some questions based on the latest Toolkit 3.2 or 4.0 RC?
It says Fermi fully support C++ in Fermi's whit... |
Your host already supports C++, doesn't it? But now the GeForce 400 Series (codename Fermi) supports C++ code on the device.
Classes too, with some restrictions. See appendix D of the programming guide for details.
You can pass a reference of the class. Check section D.6.2 of the programming guide.
In general, append... |
5,279,643 | 5,279,674 | Declaring Dynamic 2D Vector in class | We're trying to use a 2D vector because we want a 2D array that will grow dynamically.
We tried this:
In the class declaration:
vector<vector<double> > table;
But then table doesn't seem to be allocated. We get a segfault when we try to access members.
So then we tried this:
Class Declaration:
vector<vector<do... | You'll need to resize the tables before you access elements.
vector<vector<double> > table;
table.resize(10);
for (int i = 0; i < 10; ++i)
table[i].resize(20);
|
5,279,968 | 5,279,988 | C++ library comparison: Boost and Tr1 | Which is more robust? Coz I read Linus Torvalds 's article about how bad is boost. Is that tr1 is better than boost?
| TR1 is a set of libraries that were proposed additions to the C++ Standard Library. Most of them originated in Boost and most of them are now included in the latest C++0x draft standard.
There are some differences between different versions of the Boost implementations of the libraries, the TR1 specification of the ... |
5,280,011 | 5,280,532 | C++ Templates - How to use across multiple MTU's | class A : boost::noncopyable {
int type;
A(int type, enum e) : type(type) { /* ... */ }
}
typedef boost::shared_ptr<A> A_ptr;
template <enum VAR>
class B : boost::noncopyable {
static A_ptr x, y;
B() {
if (!x.get()) {
x.reset(new A(0, VAR));
}
if (!y.get()) {
... | a) Set it up like this:
A.h:
#ifndef A_HEADER_GUARD
#define A_HEADER_GUARD
class A {...};
#endif
A.cpp:
// A::method1 implementation
// A::method2 implementation
// etc...
B.h:
#ifndef B_HEADER_GUARD
#define B_HEADER_GUARD
#include "A.h"
template <enum VAR> class B {...}
#endif
Note that class B can't be implem... |
5,280,089 | 5,280,105 | C++ Expression Template: operator what? | template <typename E>
class VecExpression{
public:
operator E&(){
return static_cast<E&>(*this);
}
operator E const&() const{
return static_cast<const E&>(*this);
}
};
could someone please explain to me this code? I've never seen this kind of operator overloading. What is its return type? Does it h... | This is the conversion operator.
int i = (int)a;
that would invoke a::operator int()
|
5,280,168 | 5,280,217 | Making a cross platform library with CMake? | Is CMake difficult to use? I've been developing a library using Windows and MSVC++ . I tested my code in Linux and OSX by tediously making objects from each file and making a library out of this.
I have several Directories ex:
Agui
-> Widgets
->Button
->ListBox
-> Backends
-> Allegro
And what I'd ... | Yes, that is exactly the reason CMake is made for. Huge projects like KDE use CMake.
And its easy to setup.
|
5,280,292 | 5,280,411 | Need to duplicate an IDispatch* with .NET backing; don't know class name | I'm hosting a .NET library in my C++ program using the following methods, though not an exhaustive list:
CorBindToRuntimeEx()
GetDefaultDomain()
CreateInstance()
Invoke()
I have C++ classes which correspond to .NET classes. Each class instance contains a CComPtr<IDispatch>, which I use to call functions and get/set me... | This is the expected behavior, the CComPtr copy constructor will simply copy the interface pointer and add a reference with AddRef(). There is no mechanism to automatically create a deep copy, neither in COM nor in .NET. This isn't fundamentally different from C++. There is a well-known interface defined in .NET, IC... |
5,280,302 | 5,280,332 | Why does it say that my 'destroystack' isn't declared? | #include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
string name;
double gpa;
double high = 0;
stack<string>names;
for (int i=0;i<7;i++)
{
cout << " Enter student's name and gpa " <<endl;
cin >> gpa ;
cin >> name ;
if (gpa > high)
{
names.destroyStack();
high = gpa;
names... | This code should work to empty your stack:
replace:
names.destroyStack();
with:
while (!names.empty())
{
names.pop();
}
As you can see, empty is a function; it returns a value. In this case, it returns a boolean (true/false), so you'll need to have parenthesis after it, in order to call it.
That's w... |
5,280,550 | 6,061,159 | C++ Boost's sregex_token_iterator crash | I'm using the following code to get the image filenames from an HTML file.
The code goes somehow like this:
std::tr1::regex term=(std::tr1::regex)r;
const std::tr1::sregex_token_iterator end;
for (std::tr1::sregex_token_iterator i(s.begin(),s.end(), term); i != end; ++i)
{
std::cout << *i << std::endl;
}
s... | I really forgot about this-- I'm pretty sure there was an external problem on this, linker-related, so it was kinda hard to figure out. But the code was fine.
|
5,280,575 | 5,280,602 | GCC Compile error when copying compiled version to another host | I compiled gcc on one of my ubuntu 10.10 hosts, and installed it in /c. I can compile c and c++ programs fine on that host but when i copy /c (which contains bin, libexec etc) to a ubuntu 10.04.2 host i get:
/c/libexec/gcc/i686-pc-linux-gnu/4.5.2/cc1: error while loading shared libraries: libmpc.so.2: cannot open share... | did you export your LD_LIBRARY_PATH environment variable? Looking at the error, it's not able to find libmpc.so.2.
Try 'locate libmpc.so.2' and if you can find that,
export LD_LIBRARY_PATH=
|
5,280,642 | 5,280,892 | logging last eight character of the thread id? | In my multithreaded program, I am logging process id and thread id. Thread id is generated using pthread_self() function. when I print in hex, generally it has 12 characters out of which first four are always common and I don't want to log them.
What is the best way in C++ to print last 8 characters, I tried to use bo... | Your magic constant should be in hex:
pthread_self() & 0xffffffff
This lets bits in the bottom 8 hex digits pass through unchanged, but sets bits in the higher hex digits to 0. They should then be suppressed, since you haven't specified leading 0 printing.
|
5,280,756 | 5,299,198 | libjpeg ver. 6b jpeg_stdio_src vs jpeg_mem_src | I am using Libjpeg version 6b. In version 8 they have a nice function to read data out of the memory called jpeg_mem_src(...), unfortunately ver. 6b does not have this function.
What can I use to read compressed data directly from memory? All I see is jpeg_stdio_src which reads from the hard drive.
| Write your own...
/* Read JPEG image from a memory segment */
static void init_source (j_decompress_ptr cinfo) {}
static boolean fill_input_buffer (j_decompress_ptr cinfo)
{
ERREXIT(cinfo, JERR_INPUT_EMPTY);
return TRUE;
}
static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
struct jpeg_source... |
5,280,952 | 5,281,076 | how to compile Qt code in command line on Mac OS | I download this : http://get.qt.nokia.com/qt/source/qt-mac-opensource-4.7.2.dmg and install it.
Then I got a Qt helloworld.cc.
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton hello("Hello world!");
hello.resize(100, 30);
... | It works here for me. You didn't show your command line, but it seems like you aren't passing the right flags to tell your compiler where the headers/frameworks are. Here's what I used:
g++ -I /Library/Frameworks/QtGui.framework/Versions/4/Headers \
-o example example.cpp \
-framework QtGui -framework QtCore
... |
5,281,038 | 5,281,050 | Detect long double overflows on embedded systems | I'm going to use big numbers in C++ code on an embedded system. Luckily the compiler recognizes long doubles.
I can not use standard libraries, boost libraries, gnu math libraries, etc. And the system has not got built-in float math cpu.
Now how can I detect long double overflows?
| As it's not standard C++, you will have to rely on methods provided by your specific environment. The manufacturer of the embedded system should have documented how it can be done. Ask him.
|
5,281,103 | 5,286,442 | How to query for all base classes of a class at compile time? | With std::is_base_of<A,B>::value one can check if a class A is a base class of
class B. Is it also possible to query the compiler for all base classes of a class
B, e.g., something like base_classes_of<B> returning a std::tuple containing all base classes of B ?
Is there evtl. a non-standard extension in g++ that can ... | Similar facility bases and direct_bases were proposed in
N2965.
As for data members, since data members can be bit-fields, their type traits
have some subtleties.
On the other hand, base classes don't have such problems.
I think there is the demand on some compile-time query like bases
in some situations, as mentioned ... |
5,281,159 | 5,281,228 | Signal handling in c++ | im new in c++,i want to know when we need to use signal handling in our program?and i saw in some codes that they fork after setting up signal,what fork means here?
TIA
| I strongly recommend the book Advanced Programming in the Unix Environment, 2nd Edition as your guide to systems programming.
fork(2) spawns a new process; it is almost entirely a clone of the current process. But the differences are vast: the return value from fork(2) is different in parent and child, the child has a ... |
5,281,197 | 5,281,223 | program crashes sometimes | The following routine is expected to remove the node at the start of a single linked list but it fails sometimes.
void remove_from_front(node *start)
{
delete start;
start = start->link;
print_list(start);
}
| There are few problems I can see:
You are freeing the start node and then accessing the freed memory. This is incorrect, it leads to undefined behavior which means anything can happen. In one run it might work and in the next run it might crash.
Your function needs to make changes to the head of the list but it is not... |
5,281,261 | 5,284,527 | Generating a normal map from a height map? | I'm working on procedurally generating patches of dirt using randomized fractals for a video game. I've already generated a height map using the midpoint displacement algorithm and saved it to a texture. I have some ideas for how to turn that into a texture of normals, but some feedback would be much appreciated.
My he... | Example GLSL code from my water surface rendering shader:
#version 130
uniform sampler2D unit_wave
noperspective in vec2 tex_coord;
const vec2 size = vec2(2.0,0.0);
const ivec3 off = ivec3(-1,0,1);
vec4 wave = texture(unit_wave, tex_coord);
float s11 = wave.x;
float s01 = textureOffset(unit_wave, tex_coord... |
5,281,279 | 5,281,488 | Can i store the unspecified type in GtkListStore? | Can i store the unspecified type in GtkListStore? For instance, I want to store in one field - the field of int type and the field of GdkColor type ?
| Me asked that It will be set the G_TYPE_VALUE type of field
#include <gtk/gtk.h>
int main (int argc, char * argv[])
{
gtk_init(&argc, &argv);
GtkListStore* store = gtk_list_store_new(1, G_TYPE_VALUE);
GValue v = { 0 };
GtkTreeIter iter;
gtk_list_store_append(store, &iter);
g_value_init(&v, G_TYPE_INT);
... |
5,281,332 | 5,281,389 | which is time consuming construct in following program? | while submitting a solution for practise problem 6(odd) i got TLE error
but while using using print and scanf in place cin and cout my sol was submitted successfully with 0.77s time..i want to know how can i make it more efficient
link to problem is codechef problem 6
#include<iostream>
#include<cstdio>
using namespace... | The answer is effectively greatest power of 2 <= n.
I used the following function from hackers delight to solve this:
unsigned int pow2 (unsigned int x){
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return x - (x >> 1);
}
a... |
5,281,487 | 5,339,427 | C++ Factory using lua | I had a script with:
Custom language used only for data
Was loaded using a Script class from C++
I had tags like Type, etc
An interface to get a value for a tag - Script::GetValue(Tag, T& value)
The script was used like this:
Script* script("someFile");
script->GetValue("Type", type);
Object* obj = CreateObject(type)... | You may allow your script environment to create C++ objects or not, depending on your needs.
tolua++ uses all the metatable features to allow a very straightforward manipulation of your c++ types in lua.
For example, this declaration :
// tolua_begin
class SomeCppClass
{
public:
SomeCppClass();
~SomeCppClass();
... |
5,281,517 | 5,281,522 | c++ constructor question | #include <QApplication>
#include <QFont>
#include <QPushButton>
#include <QWidget>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0);
};
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
{
setFixedSize(200, 120);
QPushButton *quit = new QPushButton(tr("Quit"), this);
qui... | It is called an Default parameter
Basically you are saying unless you pass another value, the function (or constructor in this case) will be called with parent as 0.
When you'd had MyWidget(QWidget *parent); as constructor, you'd had to call it like MyWidget widget(0);
|
5,281,988 | 5,282,007 | Why L before dll path? | I've read the code that imports a dll into a project but I don't understand why we have the "L" before the path
module = LoadLibrary(L"freeglut.dll");
How I set the absolute path like "C:/VisualStudo/Project"
And how I set the relative path? like "../../Project1"
Thanks
| L is the string literal prefix to indicate that the string is made from wide characters (wchar_t).
In windows you have two version of LoadLibrary: LoadLibraryA (ansi) and LoadLibraryW (unicode), normally sone #define choose the proper version for your compilation. If you are using the A version you have to pass an ansi... |
5,282,113 | 5,282,352 | Is Visual Studio 2010 SP1 safe to install and what exactly is Assembly signing | I've just received this MSDN blogpost in my rss reader and I would like to know (since I don't fully understand the process that he talking about if I should or should not install SP1
Furthermore I would like to know:
how are assemblies signed in visual studio ?
how the operating system checks these signs ?
does the g... | 1) Yes. If you aren't delivering signed assemblies, then you don't have to worry about patching the MSBuild tools.
2) With a public key. http://msdn.microsoft.com/en-us/library/ab4eace3.aspx
3) The OS doesn't. The .Net Framework does. The assembly loader verifies the public key against a digest to detect modifications.... |
5,282,151 | 5,282,153 | Can we overload main() function in C++? | Since C+++ allows function overloading, can we overload main()?
For example,
int main(const std::string &)
{
return 0;
}
int main(int argc, char *argv[])
{
return main("calling overloaded main");
}
gcc-4.3.4 doesn't compile this, and gives these errors: (see at ideone)
prog.cpp:4: error: first argument of ‘int m... | Yes it explicitly forbids that. Refer to 3.6.1p2
An implementation shall not predefine the main function. This function shall not be overloaded.
This way, the main function's name can stay unmangled. That is, the runtime library can call a symbol having a fixed name (e.g main or _main) to jump to the main function.... |
5,282,160 | 5,282,452 | file handling in c++ | I wrote the following code to input numbers from a file however the last number gets printed twice which I find perplexing. What could be the possible answer.
Thanks in advance.
code:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int x;
ifstream f;
f.open("note");
while(!f.eof()... | Every solution so far presented has a good explanation of why the OP code is wrong. But most have the incorrect solution to the problem.
As stated many times before the EOF flag is not set until you try and read past the end of file. The last successful read may read up-to (inclusive) the last character. So in your cas... |
5,282,170 | 5,282,362 | QTabWidget set title font of only one tab | I've created a chat program with an Interface using QTabWidget. If there's an update in a tab i want to set the tabs title font to a bold font. With QTabWidget::font i can only set the font of the titles of all tabs.
| Unfortunately, you can only access the text itself. The font of the text is not exposed in the QTabBar of the QTabWidget. Perhaps changing the color of the tab would suffice? Otherwise, you'd have to override the painting algorithms, which probably would prove to be cumbersome. In Qt 3 it was possible accessing the QTa... |
5,282,681 | 5,282,708 | CUDA and Linker errors | This may be a similar question to Linker errors 2005 and 1169 (multiply defined symbols) when using CUDA __device__ functions (should be inline by default), but not exactly. I'm getting several LNK2005 errors when trying to build a project (using code that has been shown to work elsewhere) on VS2010. I'm at my wits' en... | There is a redefinition occurring if you are compiling both transposeCUDA.cu and transposeGPU.cu, since the definition appears in both translation units. You should not #include transposeCUDA.cu and apply nvcc to that file.
|
5,282,692 | 5,282,705 | and, or, not versus &&, ||, ! | Yes, this is valid C++ :
if (false or (true and not false)) ...
Among others such as bitand and xor. In C, they used to be macros, but now they are keywords ! You can even overload them ! Then why would someone ever teach or write something like :
if (false || (true && !(false))) ...
Why is nobody using them ?
| Because they don't allow mixed C/C++ code without including additional header files, are less known to programmers, and it's not immediately clear whether and is the short-circuit or bitwise version.
|
5,282,750 | 5,282,808 | is it possible cutting compiler complaint if return type is object? | pseudocode :
function takes "int c" and "list d"
from start to end of the list search "c" in "list d"
when see it
return index
Due to writing return in iteration, compiler start to complain about non void function.
How can I cut compiler complaint ?
Note : c always in ... | Posting real code would really help. I'm guessing you have something like:
int find(int c, list d) {
for (*iterate over list*) {
if (item == c)
return index;
}
// <- nothing here
}
The compiler in most cases cannot know that list will always contain c. So you need to add a return statement. Something l... |
5,282,780 | 5,282,829 | Problem in creating QFile inside a location other than the current directory | I am using Qt 4.7 installed on Ubuntu 10.04 ....
I can't create a qt file inside a location other than the current directory "."
This code works well:
QFile file("data.txt");
if (!file.open(QIODevice::Append))
{
qDebug("ERROR WHILE OPENING THE FILE TO APPEND Data");
return ;
}
but this code fails (I think bec... | You solve this quickly in one of these ways:
Run as root (this is a big no-no)
As root, change the permissions of the directory you need, chmod /the/dir o+rwx - this lets everyone write to the directory.
As root, change the owner of the directory you need, chown myuser /the/dir - this lets your user write to the direc... |
5,282,937 | 5,282,957 | C++ using ldap_bind from ldap.h | I'm trying to use ldap_bind, but get an this error.
error: âldap_bindâ was not declared in this scope
code:
#include <lber.h>
#include <ldap.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
LDAP *ld;
char *ldap_host = "ldap://localhost";
int ldap_port = 3... | I've no experience with OpenLDAP, but from the header it seems you need:
extern "C" {
# define LDAP_DEPRECATED
# include <ldap.h>
# include <lber.h>
}
|
5,282,977 | 5,282,993 | Running compiled program - "Invalid argument" | I have simple Hello World C++ program (main.cpp):
#include <iostream>
using namespace std;
int main ( void ) {
cout << "Hello world" << endl;
return ( 0 );
}
I compile it through
g++ -Wall -pedantic -Wno-long-long -Werror -c main.cpp
then add the "be executable" permission
chmod +x main.o
and try to run it... | The -c option instructs the compiler to just compile the source file in an "object file", and not to link it.
Without the linking step the object file you get is not an executable, but just an intermediate step. What you probably want to do is
g++ -o main.x -Wall -pedantic -Wno-long-long -Werror main.cpp
This will gen... |
5,283,031 | 5,283,067 | How to get the time elapsed running a function in C++ | I tried some codes by googling :
clock_t start, end;
start = clock();
//CODES GOES HERE
end = clock();
std::cout << end - start <<"\n";
std::cout << (double) (end-start)/ CLOCKS_PER_SEC;
but the result elapsed time always was 0, even with
std::cout << (double) (end-start)/ (CLOCKS_PER_SEC/1000.0 );
Don't know why bu... | I don't think it's guaranteed that clock has a high enough resolution to profile your function. If you want to know how fast a function executes, you should run it maybe a few thousands times instead of once, measure the total time it takes and take the average.
|
5,283,112 | 5,283,760 | C++0x: Capture By Value for Lambda, always a copy? | Is the compiler allowed to eliminate the copy that is required for the by-value capture?
vector<Image> movie1;
apply( [=movie1](){ return movie1.size(); } );
Is there any circumstance that the compiler does not need to copy movie1?
Maybe if the compiler could know, that apply does not actually change movie1?
Or does... | I'm fairly sure it cannot.
Even if the outer function no longer explicitly uses the variable, moving the variable would change the semantics of destruction.
Having move constructors for Image doesn't help, a vector can move or swap without moving its elements.
If the variable is read-only from this point forward, why n... |
5,283,132 | 5,283,211 | Called ReadFile on a text file, got weird (Japanese?) characters | I use the next code to read all of the elemnts from a file with the handle hFile that works, and with its size that I got with GetFileSize(hFile, NULL).
_TCHAR* text = (_TCHAR*)malloc(sizeOfFile * sizeof(_TCHAR));
DWORD numRead = 0;
BOOL didntFail = ReadFile(hFile, text, sizeOfFile, &numRead, NULL);
after the operatio... | Modern IDEs default to Unicode applications, meaning _TCHAR is actually wchar_t. ReadFile() works with simple bytes and if you use it to fill a _TCHAR array directly, you'll get 8-bit characters interpreted as UTF-16 Unicode. These usually show as CJK (Chinese/Japanese/Korean) glyphs.
You have three options:
convert y... |
5,283,141 | 5,283,177 | C++ Vector Of Base Class Containing Derived Types | I have a several classes DemandBuilding, Factory, Farm and some others. I want to store instances of these in a single 2d array, I did this by making a base class, Building, which does nothing but allows me to do this: (Note that the second vector is because it is a 2d vector for storing these buildings on a map)
vecto... | Conceptually there's nothing wrong with this - it all depends on how you use it. If you find yourself having to cast a lot, you may need to rethink the design.
Also, you very likely should have a virtual destructor, if you delete a Building * and the destructor isn't virtual, the subclass destructor is not executed.
|
5,283,162 | 5,283,205 | DirectX HLSL Include Directive Doesn't Work | The document:
http://msdn.microsoft.com/en-us/library/dd607349(v=vs.85).aspx
states that #include "foobar.fx" will look for that file in the same directory as the current effect file.
It doesn't work, but using an absolute path does, which is of course useless.
Google doesn't come up with anything. Anything I'm missing... | That automatic handling only works for the offline shader compiler tool, as mentioned in the link you provided. If you're compiling using one of the APIs, you'll need to specify an include handler for the compiler to use whenever it encounters an include directive: ID3DInclude
|
5,283,197 | 5,283,320 | C++ macro with variable number of arguments |
Possible Duplicate:
C/C++: How to make a variadic macro (variable number of arguments)
I need macro that will expand in a array that contains it's arguments. For example:
#define foo(X0) char* array[1] = {X0}
#define foo(X0, X1) char* array[2] = {X0, X1}
and so on. My problem is that I need to use foo with variable ... | How about:
#define FOO( ... ) char* x[] = { __VA_ARGS__ };
|
5,283,251 | 5,283,749 | Boost::multi_array -- referencing too slow | I have to pass arrays to other functions, through referencing or pointer, I don't care as long as it works fast. That's why I started to use the boost library. I did it in the following way:
using namespace boost;
typedef multi_array<long double, 4> array_type;
typedef multi_array<long double, 2> twod_array_type;
ty... | Where you zero-initialize your multi_arays, you can try using std::memset instead. For example
std::memset(b.data(), 0, size_of_b_in_bytes);
There are a few places in your code where you index the same multi_array element more than once. For example, instead of
h[i][j] = h[i][j] + pp[k]*v[k][i]
try
h[i][j] += pp[k]*... |
5,283,378 | 5,283,418 | Variadic list parameter | Say I have 2 functions
void f1(int p1, int v1, ...);
AND
void f2(int v1, ...);
Inside f1 I want to pass all parameters from variadic list to f2:
void f1(int p1, int v1, ...) {
f2(/*pass all variadic parameters*/);
}
For example when I call f1(1, 2, 3, 4, 5) I want to pass 2,3,4,5 to f2
| It's not possible directly, but you can use the va_list type to wrap the full complement of values and pass them to a version of the function that takes such an argument. Basically, break f2() into:
void f2v(int v1, va_list args) {
// ...
// use va_arg() repeatedly to get the various arguments here
}
void f2(i... |
5,283,441 | 5,283,555 | Library types in Stanley Lipmann's "C++ Primer" | Newbie to C++ but I am a Java programmer. Trying to learn C++ now. Reading the C++ Primer by Stanley Lipmann.
I don't understand this sentence in Chapter 3 about library types. He's talking about library type string and vector:
These library types are abstractions of more primitive types - arrays and pointers - that a... | You've chosen a very good book but I can see where the sentence could confuse you.
I think this:
"These library types are abstractions of more primitive types - arrays and pointers - that are part of the language"
Should say something more like this:
"These library types are extensions of more primitive types - array... |
5,283,841 | 5,283,906 | Why Compile to an Object File First? | In the last year I've started programming in Fortran working at a research university. Most of my prior experience is in web languages like PHP or old ASP, so I'm a newbie to compile statements.
I have two different code I'm modifying.
One has an explicit statement creating .o files from modules (e.g. gfortran -c fi... | Compiling to object files first is called separate compilation. There are many advantages and a few drawbacks.
Advantages:
easy to transform object files (.o) to libraries and link to them later
many people can work on different source files at the same time
faster compiling (you don't compile the same files again and... |
5,283,877 | 5,283,917 | Downloading files with names stored in a database | So, I have a database table with the following fields: title, date, text, file1, file2, file3, file4, file5. I use it to store news and occasionally, the title of files related to the news. The problem is that different news have a different number of files, ranging from 0 to 5. Now, how can I post the link to the exac... | I think this is what you want:
for($i=1;$i<=5;$i++) {
$sfile = $row["file$i"];
if($sfile != "") {
?>
<p><a href="/admin/uploads/<?php echo $sfile?>"><?php echo $sfile?></a></p>
<?php
}
}
|
5,283,894 | 5,283,923 | Recommended -W flags for building C++ with gcc | I was looking for a list of recommended g++ warning options for C++ and only could find this: Recommended gcc warning options for C and Useful GCC flags for C which are all quite C specific
-Wall and -Wextra enable most but not all of the warnings gcc can generate.
Which warnings that aren't enabled by those options e... | -Wall -Wextra tends to cover the really noteworthy ones. Personally, I also like to compile with -ansi -pedantic and occasionally -Wshadow.
Also, it can be a little noisy and not useful 100% of the time, but -Weffc++ sometimes has good suggestions for better code quality as well.
EDIT In the age of modern C++, you shou... |
5,283,977 | 5,284,670 | how can I get the lognormal_distribution from boost::random to act like boost::math::lognormal_distribution | I want to get a boost::variate_generator which gives me numbers distributed to the lognormal distribution according to http://en.wikipedia.org/wiki/Log-normal_distribution.
There is a distribution in boost::math that implements the formula from the wikipedia entry, but it doesn't work with the variate_generator.
And t... | I may be mistaken, but from inspecting the boost code, it looks to me like the boost lognormal_distribution is consistent with the wikipedia description. The documentation would be consistent if the boost documentation dropped the N subscript from mu and sigma.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.