question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,702,548 | 5,702,599 | C++ multiple definition of operator>> | I'm using the proposed solution by @Martin for csv parsing with C++, as I'm trying to avoid using libraries like boost and such for my current project. I've placed his implementation in a "csv.h" header and am trying to include it with some other files. I keep getting the following error
multiple definition of operator... | Chances are you have the same operator included in multiple compilation units (ie cpp files) so you're getting the same code generated, the linker than looks at all the .obj files to pull them together and sees multiples.
You have 3 choices:
mark it as static - this will make
the operator visible only to the file
it w... |
5,702,557 | 5,702,629 | Searching using regular expressions C++ | I'm using Boost.Regex to achieve something like this: search for a "|" and then take the left part of the "|" and put it a string, same with the right part:
string s1;
string s2;
who | sort
After this s1 should be "who" and s2 shoudl be "sort".
If I remember good, it was posible in Python, how can I do it using regula... | #include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("|"));
Split a string in C++?
|
5,702,849 | 5,702,879 | c++ template specialisation method definition | The following code works fine, a simple template class with a definition and a use
#include <string>
#include <iostream>
using namespace std;
template<class T> class foo{
public:
string what();
};
template<class T> string foo<T>::what(){
return "foo of type T";
}
int main(){
foo<int> f;
cout << f.what() <<... | template<> class foo<char>{
public:
string what();
};
/*template<>*/ string foo<char>::what(){
return "foo of type char";
}
You don't need that template<>. foo<char> is already a complete type after it's specialized.
|
5,702,974 | 5,740,221 | How to exploit periodicity to reduce noise of a signal? | 100 periods have been collected from a 3 dimensional periodic signal. The wavelength slightly varies. The noise of the wavelength follows Gaussian distribution with zero mean. A good estimate of the wavelength is known, that is not an issue here. The noise of the amplitude may not be Gaussian and may be contaminated wi... | We have used wavelets for noise suppression with similar signal measured from cows during walking.
I'm don't think the noise is so much of a problem here and the biggest peaks represent actual changes in the acceleration during walking.
I suppose that the angle of the leg and thus accelerometer changes during your ex... |
5,703,053 | 5,703,482 | C++ Add DNS entry into network adapter | I have to programatically add DNS server address in network adapter settings on windows. Programming language is C++.
| Setting DNS using iphelp and register at CodeProject.
bool RegSetDNS(LPCTSTR lpszAdapterName, LPCTSTR pDNS)
{
HKEY hKey;
string strKeyName = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\";
strKeyName += lpszAdapterName;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
strKeyNa... |
5,703,111 | 5,703,149 | Set difference in C++ | If I know that one set is a subset of another set and I would like to find the difference, what's the most efficient way to do this?
ex.
PSEUDO CODE
> set<int> set1 = {1 2 3 4 5 6 7 8 9 10}
> set<int> set2 = {5 6 7}
I want to subtract set2 from set1:
The answer here would be
{1 2 3 4 8 9 10}
| Use std::set_difference found in <algorithm>:
#include <algorithm>
#include <set>
#include <iterator>
// ...
std::set<int> s1, s2;
// Fill in s1 and s2 with values
std::set<int> result;
std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
std::inserter(result, result.end()));
Snippet source
|
5,703,139 | 5,704,277 | Controlling the individual pixels of a projector | I need to control the individual pixels of a projector (an Infocus IN3104) whose native resolution is 1024x768. I would like to know which subset of functions in C or an APL to do this either by:
Functions that control the individual pixels of the adapter (not the pixels of a window).
A pixel-perfect, 1:1 map from an... | The usual approach to this problem on current systems is:
Set graphics card to desired resolution
Create borderless full screen window
Draw whatever you want
There's really not much to gain from a "low level access", although it were certainly possible.
|
5,703,448 | 5,703,655 | Is there any downside to marking all C++ constructors explicit? | A few times, when refactoring code, I have forgotten to add the explicit keyword when adding a parameter to a previously-parameterless constructor, or removing parameters from a previously multi-parameter constructor. To prevent this, I have gotten in the habit of marking every constructor explicit, no matter no many a... | It doesn't have any downsides. It will be future safe, because in C++0x multi-parameter constructors participate in initializations using multi-element initializer lists and can forbidden to be used in the cases where only implicit conversions apply using explicit.
So if you find out a give multi-parameter constructor... |
5,703,688 | 5,703,776 | Query Windows For ISO Currency String | How can I query Windows to get the current regional settings for currency (e.g. USD, CAD, MX) per ISO standard? Not dollar-sign, for instance ($).
| Try this: http://support.microsoft.com/kb/199244
It tells you, that you should use
GetUserDefaultLCID
http://msdn.microsoft.com/en-us/library/dd318135%28v=vs.85%29.aspx
and then
GetLocaleInfo
http://msdn.microsoft.com/en-us/library/dd318101%28v=vs.85%29.aspx
|
5,703,812 | 5,703,838 | arithmetic with double vs bit operations | There is some obvious stuff I feel I should understand here, but I don:t:
void main()
{
long first = 0xffffffc1;
long second = 0x92009019;
//correct
__int64 correct = (((__int64)first << 32) | 0x00000000ffffffff) & (0xffffffff00000000 | second); //output is 0xffffffc192009019;
//incorrect
__in... | Probably because second is signed, which mean that 0x92009019 is negative.
EDIT: The quesiton actually contains two questions.
1) How do you join two 32 bit numbers to a 64 bit value?
Answer:
(((uint64_t)first) << 32) | (uint32_t)second
2) Is it wise to do bit operations using the floating-point type double?
Answer: N... |
5,703,842 | 5,703,855 | How to make a parameter to char C++ | I have a split-method which takes 2 parameters in, a char and a string:
split(char sk, string st)
But when I'm calling the method like below, I get this error-message:
expected primary-expression before ':' token
g.split(:, string);
Is it any way I can make call to understand that : is a char?
| Use single quotes
g.split(':', string);
|
5,703,884 | 5,704,135 | Multiple C++ files and variable scope | I have a program, it starts in a winmain which calls run_game in its loop.
Because I treat run_game like a main function I am having to define many global variables.
The win main is in one file and everything is in another .cpp file. It started as a tutorial from a book and I have kept adding to it for a while now. Be... |
I see a lot of people having one giant
source file. I am self taught so not
sure if this has a benefit or is just
style.
Its usually better to have smaller well defined files instead of one giant source file. Each file would either have a single C++ class definition or a set of interrelated functions. A rough g... |
5,704,066 | 5,704,592 | Is it possible force Qt to call paintEvent after other Qt components are drawn? | I've a class that extends QWidget and contains a QLabel (lblBackground). I've overriden paintEvent function too.
I want to draw something on top of lblBackground however paintEvent method is called before the QLabel is drawn. Thus my custom drawings are overwritten.
Is there a way to change drawing order?
| Painting the children on top of their parent is the common thing to do. That being said you could try one of the following options:
extend QLabel itself to paint whatever you want
try to set the Qt::WA_TranslucentBackground flag on the QLabel and having an alpha channel, so that the underlying parent (QWidget) would s... |
5,704,103 | 5,713,379 | What causes a nul character written to file just before a pc crash? | We have an application running on several thousand identical machines. Same OS, same hardware, same application installation. On very rare occasions, the machine locks up. Alt tab, ctrl-alt-del, application are all unresponsive. After inspecting our applications log file, a series of null characters are written to ... | NTFS does not journal data (only metadata), so things like that can happen. The reason why is just that at the time of the crash/hang, the metadata (file size, data block allocation) was committed, but not the data (data block contents). Unfortunately this is normal behavior with NTFS and will not give you any insight ... |
5,704,110 | 5,704,146 | Should I make wrappers for polymorphic classes that need to be allocatd on the heap? | Right now, the GUI API for games I''m developing has an abstract Image and Font class. Depending on whether they use a GL, SDL etc Font, they load fonts like this:
Font *segoe = Font::load("segoe.ttf");
There is also a corresponding destroy() static function as well.
I like this design, but I was wondering if it would... | Basically, that's a custom smart pointer type to handle the load/destroy logic. This is very idiomatic and the way to go in C++. Resource management should be automatic.
So your wrapper is fine, but perhaps you are reinventing the wheel here. You may consider rewriting the font system that the work done by destroy is m... |
5,704,134 | 5,704,615 | Preparing a library for plugin support | I searched for this particular question but could not come up with any results, neither here nor on-line in general (maybe because it is a little harder to phrase for me). If it has already been asked, please point me in the right direction.
I am at a point where I would like my libraries/software to be pluggable. I se... | You have to understand some things before starting :
There is no support for modules (static or dynamic) in standard C++. Nope. Not yet. Maybe in 2015.
Dlls (or .so on unix-like systems) are dynamically loaded libraries that are compiler/os dependant. So it's a pragmatic solution that fill the need.
So, you'll have t... |
5,704,411 | 5,704,612 | Time complexity of the code below? | Can someone tell me the time complexity for the following code?
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char a[100]= "Gosh I am confused :D";
int i,count= -1,display_ToVal= strlen(a)-1, display_FromVal;
for( i=strlen(a)-1 ; i>=0 ; i=i+count)
{
if ( (a[i] == ' ' || i == 0) && cou... | The algorithm can be summarrized in pseudo-code as :
mark the current position
go backward one character at a time until a space is found or end of input is reached
now go forward copying each character to output, then go back to 1., except if eoi is reached
So the input is traversed once in reverse, and one more tim... |
5,704,498 | 5,733,997 | gcc and class keyword | I know that typename and class keywords are interchangeable in template arguments, but I thought only typename is allowed for nested classes specification.
Once I've accidentally wrote incorrectly "class" instead of "typename" for a nested class.
And I found is that gcc accepts class there too, so you can write somethi... | class a::b is an elaborated type specifier. Name lookup for an elaborated type specifier ignores non-type names. So if you are parsing a template, you can assume two things:
When we are instantiating and do name-lookup for b, either name lookup gives us a type, or it errors out (wouldn't find any name).
In C++0x for... |
5,704,649 | 5,719,567 | Problem with Lint warning 559 | The following code generates Lint warning 559 "Size of argument no. 3 inconsistent with format" for the wsprintf call, can anyone explain why?
WCHAR szFoo[] = L"test";
WCHAR szBar[MAX_PATH];
wsprintf(szBar, L"c:\\path\\%s\\path", szFoo);
Amusingly, if I change the format type to %S the warning is no longer raised, but... | Your problem is that lint doesn't know that wide strings are valid for the %s format type.
Probably the easiest fix is to add the following inline in your code, either locally with the implementation or in a header file:
//lint -printf_code("s", TCHAR*)
|
5,704,697 | 5,704,941 | When is virtual inheritance a good idea? | I'm making a game GUI API where each widget inherits from the Widget class. I was thinking, when others make there own widgets, they might not be fully satisfied with the base class. They might want to add getTheme() for example. Would it be a good idea to make all my widgets virtually inherit from Widget then so that ... | Just because the user would add their own methods to a child class doesn't mean you need to use virtual inheritance. You would use it if, in your library, you have a single base class with multiple children, and people could inherit from multiple child classes at once (for example mixin rather than substitution).
|
5,704,860 | 5,705,251 | Visual Studio - Add Resource as Link (C++) | I am attempting to add a linked resource to my C++ project in Visual Studio. However when I select 'Add Existing Item' and look for the 'Add as Link' option from the 'Add' button dropdown, it is not available.
However, I do see this option available for .NET projects.
Does this functionality not exist for C++ in Visual... | That's the default. You don't need a separate button.
If you want the file in your project folder, you put it there first.
|
5,704,896 | 5,705,156 | Why do g++ and MS Visual Studio C++ execute the following code differently? | I am having trouble understanding which complier is at fault here (if any). The following code is exectued differently of g++ compared with MS Visual Studio C++.
#include <iostream>
int main() {
int a = 10; //some random value
int* ptr = &a;
//a temp rvalue of type `const int* const' created in g++
... | It's related to a Visual C++ bug I reported last year. Please do upvote the bug report.
https://connect.microsoft.com/VisualStudio/feedback/details/615622/identity-cast-to-non-reference-type-violates-standard
(The connection here is that the reference binds to const int*, which requires an implicit conversion from int... |
5,704,914 | 5,705,232 | Is a typedef a definition? | I'm really confused. I am reading TC++PL by Bjarne Stroustrup (special edition, 19th print - Sep 2010). Let me quote a part of the book, highlighting my confusion:
char ch;
string s;
int count = 1;
const double pi = 3.1415926535897932385;
extern int error_number;
const char* name = "Njal";
const char* season[] = { "sp... | Although I'm totally confused by this. The standard is clear. Typedef is just a declaration. Not definition.
3.1-2
A declaration is a definition unless
it declares a function without
specifying the function’s body (8.4),
it contains the extern specifier
(7.1.1) or a linkage-specification24)
(7.5) and neither... |
5,705,394 | 5,705,462 | Is this an acceptable way of managing resources? | To manage various resources in my game (fonts bitmaps etc), I want to create managers which map strings to whatever resource. And this object, when out of scope, frees all memory used by the resources.
So basically if you want a Font, you'd either add it or request with a string indicating its name and it would return ... | What you are describing is a the Factory Pattern combined with Smart Pointer/Scoped Pointer.
It is pretty reasonable. Just consider if you really need to use a string for identifying the resource. An enum might be enough.
|
5,705,400 | 5,705,476 | CreateProcess - lpApplicationName vs lpCommandLine | I've been using the CreateProcess Win API, and I was wondering what the difference was between using the lpApplicationName and lpCommandLine for arguments v.s. just the lpCommandLine parameter.
For example:
CreateProcess(NULL, L"C:\Path\To\Notepad.exe", L"C:\Path\To\File\To\Load.txt"... etc
CreateProcess(NULL, NULL, L"... | The recommended way is to to use both parameters. If you do not specify lpApplicationName you let Windows parse lpCommandLine to figure out the application name. Because space is a valid character in file names and directory names, this can (in rare cases) lead to wrong application being run. (e.g. if you have c... |
5,705,791 | 5,705,912 | Return value of glSelectBuffer in opengl | static GLuint selectBuff[BUFFER_LENGTH];
glSelectBuffer(BUFFER_LENGTH, selectBuff);
..
//Draw something..
..
// Collect the hits
hits = glRenderMode(GL_RENDER);
..
..
if(hits > 0){ //something's been selected
fprintf(stderr,"something has been selected");
unsigned int choiche;
// fi there's mor... | From http://www.opengl.org/sdk/docs/man/xhtml/glSelectBuffer.xml
"The hit record consists of the number
of names in the name stack at the time
of the event, followed by the minimum
and maximum depth values of all
vertices that hit since the previous
event, followed by the name stack
contents, bottom name f... |
5,705,797 | 5,709,966 | Boost serialization: how to choose version at runtime? | I am using Boost Serialization to serialize data members for transport from one component to another. The documentation discusses how to use the class version mechanism to unserialize both older and newer versions of a class.
My use case is slightly different. In some cases, a newer version of the code will be sendi... | There is no way to dynamically influence the type version used by Boost.Serialization as it's a compile time constant (as you mentioned). You will need to add your own versioning scheme to handle this particular case.
|
5,705,908 | 5,705,941 | How is this code working? | I am working with the company code and I see this:
ClassName(/* bunch of parameters */)
.someFunc(/* bunch of parameters */)
.someFunc(/* bunch of parameters */)
.someFunc(/* bunch of parameters */)
;
Now I have never seen this and didn't know something like this could work (the code compiles in the company so... | This technique is called Method Chaining. It basically works by returning a reference to *this in every method that you call. This allows you to directly call another method on the returned object (called chaining).
|
5,705,956 | 5,705,980 | C++ Adding String Literal to Char Literal | I have a question about string concatenation in C++.
string str = "ab" + 'c';
cout << str << endl;
char ch = 'c';
string str1 = "ab";
string str2 = str1 + ch;
cout << str2 << endl;
The code produces:
ed before SaveGraphicsState
abc
Can someone explain the processing of this line: string str = "ab" + 'c'; ?
| Your thought regarding the first line is correct, that's precisely what's happening.
There isn't any default + operator for literal strings like "ab" so what happens is the compiler takes that (as a C-style string) and uses the const char* pointer that points to the literal. It then takes your literal character 'c' and... |
5,706,010 | 5,706,031 | Error in function sort | I'm trying to use the sort function from STL, but it gives me an error during execution.
My compare function returns true if v is smaller then e:
bool smallerThan(VertexEntry &v, VertexEntry &e) {
if(v.v[0] < e.v[0]) return true;
else if(v.v[1] < e.v[1]) return true;
else if(v.v[2] < e.v[2]) return true;
re... | Your comparison function is incorrect - it doesn't enforce strict weak ordering.
Use this:
bool smallerThan(VertexEntry const & v, VertexEntry const & e) {
if (v.v[0] < e.v[0])
return true;
else if(v.v[0] > e.v[0])
return false;
else if(v.v[1] < e.v[1])
return true;
else if(v.v[1] > e.v[1]... |
5,706,099 | 5,706,145 | Cannot display in hexadecimal | unsigned int i = 0x02081;
cout << std::hex << i;
This displays 2081 when compiled with VS2010 but I think it should display 0x02081. Am I right, and if so, how can this be fixed?
| By default the base is not printed:
cout << std::hex << std::showbase << i;
|
5,706,168 | 5,706,381 | windows application crashing with pure virtual function call | I have a Windows application, it crashes every now and then and not reroducibly.
When it does, I get pure virtual function called. I have set it up to create a Windows dump using ADplus and even when it crashes, there is never a dump.
I am pretty sure this is build error, I am building using VC2008 SP1 and this is the ... | As was pointed out already, it is very unlikely that this is a build error. I had a quite complex project with a similar problem and was able to track it down by using _set_purecall_handler and providing my own handler. This way I was able to break into the debugger when it happened and see the call stack. Obviously an... |
5,706,173 | 5,706,201 | Why memset() does not work properly when placed inside a loop body? | Yesterday I programmed a small piece code in C++ which contains a loop and an array. In the program I need to reset the array every time the loop starts over. However, if I use
memset(sum,sizeof(sum),0);
Then the array won't be reset to all 0. For this program I used:
for (i=0;i<sizeof(sum)/sizeof(int);i++) sum[i]=0;
... | You're actually writing the size of sum into the 0 first bytes.
You should be doing memset(sum,0,sizeof(sum)) instead.
(In other words, the arguments are target, data and length and you provided data and length in the wrong order.)
|
5,706,259 | 5,708,137 | Qt and UTF-8: strange behaviour | To illustrate my problem I will give you an example:
I have UTF-8 encoded text file.
in.txt:
ąśćź
ąś
ŻźŹ
This program reads in.txt line by line and produces duplicate out.txt.
It not only duplicates the file but also prints it to console.
At the end it creates QString with the same text as the first line of file.
#inc... | This is no answer to why this is happening, but doing
for (int i = 0; i < qv.size(); ++i)
{
//Debugging output
qDebug() << qv[i].toUtf8();
out << qv[i] << "\n";
}
seems to fix it.
|
5,706,601 | 5,707,849 | Overloading function templates in namespaces | Why does this fail to compile with GCC 4.4?
template<typename T>
class A {
public:
void foo () {
}
private:
T x;
};
namespace Ns {
template<typename T>
void do_it (A<T> a) {
a.foo ();
}
};
template<typename T>
void myfun (T x) {
Ns::do_it (x);
}
template<typename T>
class B {
public:
void b... | The reason is that only ADL is done at the point of the call. Other function lookups are only done in the definition of the myfun function template.
And at that definition context, only the do_it overload accepting the A<int> is declared.
Edit: If you want to have a Standard reference for this, refer to [temp.dep.can... |
5,706,641 | 5,706,738 | ASIO ip::tcp::iostream and TCP_NODELAY | How do i set TCP_NODELAY option if i use ip::tcp::iostream? I need a socket for this, but i can't find how to extract it from iostream.
| use iostream::rdbuf()
#include <boost/asio.hpp>
int
main()
{
boost::asio::ip::tcp::iostream stream;
const boost::asio::ip::tcp::no_delay option( true );
stream.rdbuf()->set_option( option );
}
|
5,706,736 | 5,706,975 | How to be sure if a file descriptor has already been closed? | Before voting to close, please read, I know that there are similar questions (:
Here's my situation - I have an application, that is multithreaded. So, lets say I have 10 threads. All of them read from the same file descriptor (it's actually a socket ). And in a very rare situation, when a critical error occurs, the so... | I assume you're saying it's possible for your application to reasonably continue after shutting down the socket?
It seems that a better approach would be to have a mediator thread that gets notified of socket close requests from any of the worker threads, notifies the other threads that the socket is now dead, and take... |
5,706,905 | 5,707,563 | C++ Server-Side-Scripting | For once, I have come across a lot of stuff about the use of C++ being not advisable for SSS and recommending the use of so called interpreted languages like PERL and PHP for the same. But I need the advanced OO features and flexibility of C++ to ensure a scalable and more manageable code.
I have tried many internet ar... | Ignoring, for the moment, the advisability of using C++ for SSS, your first choice would probably be Wt. Contrary to the implications in some of the other answers, no development time is not likely to increase by 10x (or anywhere close to it). No, you're not missing all the nice infrastructure features you'd expect in ... |
5,707,324 | 5,707,517 | Using non-template functions in template classes | I have a task:
To implement a template vector class (let's name it myvector). I need to use this class in multiple files in my project, so I've put it's declarations in "myvector.h" file, and implementation into "myvector.hpp" file, and then included "myvector.hpp" in "myvector.h" after all the declarations (as describ... | You have to declare the function inline (or alternatively move the definition to a single translation unit).
The problem that you are facing is that if you define the function in the header, and include that header in more than one translation unit, the compiler will generate the function in all translation units.
Whe... |
5,707,478 | 5,707,615 | Linking C libraries with a C++ | I created a dll file. This file is compiled as C code. I want to use this dll file in a new project. This new project is a C++ project. If I compile my new project, everything is fine but when the project is compiled as a C++ program, it gives unresolved external symbol error for the functions exported from dll file. I... | Another aproach is to change the C header file to check if is being compiled by a cpp compiler and include the extern "C" conditionally:
#ifdef __cplusplus
extern "C" {
#endif
void func1(int a, int b);
//... other functions
#ifdef __cplusplus
}
#endif
|
5,707,737 | 5,708,463 | Error Handling Paradigms: Mixing Exceptions and Error Codes | I'm currently developing a game engine in C++ using various pieces of middleware including OGRE (graphics), Bullet (physics), and OpenAL (sound), and I'm fairly early on in the project. It's at this point that I'm setting up my error handling mechanisms.
I plan on exposing the engine to the user by containing it within... | I personally prefer exceptions (and have many good reasons for that). But of course throwing exceptions from DLL code to user code (and vice versa) is a bad idea. So in your situation I would use exceptions within modules (both DLLs and executable) and use error_return-based APIs for DLL exports. When using DLL's error... |
5,707,827 | 5,707,918 | No match for operator << in std::cout | I'm trying to print every element inside a vector like this:
vector<users>::iterator i;
for(i = userlist.begin(); i<userlist.end(); i++)
{
cout << *i << "\n";
}
Then I'm getting an error like this:
no match for 'operator<<' in 'std::cout << (&i)->__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* ... | Have you defined a function with this signature?:
std::ostream & operator<<(std::ostream &, const users &);
It should not be a member function of users, although it may or may not be a friend, up to you. The prototype should go in the header file of class users, and the body should go in the source(.cpp) file. I hav... |
5,707,869 | 5,707,871 | C++11 range-based for on a vector of pointers | I have just compiled GCC 4.6.0, and I wanted to try the new features out, starting with the range-based for loop.
The first loop I wanted to change was iterating on a std::vector of pointers. I changed the code to use the new syntax, but it didn't compile.
I have tried to substitute another for loop, which was on a std... | for ((int*) &p : values)
This is wrong. (int*) is an expression alone, so you need to do int*& (with no parenthesis, that makes an expression - aka "not a type name") at least to make it correct. I prefer to use auto or auto&, personally.
You can do :
for (auto p : values) // here p is a pointer, a copy of each pointe... |
5,707,957 | 5,780,603 | c++ libcurl json rest | I am trying to download a json file from a REST webpage in C++ with libcurl.
The following code works if I go to the webpage but it doesnt download if I try to access the json ....
I think it should be an easy fix but I cant find any reference to this ...
If I go to webpage it opens the json but this code only returns ... | std::string ServerContent::DownloadJSON(std::string URL)
{
CURL *curl;
CURLcode res;
struct curl_slist *headers=NULL; // init to NULL is important
std::ostringstream oss;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: a... |
5,707,977 | 5,708,010 | std::sort() C++ not working but its so simple, why :( 1D array | This should be really simple, I have found that the first argument is the array name, the second is the size of the array + array name. However, it doesnt seem to be sorting at all, in fact its not doing anything, well not writing anything on the console, am I doing somethin silly?
int main()
{
readFromFile();
... | while (!file.eof())
{
file >> numbers[i];
i++;
int elements = sizeof(numbers) / sizeof(numbers[0]);
**sort(numbers, numbers + elements);**
}
file.close();
to
while (file >> numbers[i])
{
++i;
}
sort( numbers, numbers + i );
file.close();
or
std::vector<your_int_type> numbers;
your_int_type tmp;
w... |
5,708,198 | 5,724,570 | Implementing Cached Data for C++ CGI | We have an Apache CGI application written in C++ (using cgicc extensions) that currently accesses some in-memory MySQL (using HEAP engine) tables. We are to the point now where the sheer number of transactions we are processing per day have exceeded the server's ability to service the queries required to service these... | I would implement some test code for benchmarking purposes using boost::multi_index. It is a pretty good replacement for most in-memory database operations.
I don't know if you can use it in a movable shared memory allocation, but if you are using a 64-bit OS it should be possible to choose a fixed point in memory to m... |
5,708,227 | 5,708,257 | Should I declare any method that can be const a const method | Simple question. Should I declare any method that can be const a const method? This includes methods that don't return any member variables, or return const references to member variables. Is there any reason not to do so (apart from the obvious reasons, which the compiler will point out anyway)?
| A non-const method cannot be called through a pointer to a constant object. So if method can be const, not declaring it const would impose artificial limits on its use.
Apart from that, making a method const is an important semantic detail to give the user a feeling of the effect that could be expected from calling it.... |
5,708,259 | 5,708,403 | Backslash newline at end of file warning | With this code:
#include <iostream>
int main(int argc, char *argv[])
{
return 0;
}
/** run2: A macro to call a function. */
#define run2( function, ctype, dim ) \
if ( operation == #function ) \
{ \
if ( componentType == #ctype && Dimension == dim ) \
{ \
typedef itk::Image< ctype, dim > ImageType; \
... | The problem is that there's no new-line character in the end of your code. C++ Standard §2.1/2 says:
<...>If a source file that is not
empty does not end in a new-line
character, or ends in a new-line
character immediately preceded by a
backslash character, the behavior is
undefined.
|
5,708,433 | 5,708,917 | detecting header click in QTableWidget c++ qt4 | I have a QTableWidget in my program that I use to display results and I am trying to be able to detect when a user single clicks one of the vertical headers. To do this I am trying to connect the signal sectionDoubleClicked(int) to my function hheaderclicked(int). When I try to compile the code I get a compile time e... | The error message gives the third argument as MainWindow* const, which is rather odd. If it was const MainWindow*, the call should work. How is the calling function declared?
|
5,708,610 | 5,708,732 | LLVM vs clang on OS X | I have a question concerning llvm, clang, and gcc on OS X.
What is the difference between the llvm-gcc 4.2, llvm 2.0 and clang? I know that they all build on llvm but how are they different?
Besides faster compiling, what is the advantage of llvm over gcc?
| LLVM originally stood for "low-level virtual machine", though it now just stands for itself as it has grown to be something other than a traditional virtual machine. It is a set of libraries and tools, as well as a standardized intermediate representation, that can be used to help build compilers and just-in-time compi... |
5,708,847 | 5,709,085 | Initializing a static std::map<int, STRUCTURE> in C++ | This post taught me how to initialize static std::map.
I could use this method to initialize a static map from int to STRUCTURE.
The code is as follows
#include <string>
#include <map>
#include <iostream>
typedef unsigned long GUID;
enum Function {
ADDER = 1,
SUBTRACTOR = 2,
MULTIPLIER = 3,
SQUAREROOT = 4
}... | I'd use Boost.Assignment :
#include <boost/assign/list_of.hpp>
...
/* no more temp1, temp2, or PluginDbArray */
...
PluginDB pluginDB = boost::assign::map_list_of
(1, PluginInfo(1, "Adder", ADDER))
(2, PluginInfo(2, "Multiplier", MULTIPLIER));
|
5,708,860 | 5,715,001 | How do you draw text in DirectX 11? | In DirectX 10 you could use the font interface provided by D3DX10. In DirectX 11 you are supposed to use DirectWrite. But it looks like DirectWrite doesn't speak natively to Direct3D? Is there something basic I'm missing? How do you draw simple text with DirectX 11?
| Edit 2014:
As pointed out in comment, the link to RasterTek tutorials no longer functions, here is a link to Webarchive of RasterTek provided by RadioSpace.
The second point of the original answer is no longer valid either, because its now possible to share D3D11 backbuffer with Direct2D and through it draw text with D... |
5,708,885 | 5,708,987 | storing data and access it | What is the best way to store data & fastest way to access it, that is free and doesn't require additional stuff to install ?
| Well if the language is C, you could use structs and fread() & fwrite() to save the data into single "database" file. It is not the most compatible way but it certainly is fast. And it doesn't require any additional stuff to be installed.
|
5,709,138 | 5,709,291 | Using Objects into a Glut Display Function | i'm having trouble using an object in a glut DisplayFunction.
class Modelisation
{
private:
int hauteur, largeur, x, y;
Camera *Cam;
void DisplayFunction ();
static void RedisplayFunction (int, int);
public:
Modelisation (int argc, char **argv, char[]);
~Modelisation ();
void StartMainLoo... | In C++, data members and methods that a static method uses must also be declared static. The easiest way out of this is to declare Cam to be static.
You'll also have to initialize it statically, that is, in your implementation file:
Modelisation::Camera* Cam = new Camera();
(Note that, depending on how else Cam is us... |
5,709,218 | 5,709,318 | Safely synchronizing a COM thread | I've done a lot with multithreading in the past, but I'm fairly new to COM. Anyway, here's my issue:
I create a worker thread, which registers as an STA, and creates a COM object. Then the worker thread and the main thread try to communicate with each other. Using CoMarshalInterThreadInterfaceInStream and CoGetInter... | Your main thread has a message queue (must be, since is an STA host), why not simply post a message to it, PostThreadMessage? Post an user message (WM_USER +X) and your normal main thread message pump can handle this user message as a notification that the COM object has marshaled the interface into the stream and the ... |
5,709,480 | 5,709,537 | Using Event Handles Across Threads - C++ | I have an application wherein I am sharing event handles across threads. These event handles are used to signal transmit complete and received data notifications of serial I/O to the application. The handles are copied to the new threads as a passed parameter of class constructors or calls to CreatThread. I thought ... | It should not be necessary to use that API (DuplicateHandle) if all the threads using the existing handle are in the same process. Threads within the same process can use the same handle value for events, semaphores, etc.
|
5,709,593 | 5,711,900 | Positioning an array of objects in OpenGL | Edit:
I'm still not getting the correct position, all the balls are being drawn at the origin, I think I may be putting things in the wrong places...
Ball.cpp
#include "Ball.h"
#include "Vector2f.h"
#include "Vector3f.h"
#include "Glut/glut.h"
#include "GL/gl.h"
#include "GL/glu.h"
Ball::Ball(void)
{
Vector3f T... | Do something like this:
// first of all, include the x,y position (assuming 2D, since pool) in the Ball object:
class Ball
{
//...
private:
int xpos, ypos;
//...
};
Then when you construct the array of balls, rather than just making 8 balls, you're going to want to allocate the memory on the heap so th... |
5,709,637 | 5,709,653 | C++ vector insertion sort algorithm method - pass vector into method | Ive look everywhere and whatever algorithm I find (if any lol) for insertion sort on a vector in c++, it wont work so im assuming it has something to do with my code. Can anyone help me find a way I can pass a vector into a method as an argument and then do an insertion sort on it? At the moment it waits for a few seco... | Your function accepts its argument by value; this means it gets a copy. You sort the copy, in vain.
Change it to a reference instead:
void insertionSort (vector<int>& data, int n)
|
5,709,820 | 5,714,995 | Communication between C++ and QML | This page shows how to call C++ functions from within QML.
What I want to do is change the image on a Button via a C++ function (trigger a state-change or however it is done).
How can I achieve this?
UPDATE
I tried the approach by Radon, but immediately when I insert this line:
QObject *test = dynamic_cast<QObject ... | If you set an objectName for the image, you can access it from C++ quite easy:
main.qml
import QtQuick 1.0
Rectangle {
height: 100; width: 100
Image {
objectName: "theImage"
}
}
in C++:
// [...]
QDeclarativeView view(QUrl("main.qml"));
view.show();
// get root object
QObject *rootObject = dynam... |
5,709,825 | 5,710,248 | Is this a valid use of intrusive_ptr? | Within my code I follow two rules when it comes to intrusive_ptrs:
Passing a raw pointer by value implies that the raw pointer is guaranteed to be valid during the lifetime of that function.
If the raw pointer is to be stored and used beyond the lifetime of the function, it should be stored in an intrusive_ptr.
Many ... | Passing a raw pointer around in a public API that has ownership semantics should be done only rarely, and only when absolutely necessary. E.g. interfacing with code whose interface you can not change.
Passing around a raw pointer in a private API, e.g. within the members of a single class is no problem.
Consider these... |
5,709,841 | 5,709,851 | Address of &this instantiated class? | My goal is to write a function that returns the address of the instantiated class from which it is called.
My initial guess was
return &this
But this does not yield any good results.
Any and all suggestions are much appreciated! Thanks!
| Simply return this will return the address of an object from within that object.
|
5,710,091 | 5,710,131 | How does atoi() function in C++ work? | So...I know that the atoi function in the C++ standard library is supposed to convert a string into an integer...how does it work?...(I'm trying to learn stuff and I was just wondering)...if you could show me the code from it or make your own that would do the same task it'd be greatly appreciated...thanks in advance.
| Something like this:
int atoi( const char *c ) {
int value = 0;
int sign = 1;
if( *c == '+' || *c == '-' ) {
if( *c == '-' ) sign = -1;
c++;
}
while ( isdigit( *c ) ) {
value *= 10;
value += (int) (*c-'0');
c++;
}
return value * sign;
}
You loop through... |
5,710,302 | 5,710,307 | Why won't my constructor re-initialize variables when the loop executes? | My tic-tac-tow board maintains the same values as the last game, instead of reinitializing to the values it is supposed to be assigned in the constructor. (123, 456, 789)
Does anyone have a clue why this may be?
Constructor:
ticTacToe:: ticTacToe()
{
for (int i = 0; i < 1; i++)
for (int j = 0; j < 3; j++)
... | ticTacToe();
This constructs a temporary ticTacToe object then destroys that temporary object. It doesn't actually "re-call" the constructor of the current object.
I think the correct approach here would be to provide a "reset()" function that redraws the game board. That said, even that doesn't make sense since yo... |
5,710,458 | 5,710,477 | Is it Possible to Display Editable Text In A Shell Via The Standard C++ IOStream? | Is it possible to display interactive and editable text in a console via a standard C++ iostream?
In other words, would it be possible to have basic Vim-esque text editing abilities using only the standard C++ iostream within a shell?
For example, suppose a simple string exampleText containing the text "Example text." ... | Of course it is possible. Just output the correct terminal escapes. For each escape make sure you cover for all the popular terminals.
Or save yourself the trouble and use readline or ncurses.
|
5,710,513 | 5,710,544 | difference between two ways to insert into map | I was asked the two ways to insert a record to a map,
mymap["foo"] = 123;
mymap.insert("foo", 123);
so is there any difference between these two except the syntax?
| In addition to Timo's excellent answer--
If no element at "foo" exists, the first will first default construct a value at the "foo" location, THEN using a reference to the default constructed "foo" value, assign 123 to that location.
Just doing
mymap["foo"]
will cause a value to be default constructed and placed at t... |
5,710,661 | 5,710,699 | Is std::clock() reliable accross Windows, Mac and Linux? | I want to use this as a means to compare how long since my last update in my game. Is the precision of it pretty consistent across these platforms.
Thanks
| What has this to do with the Standard? That is totally dependent on the underlying implementation, also, the clock can be skewed by battery, drifts, underlying operating systems etc...
Really, for a game, you should be using a multimedia timer mechanism, that would be part of a multimedia library, to get the precision... |
5,710,698 | 5,710,735 | C++ call class method from within class | I have a class that implements a linked list. The class has a find() method which finds a value if it exists in the linked list. I have another method add() which adds a node, but ONLY if that value contained in that node does NOT already exist in the list.
So what I want to do in my add() function is use my find meth... | Just call find(x). No this required. Also, this is a pointer to the current object. So you would have to do this->find(x).
|
5,710,703 | 5,710,720 | What does char * mean | So...say I had a function like this...
int function( const char *c )
{
//do something with the char *c here...
}
what does char *c mean? I know about chars in general I think but I don't get what the * does...or how it changes the meaning.
| It means that this is a pointer to data of type char.
|
5,710,747 | 5,710,808 | How is a global object constructed before a const it was declared after? | I just encountered a strange issue. In WinMain.cpp, AFTER I include a user-created header file, but BEFORE WinMain, I declare a global instance of my class Brain, like so:
(windows includes)
#include "BrainLib.h"
#include "Brain.h"
Brain brain;
(wndproc declaration)
WinMain() {
(some code using Brain)
}
In BrainL... | The order in which global objects are initialized is undefined.
|
5,710,942 | 5,721,471 | C++ on Small-Footprint Microcontrollers | It seems to me people consistently shy away from, or rather vehemently oppose the use of, C++ on microcontrollers, but I can't for the life of me figure out why. If you stay away from large C++ libraries (e.g. STL) and you don't try to use complicated features like RTTI or exception handling, is there really any notice... | In C++ you essentially only pay for what you use over and above what would otherwise be C compilable code, and some of the extras are cost free.
The biggest issue with some C++ compilers for small targets is the completeness of available C++ implementations or the availability of a C++ compiler at all.
EETimes/Embedde... |
5,710,998 | 5,712,018 | Is there a convenient font library for OpenGL-ES 2 like glFont? | Brad Fish's glFont seems pretty cool. But it won't work under OpenGL ES 2.0. Has anyone found a set of font utilities that work in OpenGL-ES 2.0?
I suppose I could port glFont, but it's quite a bit of work.
| Looks like this might be what you're looking for. This is for OpenGL ES 1.1 however, not sure if it's also compatible with 2.0. It should be as far as I know.
|
5,711,038 | 5,711,118 | C++ Passing an Array of Struct one by one - so simple but I'm stumpted | First a big THANK YOU to everyone that helps!
I am trying to pass one variable at a time here and not the whole array. I know I'm close, but I've searched and searched and can't find out what I'm doing wrong.
There error I am getting it says is with
void PrintRecords(studentRec& myRec)
it says: Variable for field 'P... | You have declared as struct StudenRecord {}; It seems to be a typo. Change everywhere to StudentRecord.
|
5,711,067 | 5,720,972 | What is the best way to communicate with DLLs each other | My program has several modules which is dll.
And one of dlls should notify to the others with some data.
What would you do?
Use shared memory map and event?
or give them a callback function and relaying of program(exe)?
Please let me know the general way.
| Here's a nice trick for communication between modules:
struct A { int a; int b; };
void dll1(A &a);
void dll2(A &a);
int main() {
A a;
while(1) {
dll1(a);
dll2(a);
}
}
This will put the whole dll1 to a single function. It can communicate with the other dll by modifying the struct A. Now this will have ... |
5,711,176 | 5,711,257 | Can't find the memory leak in this code | I've been looking for over 2 hours and it turns out my memory leak is coming from this section, only I am unable to determine what is causing the leak. BTW, I am using Allegro5, but made some wrappers.
void WidgetLabel::updateBitmap( Display* display )
{
Size textSize = getTextSize( _font, _text.c_str() );
_b... | Assuming that createbitmap allocates memory, are you overwriting _bitmap always, when you call updateBitmap() ? (Is there any statement you are missing to manage _bitmap ?)
It might crash, if _bitmap is not initialized and you are trying to free it. You can initialize _bitmap in constructor as 0 and then check for NULL... |
5,711,272 | 5,711,286 | c++ const_cast question | const int a = 1;
int *p = const_cast<int*>(&a);
*p = 2;
cout << “value a=”<< a << endl;
cout << “value *p=” <<*p << endl;
cout << “address a=” <<&a << endl;
cout << “address p=” <<p << endl;
output:
value a=1
value *p=2
address a=0xbff1d48c
address p=0xbff1d48c
WHY???
why same addr ,diff value?
confused.
thank you!
| In C++ language it is illegal to attempt to modify constant objects. Such an attempt results in undefined behavior.
In your program the *p = 2 assignment attempts to modify a constant object a. The behavior is undefined. The weird output you observe is exactly that: undefined behavior.
There's no meaningful explanati... |
5,711,291 | 5,721,463 | Get the handle and write to the console that launched our process | How could I write to the standard output of some already open console?
I find the console I need with this piece of code:
IntPtr ptr = GetForegroundWindow();
int u;
GetWindowThreadProcessId(ptr, out u);
Process process = Process.GetProcessById(u);
The problem is how to get the standard outpu... | I finally figured out how to attach transparently to a console if it is the foreground window while launching the windows app.
Don't ask me why STD_ERROR_HANDLE must be passed instead of STD_OUTPUT_HANDLE, but it simply works, probably because the standard error can be shared.
N.B.: the console can accept user input wh... |
5,711,295 | 5,711,324 | MergeSort a vector using Iterators | For a class assignment, I am required to mergeSort a vector using its iterators.
I wrote the following that works on vectors, but does not use iterators:
void MergeSort(IntVector &vec, int left, int right)
{
if (left < right)
{
int nMid = ((left + right) / 2);
MergeSort(vec, left, nMid);
... | You want to compare if the iterators are the same (only error condition possible with sane input):
if (left!=right)
As for your addition concerns, you're thinking of it wrong. Semantically adding left and right makes no sense since it goes past the end of your array, not to mention it will overflow. What you want is ... |
5,711,318 | 5,711,439 | Why is my expected output not happening? | /*This program will ask a user to enter a song list. By doing this each time that the user enters
a song, he/she will then be asked if they want to enter another song, if yes then they will enter another song.There will be a maximum of 15 songs.
This progarm will help a user keep track of their songs. But then the p... | In...
songarray[j].length();
...j has been set to 0, so it asks for the length (in characters) of the first song title, not the number of populated song titles in the array (which you're not keeping track of at all).
Suggestions:
use a std::vector<std::string> for your song titles, and push_back() new song titles as ... |
5,711,499 | 5,712,103 | Using a C++ iterator to read a list from a file? | I am trying to read/deserialize a list of elements from a file (and then filter out some of them). It is a useful approach to use an iterator for this purpose?
My current try is
#include <boost/iterator/iterator_adaptor.hpp>
class ReadIterator : public boost::iterator_adaptor<ReadIterator, Elem *, boost::single_pass_... | The easy way to do this is to use the std::istream_iterator
std::vector<YourObjectClass> data;
std::remove_copy_if(std::istream_iterator<YourObjectClass>(file),
std::istream_iterator<YourObjectClass>(),
std::back_inserter(data),
YourFilter
... |
5,711,522 | 5,711,554 | Get parent directory from file in C++ | I need to get parent directory from file in C++:
For example:
Input:
D:\Devs\Test\sprite.png
Output:
D:\Devs\Test\ [or D:\Devs\Test]
I can do this with a function:
char *str = "D:\\Devs\\Test\\sprite.png";
for(int i = strlen(str) - 1; i>0; --i)
{
if( str[i] == '\\' )
{
str[i] = '\0';
break;
... | Editing a const string is undefined behavior, so declare something like below:
char str[] = "D:\\Devs\\Test\\sprite.png";
You can use below 1 liner to get your desired result:
*(strrchr(str, '\\') + 1) = 0; // put extra NULL check before if path can have 0 '\' also
|
5,711,621 | 5,716,413 | SIGSEGV after Glib::RefPtr goes out of scope? | I have this bit of code, which is working fine:
WebKit::WebView web;
// later:
{
Glib::RefPtr<WebKit::WebSettings> settings = WebKit::WebSettings::create();
// do some stuff to the object
web.set_settings(settings);
}
At some later time, when web is still in scope but settings has fallen out of scope, I do... | it's quite possibly a bug in the binding. You should report it.
|
5,711,662 | 5,711,726 | function template for serialization of enums | I have written a function template for serialization of enums to/from our stream class (Yes, I know boost::serialization, but it is not an option in my situation). Enums by convention in our company are serialized as int:
template<typename T>
Stream& operator<<( Stream& s, T const& value )
{
s << ( int ) value;
}
... | There are two improvements to be made here: not always serializing as int (not all enums are), but as whatever the underlying type is. And, as your request, to only accept enums.
The latter is easily solved with std::enable_if and std::is_enum:
typename std::enable_if<std::is_enum<T>::value, Stream&>::type
operator... |
5,711,772 | 5,712,019 | error: lvalue required while operator overloading ++/-- etc | I transferred my code to Ubuntu 4.4.1 g++ compiler. While overloading operator ++ (int) as below, it throws error for (T*), but works fine for (T*&). In my earlier version (linux-64, but don't remember exact version) it was working fine with (T*) also.
Any reason, why ?
template<typename T>
struct Wrap
{
void *p; //... | A result of a type-cast is not an lvalue, so it cannot be assigned to and (built-in) ++ is a form of assignment. It was a bug in the compiler if it ever worked.
With reference it compiles (in efect it's the same as *(T**)&p), but due to aliasing rules (compiler may assume that pointers (and references) of different typ... |
5,711,801 | 5,711,831 | C++ Multi-thread text output print to dos console overlapped/Mess up the outputs | I had a multi-thread program which execute from dos prompt, there are some prints and outputs dump to dos console using std::cout, but when thread1 and thread2 finished it jobs and then join() to main app, some printouts and outputs were overlapped and not aligned (no newline,running into each other).
Sometime they ar... | Well, it's simple. Output has no concurrency control, you're getting data races. You need to have your threads lock a mutex before they use output, then release it when they're done.
|
5,711,915 | 5,712,009 | Use only standard C++ to print any float to exactly N spaces | I have a float that I would like to print to exactly N spaces. For example, with N = 5. I want to get the following numbers printed as so:
0.1 => 0.1
123.456789 => 123.5
-123.45678 => -123 (or -123.)
0.123456 => 0.123
123456.789 => 123456 (obviously, in this case, we cannot print less than 6 digits, if I can d... | int main ()
{
const int N = 4;
double f = 123.456789;
// just use default floating-point notation to display N significant digits.
// no fixed or scientific notation work for your requirement.
// you can comment setf() line out if there is no one changing ios::floatfield.
cout.setf(0, ios::floatfield);
... |
5,712,172 | 5,712,235 | how can I store 3 integer in priority_queue? | I want to store 3 integer in priority_queue. I know how to store 2 integer.
I store 2 integer with pair<int,int>
my code
priority_queue<pair<int,int> , vector<pair<int,int> > , greater<pair<int,int> > > pq;
pq.push(make_pair(5,6));
but I don't know how can I store 3 integer. I need help.
sorry for my English.
| Simplest would be create a struct which logically binds all the integers and create a priority queue of that struct objects.
EDIT
Sample code:
#include <queue>
using namespace std;
struct S
{
int m_n1;
int m_n2;
int m_n3;
S(int n1, int n2, int n3) : m_n1(n1), m_n2(n2), m_n3(n3)
{
}
bool o... |
5,712,222 | 5,713,308 | Making a C++/MFC application to extract AssemblyInfo from other applications? | I am trying to make a C++/MFC application (so called "Update Application") that can extract AssemblyVersion information from other applications written in C#/.NET 3.5.
So I can update my C# program according to the version information I can get.
I am pretty sure this is possible, but I don't know which way would be the... | Here's roughly how we do something similar in a native C++ app.
Compile with /clr. You can do this project-wide or just on selected C++ files, but as far as I remember there were complications doing it selectively and so we just did it project-wide. Also #include <vcclr.h> wherever appropriate.
You'll need to learn abo... |
5,712,808 | 5,712,953 | What is the first (int (*)(...))0 vtable entry in the output of g++ -fdump-class-hierarchy? | For this code:
class B1{
public:
virtual void f1() {}
};
class D : public B1 {
public:
void f1() {}
};
int main () {
B1 *b1 = new B1();
D *d = new D();
return 0;
}
After compilation, the vtable I get with g++ -fdump-class-hierarchy is:
Vtable for B1
B1::_ZTV2B1: 3u entries
0 (int (*)(...))... | Those are the offset-to-top (needed for multiple inheritence) and typeinfo (RTTI) pointers.
From the Itanium ABI (you are not using the Itanium compiler, but their description of this is really good):
The offset to top holds the displacement to the top of the object from the location within the object of the virtual t... |
5,712,818 | 5,712,841 | Why is the address of an object added to a C++ STL vector different than its original address? | I've got a very simple method that adds a node to a graph:
template<class T>
void AdjacencyList<T>::add(const GraphNode<T>& node) {
_nodes.push_back(node);
}
In another method, I iterate over the _nodes vector, looking for the added node by address:
for (unsigned int i = 0; i < _nodes.size(); i++) {
if (&(... | Because it's a different object. All standard containers own their objects and all types that you use in standard containers must be copyable.
When you pass an object to push_back it is copied into the vector. If you want to be able to find it later your object type must have a concept of equality where you can compare... |
5,712,826 | 5,713,038 | Argument type auto deduction and anonymous lambda functions | Lets say I have these lines of code;
std::vector<int> ints;
std::for_each(ints.begin(), ints.end(), [](int& val){ val = 7; });
However, I dont want to specify the argument type in my lambda functions, ie, I want to write something like this;
std::for_each(ints.begin(), ints.end(), [](auto& val){ val = 7; });
Is there... | No. "Polymorphic lambdas" is what this feature was referred to during the C++ committee discussions, and it was not standardized. The parameter types of a lambda must be specified.
You can use decltype though:
std::for_each(ints.begin(), ints.end(), [](decltype(*ints.begin())& val){ val = 7; });
|
5,713,058 | 5,713,804 | Visual Studio 2010 + CUDA 4: Unrecognized token error when attempting to allocate memory using NPP | I have the following source file (CUDA_Integral_Image.cu) for a class of the same name:
#include "cuda_runtime.h"
#include "npp.h"
#include "CUDA_Integral_Image.h"
#include <stdlib.h>
#include <time.h>
...
// allocated device source image
int step = width;
Npp8u* pSI = nppiMalloc_8u_C1(width, height, &step);
// copy ... | The last argument to nppiMalloc_32s_C1 is incorrect. It should always be a pointer to an integer variable. The routine internally calculates the correct size for the allocation (include alignment) and returns the size to the caller.
|
5,713,099 | 5,713,136 | What can cause VTable pointer to be 0xdddddddd in Win32 debug build? | I am debugging a defect and have narrowed it down to the vtable pointer for an object being 0xdddddddd. This answer indicates that Win32 debug builds will generally set dead memory, or memory which has been deleted, to this special value.
Note that the pointer itself looks valid, it's just the vtable pointer that is 0... | You are using the pointer after it has been released. Get a stack trace from a breakpoint in the destructor to see what is deleting it. Or better yet, use shared_ptr<> to avoid the problem.
|
5,713,131 | 5,713,148 | storing xml to a string | I was trying to store an xml to a string.Is that really doable in C++?I am getting a copile error:
error: parse error before string constant
when trying to write a line of code as following :
string xmlString = "<animalList dnPrefix="String">
<node>
<animal ID="xxxxxxxx"... | You have to escape the " characters and the newline characters.
Something like:
std::string str = "bryan says: \"quoted text\" :) \n\
other line";
Which will give you the following string:
bryan says: "quoted text" :)
other line
Also note that if you intend to store specific utf-8 or Latin1 characters in your string,... |
5,713,229 | 5,713,519 | Is it safe to store a local declared object in a global QList? | I got a CPP program where i make a local object A and want to store it in global object B which is a QList.
Is it save to statically allocate object A or do i need to use the new keyword.
Does QList uses the copy constructor?
Thanks
| QList stores copies of objects, so it should work. However make sure that copying is indeed what you want. If this isn't the case, allocate your object with new and store the pointer in the QList.
|
5,713,451 | 5,880,485 | Is it safe to parse a /proc/ file? | I want to parse /proc/net/tcp/, but is it safe?
How should I open and read files from /proc/ and not be afraid, that some other process (or the OS itself) will be changing it in the same time?
| In general, no. (So most of the answers here are wrong.) It might be safe, depending on what property you want. But it's easy to end up with bugs in your code if you assume too much about the consistency of a file in /proc. For example, see this bug which came from assuming that /proc/mounts was a consistent snapshot.
... |
5,713,685 | 5,713,858 | Can one extend virtual interface without recompilation of client code? | A library provides a class with virtual functions. Can this class be extended with new virtual functions without recompiling binaries dynamically linked to the library?
I beleive this is not possible in standard. Are there platforms allowing this?
Would that be easier if new functions are only added to the end of the c... | The standard is not concerned with binary compatibility. It is concerned though with classes, and by "changing" the definition of a class from one translation unit to another you indeed invoke undefined behavior.
Most compilers do allow a number of changes without the need for recompilation, however the list is small..... |
5,713,776 | 5,714,148 | How to improve performance without going parallel for my backprop ANN | After profiling my Back propagation algorithm, I have learnt it is responsible for taking up 60% of my computation time.
Before I start looking at parallel alternatives, I would like to see if there is anything further I can do.
The activate(const double input[]) function is profiled to only take ~5% of the time.
The g... | You can't avoid an O(n^2) algorithm if you want to train/use a NN. But it is perfectly suited for vector arithmetic. For example with clever use of SSE or AVX you could process the neurons in chunks of 4 or 8 and use a multiply-add instead of two separate instructions.
If you use a modern compiler and carefully reformu... |
5,713,894 | 17,789,868 | File not recognized: File truncated GCC error | I'm trying to compile a simple "Hello World" program in Linux using Eclipse, but I always get this:
Building target: hello
Invoking: GCC C++ Linker
g++ -o "hello" ./src/hello.o
./src/hello.o: file not recognized: File truncated
collect2: ld returned 1 exit status
make: *** [hello] Error 1
**** Build Finished ****... | Just remove the object file.
This error most likely appeared after the previous build was interrupted and object file was not generated completely.
|
5,714,119 | 5,715,310 | Ideas for Garbage Collection | I am working on a toy language that uses C++ as an intermediate language, currently it only supports three types all decent from a base class, integer, list and lambda. All functions pass base class back and forth. Compiled code runs on a microcontoller, which means there are certain restrictions I only have 8 kb of ra... | I know of two general mechanisms for garbage collection:
Reference Counting
Mark And Sweep
There are various flavors / improvements which correspond more to implementations strategies (Generational, Copying, Compacting, ...).
In general, the Reference Counting is the best for reactivity (which is important here), how... |
5,714,484 | 5,714,799 | Remove unused method in dependency | I have a project that contains several submodules, that communicate using some objects that are serialized by one process and then deserialized by another process and used at this other point. So these objects need to contain logic for usage in the first process, in the second process as well as serialization and deser... | One way to solve this is to dynamically link with libB (if the size of the executable is your concern).
The other option is to take the common code out of libA and libB into a library (libC). Then, your programs will need to link with libA and libC, and libB and libC.
I do not see other way around this.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.