question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,391,104 | 2,391,128 | Are the subscripts for three-dimensional arrays strictly defined? | Let's say I declare this:
int [a][b][c];
Does a stand for the level/page, b the row and c the column?
Or can it be anything I want it to be i.e. a stands for column, b stands for page, and c stands for row (since data is just data and a cube can be abstracted any way)?
| Anything you want in any order you want, the designations row and column are just convention. The layout in memory will be http://en.wikipedia.org/wiki/Row-major_order in C++, That part can't be changed.
How you iterate through the elements will have an impact on performance in many cases. You want to change the r... |
2,391,233 | 2,391,240 | return type of the constructor in C++ | I know that there is no return type of the constructors in C++
However, the code below compiles right. What is returned by the constructor in the code below?
class A{
public:
A() {}
}
A a = A(); //what is returned by A() here, why?
Is there any conflict here?
| Nothing is returned from the constructor. The syntax A() is not a constructor call, it creates a temporary object of type A (and calls the constructor in the process).
You can't call a constructor directly, constructors are called as a part of object construction.
In your code, during the construction of the temporary ... |
2,391,294 | 2,391,306 | Are functions defined in headers guaranteed to be inlined? | If I define a non-member function in a header, will it always be inlined by the compiler, or does the compiler choose based on its heuristics? I know that __inline is just a hint, is it the same with functions in headers?
| Remember that including something from a header is no different than just typing it directly in the source file. So being in a header makes no difference as far as the compiler is concerned; it never knew it was there.
So when you define a function in a header file, and you include that header file in a file, it's like... |
2,391,334 | 2,391,353 | How do i begin writing a windows shell extension? | I'm looking at writing a shell extension so when a file is clicked an action can be performed against it. (Like any other context menu :))
What is the minimum i need to insert a new Menu Item in the Context menu and perform an action against one or more files. A comparative example would be that i selected 10 files a... | This MSDN article will get you started.
Your approach of spawning a process (written in managed code) to do the actual work of the shell extension should be fine. I'd suggest just passing the selected files as command line parameters via CreateProcess.
As to the project type, you'll be wanting to generate a Win32 dyna... |
2,391,458 | 2,391,623 | Map file with GCC on OSX | I am using GCC on Mac OSX. I am trying to get GCC to create a map(or listing) file of all the symbols in the project so it contains the addresses at which they are mapped.
I read in the GCC manual that a way of generating such map files is to pass system specific flags to the GCC linker using -Xlinker option.
But I can... | The ld option is -map. With -Xlinker you would write:
gcc -Xlinker -map -Xlinker /path/to/map ...
You can also write this more concisely with -Wl:
gcc -Wl,-map,/path/to/map ...
|
2,391,471 | 2,391,481 | Why does this code not compile correctly? | I just found my code like this does not compile right? Is there any compiler-provided constructor here?
class A
{
private:
A(const A& n);
};
int main()
{
A a;
}
The error is
test.cpp:18: error: no matching function for call to ‘A::A()’
test.cpp:11: note: candidates are: A::A(const A&)
I a... | The compiler will provide for you
the default constructor A() if and only if there are no user-defined constructors, and
the copy constructor A(A const &) unless you provide either of the four possible copy constructors A(A cv &), where cv is any combination of const and volatile.
In your case, you've declared your o... |
2,391,476 | 2,391,650 | problem with dead keys (acute, diaeresis, etc) c++ | I'm currently writing my own virtual keyboard for linux using the X11 lib and i just can't find the way to simulate a KeyPress event of any dead keys.
I'd tried , for example, to write "á" using the asigned macro, which is XK_aacute, and nothing happens.
later i'd tried to send XK_acute (the acute accent macro) and th... | i just figured out ¬¬
#include <X11/extensions/XTest.h>
#include <X11/keysym.h>
#include <X11/Xlib.h>
#include <iostream>
int main(){
Display *display;
unsigned int keycode;
unsigned int keycode1;
display = XOpenDisplay(NULL);
keycode1 = XKeysymToKeycode(display, XK_dead_acute);
XTestFakeKeyEvent(display, keyco... |
2,391,483 | 2,391,487 | Quick question: Where is the C++ compiler located in Windows? | For some MATLAB code that I want to make executable, I need the location to a compiler in Windows. I have Visual Studio installed, so would I be able to reference the compiler that that uses? If so, how can I find it?
Thanks.
| Run the "Visual Studio Command Prompt", and you'll have the environment setup for compilation.
|
2,391,679 | 2,391,781 | Why do we need virtual functions in C++? | I'm learning C++ and I'm just getting into virtual functions.
From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived classes.
But earlier in the book, when learning about basic inheritance, I was able to override base functions in derived classes... | Without "virtual" you get "early binding". Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through.
With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object... |
2,391,823 | 2,398,307 | C++ code snippet for a new baby greeting card | A friend of mine sent me this code snippet to celebrate his new baby birth:
void new_baby_name() { father_surname++; }
The snippet is from his point of view, he is the father and the new baby get the surname from him.
I answered with this:
class father_name {};
class mother_name {};
class new_baby_name: public father_... | The correct reply is:
Sleep(0);
|
2,392,178 | 2,392,188 | extracting numbers and characters from a string, which doesn't follow a specific format? (postfix calculator) | I'm having trouble separating numbers and characters from my input string. The purpose of my program is to add,subtract,multiply and divide in postfix
so i cant predict the input form as it can be anything from
2 2 3 + * (answer being 10) to 2 2 + 3 * (answer being 12). So i cant use sscanf to extract the numbers and t... | Well, to process postfix you're going to want to implement a stack, so you should push each number onto a stack as you get it, each operator pops two off the stack and pushes the result back.
|
2,392,232 | 2,396,530 | Displaying a pop-up notification window | How do you create a window that pops up from system tray notification area vertically upwards and displays a message? for example - In MSN, it displays it when someone gets online/offline.
| Create a window with the look you want, and call AnimateWindow to get the pop-in effect. AnimateWindow doesn't really like windows with anything except a simple border.
|
2,392,308 | 2,392,319 | C++ vector of char array | I am trying to write a program that has a vector of char arrays and am have some problems.
char test [] = { 'a', 'b', 'c', 'd', 'e' };
vector<char[]> v;
v.push_back(test);
Sorry this has to be a char array because I need to be able to generate lists of chars as I am trying to get an output something like.
a a
a b
a... | You cannot store arrays in vectors (or in any other standard library container). The things that standard library containers store must be copyable and assignable, and arrays are neither of these.
If you really need to put an array in a vector (and you probably don't - using a vector of vectors or a vector of strings ... |
2,392,318 | 2,394,541 | Copy constructor and dynamic allocation | I would like to ask you how to write a copy constructor (and operator = ) for the following classes.
Class Node stores coordinates x,y of each node and pointer to another node.
class Node
{
private:
double x, y;
Node *n;
public:
Node (double xx, double yy, Node *nn) : x(xx), y(yy), n(nn) {}
void setNode (Node *nn) : ... | Perform a shallow copy in NodeList::NodeList(const NodeList&) and you don't have to worry about cycles breaking the copy operation. Disclaimer: the following is untested, incomplete and may have bugs.
class NodeList {
private:
typedef std::vector<Node*> Delegate;
Delegate nodes;
public:
NodeList(int capaci... |
2,392,397 | 2,392,483 | going through a string of characters and extracting the numbers? | Given a string of characters, how can I go through it and assign all the numbers within that string into an integer variable, leaving out all other characters?
I want to do this task when there is a string of characters already read in through gets(), not when the input is read.
| unsigned int get_num(const char* s) {
unsigned int value = 0;
for (; *s; ++s) {
if (isdigit(*s)) {
value *= 10;
value += (*s - '0');
}
}
return value;
}
Edit: Here is a safer version of the function.
It returns 0 if s is NULL or cannot be converted to a numeric value at all. It return UINT_... |
2,392,408 | 2,392,411 | What is significance/use of doing void(param); at the start of function? | I was just going thro' source code of Yahoo's Trafic Server
It is written in C++.
In almost all methods (from one of modules),
they do void(param) on each param that function receive.
(Eg below)
Can someone explain what this could be for ?
int ... | This suppresses the "unused argument" warnings. Those statements do nothing, but count as using the argument.
|
2,392,485 | 2,392,544 | algorithm for nth_element | I have recently found out that there exists a method called nth_element in the STL. To quote the description:
Nth_element is similar to
partial_sort, in that it partially
orders a range of elements: it
arranges the range [first, last) such
that the element pointed to by the
iterator nth is the same as the
... | It's called a selection algorithm and wikipedia has a decent page on it: http://en.wikipedia.org/wiki/Selection_algorithm
Also read about order statistics: http://en.wikipedia.org/wiki/Order_statistic
|
2,392,515 | 2,407,544 | GCC/VS2008: Different behaviour of function call when templated base class is derived from itself | The following code works with Visual Studio 2008 but not with GCC/G++ 4.3.4 20090804. Which behaviour is - according to the C++ standard - correct?
template <int N>
struct A : A<N-1> {};
template <>
struct A<0> {};
struct B : A<1> {};
template <int N>
void Func(const A<N> &a) {}
int main()
{
A<1> a; //is deri... | After some digging through N3035, I found this in section 14.9.2.1.4:
If P is a class and P has the form simple-template-id, then the transformed A can be a derived class of the deduced A. Likewise, if P is a pointer to a class of the form simple-template-id, the transformed A can be a pointer to a derived class point... |
2,392,584 | 2,392,611 | In c++, how to create a conversion from T to T*? | In preparing to a OOP exam, I enjoyed seeing g++ compile the following code (without an instantiation) even though it appeared to make no sense:
template<class T> void f() {
T t = "a";
t += 5.6;
t->b();
T* p = t;
p = p*(t/"string");
}
I then set out on a challenge to make this instantiate and compi... | That is a completely meaningless line.
But to make it compilable, you can provide the conversion operator:
operator A* () { return 0; }
Hope you realize how evil this is.
|
2,392,655 | 2,392,693 | What are the signs of crosses initialization? | Consider the following code:
#include <iostream>
using namespace std;
int main()
{
int x, y, i;
cin >> x >> y >> i;
switch(i) {
case 1:
// int r = x + y; -- OK
int r = 1; // Failed to Compile
cout << r;
break;
case 2:
r = x - y;
... | The version with int r = x + y; won't compile either.
The problem is that it is possible for r to come to scope without its initializer being executed. The code would compile fine if you removed the initializer completely (i.e. the line would read int r;).
The best thing you can do is to limit the scope of the variable... |
2,392,660 | 2,392,682 | How to compute number of seconds since the beginning of this day? | I want to get the number of seconds since midnight.
Here is my first guess:
time_t current;
time(¤t);
struct tm dateDetails;
ACE_OS::localtime_r(¤t, &dateDetails);
// Get the current session start time
const time_t yearToTime = dateDetails.tm_year - 70; // year to 1900 converted into year ... | You can use standard C API:
Get current time with time().
Convert it to struct tm with gmtime_r() or localtime_r().
Set its tm_sec, tm_min, tm_hour to zero.
Convert it back to time_t with mktime().
Find the difference between the original time_t value and the new one.
Example:
#include <time.h>
#include <stdio.h>
ti... |
2,392,689 | 2,392,729 | How can we find second maximum from array efficiently? | Is it possible to find the second maximum number from an array of integers by traversing the array only once?
As an example, I have a array of five integers from which I want to find second maximum number. Here is an attempt I gave in the interview:
#define MIN -1
int main()
{
int max=MIN,second_max=MIN;
int a... | Your initialization of max and second_max to -1 is flawed. What if the array has values like {-2,-3,-4}?
What you can do instead is to take the first 2 elements of the array (assuming the array has at least 2 elements), compare them, assign the smaller one to second_max and the larger one to max:
if(arr[0] > arr[1]) {
... |
2,392,714 | 2,392,725 | Adding a struct to std::list | struct Group
{
Group(string _N, set <string> M_)
{Name = N_; Member = M_}
string Name;
set <string> Members;
};
int main()
{
list <Group> GroupList;
set <string> Members;
//collect the members from a file and add to set
GroupList.pushback(Group(Name, Members));
}
is there a less memory cons... | You can pass a reference and then make a copy and use initialisation list, same with the string.
Group(const string& n, const set <string>& m)
: Name(n), Members(m) {}
|
2,392,762 | 2,392,774 | Class reference to parent | i'm pretty new at using C++ and I'm actually stopped at a problem.
I have some class A,B,C defined as follow (PSEUDOCODE)
class A
{
...
DoSomething(B par1);
DoSomething(C par1);
...
}
class B
{
A parent;
...
}
class C
{
A parent;
...
}
The problem is :
How to make this? If I simply do it (as I've alway... | Forward-declare B and C. This way compiler will know they exist before you reach the definition of class A.
class B;
class C;
// At this point, B and C are incomplete types:
// they exist, but their layout is not known.
// You can declare them as function parameters, return type
// and declare them as pointer and refe... |
2,392,870 | 2,392,886 | Executing functions depending on a variable's value - C++ | I am working on a transliteration tool. I have two modules lexer and translator. Lexer generates tokens out of the input text. Depending on the current language chosen, I have to call appropriate translation routine.
I have came up with couple of ideas to do this. First one is to create a base class something called ba... | Your second approach might look simpler to you for just two items (well for me it doesn't...), but it is more error-prone and difficult to maintain in the long run. Whenever you add a new language, you need to touch the code in at least two places. (And trust me: even if this seems unlikely to you at the moment, it is ... |
2,392,932 | 2,393,038 | Why does the speed of this SOR solver depend on the input? | Related to my other question, I have now modified the sparse matrix solver to use the SOR (Successive Over-Relaxation) method. The code is now as follows:
void SORSolver::step() {
float const omega = 1.0f;
float const
*b = &d_b(1, 1),
*w = &d_w(1, 1), *e = &d_e(1, 1), *s = &d_s(1, 1), *n = &d_n(... | The short answer to your last question is "yes" - denormalized (very close to zero) numbers require special handling and can be much slower. My guess is that they're creeping into the simulation as time goes on. See this related SO post: Floating Point Math Execution Time
Setting the floating-point control to flush den... |
2,393,053 | 2,398,901 | Performancetest: Flash/AS3 Processing/Java and openFrameworks/C++ | I need to compare the performance of AS3, Processing and openFrameworks for my Bachelor thesis. Are there any comparison tables you know of or do I have to do the test myself?
How would a good test look like? I'm just focused on graphics so I thought about maybe three different programs, a 2d-graphics app, a typograph... | I know in the AS3 world there is a popular performance monitor called stats, you can find it here. Honestly I think you may be comparing apples to oranges. My initial assumption would be that openFrameworks (C++) outperforms Processing (Java) and Processing outperforms AS3 for many of the problems you will be exploring... |
2,393,163 | 2,393,170 | One question about array without default constructor in C++ | From previous post, I learnt that for there are two ways, at least, to declare an array without default constructors. Like this
class Foo{
public:
Foo(int i) {}
};
Foo f[5] = {1,2,3,4,5};
Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)};
I also learnt that the first one will construct the object us... | The first won't construct the objects directly. It will first construct a temporary Foo, and then copy the Foo into the element. It's similar to your second way. The difference is that your second way won't work with a explicit copy constructor, while your first will. And conversely, the first will not work with a expl... |
2,393,225 | 2,522,715 | Where are the static methods in gcc's dump file.c.135r.jump | When I run gcc with the parameter -fdump-rtl-jump, I get a dump file with the name file.c.135r.jump, where I can read some information about the intermediate representation of the methods in my C or C++ file.
I just recently discovered, that the static methods of a project are missing in this dump file. Do you know, wh... | My guess is that the static methods are inlined and, since they are static, everything is known about their calls, no out-of-line code of them is emitted. A way to confirm or reject this is to add -fkeep-inline-functions gcc option and then they should appear in the dumps.
|
2,393,325 | 2,393,495 | Why is protected constructor raising an error this this code? | One question about protected constructor. I learnt that the protected constructor can be used in the derived class. How ever, I found the code below has an error. Why does it happen like this?
class A
{
protected:
A(){}
};
class B: public A {
public:
B() {
A* f=new A(); //... | This has nothing to do with constructors specifically. This is just how protected access works.
The way protected access specifier works, it allows the derived class B to access the contents of an object of base class A only when that object of class A is a subobject of class B. That means that the only thing you can d... |
2,393,345 | 2,393,389 | How to append text to a text file in C++? | How to append text to a text file in C++? And create a new text file if it does not already exist and append text to it if it does exist.
| You need to specify the append open mode like
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
|
2,393,399 | 2,393,504 | HTML to XML conversion with C++ | Is there a C++ code or library to convert a HTML document to a XML document?
Thanks.
| You can take a look at Tidy library
Tidy is composed from an HTML parser
and an HTML pretty printer. The parser
goes to considerable lengths to
correct common markup errors. It also
provides advice on how to make your
pages more accessible to people with
disabilities, and can be used to
convert HTML cont... |
2,393,439 | 2,393,562 | Can I overload operators on enum types in C++? | For example, if I have:
typedef enum { year, month, day } field_type;
inline foo operator *(field_type t,int x)
{
return foo(f,x);
}
inline foo operator -(field_type t)
{
return t*-1;
}
int operator /(distance const &d,field_type v)
{
return d.in(v);
}
Because if I do not define such operators it is actually ... | Yes, operator overloading can be done on enum and class types. The way you do it is fine, but you should use + to promote the enumeration, instead of *-1 or something (the purpose ultimately is to avoid infinite recursion because -t):
inline foo operator -(field_type t) {
return -+t;
}
This will scale well to other... |
2,393,458 | 2,393,467 | Why does using the same count variable name in nested FOR loops work? | Why does the following not give an error?
for (int i=0; i<10; ++i) // outer loop
{
for (int i=0; i<10;++i) // inner loop
{
//...do something
}
//...do something else
}
The way I understand it, variables in braces ({...}) are in scope only within these braces. But the inner loop is inside the braces of ... | You are actually making a new variable with the same name as another variable. Since they are in different scopes this is allowed, and the variable in the inner scope "owns" the name. You will not be able to access the outer-scoped i inside the inner scope.
The for loop declaration itself is part of the scope of the fo... |
2,393,518 | 2,393,557 | undefined C/C++ symbol as operator | I notice that the character/symbol '`' and '@' is not used as an operator in C/C++,
does anyone know the reason or historically why its so?
if its really not used, is it safe to define those symbols as another operator/statement using #define?
| Normally, #define only accepts valid identifiers in the macro name - so you cannot do:
#define @ at
#define @(x) [x]
Similarly with back-quote. And you didn't mention '$', which is sometimes allowed in identifiers.
There might be a compiler-specific extension to allow such mappings, but I wouldn't use it.
As ... |
2,393,527 | 2,393,575 | Python code to parse and inspect c++ | Is there a library for Python that will allow me to parse c++ code?
For example, let's say I want to parse some c++ code and find the names of all classes and their member functions/variables.
I can think of a few ways to hack it together using regular expressions, but if there is an existing library it would be more ... | In the past I've used for such purposes gccxml (a C++ parser that emits easily-parseable XML) -- I hacked up my own Python interfaces to it, but now there's a pygccxml which should package that up nicely for you.
|
2,393,644 | 2,394,081 | Visual studio compiler flag /arch and performance | I just noticed that in our project have left the "Enable Enhanced Instruction Set" flag left unset, probably just an oversight.
Before enabling the flag I would like to ask if anyone have seen any real-world performance improvements enabling it ?
I guess we will see some improvement our application constantly do float... | So in a nutshell: This setting only enables certain intrinsic functions that map directly on SSE instructions. In normal C++ programs you don't use these intrinsic functions, so this setting won't improve performance.
If you need more performance, you could try to find a compiler that rewrites your code to use SSE ins... |
2,393,673 | 2,393,696 | C++ and,or,not,xor keywords |
Possible Duplicate:
The written versions of the logical operators.
I notice that C++ define keyword and, or, not, xor, and_eq, or_eq, not_eq and xor_eq as an alternative to &&, ||, !, ^, &=, |=, != and |=. and they're rarely used! What's wrong? Are they not portable?
| They come from C AFAIR from times when it was not known what special symbols are on the keyboard. So to have portable language they were defined so anyone can use C even if they used keyboard with no &, |, or ^ (etc.).
Nowadays when QWERTY is a standard (with AZWERTY & co. as variations) it is no longer an issue.
PS. A... |
2,393,817 | 2,394,085 | C++: Why isn't operator placement new recognized as an inline friend function in a (template) class in VS2005? | I've inherited a Visual Studio 6.0 project to convert to 2005. It includes this fantastic MyClass class below that client code uses everywhere by invoking placement new on an instance of it (greatly simplified here):
#include <new>
#include <cstdio>
template<class T>
class MyClass {
public:
// This is what the au... | The problem is that the allocation function is looked up in the global scope, it is not looked up using ADL. Since friend functions defined inside a class are hidden from the enclosing scope, the function is not found.
5.3.4/9:
If the new-expression begins with a unary :: operator, the allocation function’s name is lo... |
2,393,873 | 2,393,889 | how do i add a int to a string | i have a string and i need to add a number to it i.e a int. like:
string number1 = ("dfg");
int number2 = 123;
number1 += number2;
this is my code:
name = root_enter; // pull name from another string.
size_t sz;
sz = name.size(); //find the size of the string.
name.resize (sz + 5, account); /... | Use a stringstream.
#include <iostream>
#include <sstream>
using namespace std;
int main () {
int a = 30;
stringstream ss(stringstream::in | stringstream::out);
ss << "hello world";
ss << '\n';
ss << a;
cout << ss.str() << '\n';
return 0;
}
|
2,393,874 | 2,393,900 | Removing the repeating pattern in C++ | I have atleast 16 functions of the following form.
bool Node::some_walker( Arg* arg1 )
{
if(this == NULL)
return false;
bool shouldReturn = false;
if( this->some_walker_p(arg1, shouldReturn) ) //This line alone varies
return true;
if( shouldReturn ) // true is already returned
... | It depends on whether the arguments to the private functions are similar or not. The following solutions are possible, ranging from simple and limited to complex and generic:
Equivalent =< Use member-function-pointer)
Same number, different types => Templatize over each argument)
Different numbers/types of arguments =... |
2,393,888 | 2,396,704 | Possible to create a dual-seekable Boost Iostream using a file_descriptor? | I'm trying to update a random-access binary file using the std::iostream interface with separate get/put positions managed via seekg/seekp. Everything works fine with stringstream, but when I create a file descriptor-based stream using Boost.Iostream (specifically boost::iostreams::stream<boost::iostreams::file_descrip... | If you construct a bidirectional_seekable boost::iostreams::device it will support two separate get/put positions which can be modified with the help of the iostreams::seek function.
Roughly, this will look like:
struct binary_seekable_device
: boost::iostreams::device<boost::iostreams::bidirectional_seekable>
{
... |
2,394,017 | 2,394,040 | Remove comments from C/C++ code | Is there an easy way to remove comments from a C/C++ source file without doing any preprocessing. (ie, I think you can use gcc -E but this will expand macros.) I just want the source code with comments stripped, nothing else should be changed.
EDIT:
Preference towards an existing tool. I don't want to have to write thi... | Run the following command on your source file:
gcc -fpreprocessed -dD -E test.c
Thanks to KennyTM for finding the right flags. Here’s the result for completeness:
test.c:
#define foo bar
foo foo foo
#ifdef foo
#undef foo
#define foo baz
#endif
foo foo
/* comments? comments. */
// c++ style comments
gcc -fpreprocessed... |
2,394,061 | 2,394,095 | STL set not adding properly c++ | I am adding musicCD information to a set. I have two different functions for this. The problem is adding the musicians. Its only adding the last musician being passed in like its copying over the first ones.
here is the required output to give you an idea of the info. Only ringo starr is adding and not "George Harrison... | Yes.
string musicians;
This variable stores a single string. Hence, even though the call succeeds for addBandMember it gets overwritten by the next call. Hence, all you are left with is the name of the last added musician -- Ringo in your case. Use a list or vector instead to hold all musicians.
vector<string> musicia... |
2,394,098 | 2,403,916 | Graph colouring algorithm: typical scheduling problem | I'm training code problems like UvA and I have this one in which I have to, given a set of n exams and k students enrolled in the exams, find whether it is possible to schedule all exams in two time slots.
Input
Several test cases. Each one starts with a line containing 1 < n < 200 of different examinations to be sched... | I've translated the polygenelubricant's pseudocode to JAVA code, in order to provide a solution for my problem. We have a submission platform (like uva/ACM contests), so I know it passed even in the problem with more and hardest cases.
Here it is:
import java.util.ArrayList;
import java.util.Hashtable;
import java.util... |
2,394,170 | 2,394,193 | Searching std::string between a limit | if you know the start and end positions in string from where to begin and end the search. For example -
string s = StringStringString
|S |t |r |i |n |g |S |t |r |i |n |g |S |t |r |i |n |g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
How would you find "tr" in the string specifying the the position to begin ... | If you really want to limit the length of the sequence that gets traversed (presumably because the string is very long compared to the interesting region), use std::search and pass it the corresponding iterators into the string.
|
2,394,402 | 2,394,463 | C/C++: Bitwise operators on dynamically allocated memory | In C/C++, is there an easy way to apply bitwise operators (specifically left/right shifts) to dynamically allocated memory?
For example, let's say I did this:
unsigned char * bytes=new unsigned char[3];
bytes[0]=1;
bytes[1]=1;
bytes[2]=1;
I would like a way to do this:
bytes>>=2;
(then the 'bytes' would have the foll... | I'm going to assume you want bits carried from one byte to the next, as John Knoeller suggests.
The requirements here are insufficient. You need to specify the order of the bits relative to the order of the bytes - when the least significant bit falls out of one byte, does to go to the next higher or next lower byte.
W... |
2,394,529 | 2,394,576 | Memory Leaks - STL sets | I am trying to plug up all my memory leaks (which is massive). I am new to STL. I have a class library where I have 3 sets. I am also creating a lot of memory with new in the library class for adding info to the sets...
Do I need to deallocate the sets? If so, how?
Here is the library.h
#pragma once
#include <ostr... | You need to free the memory for each element of the set. The container will not do that for you, and it shouldn't because it can't know whether it owns that data or not -- it could just be holding pointers to objects owned by something else.
This is a generic free function that will deallocate any STL container.
templ... |
2,394,581 | 2,394,594 | Pure Virtual Class and Collections (vector?) | I'm working on a graphics application that is using virtual classes fairly extensively. It has:
A picture class, which is essentially a collection of shapes.
A shapes class, which is purely virtual and has a few classes that inherit from it:
Circle
Polygon
Rectangle
A Figure shape, which is any graphical figure (als... | When you need polymorphism, you need to use either pointers or references. Since containers (or arrays) can't store references, you have to use pointers.
Essentially change your picture class's vector to:
std::vector<Shape*>
and appropriately modify the other member functions.
The reason why you can't/shouldn't store ... |
2,394,815 | 2,394,844 | testing a string to see if a number is present and asigning that value to a variable while skipping all the non-numeric values? | given a string say " a 19 b c d 20", how do I test to see if at that particular position on the string there is a number? (not just the character '1' but the whole number '19' and '20').
char s[80];
strcpy(s,"a 19 b c d 20");
int i=0;
int num=0;
int digit=0;
for (i =0;i<strlen(s);i++){
if ((s[i] <= '9') && (s[i] >... | These are C solutions:
Are you just trying to parse the numbers out of the string? Then you can just walk the string using strtol().
long num = 0;
char *endptr = NULL;
while (*s) {
num = strtol(s, &endptr, 10);
if (endptr == s) { // Not a number here, move on.
s++;
continue;
}
// Found a number and it i... |
2,394,869 | 2,394,913 | Where can I find a good quick reference for learning C after years of C++? | I last used C professionally around 1997 IIRC. I've used a lot of C++ since then. Now, I find I need to use some C again.
One thing I'm sure of is that I can't just drop the obvious C++ features (e.g. classes) and expect everything to work. There are various less obvious syntax changes. I just don't remember what they ... | As dirkgently suggests, Harbison and Steele is a good reference, but I don't find it useful to brush up on. To retrain your mind, I have these suggestions:
Reread Kernighan and Ritchie
Optional: read Peter van der Linden's superb Expert C Programming: Deep C Secrets.
Don't forget libraries! Look at P. J. Plauger's b... |
2,394,980 | 2,394,992 | seekg() failing mysteriously | I have a 2884765579 bytes file. This is double checked with this function, that returns that number:
size_t GetSize() {
const size_t current_position = mFile.tellg();
mFile.seekg(0, std::ios::end);
const size_t ret = mFile.tellg();
mFile.seekg(current_position);
return ret;
}
I t... | You can seekg before a given position, so pos is signed. Try it with files of size 0x7fffffff and 0x80ffffff and see if the latter triggers the problem, that's my guess.
|
2,394,983 | 2,395,159 | Is Unix coded in C or C++ or both? | Many system calls in Unix use overloading and default variables. This concept is absent in C, so Unix is coded in C++ also right?
| Unix was first created at Bell Labs in 1969, well before C++ was conceived. (Src: Unix), you can confirm this by reading Lions' Commentary on Unix, or the BSD 4.4-Lite (which is similar to BSD Net/2) which is available in tarball or via cvs (from FreeBSD). Or the archives from The Unix Heritage Society which is from th... |
2,395,040 | 2,395,103 | How do Clang 'blocks' work? | http://clang.llvm.org/docs/BlockLanguageSpec.txt
Looks really cool.
However,
I don't understand it.
I don't see examples it.
I don't see examples of ideas hard to express in C++ as is, but trivial to express in blocks.
Can anyone enlighten me on this?
| Blocks are, essentially, a way to pass code and scope around as data. They're known in some other languages as closures and anonymous functions.
Here's an article with more details and code examples.
|
2,395,158 | 2,395,187 | Linker error: "linker input file unused because linking not done", undefined reference to a function in that file | I'm having trouble with the linking of my files.
Basically, my program consists of:
The main program, gen1.
gen1 - receives input sends to str2value for
processing, outputs results str2value, breaks input into tokens
using "tokenizer" determines what sort of processing to do to each
token, and passes them off to str2n... | I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All o... |
2,395,178 | 2,395,203 | Given N points in a 3D space, how to find the smallest sphere that contains these N points? | Given N points in a 3D space, how to find the smallest sphere that contains these N points?
| This problem is called minimal enclosing ball problem. (google this term to find tutorials and papers on it).
Here's one implementation: http://www.inf.ethz.ch/personal/gaertner/miniball.html in c++.
Its 2d case (find a circle to enclose all points in a plane) is a classic example taught in computational geometry cour... |
2,395,275 | 2,395,311 | How to navigate through a vector using iterators? (C++) | The goal is to access the "nth" element of a vector of strings instead of the [] operator or the "at" method. From what I understand, iterators can be used to navigate through containers, but I've never used iterators before, and what I'm reading is confusing.
If anyone could give me some information on how to achieve ... | You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively.
using namespace std;
vector<string> myvector; // a vector of stings.
// push some strings in the vector.
myvector.push_back("a");
myvector.push_back("b");
myvec... |
2,395,300 | 2,395,317 | std string problem with libcurl - c++ | I'm pretty new to c++ and I'm using libcurl to make an http request and get back a string with the respond's content.
size_t write_to_string(void *ptr, size_t size, size_t count, void *stream) {
((std::string*)stream)->append((char*)ptr, 0, size*count);
return size*count;
}
int main(void) {
CURL *curl;
... | std::string generally should not be part of a public interface of a library distributed in binary form (object, static lib, or DLL). But libcurl is pretty intelligently designed, probably the std::string support is provided by an include file (that's ok) which converts things to a portable format before calling into t... |
2,395,501 | 2,396,064 | Passing non-Global C++ objects to Lua functions (Swig) | I am extending an interface with lua, and I've run into a problem in that I would need to pass pointers to objects to the lua code to work upon. These classes will have been wrapped via SWIG, and I could instantiate them via lua using swig, but that would leave me with useless objects.
I need to be able to pass a callb... | Aha, answering my own question, but I founds it!
http://lua-users.org/lists/lua-l/2007-05/msg00053.html
Hello Joey,
I do almost all my SWIG-LUA work from
the lua side. Swig is really good for
just wrappering up a C/C++ library to
get it readable by lua. Getting the
C++ to talk to lua is fairly easy, but
not ... |
2,395,514 | 2,395,521 | Is wchar_t just a typedef of unsigned short? | for example, does:
wchar_t x;
translate to:
unsigned short x;
| In short: in C may be in C++ no.
Widely. C defines wchar_t as typedef but in Unix it is generally 4 bytes (so generally not short) and in Windows 2 so it may be short.
Under C++ it is unique built-in type like char or int, so you can legally overload void foo(short x) and void foo(wchar_t x)
|
2,395,552 | 2,395,568 | C++: having trouble linking from command line | Just getting started with C++ here. I am working on OSX with Eclipse CDT. I have a project with some custom classes and two files "Test.hpp" and "Test.cpp" - the later with my main() method that runs some tests that I have defined and implemented in these two files.
I can compile and run from Eclipse with no problems, ... | Command 'g++ Test.cpp' does both compilation and linking. If you have many source files, you should link Test.cpp with them too like 'g++ Test.cpp other1.cpp other2.cpp' or just compile all files and link them all together later like 'g++ Test.o other1.o other2.o'.
|
2,395,613 | 2,395,626 | Question on overloading operator+ | Consider the following code:
class A
{
public:
A& operator=( const A& );
const A& operator+( const A& );
const A& operator+( int m );
};
int main()
{
A a;
a = ( a + a ) + 5; // error: binary '+' : no operator found which takes a left-hand operand of type 'const A'
}
Can anyone explain why the a... |
which is then passed to "const A& operator+( int m )" if I'm not mistaken
No. Since the LHS is a const A& and RHS is an int, it will call*
[anyType] operator+ (int rhs) const
// ^^^^^ note the const here.
as you've only provided the non-const version const A& operator+( int m ), the compil... |
2,395,703 | 2,395,756 | Variable sized packet structs with vectors | Lately I've been diving into network programming, and I'm having some difficulty constructing a packet with a variable "data" property. Several prior questions have helped tremendously, but I'm still lacking some implementation details. I'm trying to avoid using variable sized arrays, and just use a vector. But I can't... | This cast is very dangerous as you have allocated some raw memory and then treated it as an initialized object of a non-POD class type. This is likely to cause a crash at some point.
Packet* p = (Packet *) malloc(8 + 30);
Looking at your code, I assume that you want to write out a sequence of bytes from the Packet obj... |
2,395,949 | 2,395,990 | Copy Directory - Post Build Event | How do I copy some directory from one place to another (not file by file)
in post build event (whats the comman line??). im using vs 2005 (c++ project)
| The commandline is simply a batch script that is executed upon completion of the build. Therefore, you can just use regular Windows shell commands, such as mkdir, copy, ... To copy whole directories recursively, use xcopy <src> <dest> /E.
|
2,395,954 | 2,396,173 | C++: building iterator from bits | I have a bitmap and would like to return an iterator of positions of set bits. Right now I just walk the whole bitmap and if bit is set, then I provide next position. I believe this could be done more effectively: for example build statically array for each combination of bits in single byte and return vector of positi... | I can suggest several ideas.
Turns out modern CPUs have dedicated instructions for finding the next set bit in a 32- or 64-bit word.
I like very much your idea of constructing the iterator for the whole bitmap from prepared efficient per-byte mini-iterators, this is really cool and I'm surprised I've never seen it bef... |
2,395,999 | 2,396,010 | Inserting into a specific part of a string using iterators? (C++) | string str = "one three";
string::iterator it;
string add = "two ";
Lets say I want to add: "two " right after the space in "one".
the space would be str[3] correct? so: in this case, n = 3;
for (it=str.begin(); it < str.end(); it++,i++)
{
if(i == n)
{
// insert string add at current posit... | You can make use of the insert method of the string class.
string str = "one three";
string add = "two ";
str.insert(4,add); // str is now "one two three"
|
2,396,019 | 2,396,028 | C++ templates hides parent members | Usually, when A is inheriting from B, all the members of A are automatically visible to B's functions, for example
class A {
protected:
int a;
};
class B : public A {
int getA() {return a;}
//no need to use A::a, it is automatically visible
};
However when I'm inheriting with templates, this code becomes ... | You can also do
class B : public A<T> {
int getA() {return this->a;}
};
The problem is that the member is in a base, which depends on a template parameter. Normal unqualified lookup is performed at the point of definition, not at the point of instantiation, and therefore it doesn't search dependent bases.
|
2,396,065 | 2,396,122 | C++ overloading operator comma for variadic arguments | is it possible to construct variadic arguments for function by overloading operator comma of the argument? i want to see an example how to do so.., maybe something like this:
template <typename T> class ArgList {
public:
ArgList(const T& a);
ArgList<T>& operator,(const T& a,const T& b);
}
//declaration
void myF... | It is sort-of possible, but the usage won't look very nice. For exxample:
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
template <class T>
class list_of
{
std::vector<T> data;
public:
typedef typename std::vector<T>::const_iterator const_iterator;
const_iterator begin() con... |
2,396,087 | 2,396,170 | Direct3D - How do I calculate Roll from View Matrix? | This one has been eating up my entire night, and I'm finally throwing up my hands for some assistance. Basically, it's fairly straightforward to calculate the Pitch and Yaw from the View Matrix right after you do a camera update:
D3DXMatrixLookAtLH(&m_View, &sCam.pos, &vLookAt, &sCam.up);
pDev->SetTransform(D3DTS_VIEW,... | It seems the Wikipedia article about Euler angles contains the formula you're lookin for at the end.
|
2,396,106 | 2,396,387 | Most efficient way to add data to an instance | I have a class, let's say Person, which is managed by another class/module, let's say PersonPool.
I have another module in my application, let's say module M, that wants to associate information with a person, in the most efficient way. I considered the following alternatives:
Add a data member to Person, which is ac... | The first and third are reasonably common techniques. The second is how dynamic programming languages such as Python and Javascript implement member data for objects, so do not dismiss it out of hand as impossibly slow. The fourth is in the same ballpark as how relational databases work. It is possible, but difficult, ... |
2,396,133 | 2,396,195 | OpenGL multiple texture mapping on a cube using GLUT | Have been trying to figure out how to put a different texture on each side of a cube using OpenGL and GLUT. I can get it to be a simple texture but multiple texture won't. I would put up my code but it is ugly and cluttered right now. If this is pretty easy to do please post some code for me to follow. Thanks!
| its NEHE openGL lesson #22 http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=22 , then if you want to have different texture for each face, you can modify the cube rendering part for each face by switching glClientActiveTextureARB(GL_TEXTURE0_ARB); ,or glClientActiveTextureARB(GL_TEXTURE1_ARB); depend on the numbe... |
2,396,328 | 2,396,340 | Get HModule from inside a DLL | I need to load some resource from my DLL (i need to load them from the DLL code), for doing that I'm using FindResource.
To do that i need the HModule of the DLL.
How to find that?
(I do not know the name (filename) of the DLL (the user can change it))
| The first argument to DllMain() is the HMODULE of the DLL.
|
2,396,370 | 2,396,420 | How to make google-test classes friends with my classes? | I heard there is a possibility to enable google-test TestCase classes friends to my classes, thus enabling tests to access my private/protected members.
How to accomplish that?
| Try this (straight from Google Test docs...):
FRIEND_TEST(TestCaseName, TestName);
For example:
// foo.h
#include <gtest/gtest_prod.h>
// Defines FRIEND_TEST.
class Foo {
...
private:
FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
int Bar(void* x);
};
// foo_test.cc
...
TEST(FooTest, BarReturnsZeroOnNull) {
Fo... |
2,396,430 | 2,397,588 | How to use lock in OpenMP? | I have two pieces of C++ code running on 2 different cores. Both of them write to the same file.
How to use OpenMP and make sure there is no crash?
| You want the OMP_SET_LOCK/OMP_UNSET_LOCK functions:
https://hpc.llnl.gov/tuts/openMP/#OMP_SET_LOCK
Basically:
omp_lock_t writelock;
omp_init_lock(&writelock);
#pragma omp parallel for
for ( i = 0; i < x; i++ )
{
// some stuff
omp_set_lock(&writelock);
// one thread at a time stuff
omp_unset_lock(&write... |
2,396,467 | 2,396,480 | Using C Code in C++ Project | I want to use this C code in my C++ project :
mysql.c :
/* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>
#include <string.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "rebou... | First things first: it would probably be a lot more helpful if you showed us the compilation errors.
That being said, my initial instinct is to suggest:
extern "C"
{
#include <mysql.h>
#include <stdio.h>
#include <string.h>
}
This is a guess right now, but without the actual error messages it's the best yo... |
2,396,548 | 2,396,827 | Appending to boost::filesystem::path | I have a certain boost::filesystem::path in hand and I'd like to append a string (or path) to it.
boost::filesystem::path p("c:\\dir");
p.append(".foo"); // should result in p pointing to c:\dir.foo
The only overload boost::filesystem::path has of append wants two InputIterators.
My solution so far is to do the follow... | #include <iostream>
#include <string>
#include <boost/filesystem.hpp>
int main() {
boost::filesystem::path p (__FILE__);
std::string new_filename = p.leaf() + ".foo";
p.remove_leaf() /= new_filename;
std::cout << p << '\n';
return 0;
}
Tested with 1.37, but leaf and remove_leaf are also documented in 1.3... |
2,396,576 | 2,396,592 | How to get the cursor position | I want to know how to get the cursor position on Windows in c++,
Reasons: I try to move the mouse position on X Y coordinate with the screen information
e.g: i want to set the mouse position in the offset x:576 y:854 on the screen.
The only method that I found for do that is:
mouse_event(MOUSEEVENTF_ABSOLUTE|MOUSEEVENT... | Try GetCursorPos().
|
2,396,632 | 2,396,669 | How To Shift Array Elements to right and replace the shifted index with string in Visual C++ | VISUAL C++ Question
Hi,
I have array of 3 elements and I want to shift its elements to the right and replace the shifted index cell with "SHIFTED" string and this should loop until all the cells has "SHIFTED" string.
For example:
int a[x]={0,1,2};
Initial index and elements Order:
[0]=0
[1]=1
[2]=2
should become in ... | As Peter mentioned in his answer, you cannot assign a string to a int. I've assumed SHIFTED to be -1. So every time you shift you bring in a -1 in the gap created.
You need two loops. The outer loops iterates N (3) times and inner loop starts at the end of the array and copies (n-1)th element to nth position:
for(int c... |
2,396,744 | 2,396,971 | QTableView has unwanted checkboxes in every cell | I'm just getting started with Qt programming, and I'm trying to make a simple tabular data layout using a QTableView control with a model class of my own creation inheriting from QAbstractTableModel. For some reason, my table view ends up looking like this:
(source: nerdland.net)
What in the heck are those things tha... | Try changing MyTableModel::data() to the following:
QVariant MyTableModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::DisplayRole)
return "foo";
else
return QVariant();
}
Probably the returned QVariant for role Qt::CheckStateRole was misunderstood by the QTableView.
|
2,397,005 | 2,397,483 | vertical text won't be bold in win32 GDI c++ | I'm trying to draw vertical text in win32 GDI api.
I call CreateFont() with 2700 for the angle and 900 for bold.
logPxlY = ::GetDeviceCaps (c->_hdc, LOGPIXELSY);
_hfont = ::CreateFont (-::MulDiv (point, logPxlY, 72),
0, angle, weight, 0, FALSE, FALSE, FALSE, 0, 0, 0, 0,
FIXED_PITCH | FF_MODERN, face);
where fa... | The font mapper can be a bit strange at times. 700 is bold, 900 is supposed to be "black". However, you probably have a Courier New Bold font file, so it can be used directly, whereas you probably do not have a Courier New Black font file, so it'll be synthesized -- probably from the normal Courier New font instead of ... |
2,397,103 | 2,397,118 | I have a text-box and I want to enter a string in language A | I have a text-box, and I want to enter a string in language A and send it to Google Translate. After Google has translated it, I want to take the new string (in language B) (after translation) and store it in some variable.
How can I do it?
| The basic idea is shown in a simple example of Language Translation like this:
google.language.translate("Hello world", "en", "es", function(result) {
if(!result.error) {
var container = document.getElementById("translation");
container.innerHTML = result.translation;
}
});
translation is the id of your te... |
2,397,297 | 2,397,593 | Iphone, callback and objective c | I am using a c++ library using callback to inform about the progress of an operation.
Everything is working fine except this:
I need to have a function in my controller to be use as a c++ callback function.
I've tried a lot of things but none of them are working.
Do you know how we can manage this kind of thing?
Thanks... | You have to define a c++-class in your .h with your callback methods, implementing the c++-interface. This class also keeps a delegate of your objC Class.
in your .m File after @end you specify the c++ methods. You may then use the delegate to perform selectors of your objC class
in .h
@interface YourObjcClass {
#ifdef... |
2,397,309 | 2,397,320 | error: '' has not been declared | I'm trying to implement a linked list but get an error when compiling:
intSLLst.cpp:38: error: ‘intSLList’ has not been declared
intSLList looks like it's been declared to me though so I'm really confused.
intSLLst.cpp
#include <iostream>
#include "intSLLst.h"
int intSLList::deleteFromHead(){
}
int main(){
}
in... | You're using a lower case i
int intSLList::deleteFromHead(){
}
should be
int IntSLList::deleteFromHead(){
}
Names in c++ are always case sensitive.
|
2,397,354 | 2,397,384 | How to prevent double inclusion of a .lib when inheriting dependencies? | I'm working to a Visual C++ 2008 project which needs two libraries (A and B), both of them are compiled using a a particular .lib (C). When I compile my project I'm asked for C again, and thus I specify it in the additional libraries. Then everything goes ok until the linking phase, where I get errors for external symb... | This sounds like you're adding two different versions of this library (Debug/Release, MT/ST etc.). Otherwise the linker would just ignore the second one.
|
2,397,578 | 2,397,637 | How to get the Executable name of a window | I try to get the name of executable name of all of my launched windows and my problem is that:
I use the method
UINT GetWindowModuleFileName(
HWND hwnd,
LPTSTR lpszFileName,
UINT cchFileNameMax);
And I don't understand why it doesn't work.
Data which I have about a window are: -HWND AND PROCESSID
The error is:
e... | The GetWindowModuleFileName function works for windows in the current process only.
You have to do the following:
Retrieve the window's process with GetWindowThreadProcessId.
Open the process with PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights using OpenProcess.
Use GetModuleFileNameEx on the process hand... |
2,397,728 | 2,397,738 | Variable accessible to all instances of a class | Let's say I have a lookup table which I'd like to make accessible to all instances of Foo. Should I make the table private static? If not, what should I do?
Basically I want a way to save just one copy of the table (so it doesn't consume extra memory for each instance of Foo) and have it available privately to all inst... | That sounds like private static to me.
|
2,397,745 | 2,397,837 | Iterator from both ends of a Vector | I have a vector of IntRect: vector.
How can I iterate from both ends of the list and stop the iterator when the iterator intersects?
vector<IntRect>::iterator itr = myVector.begin();
vector<IntRect>::reverse_iterator revItr.rbegin();
for (; /*check itr and revItr does not intersect, and itr and revItr do not end *... | if(!myVector.empty()) {
for(vector<IntRect>::iterator forwards = myVector.begin(),
backwards = myVector.end()-1;
forwards < backwards;
++forwards, --backwards) {
// do stuff
}
}
I think you need to check empty() with that implementation - suspect ... |
2,397,894 | 2,397,933 | How to have a policy class implement a virtual function? | I'm trying to design a policy-based class, where a certain interface is implemented by the policy itself, so the class derives from the policy, which itself is a template (I got this kind of thinking from Alexandrescu's book):
#include <iostream>
#include <vector>
class TestInterface {
public:
virtual void test() = ... | For this to work the policy class needs to inherit from the interface class:
class TestInterface {
public:
virtual void test() = 0;
};
template< class Interface >
class TestImpl1 : public Interface {
public:
void test() {std::cerr << "Impl1" << std::endl;}
};
template<class TestPolicy>
class Foo : public TestPol... |
2,397,984 | 4,105,123 | Undefined, unspecified and implementation-defined behavior | What is undefined behavior (UB) in C and C++? What about unspecified behavior and implementation-defined behavior? What is the difference between them?
| Undefined behavior is one of those aspects of the C and C++ language that can be surprising to programmers coming from other languages (other languages try to hide it better). Basically, it is possible to write C++ programs that do not behave in a predictable way, even though many C++ compilers will not report any err... |
2,398,031 | 2,398,817 | Calling handwritten CUDA kernel with thrust | since i needed to sort large arrays of numbers with CUDA, i came along with using thrust. So far, so good...but what when i want to call a "handwritten" kernel, having a thrust::host_vector containing the data?
My approach was (backcopy is missing):
int CUDA_CountAndAdd_Kernel(thrust::host_vector<float> *samples, thrus... | You are calling the kernel with the name of the function the call is in, not the name of the kernel - hence the parameter mismatch.
Change:
CUDA_CountAndAdd_Kernel<<<1, n>>>(dSamples_raw, dCounts_raw);
to
CUDA_CountAndAdd_Kernel_Device<<<1, n>>>(dSamples_raw, dCounts_raw);
and see what happens.
|
2,398,129 | 2,398,202 | Writing to the middle of the file (without overwriting data) | In windows is it possible through an API to write to the middle of a file without overwriting any data and without having to rewrite everything after that?
If it's possible then I believe it will obviously fragment the file; how many times can I do it before it becomes a serious problem?
If it's not possible what appro... | I'm unaware of any way to do this if the interim result you need is a flat file that can be used by other applications other than the editor. If you want a flat file to be produced, you will have to update it from the change point to the end of file, since it's really just a sequential file.
But the italics are there f... |
2,398,525 | 2,398,585 | Comparing objects with IDispatch to get main frame only (BHO) | I don't know if anyone familiar with BHO (Browser Helper Object), but an expert in c++ can help me too.
In my BHO I want to run the OnDocumentComplete() function only on the main frame - the first container and not all the Iframes inside the current page. (an alternative is to put some code only when this is the main f... | What jeffdav suggested is, to test wether the pDisp supports IWebBrowser2 via QueryInterface(), and if so, to check wether it is the same object as the one you stored in SetSite().
The QueryInterface() rules only require that a QI for IUnknown always results in the same pointer value, so you have to additionally QI to ... |
2,398,682 | 2,398,695 | Multiple constructors definitions with same name but different signatures (C++) | With the following code, I keep getting error C2535 when I compile. It's complaining that a member function already defined or declared.
Rationnel.h
...
class Rationnel
{
public:
Rationnel(int); //Constructor
Rationnel(int,int); //Constructor
void add(const Rationnel);
...
Rationnel.cpp
...
//Constructor
Rationnel:... | If you write Rationnel (5), how do you know which one of the following will be called ? Both can be used so an error occurs.
Rationnel::Rationnel(int n = 1)
Rationnel::Rationnel(int n = 1, int d = 1)
|
2,398,992 | 2,399,005 | How to access member with same name in the inheritance | I have a question about how to access the member with the same name with inheritance. For example,
class Base {
public:
int i;
};
class Derived1 : public Base {
public:
int i;
// how to access the i in the base class here?
};
int main() {
Derived1 d;
cout<<d.i; //which ... | d.i in your example refers to the i in the derived class.
You can refer to the base class i by qualifying it with the base class name:
d.Base::i
In general, it's a bad idea to have derived classes with members having the same name as members in base classes.
|
2,399,101 | 2,399,114 | how to use Application window? c++ | i have been programming for sometime but all of my programming books have not really showed me how to use the Application window i always use the console window. i was looking at the Application project and i noticed that it has a .cpp file that is the main file but how do work with the window? i have tryed googleing i... | There are many many GUI frameworks, so this question has hundreds of possible answers.
If you are developing on Windows you have the choice of many frameworks including:
Straight Win32 API
MFC
Qt
WinForms (.Net)
WPF (.Net)
Silverlight (.Net)
Depending on what you want to do, and on which platform you will have to s... |
2,399,269 | 2,399,283 | Checking for underflow/overflow in C++? | Is there a general way to check for an overflow or an underflow of a given data type (uint32, int etc.)?
I am doing something like this:
uint32 a,b,c;
... //initialize a,b,c
if(b < c) {
a -= (c - b)
}
When I print a after some iterations, it displays a large number like: 4294963846.
| To check for over/underflow in arithmetic check the result compared to the original values.
uint32 a,b;
//assign values
uint32 result = a + b;
if (result < a) {
//Overflow
}
For your specific the check would be:
if (a > (c-b)) {
//Underflow
}
|
2,399,330 | 2,399,346 | String vectors not working as expected with newline and iterators? (C++) | I have a text file made of 3 lines:
Line 1
Line 3
(Line 1, a blank line, and Line 3)
vector<string> text;
vector<string>::iterator it;
ifstream file("test.txt");
string str;
while (getline(file, str))
{
if (str.length() == 0)
str = "\n";
// since getline discards the newline character, replacing blank string... | Wasn't? Actually, it was! The reason you have a newline after Line 1 is exactly that empty string with newline in it and nothing else. If not for that second line, you'd see Line 1Line 3 as output. (You said it yourself: getline discards newline characters.)
Apparently, the way I understand your intent, you were suppos... |
2,399,375 | 2,399,860 | Returning ifstream in a function | Here's probably a very noobish question for you: How (if at all possible) can I return an ifstream from a function?
Basically, I need to obtain the filename of a database from the user, and if the database with that filename does not exist, then I need to create that file for the user. I know how to do that, but only b... | bool checkFileExistence(const string& filename)
{
ifstream f(filename.c_str());
return f.is_open();
}
string getFileName()
{
string filename;
cout << "Please enter in the name of the file you'd like to open: ";
cin >> filename;
return filename;
}
void getFile(string filename, /*out*/ ifstream&... |
2,399,377 | 2,399,393 | Examples for Winsock? | What do you guys recommend for a resource for winsock?
I have an assignment that we have only have a few days to do that needs to send a simple packet using UDP (and receive the same type of packet).
I am fairly familiar with C# sockets but nothing with C++.
Any tips or resources?
| Some are as follows:
Winsock Programming
Winsock Networking Tutorial (C++)
WinSock Tutorial
|
2,399,619 | 2,399,652 | Should a C++ constructor that interfaces with hardware do real work? |
Possible Duplicate:
How much work should be done in a constructor?
I'm strugging with some advice I have in the back of my mind but for which I can't remember the reasoning.
I seem to remember at some point reading some advice (can't remember the source) that C++ constructors should not do real work. Rather, they s... | I remember that Scott Meyers in More Effective C++ recommends against having a superfluous default constructor. In that article, he also touched on using methods liked Init() to 'create' the objects. Basically, you have introduced an extra step which places the responsibility on the client of the class. Also, if you wa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.