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,400,064 | 5,400,086 | C++ lint: detect improper pass by value | Howdy. Is there a lint tool which can find all function declarations accepting non-primitive arguments by value. My googleFu failed.
Thanks.
| Yes, Cppcheck can do this (among a wide variety of other useful checks). Since this particular situation is considered a "style" warning in Cppcheck, you will want to use the --enable=all command line switch.
|
5,400,101 | 5,400,281 | Creating a linked list of objects | I have a class assignment (read: no use of the STL) where I need to create a sorted linked list of objects, but I'm not quite sure how to go about doing this.
The class that I am using contains both integer and string members, but it is only one of these integer members that will be sorted. I currently have a fully fu... | Im guessing that the declaration of the LinkedList class looks something like
template<class Type>
class LinkedList
{ ... }
When the program that uses the linked list class (the main program) instantiates a LinkedList class like following
LinkedList<Poster> myLinkedList;
The compiler, at compile time, generates code ... |
5,400,191 | 5,400,245 | Why does my "while" loop execute no matter what i enter? | /*********************************************************
** Purpose: Asks the user for cable package they bought **
** and the amount of hrs they used and //tells them **
** their monthly bill **
**********************************************************/ ... | Your test for A, B, or C is wrong
while (package != 'A' || package != 'B' || package != 'C')
should be
while (package != 'A' && package != 'B' && package != 'C')
|
5,400,385 | 5,400,912 | Why use boost::ice_or instead of || and boost::ice_and instead of && in enable_if? | As question states, is there a reason why people use the struct version over the normal conditionals?
| An excerpt from the Boost Coding Guidelines for Integral Constant Expressions:
Don't use logical operators in integral constant expressions; use template meta-programming instead.
The header contains a number of workaround templates, that fulfil the role of logical operators, for example instead of:
INTEGRAL_CONS... |
5,400,679 | 5,400,700 | Calling a non-static class function on another thread | I rewriting some code that i written a long time ago.
The code is a class that start another worker thread with AfxBeginThread. When the thread ends, it needs to return it work to the calling class.
Actually when the thread ends it send a message by PostMessage with its results to the called class.
But this way is real... | Rather than trying to call a method directly (which will introduce a whole new set of threading problems of its own), try using the native Win32 ::PostMessage() instead of the MFC implementation of the same function. Any thread can call ::PostMessage() to deliver a message to another thread safely.
|
5,400,848 | 5,400,865 | Difference between declaring a C++ object with/without braces |
Possible Duplicate:
constructor invocation mechanism
It took me long to figure this problem. So I was curious to know the difference between them. Below is the code snippet:
struct Test
{
Test () { cout<<" Test()\n"; }
~Test () { cout<<"~Test()\n"; }
};
int main()
{
Test obj(); // Remove braces of 'obj' & const... | Test obj();
declares a function named obj that takes no parameters and returns an object of type Test. It does not create an object obj of type Test with the default constructor.
|
5,401,062 | 5,424,199 | Comma operator and void expression | I came across this code snippet 1
int return_printChar1()
{
// code
// oops! no return statement
}
int return_printChar2()
{
// code
return printf("Return");
}
int main()
{
int i;
// some more code
i = return_printChar2();
if((return_printChar1(),i))
{
printf ("Gotcha");
}
}
... | The C spec I have (C99 TC3) says
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
The value of an expression that's said to be "evaluated as a void expression" is discarded. So in the C case, there is no undefined behavior. It may have... |
5,401,262 | 5,401,328 | Unique vector objects by specified object property | What is the most effective way to obtain a vector having a unique specified object property (not unique objects just objects with unique specified property).
If y needed to be a unique property
point.x = 2 point.y = 3
point.x = 3 point.y = 3
point.x = 4 point.y = 4
point.x = 4 point.y = 5
Could become:
point.x = 3 poi... | One way to do this is like this:
struct Point
{
Point(int x_in,int y_in): x(x_in), y(y_in){}
int x;
int y;
};
int main()
{
using namespace boost::lambda;
using namespace std;
vector<Point> v;
v.push_back(Point(2,3));
v.push_back(Point(3,3));
v.push_back(Point(4,4));
v.push_bac... |
5,401,284 | 5,401,382 | Remove from a std::set<shared_ptr<T>> by shared_ptr<const T> | I have a a function, that essentially boils down to this (the part that I'm struggling with, ignoring the stuff that is actually happening)
class CellSorter
{
public:
bool operator()( std::shared_ptr<const Cell> a,
std::shared_ptr<const Cell> b ) const
{
return ( ( a->GetY() < b->Ge... | It's because the shared_ptr in Container has type std::shared_ptr<Cell>. You are passing a std::shared_ptr<const Cell> to the erase() method. Different types. You can fix it by removing the const qualifier.
Apparently you can also use std::const_pointer_cast in this situation.
http://msdn.microsoft.com/en-us/library... |
5,401,464 | 5,406,543 | Finding the cache block size | How do I find the cache block size in Ubuntu, programmatically (with C++) or otherwise?
| You can find it in /proc/cpuinfo; cache size for the total size, and cache_alignment for the block size.
|
5,401,524 | 5,401,832 | I need help with parsing from a file in C++ | Ok so basically I have this text file with numbers and letters that's supposed to represent the vertices of a polygon. This part isn't important because I'm having trouble parsing from the file into an int. So far the function looks like:
void parseModel(void)
{
int num_vertices, num_faces;
char data[255];
... | After you read the text string "data" it will contain "data 8 6".
The line ins >> num_vertices; will try to read an integer, but will find "data 8 6" and so will fail. Try something like this:
void parseModel(void)
{
int num_vertices, num_faces;
char data[255];
std::ifstream ifs("rect-skinny.... |
5,401,575 | 5,401,792 | check this is correct or not | form ISO Standard Draft
n3234 says:
Two names are the same if
— they are identifier s composed of the same character sequence, or
According to this meaning..Check whether this is correct or not
class ABC{};
class abc{};
int ABC(){}
int abc(){}
int main(){
int abc;
char ABC;
}
is this pro... | From ISO/IEC 14882:2003(E) 9.1.2 -
A class definition introduces the class name into the scope where it is defined and hides any class, object, function, or other declaration of that name in an enclosing scope (3.3). If a class name is declared in a scope where an object, function, or enumerator of the same name is al... |
5,401,599 | 5,402,484 | stackoverflow error at the beginning of the program in function main | I made a program, I want to debug it (or run) and before the first operator in function main it breaks with a message: Unhandled exception at 0x0020f677 in name.exe: Stack overflow.
Why is this happening and how to resolve the problem?
Visual C++ 2010, Win32 console application.
EDIT1:
Debugger shows me the asm code a... | If you decleared a fixed size array and if its size is too much, you may have this error.
int fixedarray[1000000000];
Try to decrease the length or create it on the heap.
int * array = new int[1000000000];
Do not forget to delete it later.
delete[] array;
But it is better to use std::vector instead of pointers even ... |
5,401,635 | 5,401,664 | Why can I access an element I just erased from an stl vector in c++? | In this example, I create a vector with one integer in it and then I erase that integer from the vector. The size of the vector decreases, but the integer is still there! Why is the integer still there? How is it possible for a vector of size 0 to contain elements?
#include <vector>
#include <iostream>
using namespace... | IIRC a vector doesn't release space unless specifically told to, so you're seeing an item which is still in its memory but not being tracked by the vector. This is part of the reason why you're supposed to check the size first (the other being that if you never assigned anything, you'll be dereferencing a garbage poin... |
5,401,790 | 5,401,961 | How to sort date and time in mfc? | I know how to get the current date and time in mfc.but I want to sort the array with the help of date and time datatype.
How can I do this?
Regards,
karthik
| CTime has a "<" operator, so you can use std::sort()
void SortTime(CTime vals[], size_t nVals)
{
std::sort(vals, vals+nVals);
}
If you have an object containing CTimes, you can create your own "<" operator.
struct MyStuff
{
std::string sName;
int nNumber;
CTime time;
};
bool operator < (... |
5,402,158 | 5,402,472 | using sendmessage to send wm_close to another process | I want to send wm_close to another process, with which i want end that process safely.
int _tmain(int argc, _TCHAR* argv[])
{
DWORD SetOfPID;
SetOfPID = GetProcId(_T("abc.exe")); //this will return pid
HANDLE h = OpenProcess(PROCESS_ALL_ACCESS,false, SetOfPID);
HWND hwnd = ::GetTopWindow(NULL);
w... | Are you sure that the window you are finding is the correct one? You can check easily with Spy++. Moreover, when searching for a window, I think it's better to use EnumWindows. I'm not sure your method is correct.
|
5,402,189 | 5,402,277 | Changing what THIS is | Is there a way to change what THIS point to?
class foo{...}
foo* fooinstance = new foo();
foo* otherfooinstance = new foo();
void
foo::bar(){
this = otherfooinstance;
}
fooinstance->bar();
for those of you who are wondering in what case I would change the this pointer here is case. I had to do a tree recursion ... | C++ standard forbids assignment to this in "9.3.2 The this pointer" by stating that "keyword this is a non-lvalue expression". Although, some compilers still allow assignment to this by using a certain compile-time switch, because at some point in early drafts C++ standard actually allowed assignment to "this".
Anyway,... |
5,402,314 | 5,402,347 | Difference between while(i=0) and while(i==0) | In my exam the following problem appeared in C++
Code:
int i, n;
int* A
cin >> n;
A = new int[n]
for(int i = 0; i < n; i++) cin >> A[i];
while(i = 0){
cout << A[i] << endl;
i--;
}
}
What will be the output?
I think that it should go into indefinite loop!
| while (i = 0) will assign the value 0 to i and then check whether the value of the expression (which is the value assigned, i.e. 0) is non-zero. In other words, it won't execute the body of the loop even once... it'll just set i to 0. It'll also raise a warning on any decent compiler, as it's a common typo.
Following t... |
5,402,432 | 5,402,562 | Finding a submatrix with largest sum |
Possible Duplicate:
Finding a submatrix with the maximum possible sum in O(n^2)
I have an NxN matrix. I want to find out an MxM submatrix, with largest sum of its elements, of the above matrix.
What is the efficient algorithm for this.
| I have an algorithm that runs in constant time when enlarging M and quadratic time when enlarging N.
First submatrix count as usual. Save the sum. Then move one row field right - the two MxM matrices overlap, so you can just just sum the two non overlaping columns. Save all the sums. Now you can choose the largest sum ... |
5,402,663 | 5,402,978 | Error in <cstdio> when <string> is included | _gnu_cxx::snprintf has not been declared
when I include string in my cpp. This error is in on this line:
using ::__gnu_cxx::snprintf;
cstdio is include in this order:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/usr/include/c++/4.2.1/string:47,
/Developer/Platforms/iPhoneOS.platform/Develope... | I solved this by adding #define _GLIBCXX_USE_C99_DYNAMIC 1 in my header.
|
5,402,745 | 5,402,935 | GCC switch on enum, retain missing warning but use default | Using GCC, if you switch on an enum value and one of the enums is missing a case statement a warning will be emitted. When you add a default item the warning will no longer be emitted, which makes sense in the general case.
Is there a way to use a default statement and still have a warning if not all the enum values ar... | -Wswitch-enum, but unluckily only the most recent version supports this.
(You could of course simulate the behaviour that you want by using a goto outside the switch and omitting the default, but I would strongly advise against that, it's ugly and someone else reading your code would have a WTF experience.)
|
5,402,957 | 5,406,410 | target mingw with cygwin | I've tried building the gtest 1.5 library for MinGW
Using MSys to configure and then make results in a lot of errors, most about Win32API
On their website it says mingw is not supported but in the FAQ it is specified that a user managed to build it for mingw from cygwin configuring like this:
./configure CC="gcc -mno-c... | Generally, the library could be smoothly configured and built with cygwin gcc (3.4.4) using the flags you have specified above. You should only validate that gcc-mingw, gcc-mingw-core & gcc-mingw-g++ packages are installed in cygwin. There is no need in mingw-gcc4
|
5,402,994 | 5,403,058 | Question about the floating point values in xcode | I have two floating point numbers. If I add that 2 numbers means. It will displaying the answer as 4.50000 (I used just %f). If I used (2.%f) means the answer is just 4.
I want the answer as 4.5. What do I have to modify in this?
| Try the format string %2.1f:
$ printf "%2.1f\n" 4.5
4.5
The .1 says "one character after the radix".
|
5,403,317 | 5,403,401 | Is there a floating point data type that converts without loss from int64? | is there a floating point data type in Visual C++ that has enough precision in the mantissa to hold an INT64?
Example it should be possible to do the following:
__int64 from = 0xFFFFFFFFFFFFFFFF;
mightyFP intermediate;
__int64 to;
intermediate = from;
to = intermediate;
assert(from == to);
where mightyFP is the unknow... | Short answer, no. long double and double have the same representation in visual studio. For x86 the size of both is 64 bits, which isn't enough to hold the full range of a 64-bit integer.
You need GMP
|
5,403,499 | 5,403,620 | Memory leaks: When do they happen? | I have a ram of 8GB and I have Hard disk of 80GB.
I have three programs as shown in below.
1)
main()
{
while(1)
x();
}
x()
{
printf("hello\n");
}
Will there be a memory leak here in the above program? I suppose not. In case if it does not happen then what will happen? When will this stop?
2)
main()
{
int... | There is no memory leak in the first program, it will run forever (or until it's killed from outside), happily printing that string.
There is a memory leak in the second but it won't crash. You'll just start getting NULL back from the malloc. Otherwise, same effect as number 1 above.
Number three will eventually overfl... |
5,403,581 | 5,403,642 | Inheriting constructors in C++0x | Lets say I have the following code in what we expect to become the next C++ standard:
int f(int x)
{
std::cout << x;
return x * x;
}
struct A
{
A(int x) : m_x(x) {}
int m_x;
};
struct B : A
{
using A::A;
B() : m_y(f(m_x)) {}
int m_y;
};
int main()
{
B(5);
}
Would this call the default constructor... | using A::A; implicitly declares B(int) in the derived class. That is it.
The rest of your program should not work as you expect. Because you're invoking B(int) with B(5), and that leaves m_y uninitialized.
See this example from Bjarne Stroustrup's site:
struct B1 {
B1(int) { }
};
struct D1 : B1 {
using B1::B1;... |
5,403,664 | 5,403,743 | How to match parenthesis using a regular expression? | I am using using boost libraries to parse a file. Its known that when you use a parenthesis it denotes a sub-expression in a regular expression. How would I declare a regular expression if my file contains parenthesis? I tried using \( with no luck. Could anyone tell me how I should declare a regular expression for the... | If you want to use parentheses you need to escape them with a backslash. The issue is that you need to escape that backslash too (for the C++ compiler). Example:
std::string regexstring = "\\([a-z]\\):\\([0-9]\\)";
|
5,403,810 | 5,405,466 | Qt multiple inheritance and signals | I'm having a problem with QT regarding multiple enheritance because of QObject. I know that a lot of others have the same problems but I don't know how I should fix it.
class NavigatableItem : public QObject
{
Q_OBJECT
signals:
void deselected();
void selected();
void activated();
};
c... | It requires a bit more code, but what I have done in the past is make one of them (your NavigatableItem in this case) a pure virtual class, i.e. interface. Instead of using the "signals" macro, make them pure virtual protected functions. Then multiply-inherit from your QObject-derived class as well as the interface, an... |
5,403,882 | 5,403,911 | Is it compulsory to initialize pointers in C++? | Is it compulsory to initialize t in the following code, before assigning value to t? Is the code correct?
void swap(int *x, int *y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
}
| You don't need pointer to begin with:
void swap(int *x,int *y)
{
int t; //not a pointer!
t=*x;
*x=*y;
*y=t;
}
int a = 10, b = 20;
swap( &a, &b); //<-----------note : Needed &
--
Or maybe, you want the following swap function:
void swap(int & x,int & y) //parameters are references now!
{
int t; //no... |
5,403,927 | 5,404,004 | Is this design over-engineering? | Would you consider using an interface and polymorphism to extend this design to be over-engineering?
Pros
Extensible
Encapsulated
Auto-magical
Cons
Lots more code
A little bulky to use (you have to use a different type name to get the different behaviour)
May be less efficient to use due to virtual function calls.
... | It depends on what you will use it for. If you have a big project and will use variants of the class many times then certainly it makes sense to make it flexible.
A rule of thumb:
Use it once - just keep it simple.
Use it twice - Keep it simple and make a copy and change as needed
Three or more - Generalise it and ... |
5,404,058 | 5,726,753 | Intel TBB using task_group to do a Bitonic Sort | I'm implementing a bitonic sort using intel TBB. When using the parallel_invoke method all goes well. But when using task_group(without calling the wait method), the output is not sorted. When using task_group as below the program does not terminate.
void bitonic_merge(bool up, int array[],int size){
if(size==1){
... | The program doesn't terminate because it is deadlocked. Your code is very close to correct, but the problem is that 'g' is a global pointer to a task_group and your doing a recursive task decomposition and this is not a combination that mixes well.
If you broke into the debugger, I expect that you would see lots of th... |
5,404,096 | 5,404,135 | Why separate variable definition and initialization in C++? | I'm currently working on some quite old C++ code and often find things like
int i;
i = 42;
or
Object* someObject = NULL;
someObject = new Object();
or even
Object someObject;
someObject = getTheObject();
I completely understand what this code does but I really have no idea when such a separation of variable definiti... | Object someObject;
someObject = getTheObject();
This uses the assignment operator.
Object someObject = getTheObject();
This uses the copy constructor.
Apart from that, your suggested changes are equivalent, and you should implement them. The copy ctor/assignment operator difference is expected to produce the same res... |
5,404,277 | 5,404,467 | Porting clock_gettime to windows | I have the following code running on qnx momemntics.
#define BILLION 1000000000L;
struct timespec start_time;
struct timespec stop_time;
void start MyTestFunc() {
//Initialize the Test Start time
clock_gettime(CLOCK_REALTIME,&start_time)
// ... additonal code.
cout << "The exectuion time of func "<... | You can implement a clock_gettime() replacement for windows as follows:
LARGE_INTEGER
getFILETIMEoffset()
{
SYSTEMTIME s;
FILETIME f;
LARGE_INTEGER t;
s.wYear = 1970;
s.wMonth = 1;
s.wDay = 1;
s.wHour = 0;
s.wMinute = 0;
s.wSecond = 0;
s.wMilliseconds = 0;
SystemTimeToFileTi... |
5,404,489 | 27,672,798 | Standard container re-allocation multipliers across popular toolchains | Containers like std::basic_string and std::vector perform automatic re-allocations when internal capacity runs out. The standard specifies that, after a re-allocation, .capacity() >= .size().
What are some of the actual multipliers used by mainstream toolchains when performing re-allocations?
Update
So far, I have:
D... | New answer for an old question.
Rationale: The answer can be answered programatically, and with online compilers, relatively easily. Here is a program that can help you answer this question:
#include <climits>
#include <cstddef>
#include <cstdlib>
#ifndef _MSC_VER
# include <cxxabi.h>
#endif
#include <iostream>
#in... |
5,404,636 | 5,408,619 | Building Google Breakpad on Mac OS X | I am attempting to build Google Breakpad for Mac OS X as a part of porting an application, based on the trunk revision 782.
The Breakpad wiki specifies that one should build client/mac/Breakpad.xcodeproj, which produces a Breakpad.framework including a dynamically linked lib if I understand correctly. There is also sam... | There is no solution in the Breakpad source for this, unfortunately. The XCode projects simply build the Breakpad framework, as that's the more-supported client API. You can build the code with your own set of Makefiles or whatever build setup you desire the same way Firefox does by looking at the set of Mozilla makefi... |
5,404,845 | 5,404,970 | Link problem between projects in same solution (Exe depends on Lib) | I have one solution with several projects. Say ProjectA is the one that will produce the exe file, and ProjectB simply produces a .lib file. I have checked that ProjectA depends on ProjectB, so that ProjectB will always compile before ProjectA.
When I compile ProjectB everything goes fine. But if I compile ProjectA I g... | Project Properties, Linker, General: Set "Link Library Dependencies" to Yes.
|
5,404,975 | 5,405,052 | Java applet, problem loading native dll | I am writing a Java applet which loads dll's created in unmanaged C++. I am writing some basic test to get it loading.
Here's the code:
The DLL:
#define DllExport _declspec(dllexport)
DllExport int calc();
DllExport int calc() {
return 1000;
}
The applet:
import java.applet.*;
import java.awt.*;
public class app e... | First, the function should be called Java_app_calc(). Second, it should take a single argument of type "JNIEnv *". That should do it.
If you run the program "javah", it can generate your C/C++ header file for you, which will help you get the function names and signatures correct. The argument is the name of a class (it... |
5,405,016 | 5,405,268 | Can I check my program's output with boost test? | Like in:
void f()
{
cout << "blah" << endl;
}
BOOST_AUTO_TEST_CASE(f)
{
f();
// This would be a beauty
// BOOST_CHECK_PROGRAM_OUTPUT_MATCH("blah");
}
| Yes, you can do it by redirecting std::cout to a boost::test_tools::output_test_stream, which provides special methods to compare the output. To make sure std::cout is always restored correctly, you can use a custom struct, like shown in the following example.
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp... |
5,405,070 | 5,406,264 | cv::Mat_ to std::vector conversion | I use OpenCV 2.0, there is a method in the cv::Mat_<_Tp> class:
// conversion to vector.
operator vector<_Tp>() const;
When instantiated, the implementation does not compile on MSVS 2005:
template<typename _Tp> inline Mat_<_Tp>::operator vector<_Tp>() const
{
CV_Assert( rows == 1 || cols == 1 );
return isConti... | No, there are new constructors from rvalues in C++0x, but nothing like the one used here.
If isContinuous() means that all vales are the same, you could possibly use vector<_Tp>((size_t)(rows + cols - 1), *(_Tp*)data) to make copies of the first value.
Your iterator version seems correct otherwise.
|
5,405,098 | 5,405,120 | Is it possible to use Xcode for Linux Development? | My team is planning to start development on linux platform. Previously we have been developing C++ applications in Windows using MS Visual Studio. And recently, I fell in love with Mac OSX and use it as my personal development machine.
The question is once again: Is it possible to use Xcode for Linux Development?
The a... | As long as you stick to cross-platform interfaces (glibc, POSIX, STL, etc.), sure. You might need a Linux machine to actually build the binaries for Linux though.
|
5,405,203 | 5,405,218 | Is there a standard way to compare two ranges in C++? | By range I mean a pair of iterators. In pseudo C++:
std::vector<int> v1 = { 1, 2, 3, 4, 5 };
std::vector<int> v2 = { 2, 3, 4 };
if( std::compare_range( v1.begin() + 1, v1.end() - 1, v2.begin(), v2.end() ) {
std::cout << "Alright\n";
}
compare_range being of course the function I'm looking for.
Disclaimer: This is ... | std::equal is the function template you are looking for.
if (std::equal(v1.begin() + 1, v1.end() - 1, v2.begin())
{
std::cout << "Alright\n";
}
Note that std::equal only takes three arguments, not four.
|
5,405,507 | 5,405,811 | GCC linker error when building for iPhone | Undefined symbols:
"vtable for NameSpaceA::NameSpaceB::ClassA", referenced from:
__ZTVN4NameSpaceA17NameSpaceB15ClassAE$non_lazy_ptr in libSomeLib.a(SomeLib.bulk.o)
(maybe you meant: __ZTVN4NameSpaceA17NameSpaceB15ClassAE$non_lazy_ptr)
for some classes that are build in this lib. Same code compiles and links fine on W... | In order for gcc to emit the vtables, each of your (polymorphic) classes needs to have at least one virtual, non-inline method. For example if your virtual destructor is inline currently, un-inline it and move it to the source file and that should fix it up.
|
5,405,923 | 5,406,103 | Random subset of elements from multimap grouped by keys | I have a list consisting of car brands ID's and associated car models, e.g.:
1 Corolla
1 Yaris
1 Matrix
2 Cherokee
2 Liberty
3 CR-V
3 CR-Z
3 Element
3 Civic
3 Pilot
where 1=Toyota, 2=Jeep, and 3=Honda. Note that the cardinality of car models per car brand differs.
I would like to retrieve random car models per car-bran... | Perhaps the simplest approach to follow would be to copy all values for the given key out into a new container, say, a vector, random_shuffle it, and resize() it to reduce its size to x:
int x = nPercentage * countPerKey;
auto range = m_mapDatasetMapping.equal_range(*pLastKey);
std::vector<std::string> values;
for(auto... |
5,405,955 | 5,406,461 | Using new with fixed length array typedef | How do I define a typedef for a fixed length array so that I can also 'new'. The following does not work:
typedef double Vector[3];
Vector *v = new Vector; // does not compile
We are trying to wrap into C++ some old C code which handles float * and float (*)[3] in a generic way.
| The pointer to an double[3] is double * - so this will work:
typedef double Vector[3];
double *v = new Vector;
But I suggest you don't use it that way - to delete the array you need the array-delete-operator:
delete[] v;
But on new Vector you don't see it is an array and so it might be forgotten.
This case is h... |
5,406,199 | 5,406,262 | Overloading operator new for a class | When we overload new operator of a class, we declare the function as a member function.
For eg:
class OpNew {
public:
OpNew() { cout << "OpNew::OpNew()" << endl;}
void* operator new(size_t sz) {
cout << "OpNew::new: "
<< sz << " bytes" << endl;
return ::new char[sz];
}
};
How ... | An operator new() or operator new[]() for a class is always a static class member, even if it is not declared with the keyword static.
What the C++ standard says (draft n3242), in section [class.free]:
Any allocation function for a class T is a static member (even if not explicitly declared static).
|
5,406,334 | 5,406,938 | How to wrap an init/cleanup function in Boost python | I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library.
While wrapping the basic library API calls is quite simple (nothing special, just regular function calls and very common parameters), I don't know ho... | You could try to do a guard object and assign it to a hidden attribute of your module.
struct MyLibGuard
{
MyLibGuard() { myLib::initialize();}
~MyLibGuard() { myLib::cleanup();}
};
using namespace boost::python;
BOOST_PYTHON_MODULE(arch_lib)
{
boost::shared_ptr<MyLibGuard> libGuard = new MyLibGuard();
... |
5,406,436 | 5,407,338 | Qt WebKit and Permanent Cookies | I have a mainwindow, in it, I have a single QWebView.
I want to make a certain website (www.kdkdkkd.com for instance) cookies permanent, so each time a user closes and repopens the browser he doesnt need to log in again.
Thanks,
| You need to set your own "Cookie Jar".
Use QNetworkAccessManager::setCookieJar .
Extend QNetworkCookieJar - as it doesn't persist cookies by default when browser is closed:
Once the QNetworkCookieJar object is
deleted, all cookies it held will be
discarded as well. If you want to save
the cookies, you should ... |
5,406,533 | 5,406,565 | overloading vs overriding | I am a little confused over the two terminologies and would be glad to get some doubts clarified.
As I understand function overloading means having multiple methods in the same class with same name but either with different number of arguments, different types of arguments or sequence of arguments irrespective of the r... | In this case neither. The derived-class method hides the base-class method.
|
5,406,564 | 5,406,613 | problem with a function in c (linux) | I'm writing a C script to generate some sitemaps for some sections of my site. I'm trying to clean it up by moving a loop into a function that I can call instead of having several large loops on top of eachother in my script.
I'm not fluent in C by ANY means, I can work my way around it but functions are pretty confusi... | You just need to (pre)declare write_to_sitemap before its first use:
void write_to_sitemap(MYSQL_ROW row2, MYSQL_RES* resultset2);
or move its entire definition up in your file.
|
5,407,286 | 5,407,323 | Irrational number representation in any programming language? | Does anyone know of an irrational number representation type/object/class/whatever in any programming language?
All suggestions welcome.
Simply put, if I have two irrational objects, both representing the square root of five, and I multiply those objects, I want to get back the integer five, not float 4 point lots o' 9... | What you are looking for is called symbolic mathematics. You might want to try some computer algebra system like Maxima, Maple or Mathematica. There are also libraries for this purpose, for example the SymPy library for Python.
|
5,407,304 | 5,407,531 | Error: pure virtual method called - terminate called without an active exception - Aborted | In my A.h file:
class A{
private:
unsigned short PC;
public:
A():PC(0){}
virtual ~A(){}
virtual void execute(unsigned short PC)=0;
};
In my B.h file:
class B:public A{
private:
int status;bool exe;
public:
B:status(0),exe(false){}
virtual B(){}
void execute (unsigned short PC... | Usually you get this error when call your virtual function from constructor or destructor.
Check that that is not the case.
(I assume that your demo code is not complete).
|
5,407,514 | 5,408,956 | std::sort on an std::vector compares but never replaces | the array stays the same after the sort. How is that possible? I can see the healthy comparison result.
There's a model class that owns a std::vector:
private:
std::vector<Contact> contacts;
The class contact has:
QString private member
QString private member getter - GetName()
Copy constructor that handles the ... | I found the problem.
My assignment operator on the class stored in the vector was faulty.
My assignment operator wasn't returning a healthy "*this", instead it declared a new object, initialized it with the rhs data and returned it.
so the effect was as I described. Correct comparison, but no "swapping" due to this err... |
5,407,660 | 5,407,904 | How do I go back to end of the first line in csv file? | I am using ofstream to write a csv file.
Currently, I am writing it left to right using "<<" operator, which is easy.
For example,
Shape,Area,Min,Max
Square,10,2,11
Rectangle,20,3,12
I want to change so that it looks like
Shape,Square,Rectangle
Area,10,20
Min,2,3
Max,11,12
I know I can use "<<" operator and just writ... | You can't insert other than at the end of an ostream without
overwriting already written data. For something like what
you're trying to do, you probably have to collect each row in
separate string (perhaps using ostringstream to write it), then
output the rows. Something like:
std::ostringstream label;
label << "Shap... |
5,407,713 | 5,407,744 | Error in iterator declaration in a for loop | void catchlabel()
{
if(vecs.empty())
return;
else
{
cout << "The Sizeof the Vector is: " << vecs.size() << endl;
cout << "Currently Stored Labels: " << endl;
/* Error 1 */
for ( int i = 1, vector<string>::iterator it = vecs.begin(); it != vecs.end(); ++it , i++)
cout << i ... | You can't declare items of multiple types in the initial statement of a for loop, just like you can't say int i = 1, vector<string>::iterator it = vecs.begin(); as a standalone statement. You'll have to declare one of them outside the loop.
Since the C language you have never been able to declare multiple variables of ... |
5,407,764 | 5,407,828 | Creating new instance of class on stack with no empty no arguments constructor |
Possible Duplicates:
Calling the default constuctor
Why is it an error to use an empty set of brackets to call a constructor with no arguments?
I am wondering what it means to create an instance of a class using a no arguments constructor.
For example if I have a class "A" and try to create a variable like so:
A myV... | The syntax:
A myA0();
Does not create a variable of type A by calling the default constructor, but rather declares a function taking no arguments and returning A by value. Lookup in the tags for most-vexing-parse or something similar. To create a local variable just do:
A myA0; // no ()!!!
A different issue that you ... |
5,407,809 | 5,408,165 | Design approach on a program with many GUI screens | I've terribly confused myself to the point of no return and feel my project is ballooning too huge to keep up with my current ways.
In a nutshell:
1) There are many graphical screens (windows), each screen is a class defined in its own .cpp with a accompanying .h header w/ public & private decelerations.
2) I'm using... | Here are a few suggestions:
Create a new header file with all of your screen includes. Then you can just include this one header file and capture all of your other screen header files.
You might consider a screen manager that keeps all of the references to your screens. Navigation between screens is then left up to ... |
5,407,814 | 5,408,008 | C++ - interval tree implementation | Does someone know any good interval tree implementation in C++?
Obviously, something template-driven, better in boost-like style.
And another question - if somebody tested, does a basic std::vector-based interval tree implementation with sorting can beat the generic interval tree (with O(lg) operations) in practice?
| Boost-like ? Boost ICL!
The Boost Interval Container Library
|
5,407,838 | 5,418,915 | System.Windows.Controls.Expander MFC equivalent | Does anybody know an MFC equivalent of the WPF System.Windows.Controls.Expander?
| There is no direct correlation. One option is to inherit CGroupBox and roll it up when the header is clicked. The more difficult aspect of mimicing WPF-style GUI is the layout engine. If you want any kind of fluid layout in MFC you'll have to use a 3rd-party library (example) or roll your own.
|
5,407,957 | 5,411,435 | fftwpp creates a zero filled array after a convolution | I use fftwpp to transform both my data and my convolution kernel into the fourier space, multiply them together like in a scalar product and convert them back to the real space. When I first run the program, it creates an array which is completely filled with zeros. When I run it again, it gives me the desired results.... | FFTW++ is a wrapper over FFTW. FFTW requires generating an execution plan to process your data efficiently. Once the plan is generated, it can be reused to process various sets of data. The file you're seeing wisdom3.txt is information about the plan that your program generates on its first run. Once it exists, it is l... |
5,408,050 | 5,408,144 | Should I convert shared_ptr to weak_ptr when passed to a method? | there are already a couple of questions regarding this topic, but I am still not sure what to do: Our codebase uses shared_ptr at many places. I have to admit that we did not define ownership clearly when writing it.
We have some methods like
void doSomething(shared_ptr<MyClass> ptr)
{
//doSomething() is a mem... |
We did not define ownership clearly.
You need to clearly define who owns what. There's no other way to solve this. Arbitrarily swapping out some uses of shared_ptr with weak_ptr won't make things better.
|
5,408,106 | 5,408,269 | RTTI Overhead in C++ | What are the memory/performance overheads of enabling RTTI in a C++ program?
Can anyone please throw some light between the internal implementation of RTTI mechanism and the relevant overheads?
I do understand how to use RTTI through typeid and dynamic_cast, what I am trying to know is the internal implementation detai... | Enabling RTTI typically brings only a small overhead. The usual implementation carries a pointer to the type information structure in the vtable of an object. Since the vtable must be constructed anyway, the extra time is small - it's like adding another virtual function to the class.
typeid is therefore comparable to ... |
5,408,189 | 5,408,298 | How to get the output of a Executable made in C++ in Rich text Box in C# | How to get the output of a Executable made in C++ in Rich text Box in C#?
The question is self explanatory, but just to add on further.
Say for i run a compiled program whose output is:
Made by C++
Now i want the output of this program (which is console based) in my Rich text Box in C#.
If the program name is:
example.... | Usually when you spawn a process you're able to get it's stdout and stderr descriptors.
So use appropriate class to spawn example.exe process and read it's stdout and err.
Use following classes:
ProcessStartInfo
Process
//then Process method would do the trick
proc.StandardOutput.ReadToEnd();
EDIT
I've found followi... |
5,408,342 | 5,408,393 | C/C++ Cast to const weirdness | I have a function declared as:
int myFunction(const float** ppArr, const int n, const int m);
and when I call it like so:
float** ppArr = new float*[5];
// Some initialization of ppArr
int result = myFunction(ppArr, 5, 128); <<<< Error
and the error is (VS 2008 Express):
error C2664: 'Test_myFunction.cpp' : cannot ... | Please read "Why am I getting an error converting a Foo** → Foo const**?" at C++ FAQ.
|
5,408,583 | 5,408,629 | About stdafx.h missing in my compiler(mingw32 on windows) | I just have a quick question. I've noticed that I don't have stdafx.h in my compiler(mingw32 on windows)
Am I supposed to have it? Or maybe is there a way to get around it?
Thanks for reading
EDIT: ok here is my current build log once I took out ALL of the includes of stdafx.h
http://pastebin.com/bczLr8xY
| Read this wikipedia article. The paragraph I linked and the paragraph below it (mingw32 uses GCC).
http://en.wikipedia.org/wiki/Precompiled_header#stdafx.h
Since stdafx.h contains the most common headers I would remove every instance of #include stdafx.h and try to compile. If you get compile errors that a certain func... |
5,408,733 | 5,408,755 | linux c/c++ - weird if/else issue | I'm querying a mysql table which then loops through the results.
One of the fields has a value of "0" in it, so when I try the following it doesn't work!
while ((row2 = mysql_fetch_row(resultset2)) != NULL) {
if (row2[2] != "0") {
// the field has a value of 0, but it's still executing the code here!
} ... | You're comparing row2[2], a pointer to char, with a pointer to the constant char array "0".
Use strcmp(row2[2], "0") != 0 (C solution), std::string(row2[2]) != "0" (C++ solution), or atoi(row2[2]) != 0 if you know row2[2] is always the string representation of an integer (and cannot be a SQL NULL value).
|
5,408,772 | 5,408,797 | Got problem converting string to upper case letters | Using following console application i am converting each string to uppercase letters. But string value in output remains unchanged. what I am doing wrong here. Also any help on doing this efficiently would be appreciated.Thanks for your help.
int main()
{
vector<string> svec, svec_out;
string word;
int... | toupper will return the uppercase value instead of modifying the value in-place. As such your code should read:
word[j] = toupper(word[j]);
|
5,409,589 | 5,409,741 | 2D array help in C++ | So I made my own class in order to hold a 3D vertex. That basically looks like:
class Vertex // Vertex Class
{
public:
float x; // X Component
float y; // Y Component
float z; // Z... |
cannot convert from 'Vertex (*)[4]' to 'Vertex *'
The compiler is already telling you what you need to know, just change the type of faces:
Vertex (*faces)[4] = new Vertex[num_faces][4];
|
5,409,655 | 5,410,159 | Loading a texture in GLM | hey im using GLM(made by nate robins) with SFML and opengl on mingw32 with the IDE as CodeBlocks(windows)
when loading my texture with the GLM from: http://www.3dcodingtutorial.com/Working-with-3D-models/Getting-GLM.html
hey i managed to get rid of the color problem by changing up my code to better load the textures, b... | The default GL_TEXTURE_ENV_MODE is GL_MODULATE. Make sure you aren't inadvertently setting your color state somewhere, or force the issue with glColor3ub(255,255,255) before you render something with a texture.
EDIT: GL_DECAL is also an option.
|
5,409,791 | 5,410,224 | Whats going on here with cctype? | To my surprise the following code compiles:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>
int main() {
std::string s="nawaz";
std::string S;
std::transform(s.begin(),s.end(), std::back_inserter(S), ::toupper);
std::cout << S ;
}
I had expected it to fail ... | It doesn't work because there are overloads of std::toupper. You can fix it by casting to your desired function overload:
std::transform(s.begin(),s.end(), std::back_inserter(S),
(int(&)(int))std::toupper);
|
5,409,995 | 5,410,003 | How do I define a constant in C++? | For the code:
#define e 2.71828183;
double p ( int x )
{
return 1 / ( 1 + pow ( e, -1.0 * x ) );
}
I get:
math.cpp: In function ‘double p(int)’:
math.cpp:11: error: expected ‘)’ before ‘;’ token
math.cpp:11: error: expected ‘)’ before ‘;’ token
math.cpp:11: error: expected primary-expression before ‘,’ token
math... | There is a ; at the end of your macro replacement:
#define e 2.71828183;
On preprocessing your return statement will look like:
return 1 / ( 1 + pow ( 2.71828183;, -1.0 * x ) );
^^
which results in syntax error.
To fix this remove that ;
|
5,410,001 | 5,410,425 | Does/can Valgrind use multiple processors? | Is there a way to get valgrind to use multiple processors?
I'm doing some bottleneck profiling with valgrind's callgrind and noticed significantly different resource usage behavior in my application vs when run outside of valgrind/callgrind.
When run outside valgrind, it maxes out several processors, but run inside val... | According to the Valgrind Docs, they do not support multiple processors:
The main thing to point out with
respect to threaded programs is that
your program will use the native
threading library, but Valgrind
serialises execution so that only one
(kernel) thread is running at a time.
This approach avoids th... |
5,410,035 | 5,410,129 | When does a std::vector reallocate its memory array? | I can't find anything that gives a definitive answer. I was just curious if a std::vector reallocate its internal array only when it absolutely must or will it reallocate ahead of time in anticipation (so to speak).
For example:
std::vector<int> myVector;
for (int i = 0; i < 1000; ++i) myVector.push_back(i);
cout << m... | From C++ standard 23.2.4.2:
size_type capacity() const;
Returns: The total number of elements that the vector can hold without requiring reallocation.
Also from Standard
Notes: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the
sequence. It is guaranteed that no ... |
5,410,141 | 5,410,429 | Is there a widely available C++ version of Java's NavigableMap interface? | In Java, you can have a NavigableMap, which lets you do useful things such as "find the greatest key less than or equal to the given value" (floorKey method). So if myMap contains {1->"One", 2->"Two", 3->"Three", 7->"Seven"}, you can call myMap.floorKey(6) and it will return the key of 3.
In C++, STL provides a map cl... | The simplest way to get this in C++ would be to call map::upper_bound and decrement the returned iterator:
#include <map>
#include <string>
#include <iostream>
int main()
{
std::map<int, std::string> myMap =
{{ 1, "One"},
{2, "Two"},
{3, "Three"},
{... |
5,410,257 | 5,410,541 | How do I extract Export Table from PE standard (.exe) | I've managed to successfully extract all desired information from the "Optional Header". All those contained within the "Standard" fields and "Windows-specific" fields. However when it came to the "Data Directories" field, I found the values contained within the "Export Table" field were equal to zero.
How can I locate... | Adding to DeadMG's answer: the question's title indicates that you're using an EXE file. You will find that most EXEs do not have export tables, since they are not "consumed" by other components. Most often, they act as consumers for other DLLs. EXE files usually import other DLLs, and these DLLs may have non-empty exp... |
5,410,291 | 5,410,343 | performance comparison in custom c++ render system. calling render function for different classes | I have this library in which there is a general display list for elements of different types, for each loop of the system, this display list is rendered by calling a render() method on every object added to the list.
now, the list can have elements of different classes, say A,B,C,D all of them have their particular vo... | Why not use virtual functions?
class Renderable {
public:
virtual void Render() = 0;
};
class ARenderable : public Renderable {
public:
virtual void Render() {
// implement this
}
}
class BRenderable : public Renderable {
public:
virtual void Render() {
// implement this
}
}
// .. ... |
5,410,569 | 5,410,686 | linux c/c++ preg_replace type of function? | I'm trying to figure out an preg_replace() (php) style function that I can use in c++ (linux).
Can someone help me translate this?
$str = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'),array('-',''),$str);
| You can use the boost::regex library
http://www.boost.org/doc/libs/1_46_1/libs/regex/doc/html/index.html
|
5,410,832 | 5,410,893 | OpenGL/glut/stdc++ build errors | I'm using Ubuntu and tried using synaptic to install everything that had the word "GLUT" in it and also SDL and opengl . But still a simple program fails to compile . It shows this :
opengl1.cpp:(.text+0xe): undefined reference to `glClear'
opengl1.cpp:(.text+0x1a): undefined reference to `glBegin'
opengl1.cpp:(.text+... | Add "-lstdc++ -lGL" to your linker flags.
Or try to compile it like this:
g++ opengl1.cpp -o opengl1 -lGL -lGLU -lc -lm
(edit: added -lGLU, removed -lstdc++)
|
5,410,850 | 5,411,090 | implement a IntStack with bridge pattern in C++ | This question was from "Thinking in C++" Vol-1, Chapter 5's exercise No.14:
Create a StackOfInt class (a stack that holds ints) using the
“Cheshire cat” technique that hides the low-level data structure you
use to store the elements in a class called StackImp. Implement two
versions of StackImp: one that uses a ... | What the book author has in mind, is that the StackOfInt class should not contain any other members besides a pointer to the implementation class. The necessary data members, be it an array + count variable or a vector, should be members of the implementation class.
So in the header, you'd have
class StackOfInt {
... |
5,411,006 | 5,411,067 | Any good C++ finance (preferably high frequency trading) books people can recommend? | was in a waterstones branch today and saw a C++ book relating to derivatives. Just wondered if there are any specific books relating to high frequency trading, from the infrastructure side?
I'm especially interested in latency issues and generally how to make a c++ (or java) trading platform.
I've seen CLI mentioned a ... | The economics of publishing being what they are, I would be very surprised if there was a book published on such a narrow topic.
|
5,411,019 | 5,411,044 | Writing a simple class in C++ | I am getting an error saying that I can't access private members x and y. How do I write the methods getX() and getY() so that they could see x and y? Thanks.
#include <iostream>
#include <string>
using namespace std;
class Point {
public:
Point(int x, int y);
Point();
int getX();
int getY();
private:... | Um, you already have written getX and getY, you just need to use them:
cout << p.getX() << endl;
cout << g.getY();
Note that, because getX() and getY() don't modify your class, they should be const:
class Point {
public:
// ...
int getX() const;
int getY() const;
// ...
};
// ...
int Point::getX()... |
5,411,229 | 5,412,051 | c++0x inherited constructor in templates | Here is class foo:
template <typename T>
struct foo
{
foo()
{
t = nullptr;
}
foo(T* p, bool flag)
{
t = p;
}
private:
T* t;
};
Here is class bar:
template <typename T>
struct bar: public foo<T>
{
using foo<T>::foo<T>;
};
Is it correct syntax for inheriting constructors... | template <typename T>
struct bar: public foo<T>
{
using foo<T>::foo<T>;
};
To let this parse correctly, you would need to insert template before the foo<T>;, to tell the compiler that foo is to be regarded as a template name (it cannot look into foo<T> to tell itself, since T is unknown). But using ::template is n... |
5,411,251 | 5,411,613 | Loading an STL set with pre-sorted data, C++ | I'm working with C++ in Visual Studio 2010. I have an STL set, which I'm saving to file when my program shuts down. The next time the program starts up, I load the (sorted) data back into a set. I'm trying to optimize the loading process, and I'm having trouble. I suspect the problem is with frequent re-balancing, ... | About how many elements we are talking?
I made an short test with 10.000.000 integers (prepared in an vector) and inserted them in three different ways into the set.
Prepare Input:
std::vector<int> input;
for(int i = 0; i < 10*1000*1000; ++i) {
input.push_back(i);
}
Insert into set item by item with insert... |
5,411,515 | 5,411,641 | Binary file write problem in C++ | This is my function which creates a binary file
void writefile()
{
ofstream myfile ("data.abc", ios::out | ios::binary);
streamoff offset = 1;
if(myfile.is_open())
{
char c='A';
myfile.write(&c, offset );
c='B';
myfile.write(&c, offset );
c='C';
myfile.wri... | There are several issues with this code.
For starters, if you want to write individual characters t a stream, you don't need to use ostream::write. Instead, just use ostream::put, as shown here:
myfile.put('A');
Second, if you want to write out a string into a file stream, just use the stream insertion operator:
myfi... |
5,411,758 | 5,427,862 | Problem using Friend function in QT | I wish to add items in a ListWidget, which is a private member of a class, through a friend function. Actually, i am trying this sample snippet to use friend function for more classes to update their ListWidgets from a single function.
I need guidance in using friend function in my case.
Kindly forgive my ignorance o... | As far as I can see, the 'adda' function does not affect anything. It returns nothing, and only operates on 'I' which is deleted when 'adda' is finished.
An example of how I believe you could use a friend function would be if you declared/defined 'adda' as:
void adda(InBoxTab *I)
{
I->listWidget1->insertItem(1,... |
5,411,776 | 5,411,831 | C++/Windows API - Unable to find CreateWindow | Here's the start of my program in Visual C++ 2010 Express:
#pragma comment(lib, "detoured.lib")
#pragma comment(lib, "detours.lib")
#include <Windows.h>
#include <detours.h>
HWND (WINAPI *pCreateWindow)(LPCWSTR lpClassName,
LPCWSTR lpWindowName, DWORD dwStyle,
... | Could it be because CreateWindowW() is really a macro that references CreateWindowExW()?
Try using CreateWindowExW() instead.
|
5,411,903 | 5,412,091 | Code Analysis tool for legacy C/C++ | looking for a code analysis tool for some legacy c/c++ code on unix
specifically to identify dependencies to
specific functions
specific (include?) files
File/Socket I/O calls etc.
function dependency tree from a root etc.
| Doxygen is probably what you're looking for. It can provide cross-reference, call graphs and dependency trees without programmer's markups, that seems to be what you need.
|
5,412,046 | 5,541,564 | How to link against a static library which uses static libraries itself using scons and Visual C++? | My SConstruct file looks something like this:
jnglLibs = Split("freetype png ogg vorbisfile") # left out a few
env.Library(target="jngl", source=source_files, LIBS=jnglLibs)
env.Program("test.cpp", LIBS=Split("jngl") + jnglLibs)
The static library links fine but the program fails with unresolved external symbols from ... | There are a lot of quirks with static linking on Windows.. I've had one or two similar problems to this but mostly my problem was once the 'static' libs were compiled they still depended on the .dll's being there. Anyway, I've been feeling your pain for a while now but got through it for my purposes... here's one page... |
5,412,228 | 5,412,286 | What is static library and what is dynamic library, what is the difference and what is better to use and why? |
Possible Duplicate:
What do 'statically linked' and 'dynamically linked' mean?
I know here lot of similiar questions (for instance first or second or third one) But in no one I found full answer of my question. Please explain me the main differences and when I have to use which type of library?
| A static library is meant to be combined with your code into a single executable file by a linker.
A dynamic library is meant to be loaded by the operating system after the main executable has been loaded, and the linking of the symbol addresses will be done by the OS at that time. This may be done automatically based ... |
5,412,316 | 5,412,354 | Why go through the trouble of static_cast-ing a number to a double? | Ran across this in code I'm working through:
double part2 = static_cast<double>(2) * somthing1
* ( static_cast<double>(1) + something2 )
+ ( static_cast<double>(1) / static_cast<double>(2) ) * something3
+ ( static_cast<double>(1) / static_cast<double>(2) ) * pow ( something4, 3 );
(The somethings are doubles.)
... | Many of these static_casts are unnecessary, because of automatic numeric promotion. The ones that are extremely necessary are the ones used on constructing the number 1/2, although in this case there's no obvious reason not to just say 0.5 instead. In any case a compiler that's paying attention will remove all of these... |
5,412,382 | 5,412,417 | I don't understand these compile errors | I can not compile, this program is giving me errors. I have already spend 3 days on it.
C:\unisa\COS1511\test.cpp
[Warning] In function `float calcAllowedPerChild(float)':
error C:\unisa\COS1511\test.cpp:26
invalid operands of types float ()(float) and const float to binary operator<
#include <iostream>
using namespac... | float calcAllowedPerChild ( float nrChildren);
// ^ : Error - reomove it.
Function protoypes end with a ; but not function definitions. Also take a look at the if statement condition -
if ( calcAllowedPerChild > maxPerChild || calcAllowedPerChild < minPerChild)
Since it is a... |
5,412,384 | 5,412,438 | I can't seem to link to the desired .lib file, resulting in an unresolved external symbol error | I have inherited a VC++ solution and from one project (named "IntersonWinDriver") I'm trying to link to a .lib file that is generated by a different project (named "Utility"). I noticed that in a different project, named "MasterVu", I found "Utility.lib" included among the linker command line options.
In order to dupl... | Hmm...I see that under Common Properties->Framework and References I can add the Utility project. Now I feel silly for asking this question too soon...
|
5,412,497 | 5,412,607 | C++ Using delete on 2D-Vector of a struct with float arrays | I have a struct like this:
struct foo {
int a,b,c;
float d;
float *array1;
float *array;
};
And now I use this struct for a 8x8 2D-Vector like this:
vector< vector<foo> > bar(8);
for (int i = 0; i < 8; i++)
bar[i].resize(8);
Within my program, "bar" is now filled with data, for example:
bar[1][5].a... | This easiest way to accomplish this would be to create a constructor and destructor:
struct foo {
int a,b,c;
float d;
float *array1;
float *array;
foo()
{
array1 = array = 0;
}
~foo()
{
delete [] array1;
delete [] array;
}
};
Even better would be members to track the size of array1... |
5,412,873 | 5,412,928 | How can I structure my C++ code so that I only write my common methods once? | If C++.NET allowed multiple inheritance, I would have my common methods in a class and derive from it.
I have classes derived from Panel, Label, TabControl ... which have the same methods exactly.
How can I structure my C++ code so that I only write my common methods once?
Here is a simple example of a property I wan... | I can't quite make out for sure what you mean by "common methods" here, but generally speaking namespace level non-member functions are the best way to do that (see pretty much every algorithm in the standard library).
If it actually needs access to private attributes of your class then it's probably not a common metho... |
5,413,007 | 5,413,050 | use variables defined in header without extern C++ | I'm a library that drives a LED board. Files include led.cpp, led.h, font.h
led.cpp
#include "led.h"
//function implementation
led.h
#ifndef led_h
#define led_h
#include "font1.h"
class LED{
//some code, which uses char defined in font.h
}
font.h
#ifndef font_h
#define font_h
//Letter mapping to pixel
char CH2... | Sure: use const
const char CH200[] PROGMEM = "11111111";
const char CH201[] PROGMEM = "11000011";
// etc
|
5,413,155 | 5,416,568 | How can I overcome long compile times caused by a large amount of generated code? | I have been looking around for other OBJ file loaders and I found
obj2opengl by Heiko Behrens.
I like how simple this converter is, but there's only one problem. When compiling, it takes a really long time to build because that converted file is 63 MB when converted.
Is there a way to maybe skip the checking of a heade... | What this script probably does is converting a OBJ file into a series of OpenGL commands. That's really not how one should use OpenGL.
What you actually should do is either implement yourself, or get some library that dynamically loads a OBJ file at your programs runtime. Given the fact that Lightwave OBJ file are real... |
5,413,216 | 5,413,255 | Calculating Euler's Number in C++ | Write a program that calculates Euler’s number e. To do this, first write a function that takes a parameter n, and returns the result (1+1/n)n. The limit of this function approaches e as n approaches infinity. In your main program, write a loop that calls this function with increasing values of n. On each iteration, mu... | First of all, if i starts off at 0, and you keep multiplying by 2, it won't advance very far. Start off at 1.
Second of all, according to the problem statement, you should stop when your approximation is good enough. So the loop stop condition is not on i, but rather abs(proper_E - your_approximation) > 1e-8
|
5,413,319 | 5,413,348 | Finding problem with class copy construction | I have a problem with one of my c++ assignments. Its more of a theory question. Here is the code:
//a class implementation
class IntArrays {
public:
IntArrays(int n): data(new int[n]), size(n) { }
~IntArrays() { delete[] data; };
const int& operator[](int n) const
{ return data[n]; }
IntArrays(const ... | You're copying the wrong way.
std::copy(data, data + size, ar.data);
Should be:
std::copy(ar.data, ar.data + size, data);
|
5,413,371 | 5,413,403 | Accessing values from a two dimensional initialized array | int a[][30]={{2, 16},{4, 8},{5, 16, 21},{2,6,3,5,6}};
Since the size of the second dimension is varying. If I want to access something like for a particular value of i(first dimension), access all j values(2nd dimension), how do I write that statement?
What I thought was:
for(int j=0;j<30;j++)
a[i][j]=some operation... | The compiler does not keep any information about how many values were in the braced initializer. Instead, it fills the "missing" values with zeros.
So these two are equivalent:
int a[][4] = {{2, 16},{4, 8, 5}};
int a[][4] = {{2, 16, 0, 0}, {4, 8, 5, 0}};
If you know that none of the "actual" data elements are zero, y... |
5,413,495 | 5,413,515 | C++ Passing a vector<vector<STRUCT> > for modifying | let's say I have a
vector<vector<foobar> > vector2D(3);
for(int i=0;i<3;i++)
vector2D[i].resize(3);
So, a 3x3 vector containing 9 elements of type foobar in total.
I know want to pass "vector2D" to a function to modify some values in "vector2D".
For example, if foobar contains
struct foobar{
int *someArray;... | Yes, it's possible. You just need to pass it in as a non-const reference. Something like:
void ModifyVector( vector< vector< foobar > > & v )
{
v[0][0].someArray = new int[100];
v[0][0].someArray[49] = 1;
}
vector<vector<foobar> > vector2D(3);
ModifyVector( vector2D );
One further note: you probably should ... |
5,413,822 | 5,421,826 | Sporadic Collision Detection | I've been working on detecting collision between to object in my game. Right now everything tavels vertically, but would like to keep the option for other movement open. It's classic 2d vertical space shooter.
Right now I loop through every object, checking for collisions:
for(std::list<Object*>::iterator iter = mObjec... | This logic is wrong:
if(std::min(getAbsoluteMidPoint().y - radius, getPreviousAbsoluteMidPoint().y - radius) <= theirMidPoint.y &&
theirMidPoint.y <= std::max(getAbsoluteMidPoint().y + radius, getPreviousAbsoluteMidPoint().y + radius))
{
// then a collision is possible, check x
}
(The logic inside the braces... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.