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 |
|---|---|---|---|---|
3,638,480 | 3,641,934 | Easiest porting path from OpenGL Performer? | I have an existing program written in OpenGL Performer. Because new licences aren't available and the existing code base is old and poorly documented I was thinking about going through, fixing up the code (eliminating warnings and other bad programming practices). As part of this process I was thinking about switchin... | Most people use OpenSceneGraph, which has some heritage (developers) from Performer. My recommendation is to check the osg mailing list archives for your question, it has been discussed there.
|
3,638,520 | 3,638,554 | C++ Access a member of a class from the pointer of a vector of the class | Sorry but this is really confusing me and I know the answer is staring at me in the face and I can't figure it out. Could someone take a look? Its for a Airline Reservation System school project.
This function takes in the Flight Number, capacity, the count of the number of
flights, and the vector containing all of the... | Argument v is passed to your function as a pointer to vector. If you then use the [] operator, it thinks, just as in C, that v is a pointer to an array of vectors, so v[i] is actually still a vector.
What you should do is this:
(*v)[i].getNumber();
|
3,638,628 | 3,638,769 | Trouble with header files & c++ files | I'm creating a minimal circle-circle physics engine in a static library, and I've came across a problem. I have a header file for object manipulation, one of the variables is the objects position. The position variable is declared in bpObject.h, and I have a void function, SetPosition(), that accesses the current pos... | I'm guessing you don't actually want all those 'static's in there, is your first problem (as it stands, you pretty much can only access a single object)
Once you get rid of those, you can implement SetPosition in your source file by:
namespace bp {
void Object::SetPosition(single X, single Y) {
position[0] ... |
3,638,788 | 3,653,295 | Best way to initialize class's inherited member var of type std::array? | Entity has a member var of type std::array. Student inherits from Entity, and will need to initialize the std::array member var it inherited. Below is the code I'm using to do this, but it involves casting a brace-enclosed list to std::array. I'm not sure this is the correct or optimal way to do this. Using a brace... | There are two options, but one relies on runtime size verification. Note the latter in my example is equivalent to a cast. What is wrong with casting?
#include <cassert>
#include <algorithm>
#include <array>
#include <initializer_list>
#include <iostream>
struct A {
typedef std::array<char const*, 3> T;
T data_;... |
3,638,800 | 3,638,839 | Weird outputs with simple Arithmetic C++ | If I give this program a string as in input it gives me some very strange outputs. How do I go about handling this? I'd like it to simply state that there was an error on the consul.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
cout << endl;
cout << "Homework (out of 70 pts): ... | When you enter a value that cin isn't expecting, such as a string instead of a number, nothing will be read into your variable and cin will set an error flag that will prevent any further input. See my answer to another question on the very same topic.
|
3,638,895 | 3,638,921 | Is return atomic and should I use temporary in getter to be thread safe? | Is it necessary to use a temporary here to be thread-safe?
int getVal() {
this->_mutex.lock();
int result = this->_val;
this->_mutex.unlock();
return result;
}
I'll give you disassembly of simple RAII test function
int test()
{
RAIITest raii; //let's say it's a scoped lock
return ... | If access to this->_val is synchronized by this->_mutex, then you don't have a choice the way the code is written currently. You need to read this->_val before you unlock the mutex and you have to unlock the mutex before you return. The result variable is necessary to get this order of actions.
If you use a lock_guar... |
3,638,993 | 3,639,020 | class method error in c++ | I am getting an error when I declare a class:
#include <iostream>
#include "testing/test.h"
#include <string>
using namespace std;
int main(void)
{
test links;
string content="this is an string";
links.getcont(content);
}
test.h
#ifndef TEST_H_
#define TEST_H_
#include<string>
using namespace std;
cla... | Well , in your test.cpp file replace the getcont function for this
string test::getcont(string content){ //code here; }
The problem is that you are not saying that getcont is a member function of the test class.
Also, consider making it a const function and passing a const string reference
string
test::getcont( const ... |
3,638,996 | 3,639,043 | Is there a way in C++ to render a class' interface private to all classes except a few? | I am writing a B-link tree and its attendant sub classes like a data page class and a node class etc.
I was wondering is there a way to protect the public interfaces of the nodes and pages such that only the b-link tree class itself can access them, WITHOUT simultaneously exposing the private methods of the pages and n... | Off the top of my head, you could do something like:
class FooAdapter;
class Foo
{
private:
void funcToExpose();
void funcToHide();
friend FooAdapter;
};
class FooAdapter
{
private:
Foo foo;
void funcToExpose() { foo.funcToExpose(); }
friend SomeFriend;
};
(Not compiled or tested, but ... |
3,639,013 | 3,639,131 | C++ output with webpages | Is it possible to have a c++ program like this...
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
And have it's output on a webpage like this...
<html>
<head>
<title>C++</title>
</head>
<body>
<div src = "cpp.exe"></div>
</body>
</html>
| Not in the HTML per se, no. But if your server supports it (e.g., Apache), you can use a server-side include to execute a program and include the output on the web page.
Your HTML page would look like this:
<html>
<head>
<title>C++</title>
</head>
<body>
<div><!--#exec cmd="cpp.exe" --></div>
</body>
<... |
3,639,099 | 3,639,227 | C++ Extern / Multiple Definitions | I am trying to interface to Ada in C++ using externs. What is the difference between these two implementations?
Implementation A
namespace Ada
{
extern "C"
{
int getNumber();
int index;
int value;
}
}
Implementation B
namespace Ada
{
extern "C"
{
int getNumber();
... | extern "C" only conveys the linking conventions to use for the code within the extern "C" block. Anything in that block will be linked against as if it were pure c. Confusingly, extern int is totally different. It means that you promise there is an actual int named index and an actual int named value somewhere, but ... |
3,639,112 | 3,639,287 | Advantages of implementing a front-end over linking against a library | I want to write a C++ program that plays MP3. Among available MP3 decoding libraries, I chose mpg123.
I noticed that, besides being able to link against libmpg123 and make the necessary function calls in my code, the library includes a back-end/front-end interface that enables me to communicate with it's executable, an... | Most of the advantages comes from process separation between your executable and the library executable:
Increased safety & security: if the library is crashing, this will not crash your application.
Implicit multi-processing: since both are running on separate processes, this is almost for free.
Predisposition to ne... |
3,639,340 | 3,639,358 | typedef inheritance from a pure abstract base | Edit: Found duplicate
I've whittled down some problem code to the simplest working case to illustrate the following: my typedef in a pure abstract base class is not being inherited by the derived class. In the code below I'd like to inherit the system_t typedef into the ConcreteTemplateMethod:
#include <iostream>
//... | you should do
typedef typename TemplateMethod<X>::system_t system_t;
to "inherit" typedef. typedef is not automatically inherited (if compiler is compliant).
if you look through stack overflow, there will be duplicate of this question somewhere.
|
3,639,347 | 3,639,543 | Can a std::map value object contain a reference to the corresponding key? | Essentially, what I'd like is for the value object to maintain a reference to the corresponding key object, because there's some useful information in there, which would be nice to access via the value object.
What I'm attempting to do may just not make sense, but consider the following:
class key
{
// ... Various ... | You could put the reference in place after insertion, but you'd have to make it a pointer:
std::map<key, value>::iterator iter = m.insert(std::make_pair(k, v)).first;
iter->second.setValue(&iter->first);
|
3,639,476 | 3,642,120 | Instantiating template with a variably modified type | One of my class' member method take as an argument of enumeration type: it produces different side effects for different enum. I was wondering whether it's possible to use template as a lookup table, two possible solutions came up to my mind, but none of them seems to work:
//// 1 ////
class A {
public:
enum... | You have to make the AEnum arg a template argument to do_sth:
template<AEnum e, typename T>
void do_sth(T t) { ... }
...and call it as a.do_sth<A::first>(0).
Alternatively, you could write separate functions (do_sth_integral, do_sth_container, ...), or, if there is only one correct course of action for a particu... |
3,639,480 | 3,639,521 | whats wrong with my c++ boost regex function? | include
#include <algorithm>
#include<boost/algorithm/string.hpp>
#include<boost/regex.hpp>
using namespace std;
using namespace boost;
string _getBasehtttp(string url)
{
regex exrp( "^(?:http://)?([^\\/]+)(.*)$" );
match_results<string::const_iterator> what;
if( regex_search( url, ... | ^(?:http://)?([^\\/]+)(.*)$
the ? at the end of (?:http://)? means that bit is optional
this ([^\\/]+) captures and matches anything that is not a \ or /
this (.*) captures everything else up to the end of the line
Perhaps your after something more like
^(?:https?://)([^\\/]+)(.*)$
might like to consider full URL sy... |
3,639,518 | 3,639,535 | Help with ifstream in programming test | I recently did a programming test in which there was a ifstream section which I could not solve. Since then I have been trying to solve the problem in my free time to no avail.
The problem is basically to read from a binary file and extract the information there.
Here is the file format:
-----------------------------... | When you say you are having problems, what output are you seeing, and how is it different from what you expect to see?
Some general advice: For one thing, if you are going to be reading in binary data, try opening the stream in binary mode.
Also, your first read operation stores data into an int, but the length read wa... |
3,639,533 | 3,639,563 | operator overloading | I've created a class myString and I'm trying to run the following code:
class myString{
char* str;
int len;
public:
myString(char* str1 = " "){
len = strlen(str1);
str = new char[len+1];
strcpy(str, str1);
};
int getLen() const {
return len;
};
char* getStr... | For the following, you need a copy constructor. It does not use the assignment operator function.
myString g = s;
Edit
For the linker error - I can't help you with that. Rather than guessing at what operator<< that line calls, I will just give up on this because you haven't provided the code. In normal C++ code, there... |
3,639,645 | 3,639,689 | Finding object under mouse | I'm developing a game that basically has its entire terrain made out of AABB boxes. I know the verticies, minimum, and maximum of each box. I also set up my camera like this:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(Camera.rotx,1,0,0);
glRotatef(Camera.roty,0,1,0);
glRotatef(Camera.rotz,0,0,1);
glTrans... | This is usually referred to as 'picking' This here looks like a good gl based link
If that is tldr, then a basic algorithm you could use
sort objects by z (or keep them sorted by z, or depth buffer tricks etc)
iterate and do a bounds test, stopping when you hit the first one.
|
3,639,741 | 3,639,797 | How can I merge two STL maps? | How can I merge two STL maps into one? They both have the same key and value types (map<string, string>). If there is an overlap of the keys, I would like to give preference to one of the maps.
| Assuming you want to preserve the elements in mapA, and merge elements in mapB for which there is no key in mapA:
mapA.insert(mapB.begin(), mapB.end())
will do what you want, I think.
(EDIT: If you are using C++17 or newer, consider this answer: https://stackoverflow.com/a/56594603/118150)
Working example:
#include <i... |
3,639,744 | 3,642,986 | Least Recently Used cache using C++ | I am trying to implement LRU Cache using C++ . I would like to know what is the best design for implementing them. I know LRU should provide find(), add an element and remove an element. The remove should remove the LRU element. what is the best ADTs to implement this
For ex: If I use a map with element as value and ti... | One major issue with LRU caches is that there is little "const" operations, most will change the underlying representation (if only because they bump the element accessed).
This is of course very inconvenient, because it means it's not a traditional STL container, and therefore any idea of exhibiting iterators is quite... |
3,639,760 | 3,640,014 | SSL_accept() throws "Invalid argument" error | I'm attempting to create a client/server program, but I'm finding some difficulty continuing with the unfortunately sparse amount of OpenSSL documentation.
My issue:
SSL_accept throws an "Invalid Argument" upon executing the following code (simplified):
SSL* ssl = SSL_new(ctx); // ctx is created earlier
SSL_set_fd(ssl,... | Like you, I have had a difficult time with the dearth of documentation. So I can't say whether or not the set_fd calls are wrong or right, but I got it working without those. The sequence of calls that I have used successfully is:
BIO *sbio = BIO_new_socket( socket, BIO_NOCLOSE );
SSL* ssl = SSL_new(ctx);
SSL_set_bi... |
3,640,017 | 3,640,060 | Two really similar classes in C++ with only one different method: how to implement? | I have two classes that are almost identical, besides one method. The classes have the same data part and all the member functions but one:
class A {
private:
double data;
public:
double calc(){
return data*data;
}
double especific(){
return 2.0*data;
}
}
and the second class is identical, beside... | This sounds like a job for the Strategy pattern. It can be implemented in this case as a template parameter. Often it would be implemented as a constructor parameter or a setter method on the class, but that would require inheritance to work properly.
In this case, something like:
template <class SpecificStrategy>
cl... |
3,640,063 | 3,640,149 | Iterate through Enums in C++ | C++ enum question.
So I have a list of files, and their IDs that I need to iterate over, and do stuff to. Most of the stuff is the same, but there are a few file-specific things that need to be done. I tried putting the file IDs in an enum, and iterating over that. Howver, the fileIDs are non contiguous, and jump arou... | I guess the low-tech answer might be to skip the enum, and just create a static array:
#define ARRAYSIZE(a) (sizeof(a)/sizeof(a[0]))
int FILE_ENUM[] = { 0x1111, 0x8000, 0x75, 0x120 };
for(int i = 0; i < ARRAYSIZE(FILE_ENUM); i++) {
currentFile = myEnum[i];
// do stuff
}
TJ
|
3,640,095 | 3,640,222 | GDB can't access mmap()'d kernel allocated memory? | I'm running into an issue with GDB and some buffers allocated in kernel space. The buffers are allocated by a kernel module that is supposed to allocate contiguous blocks of memory, and then memory mapped into userspace via a mmap() call. GDB, however, can't seem to access these blocks at any time. For example, afte... | About why gdb cannot access the memory you want, I believe Linux does not make I/O memory accessible via ptrace().
According to cmemk.c (which I found in linuxutils_2_25.tar.gz), mmap() does indeed set the VM_IO flag on the memory in question.
To access this memory from gdb, add a function to your program that reads th... |
3,640,103 | 3,640,117 | Interesting Console Program for C++ beginners | I’m teaching an entry-level C++ programming class. We only use iostream in the class (No GUI). It seems like students are not so excited to printout strings and numbers to their console. (Most students even never used the console before.) It is hard to motivate or convey the excitement of programming by showing strings... | When I taught an undergrad intro course, we did the Game of Fifteen in straight C as the third homework project. It's pretty well scoped, and it's a game, so there's some inherent motivation there.
|
3,640,307 | 3,640,327 | c++ pass by reference : two level deep function calls | I have code similar to this in c++. It aborts when i try to run it. Would this type of code work ?
In the main function :
type* a = something
type* b = something
func1(a,b);
func1 declaration:
void func1(type* &a, type* &b){
func2(a,b);
// do something
}
func2 is as follows
void func2(type* &a, type* &b){
/... | Yes, it should if you modify 'a or 'b in 'func1 or 'func2.
|
3,640,308 | 3,640,402 | C++ String to Double parsing with exceptions? | In java, if I wanted to create some application which could receive both doubles and strings as appropriate input, I would probably do the following:
String input = getInput();//
try {
double foo = Double.valueOf(input);
//Do stuff with foo here
} catch (NumberFormatException e) {
//Do other validation w... | Exceptions should be reserved for exceptional situations. While you certainly can abuse them like this, it's a lousy idea -- clearly you're pretty much expecting things other than doubles, so treating it as an exception doesn't make any real sense.
The only real question is the exact circumstance under which you want t... |
3,640,337 | 3,640,370 | C++: scope of for loop? | #include <iostream>
using namespace std;
int main() {
int i;
for(i=0; i <= 11; i+=3)
cout << i;
cout << endl << i << endl;
}
output is: 0 3 6 and 9 and then once it exits the loop its 12.
The addresses of i inside the loop and out appear the same
What I need to know is: Is the i inside the for loo... | It's de same 'i' var
#include <iostream>
using namespace std;
int i = 0;
int main() {
int i;
for(i=0; i <= 11; i+=3)
cout << i;
cout << endl << i << endl;
cout << endl << ::i << endl;
}
i is 12
::i is 0
|
3,640,470 | 3,640,481 | Do I include how to use the GPL in COPYING? | I'm coding a program and I have the entire GPLv3 license from http://www.gnu.org/licenses/gpl-3.0.txt in a COPYING text file. However, at the end, there's a section on 'How to Apply These Terms to Your New Programs'. Do I keep this in COPYING? Is it part of the GPLv3 or a reminder on how to use it?
| It's part of the GPL. See the FAQ.
|
3,640,563 | 3,640,584 | C++ composition with iterator | I'll try and keep my sample code very straightforward, but it may have errors as I'm typing it on the spot.
I have a class named Phone.
class Phone
{
public:
Phone(std::string manufacturer, std::string model, std::vector<Feature> features);
private:
std::vector<Features> features;
std::string model;
std::str... | In your case I would go for better names first:
typedef std::vector<Feature> Features;
Features::iterator features_begin();
Features::iterator features_end();
Features::const_iterator features_begin() const;
Features::const_iterator features_end() const;
Examples:
1)
// Note: you'll need to define an operator<< for ... |
3,640,602 | 3,772,516 | Omni light in OpenGL? | I want to basically create a light that will make it so that its very bright around the player then gets progressively darker. Sort of like a fire torch. How can I get this effect? I can only seem to get an ambient light? How can it follow the camera?
Thanks
| It sounds like what you are looking for is known as a point light.
If you are using fixed function, the following tutorial may be use to you:
http://jerome.jouvie.free.fr/OpenGl/Tutorials/Tutorial13.php
Just note that this tutorial appears to use jogl with Java, but the conversion to C++ should be relatively straightfo... |
3,640,630 | 3,643,210 | Cannot implement meter in windows API | I am using the windows API (in C++) to create a windows application.
Now, I have a progress bar which I want to show like a meter. A meter is blue and has no animation. I cannot figure out how to implement this, and if I have to, I will just settle for the usual green progress bar.
Please help.
EDIT: At least, is it po... | You can draw this style of progress bar with DrawThemeBackground(). You'll find the theme name, part and state numbers in my answer in this thread.
|
3,640,633 | 5,610,042 | SetConsoleCtrlHandler routine issue | I'm writting a console application in C++.
I use SetConsoleCtrlHandler to trap close and CTRL+C button. This allows for all my threads to stop and exit properly.
One of the thread performs some saving that require some time to complete and I have some code to wait in the console crtl handle routine. MSDN specify that a... | It looks like you can no longer ignore close requests on Windows 7.
You do get the CTRL_CLOSE_EVENT event though, and from that moment on, you get 10 seconds to do whatever you need to do before it auto-closes. So you can either do whatever work you need to do in the handler or set a global flag.
case CTRL_CLOSE_EVENT:... |
3,640,663 | 3,640,671 | std::sort and std::unique problem with a struct | The following code:
#include <vector>
#include <algorithm>
struct myStructDim
{
int nId;
int dwHeight;
int dwWidth;
};
void main()
{
::std::vector<myStructDim> m_vec_dim;
::std::sort(m_vec_dim.begin(), m_vec_dim.end());
m_vec_dim.erase(
::std::unique(m_vec_dim.begin()... | You need comparison operators to express the "less-than" and "equality" relationships. Defining stand-alone boolean functions operator< and operator== that take two arguments, each const myStructDim&, and perform the comparison exactly the way you require, is probably simpler than defining then as methods within the s... |
3,640,721 | 3,640,745 | C++ game trainer process monitoring | I am going to open game process from my trainer app and write some values to memory. I have no problems with opening a process and writing a value to memory. But I can't realize how to monitor the game process availability. For example I opened a running process, user closed it and opened again. How can I track this in... | You can use the GetExitCodeProcess function to see if the handle you have points to a running process.
DWORD exitCode=0;
::GetExitCodeProcess(hProcess, &exitCode);
if (exitCode==STILL_ACTIVE)
; //process is alive
MSDN link
|
3,640,739 | 3,640,882 | how can I check if an object exists in C++ | I am trying to write a function that will check if an object exists:
bool UnloadingBay::isEmpty() {
bool isEmpty = true;
if(this->unloadingShip != NULL) {
isEmpty = false;
}
return isEmpty;
}
I am pretty new to C++ and not sure if my Java background is confusing something, but the compiler give... | It sounds like you may need a primer on the concept of a "variable" in C++.
In C++ every variable's lifetime is tied to it's encompassing scope. The simplest example of this is a function's local variables:
void foo() // foo scope begins
{
UnloadingShip anUnloadingShip; // constructed with default constructor
... |
3,640,852 | 3,640,920 | Difference between file.is_open() and file.fail() | Initialization of file:
ifstream file("filename.txt");
What's is the difference between if ( file.is_open() ) and if (! file.fail() ) ?
What Should I use to make sure if the file is ready for I/O ?
We assume that variable file contains a object of a file stream.
| is_open() returns true if a previous call to open() succeeded and there has been no intervening call to close(). In your example, open() is called from the constructor.
fail() returns true if failbit or badbit is set in rdstate.
failbit generally means that a conversion failed. For example, you tried to read an integer... |
3,641,157 | 3,641,209 | Is there any cleaner way to do this? (Prepared SQL queries in Qt C++) | I'm using QSqlQuery::prepare() and ::addBindValue() for my queries in a Qt project I'm working on. There's a lot of repeated code and though I think that's the "right" way, I wanted to make sure. Perhaps someone has alternative ideas? Example:
QSqlQuery newQuery;
newQuery.prepare("INSERT INTO table "
"... | In relation to your sub-question on SQL injection, that combination of ::prepare and ::addBindValue does indeed fully protect against it. This is because the bound values are never parsed by the SQL engine; they're just values that slot in after compilation (the preparation step) and before execution.
Of course, you ha... |
3,641,191 | 3,641,211 | Why is it important to call destructors at program termination? | If you check this link http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=107
it's written:
"For example, the abort() and exit() library functions are never to be used in an object-oriented environment—even during debugging—because they don't invoke objects' destructors before program termination."
Why do... | Destructors can, and often do, other operations besides freeing memory and/or resources. They are often used to make certain other guarantees such as user data is written to a file or non-process specific resources are in a known state. The OS won't do these types of operations on exit.
That being said, any program w... |
3,641,391 | 3,643,128 | What Qt widgets to use to draw a "game-of-life"-like application? | For an experiment, I'd like to create a simple graphical application.
My goal isn't complex: I just need to draw single pixels or lines of different colors, and refresh the view regularly. Something like Conway's Game of Life.
I'm used to work with Qt but never for this kind of task.
What widgets/objects should I use t... | I'd suggest the "graphics view" framework
http://doc.trolltech.com/4.6/graphicsview.html
It is extremely powerful, much more than you need it to be.
Simply, for the creatures in the game of life, create graphics items and set the coordinates for them. Nothing more.
|
3,641,657 | 3,641,728 | address of c++ template function | Why does this fail to compile? (g++-4.5)
template < typename U >
static void h () {
}
int main () {
auto p = &h<int>; // error: p has incomplete type
}
EDIT: Here is a work-around:
template < typename U >
static void h () {
}
int main () {
typedef decltype (&h<int>) D;
D p = &h<int>; // works
}
| In C++0x this is guaranteed to work. However in C++03 this wasn't working (the initializer part, that is) and some compilers apparently don't support it yet.
Furthermore, I remember that the C++0x wording is not clear what happens with &h<int> when it is an argument to a function template and the corresponding paramet... |
3,641,672 | 3,641,674 | C++ re-throw an exception caught by | how can I re-throw an exception caught by
catch(...)
block?
| throw with no operand rethrows the "current exception".
|
3,641,737 | 3,641,809 | C++ get description of an exception caught in catch(...) block | can I get description of an exception caught by
catch(...)
block? something like .what() of std::exception.
| There is one trick you might be able to use:
catch(...) {
handle_exception();
}
void handle_exception() {
try {
throw;
} catch (const std::exception &e) {
std::cout << e.what() << "\n";
} catch (const int i) {
std::cout << i << "\n";
} catch (const long l) {
std::cou... |
3,642,157 | 3,642,198 | array index and address return same value | #include<stdio.h>
int main(void) {
int a[3] = {1,2,3};
printf("\n\t %u %u %u \t\n",a,&a,&a+1);
return 0;
}
Now i don't get why a and &a return the same value, what is the reasoning and the practical application behind it? Also what is the type of &a and could i also do &(&a) ?
|
Now i don't get why a and &a return the same value, what is the reasoning
a is the name of the array that decays to pointer to the first element of the array.
&a is nothing but the address of the array itself, although a and &a print the same value their types are different.
Also what is the type of &a?
Pointer to ... |
3,642,161 | 3,642,194 | array is of same type and linked list is of different type | In an interview when I ask the recent graduate students that what is the difference between array and linked list, the first answer normally is "In array you have same data types and in the linked list you can have different data types." When I told them to explain they will say that they have just read it somewhere or... | It is possible that these students have been taught arrays with statically typed languages and linked lists with dynamically typed languages, so they have come to identify the data structure with the paradigm of the language they were using it in.
For instance, they may have used arrays in C and linked lists in Scheme.... |
3,642,370 | 3,642,419 | Using ptrace to write a program supervisor in userspace | I'll looking for advice/resources to write a program that can intercept system calls from a programm to supervise it's filesystem, network, etc access.
The aim of this is to write an online judge, so that untrusted code can be run safely on a server.
This is on linux, and I would prefer to write C++ or a scripting lang... | This looks like a good place to start.
http://www.linuxjournal.com/article/6100
|
3,642,592 | 3,642,602 | converting string to int | hello i have a problem i am trying to convert a string like "12314234" to int
so i will get the first number in the string.
from the example of string that is shown above i want to get '1' in int.
i tried :
string line = "12314234";
int command = line.at(0);
but it puts inside command the ascii value of 1 and not the ... | To convert a numerical character ('0' – '9') to its corresponding value, just substract the ASCII code of '0' from the result.
int command = line.at(0) - '0';
|
3,642,683 | 3,642,754 | boost problem in windows 7 | I have written the following code
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/system/windows_error.hpp>
using namespace boost::system;
int main(){
boost::asio::io_service io;
boost::asio::deadline_timer t(i... | Ok, for MSVC++ 2010
Under Project Properties, goto
Configuration Properties -> Linker -> General -> Additional Library Directories and add there the path to the *.lib file (For example: C:\boost_1_41_0\stage\lib)
|
3,642,700 | 3,642,725 | Vector addition operation | I am trying to add two Vectors below is the code snippet :-
#include <iostream>
#include <vector>
using namespace std;
int main()
{
unsigned int i = 0;
vector <float> v1;
vector <float> v2;
vector <float> v3;
cout << "Filling the Numbers\n";
for (i=5;i < 125 ; i = i +... | This line doesn't work, because there's no v3[i] allocated:
v3[i] = v1[i] + v2[i];
You have two choices, either use 'push_back'
v3.push_back( v1[i] + v2[i] );
Or resize the array to the given size before hand:
v3.resize( v1.size() );
If you push_back, it will be nice to preallocate the space anyway:
v3.reserve( v1.... |
3,642,840 | 3,642,857 | How can I find the most common number in an input? | This is a very abstracted explanation of what I'm doing:
Say I have a text file full of numbers separated by newlines. Right now, I take these numbers and put them in a map<int, int>, where the key is the number, and the value is the frequency.
My end goal is a list of numbers sorted by frequency. How can I go about do... | Once you've built the frequency map, copy its pairs to a std::vector<std::pair<int, int> > then std::sort the latter with the 3-args version of std::sort, which takes the comparator as the third arg; as a comparator, you can use one that compares the .second fields of the pairs first, and the .first ones (if you want) ... |
3,642,868 | 3,642,904 | How to put Char** into _stprintf | I have this code. I would like to put argv[1] as prefix to fileName. How do I do that?
int _tmain(int argc, char** argv)
{
...
_stprintf(fileName, _T("%04d-%02d-%02d-%02d-%02d-%02d-%03d.jpeg"), lt.wYear, lt.wMonth, lt.wDay, lt.wHour, lt.wMinute, lt.wSecond, lt.wMilliseconds);
| _stprintf(fileName, _T("%s-%04d-%02d-%02d-%02d-%02d-%02d-%03d.jpeg"), argv[1], lt.wYear, lt.wMonth, lt.wDay, lt.wHour, lt.wMinute, lt.wSecond, lt.wMilliseconds);
That will do what you want, but since you're using C++ you would be best to use a stringstream instead.
#include <stringstream>
int main(int argc, char** ar... |
3,642,903 | 3,642,914 | Why can't this C++ template code be compiled? | This is some sample code copied from The C++ Programming Language chapter 17 as below. When I compile it with Visual Studio 2008, it keeps giving me this error:
warning C4346: 'HashMap<Key,T,H,EQ,A>::mapped_type' : dependent name is not a type
1> prefix with 'typename' to indicate a type
Does anyone have any ide... | Change
HashMap<Key,T,H,EQ,A>::mapped_type & HashMap<Key,T,H,EQ,A>::operator []
to
typename HashMap<Key,T,H,EQ,A>::mapped_type & HashMap<Key,T,H,EQ,A>::operator []
as your error already suggests. The compiler cannot deduce on it's own that mapped_type is a typedef inside a class template.
|
3,643,131 | 3,643,158 | Using class type in switch statement: is it better than using typeid operator? | I saw below thing about switch statement in c++ standard $6.4.2.
Switch statement can take a condition.
The condition shall be of integral type, enumeration type, or of a class type for which a single conversion function to
integral or enumeration type exists (12.3). If the condition is of class type, the condition ... | Where did you get the idea that "string comparison has to be performed"? In order to determine if two type_info objects designate the same type, you need to compare these type_info objects directly, as in typeid(obj) == typeid(Test).
In fact, you cannot do the same things by comparing the strings returned by type_info... |
3,643,163 | 3,643,183 | enum flags with name | I'm going to use enum flags for options to initialize my class. The enum is:
namespace MCXJS
{
enum VARPARAM
{
STATIC = 1,
CONST = 2
}
//other things
}
If I'm right, in this case, to check for STATIC I need to do this:
if (param & MCXJS::VARPARAM::STATIC) //...
I know to do it this wa... | Huh? You don't need to prefix it with the enumeration name. That's only needed for C++0x enum class scoped enumerations.
|
3,643,220 | 3,643,521 | I need a C++ interface to S4s server | Does anyone have a C++ Object interface for the S4 server?
| using gSoap, you can generate header and support code from the provided wsdl
see this how-to for some sample code.
But what the point of the service, it's like copying to /dev/null in my opinion
|
3,643,224 | 3,643,243 | C++ Forward Declaring a class? | In a .h if I have:
#pragma once
#include <xxxx.h>
#include "yyyy.h"
class AAAAAA;
class BBBBBB;
class ZZZZZZ
{
public:
// etc
};
using class AAAAAA; is forward declaring a class right?
Why would one do this?
Is it needed?
What are the benefits? Drawbacks?
|
Why would one do this?
Because the compiler only knows names that have been declared. So if you want to use a class, you have to declare it. But if its definition depends on its user, a forward declaration can suffice if the user doesn't depend on the definitin of the class in turn, but just on its declaration (= nam... |
3,643,311 | 3,643,643 | A tool to tell you what source files are needed in a C++ project? | I am porting a large, messy, 10 year old cold base in C++ from Metrowerks on OS X to XCode. There are so many files and all the other people that touched this over the years are gone. Nobody know what files are actually needed and which are just cruft.
Is there any tool that I could run and have it produce a list of wh... | You could run doxygen on your project and have it generate inheritance diagrams for your classes. It can also generate caller graphs to help you find dead code.
|
3,643,379 | 3,643,394 | Removing volatile nature using const_cast | I heard that volatile nature of a variable can be removed using const_cast operator.
In which scenarios we need to remove volatile nature of a variable ?
are there any good use cases ?
Is it dangerours operation, because we declared it as volatile thinking that it would be modified by external factors and removing vola... | The moment you do that, behavior is undefined. Note that removing volatile from an expression that really refers to a non-volatile variable and removing volatile from an expression that refers to a volatile variable are different. The latter thing is what you asked about, and it causes undefined behavior. The Standard ... |
3,643,441 | 3,643,511 | Best C++ compiler and options for windows build, regarding application speed? | I am making a game for windows, mac and GNU, I can built it on windows already with MSVC and MingW...
But I am not finding good information regarding how much compilers optmize.
So what compiler, and options on that compiler, I can use to make my Windows version blazing fast?
Currently the profilers are showing some w... | First of all, don't expect compiler optimizations to make a huge difference. You can rarely expect more than a 15 or possibly 20% difference between compilers (as long as you don't try to compare one with all optimizations turn on to another with optimization completely disabled).
That said, the best (especially for F.... |
3,643,548 | 3,643,557 | c++ calling non-default constructor as member | let's say i have a class A and a class B. B is used as a member in A. B does not have a default constructor but one that requires a parameter.
class B {
B(int i) {}
};
class A {
B m_B;
A()
{
m_B(17); //this gives an error
}
};
how can i still use B as a member in A?
| Use initialization list.
class B {
public:
B(int i) {}
};
class A {
B m_B;
public:
A() : m_B(17) {}
};
BTW, to reset m_B somewhere outside of the constructor, the correct syntax is:
m_B = B(17);
|
3,643,644 | 3,643,706 | Mixing assembler code with c/c++ | Why is assembly language code often needed along with C/C++ ?
What can't be done in C/C++, which is possible when assembly language code is mixed?
I have some source code of some 3D computer games. There are a lot of assembler code in use.
|
Why is assembly language code often
needed along with C/C++ ?
Competitive advantage. Like, if you are writing software for the (soon-to-be) #1 gaming company in the world.
What can't be done in C/C++, which is
possible when assembly language code
is mixed?
Nothing, unless some absolute performance level is ne... |
3,643,681 | 3,643,698 | How do flags work in C? | Recently I have come across several examples of "flags" in C and C++, and I don't quite understand how they work. After looking at some source code I noticed that often flag values are defined in hexadecimal such as the following:
FLAG1 = 0x00000001,
FLAG2 = 0x00000010,
My intuitive suggests that these values are bein... | You need to offset the bits, otherwise there's no way to extract the individual flags. If you had flags corresponding to 1, 2, 3, & 4, and a combined value of 5, how could you tell if it was 2 & 3 or 1 & 4?
You can also do it this way, for example:
enum {
FIRST = 1 << 0, // same as 1
SECOND = 1 << 1, // same as... |
3,643,695 | 3,643,711 | iterator for map - problem with searching | hello i got an iterator running on a multimap ,my multimap includes two fields the first 1 is the key value which is a string Lastname and the second 1 is the data which is a pointer to an object called Employee.
in my program i need to be able to find an element inside my map using iterator (cause i am trying to find ... | If you need two keys in the container you could try Boost Multi-index Container.
Another solution is to create two maps, each one with own key, and keep your data in each by (smart) pointers.
|
3,643,828 | 3,643,846 | which is faster, and which is more flexible: printf or cout? |
Possible Duplicates:
printf vs cout in C++
cin or printf??
I've always wondered about printf and cout.. which one is ultimately faster, and is it the most flexible as well (ie can print a range of variables, and output can be formatted)?
P.S.
I know this looks similar to 'printf' vs. 'cout' in C++ ,but i'm not reall... | Short Answer
Faster : printf
More flexible : cout
Long answer
When compared to the sprintf family, the C++ streams are supposed to be slower (by a factor 6 if I recall an item of Exceptional C++, by Herb Sutter). Still, most of the time, you won't need this speed, but you need to be sure your code won't be bugged.
And ... |
3,643,874 | 3,643,920 | Problem with the compiling of the STLport under Snow Leopard | I am trying to build the latest version of stlprot under Snow Leopard.
Steps for the compiling i have made:
./configure
sudo make && make check
make && make check are working fine.
the problem occurs, if i call 'sudo make install', i get an error:
/bin/sh: /usr/local/include/stlport: No such file or directory
Can't c... | Just a wild guess: maybe they're doing "mkdir /usr/local/include/stlport", without the "-p" switch and /usr/local/include doesn't exist yet. That would trigger a no such file or directory error. Try running this before "sudo make install":
sudo mkdir -p /usr/local/include
or maybe even go the full way:
sudo mkdir -p /... |
3,643,998 | 3,644,008 | How to check if my iterator stands on nothing | i'm using a multimap stl, i iterate my map and i did'nt find the object i wanted inside the map, now i want to check if my iterator holds the thing i wanted or not and i'm having difficulties with it because it's not null or something. thanx!
| If it doesn't find the thing you want then it should equal the iterator returned by the end() method of the container.
So:
iterator it = container.find(something);
if (it == container.end())
{
//not found
return;
}
//else found
|
3,644,050 | 3,644,056 | C++ synchronization guidelines | Does anyone know of a decent reference for synchronization issues in C++? I'm thinking of something similar to the C++ FAQ lite (and the FQA lite) but with regards to concurrency, locking, threading, performance issues, guidelines, when locks are needed and when they aren't, dealing with multithreaded library code that... | I'd recommend two resources:
Herb Sutter's Effective Concurrency articles
Anthony Williams's C++ Concurrency In Action (not yet published, but available as a PDF)
|
3,644,052 | 3,644,090 | Pointer to Array of Struct | struct bop
{
char fullname[ strSize ];
char title[ strSize ];
char bopname[ strSize ];
int preference;
};
int main()
{
bop *pn = new bop[ 3 ];
Is there a way to initialize the char array members all at once?
Edit: I know I can use string or vector but I just wanted to know out of curiosity.
| If I'm not mistaken, you could add a constructor to the struct which initializes the values to default values. This is similar if not identical to what you use in classes.
|
3,644,065 | 3,644,099 | How to write an elegant collision handling mechanism? | I'm in a bit of a pickle: say I'm making a simple, 2D, Zelda-like game.
When two Objects collide, each should have a resulting action. However, when the main character collides with something, his reaction depends solely on the type of the object with which he collided. If it's a monster, he should bounce back, if it's... | I would do it vice versa - because if the character collides with an object, an object collides with the character as well. Thus you can have a base class Object, like this:
class Object {
virtual void collideWithCharacter(MainCharacter&) = 0;
};
class Monster : public Object {
virtual void collideWithCharacter(... |
3,644,188 | 3,644,561 | .NET: Inheritance Modify Base Class (C++ Conversion) | I have two classes. The base class is A. The inherited class is B. I would like copy a base class from one object into the base class of another object without affecting the original class. However, .NET seems to ignore the copying. Is this not possible in .NET. I know this is possible in C++. I have included C++ code ... | One alternative is to have a C# class that does the pointer manipulation and adds extension method to the B Class. It would be very similar to the C++ solution. This seems the best solution as it would be almost identical to the C++ implementation.
Instead I used reflection. It is only a shallow copy but in this case i... |
3,644,271 | 3,644,598 | Numerical Error in simple CUDA code | I just started experimenting cuda with the following cude
#include "macro.hpp"
#include <algorithm>
#include <iostream>
#include <cstdlib>
//#define double float
//#define double int
int RandomNumber(){return static_cast<double>(rand() % 1000);}
__global__ void sum3(double const* a,
double const* b,
... | while(i < (*n))
{
result[i] = (a[i] + b[i] + c[i]);
}
is wrong (infinite)
this is wrong
cudaMemcpy((void**) &sized, &size, sizeof(unsigned), cudaMemcpyHostToDevice);
&sized is address of pointer variable, not pointer value
Single number can be passed to device on the stack, so use
unsigned size
check return status... |
3,644,441 | 3,644,479 | Language/GUI library to make map editor | I'm designing a cross-platform map editor for an application I've developed, and I'm unsure what approach to take regarding language/gui library choice. Just for some basic info, the editor needs to parse and output xml files.
I'm most comfortable with C++, Lua, and Perl, but I'd also be willing to use Python (could us... | I can recommend using Python and PyQt for the job. Qt offers a class for scene management (i.e. layered object placement, zooming, hit testing, events,coordinate transformations etc., even collision detection) called QGraphicsScene and a matching control to display it all, called QGraphicsView. It also offers support f... |
3,644,531 | 3,644,566 | How would I find the height of the task bar? | In my windows application, I am trying to find the height of the task bar. While I can hard program this into my program, I would like to find it programmatically to support past, present (win7) and future windows versions.
So, how would I do this?
| You get it from GetMonitorInfo(), MONITORINFOEX.rcWork member.
Get the HMONITOR that you need to call this function from, say, MonitorFromRect(), passing your window rectangle. Or MonitorFromPoint() or EnumDisplayMonitors(), depends where you want to display your window. (0,0) is always the upper left corner of the... |
3,644,630 | 3,644,649 | Breaking into Debugger when a process accesses a file, or get a call stack of file accesses from a process | I'm dealing with some hundreds of thousands of lines of code, and I'm stumped where this process is accessing a particular file. I've given up searching the code, I just cannot find out.
So, here I am -- asking a question I'm almost certain there is no simple solution for.
I've tried FileMon, ProcMon from SysInternals,... | Set a breakpoint on CreateFile(). Write one in main() so you can easily trace into it an find the API entrypoint. Switch to disassembly view before single-stepping.
|
3,644,668 | 3,672,045 | How to delete IE addressbar history on Vista/Win7? | First, here is a picture of what I see
http://img713.imageshack.us/img713/4797/iedrop.png
I need an solution to clear addressbar dropdawn, but not using ClearMyTracksByProcess or IE dialogs. I need to delete only a specific URL and all his traces.
I deleted manually all traces of that URL in:
Users\\AppData\Local\Micr... | Finally I found solution.
HRESULT CreateCatalogManager(ISearchCatalogManager **ppSearchCatalogManager)
{
*ppSearchCatalogManager = NULL;
ISearchManager *pSearchManager;
HRESULT hr = CoCreateInstance(CLSID_CSearchManager, NULL, CLSCTX_SERVER, IID_PPV_ARGS(&pSearchManager));
if (SUCCEEDED(hr))
{
... |
3,644,740 | 3,644,805 | Arbitrary pointer to unknown class function - invalid type conversion | I have a hack program; it injects some functions into a target process to control it. The program is written in C++ with inline assembly.
class GameProcMain {
// this just a class
};
GameProcMain* mainproc; // there is no problem I can do =(GameProcMain*)0xC1EA90
Now I want to define a class function (which set ecx ... | The problem is that member functions automatically get an extra parameter for the this pointer. Sometimes you can cast between member and non-member functions, but I don't see the need to cast anything.
Typically it's easier to reverse-engineer into C functions than into C++. C typically has a more straightforward ABI... |
3,644,807 | 3,644,942 | C++ double value losing precision when multiplied? | I am trying to create a function to find the square root of a number. For debugging purposes, it has instructions to print current variable values. The function squareRoot accepts two arguments, x and t. It then declares and initializes n and s. n is the amount to add or subtract, halving every time it is used. s is wh... | Unrelated, but your sqrt algorithm can be sped up by using an existing one, such as Newton's Method.
It goes like this:
double mySqrt(double x, unsigned long accuracy = 10)
{
if(x < 0.0)
return(-1.0);
double retval = 1.0;
for(unsigned long rep = 0; rep < accuracy; rep++)
retval = ((x / retval) + ... |
3,644,863 | 3,644,880 | How do I get the correct case of a path? | I have a small but itching problem. How do I get the correct case for a Windows path in Qt?
Let's say i have a path c:\documents and settings\wolfgang\documents stored in a QString str and i want to know the correct case, here C:\Document and Settings\Wolfgang\Documents. QDir(str).absolutePath() doesn't get me the path... | There isn't a simple way to do this, but you can try doing a QDir.entryList, and then do a case insensitive search on the results. This will provide you with the correct filename. You'll then need to get the absolutePath for that result.
This should give you the preserved-case for the path/filename.
|
3,644,919 | 3,644,995 | A std::vector of pointers? | Here is what I'm trying to do. I have a std::vector with a certain number of elements, it can grow but not shrink. The thing is that its sort of cell based so there may not be anything at that position. Instead of creating an empty object and wasting memory, I thought of instead just NULLing that cell in the std::vecto... | How large are the objects and how sparse do you anticipate the vector will be? If the objects are not large or if there aren't many holes, the cost of having a few "empty" objects may be lower than the cost of having to dynamically allocate your objects and manage pointers to them.
That said, if you do want to store p... |
3,644,943 | 3,644,950 | How to write a double type into file in c/c++ in windows? | double Time;
...
WriteFile( tmp_pipe, Time, sizeof(double), &dwWritten, NULL );
The above reports :
error C2664: 'WriteFile' : cannot convert parameter 2 from 'double' to 'LPCVOID'
| You want &Time, not Time, for parameter 2 of the function call.
|
3,645,026 | 3,645,049 | Using Sleep() while using timers through setitimer | I am using a timer in my C++ code through setitimer function from sys/time.h. This maps the SIGALRM signal to my timer handler method. After this I am not able to use sleep function. I am assuming it is because sleep uses SIGALRM signal as well. Can you suggest any workaround for this problem?
Thanks for replying.
| You can try using select() just as a timer. I don't know if it uses SIGALRM or not but it should be simple to test. Something like:
timeval t = {1, 0};
select(0, NULL, NULL, NULL, &t);
|
3,645,058 | 3,645,102 | How to erase entries from vector in C++? | I'm basically looping through all the entries to check whether some entries is to be erased, but seems in a wrong way:
std::vector<HANDLE> myvector;
for(unsigned int i = 0; i < myvector.size(); i++)
{
if(...)
myvector.erase(myvector.begin()+i);
}
Anyone spot the problem in it? How to do it correctly?
| Your problem is algorithmic. What happens if two adjacent elements meet your criterion for deletion? The first will be deleted, but because i is incremented after each iteration of the loop, the second will be skipped. This is because a vector is contiguous in memory, and all elements after the deleted one are moved fo... |
3,645,172 | 3,645,175 | How to reset SIGINT to default after pointing it some user-defined handler for some time? | I use signal(SIGINT,my_handler) to point SIGINT to my_handler. After some time I want to reset it to whatever default handler it points to in general. How can I do that?
| Pass SIG_DFL as the func parameter to signal() to reset default behaviour:
signal(SIGINT, SIG_DFL);
|
3,645,199 | 3,645,209 | Implementing a map_keys_iterator by derivation: a single compiler error | I was working again with C++ during the weekend and came to notice something that I'm not sure where does it come from.
Following the advice in this thread, I decided to implement a map_keys_iterator and map_values_iterator. I took the -- I think -- recommended-against approach of deriving a class from std::map<K,V>::i... | The reason is that your K and V type parameters are in a non-deducible context, so your function template is never even instantiated during overload resolution.
Look at it again:
template <typename K, typename V>
map_keys_iterator<K,V> map_keys(const typename std::map<K,V>::iterator &i)
For this to work, the C++ comp... |
3,645,281 | 3,645,303 | c++ win32 set cursor position | I know which function to use but I can't get it to work right. I used SetCursorPos() the only problem is that it sets the cursor not to the windows coordinates but to the screen coordinates. i also tried the ScreenToClient() but it didn't work ethier.
Here is my code:
pt.x=113;
pt.y=280;
ScreenToClient(hWnd, &pt);
SetC... | You're approaching this slightly backwards. The SetCursorPos function works in screen cordinates and you want to set the cursor based on window / client coordinates. In order to do this you need to map from client to screen coordinates. The function ScreenToClient does the opposite. What you're looking for is Clien... |
3,645,286 | 4,033,267 | Stream of example RTP packets | I am trying to tunnel RTP traffic through a user-defined protocol, and want to test this setup. Is there any C++ library, which I can use to generate example RTP packets and then tunnel them through my library?
Thanks.
| you can see an example here: RTPpacket
but is in java.
Well this is the main page streaming tcp/udp
Hope can be helpfull!
Bye
|
3,645,359 | 3,696,816 | Possible frameworks/ideas for thread managment and work allocation in C++ | I am developing a C++ application that needs to process large amount of data. I am not in position to partition data so that multi-processes can handle each partition independently. I am hoping to get ideas on frameworks/libraries that can manage threads and work allocation among worker threads.
Manage threads should i... | Your question essentially boils down to "how do I implement a thread pool?"
Writing a good thread pool is tricky. I recommend hunting for a library that already does what you want rather than trying to implement it yourself. Boost has a thread-pool library in the review queue, and both Microsoft's concurrency runtime a... |
3,645,504 | 3,645,772 | Seed random from milliseconds in Windows and Linux | I need to seed the random number generator in boost (which is loaded from an int) for a few processes, for a program that has to compile and work both in Windows and in Linux.
I used std:time(0), which worked, but since the processes are jobs which are run simultaneously, some of them would run at the same second, pro... | If you are starting all the jobs from a single script.
Then you could pass an incremented number as an argument on the command line. Each Job then adds this value to the result of time() to generate its seed.
Note: I don't see any requirement in the OP about security.
The original code is using time(NULL) and this wi... |
3,645,534 | 3,645,547 | random complex number | i need algorithm for generate random complex number please help i know how generate random number but random complex number confuse me
| I would simply generate two random numbers and use one for the real part and one for the imaginary part.
|
3,645,712 | 3,645,839 | how to make the execution time less(ie. a faster code) for this problem | this question is from Codechef.com [if anyone is still solving this question dont look further into the post before trying yourself] and although it runs right, but i need to make it a lot faster.i am a beginner in c,c++.(i know stuff upto arrays,strings and pointers but not file handling etc).So is there a way to make... |
1) Increase the numbers between indices A and B by 1. This is represented by the command "0 A B"
2) Answer how many numbers between indices A and B are divisible by 3. This is represented by the command "1 A B".
Initially numbers are 0 and thus are divisible by 3. Increment by one make the number non-divisible. Next ... |
3,645,748 | 3,651,700 | Is there any development materials about ATL service | I want to develop a Windows service and choose ATL service as I want to use native C++, but it seems there are not much materials on this topic, I only found some concept description here, which is not enough for me to develop my service application.
Do you know any tutorials or samples on developing a ATL service?
Tha... | I am afraid there would be little chance to have an better answer as ATL is really not that popular now. But to make this post valuable to others who might meet this problem in the future, I would like to give my answers based on what I found:
Yes, it is really had to find materials on developing ATL service, if what y... |
3,645,825 | 3,645,953 | Font size QComboBox items? | Say I fill QComboBox with a number on each line. And lines are very close vertically. How can I control vertical the distance?
| If you just want to change the row height (instead of changing font size) create a new delegate class:
class RowHeightDelegate : public QItemDelegate
{
Q_OBJECT
public:
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
return QSize(1, 40); // the row height is now ... |
3,645,881 | 3,645,888 | Storing objects in vector | Is it possible to have a vector without specializing it?
My problem is: I have an abstract class N4GestureRecognizer
and a couple of subclasses of it.
So in a Controller class I want to have a vector<N4GestureRecognizer> recognizers_ but since it is abstract I cannot.
How can I store this recognizers in a vector or col... | Store them as pointers. Either pure pointers or some smart pointer class.
EXTRA
Actually, pointers are the only way even if the class is not abstracts, but is subclassed and child classes are intended to be used in the vector. Why: std::vector allocates sizeof(T) bytes for each element, but sizeof(derivedFromT) could b... |
3,645,896 | 3,645,900 | How can I make an alias to a singleton function? | I would like to make an alias in C++ to singleton calling
so instead of calling MYCLASS::GetInstance()->someFunction(); each time, I could call just someFunctionAlias(); in my code.
| Use a static function.
namespace ... {
void someFunction() {
MYCLASS::GetInstance()->someFunction();
}
};
Edit: Sorry lads, I wrote static someFunction and meant void someFunction.
|
3,645,898 | 3,645,909 | C++ Qt signal and slot not firing | I am having difficulty in my Qt program with connecting button signals to my slots. My code is:
Main.cpp
#include <QtGui/QApplication>
#include "MainWidget.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWidget mainWidget;
mainWidget.show();
return app.exec();
}
MainWidget.h
... | Add Q_OBJECT to your class, like this:
class MainWidget : public QWidget
{
Q_OBJECT
You also have to run moc to generate some helper code. qmake does that automatically for your, but if you compile this yourself, you need to run moc.
|
3,645,937 | 3,645,940 | What does `= 0` mean in the decalartion of a pure virtual function? |
Possible Duplicates:
C++ Virtual/Pure Virtual Explained
What's the difference between virtual function instantiations in c++
Why pure virtual function is initialized by 0?
This is a method in some class declaration that someone gave me. And I don't know what '..=0' means. What is it?
virtual void Print() const = 0... | The = 0 makes the function pure virtual, rendering the class an abstract class.
An abstract class basically is a kind of interface, which derived classes need to implement in order to be instantiable. However, there's much more to this, and it is some of the very basics of object-oriented programming in C++. If you do... |
3,646,055 | 3,646,089 | Pointer to pointer array understanding problem | This is probably a stupid question, but I don't understand why this works:
int** test = new int*[7];
int x = 7;
*(test+1) = &x;
cout << (**(test+1));
test is a pointer to a pointer right? The second pointer points to the array, right?
In my understand I would need to dereference the "test" pointer first to get t... | Is your misunderstanding that you think you have created a pointer to an array of 7 int? You haven't. You actually have created an array of 7 pointers to int. So there is no "second pointer" here that would point to an array. There is just one pointer that points to the first of the 7 pointers (test).
And with *test y... |
3,646,156 | 3,976,893 | How to create a bulleted or numbered list with Qt? | How to create a bulleted or numbered list in QTextEdit with Qt by clicking a button? Also it is necessary that make a list the paragraphes which are selected by clicking the same button. And when the cursor is in the list and you click the button, the the list item becomes not-list item, but a simple paragraph. In two... | I have used this code:
void TextEdit::textStyle(int styleIndex)
{
QTextCursor cursor = textEdit->textCursor();
if (styleIndex != 0) {
QTextListFormat::Style style = QTextListFormat::ListDisc;
switch (styleIndex) {
default:
case 1:
style = QTextL... |
3,646,161 | 3,646,172 | What are the differences between using pure C with a C compiler and the "C part" of a C++ compiler? | I'm not sure what programming in C really means:
- Programming in pure C with a C compiler
or
- programming in C with a C++ compiler.
Apart from the differences between the C's syntax of C and the C's syntax of C++, can I safely say there are absolutely (or in very few cases) no differences between two executables in t... | There are a lot of minor nitpicks. One that strikes me as being the most obvious is that in C++, you have to cast the return value of malloc. Also structs are automatically typedefed in C++.
Always use a C compiler for C code, not C++. C++ isn't perfectly compatible with C.
A few others:
In C, declaring void func(); d... |
3,646,182 | 3,646,193 | Is there any way to generate variable names at compile time in C/C++? | With reference to the SO thread C Macro Token Concatenation involving a variable - is it possible?,
Is it at all possible to generate variable names at compile-time in C and C++?
something like
int count = 8;
for(i=0; i<count; i++) {
int var_%i% = i*i; // <--- magic here
}
I know I can use arrays for this case, ... | If you are expecting to use the value of i to generate the name var_%i% (e.g. generating variables var_1, var_2, ..., var_count), then no, that's not possible at all. For one thing, that's not even a compile-time operation. The value of i isn't known until runtime. Yes, you can tell what it will be (and maybe a compile... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.