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
7,898,524
7,898,646
how to use a class in a function parameter
please help, im designing a contact book as a project and i'm having compiling the code properly and im getting errors. problem in relation to Address class.. feel free to copy and run code to see what im talking about. thanks in advance #include<iostream> #include<cstdlib> #include<string> using namespace...
Here's the output of your code when run through clang (for its far nicer messages). λ > clang++ blah.cxx blah.cxx:81:27: error: no viable overloaded '=' fn= f_n; ln= l_n; address ="" ;email= emaila;number= num; ~~~~~~~ ^~~ blah.cxx:5:11: note: candidate function (the implicit copy assignment operator...
7,898,552
7,898,575
ld path update for compiling
I just installed manually apr and apr_util so i can install activemq c++ library. When i try to make the cpp library i get the following error: ** libtool: link: g++ -ansi -pedantic -DLINUX=2 -D_REENTRANT -D_GNU_SOURCE -I/usr/local/apr/include/apr-1 -I/usr/local/apr/include/apr-1 -I/usr/kerberos/include -W -Wall -Wextr...
Usually you'll need to manually specify the library path using -L option. It would look like ld filename -Lpath -llibname in a single ld operation. Or in this case you may need to add the paths of your library(apr-util here) to the constant of library paths in a Makefile.
7,898,788
7,898,873
How do I solve "unresolved external symbol" errors in a DirectX 11 program?
I am working on a DirectX 11 project for school and I followed the book thoroughly when doing this. I keep thinking that maybe something is labeled wrong but I double checked all my files, all my class names are fine (I believe they are fine) and double checked how all my header files are setup and everything should be...
Evidently, you either haven't implemented a handful of methods from the DemoBase class (including its constructor and destructor), or you haven't included the implementation file in the list of files to compile or link with your program. Implement them, and then make sure you've included the source file in your project...
7,898,857
7,898,947
Scope of members in class
In the following example, will the size of array v guaranteed to be 2 or 3? static const int i = 3; class X { char v[i]; static const int i = 2; }; From the standard, 3.3.6/2 A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S I th...
The correct behavior is that it should cause an error because re-evaluation would change the meaning: Example from section 3.3.6: The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lex...
7,898,991
7,913,100
Why sync-safe integer?
I'm recently working on ID3v2.4.0. Reading 2.4.0 document, i found a particular part that i can't understand - sync-safe integer. Why does the ID3v2 use this method? Of course, i know why the ID3v2 uses Unsynchronization scheme, which is used to keep MPEG decoder from considering ID3 tag as a MPEG sync data. But what i...
I would presume for simplicity, and the unsynch/synch scheme only makes sense when used on an mpeg file. It is trivial to read in the four bytes and convert them to a regular integer: // pseudo code uint32_t size; file.read( &size, sizeof(uint32_t) ); size = (size & 0x0000007F) | ( (size & 0x00007F00) >> 1 ) |...
7,899,108
7,903,042
OpenCV get pixel channel value from Mat image
Maybe I'm not looking hard enough, but everything seems to want me to use an array. Thus, how do I get the channel value for a particular pixel for foo if foo is something like Mat foo = imread("bar.png")?
Assuming the type is CV_8UC3 you would do this: for(int i = 0; i < foo.rows; i++) { for(int j = 0; j < foo.cols; j++) { Vec3b bgrPixel = foo.at<Vec3b>(i, j); // do something with BGR values... } } Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things...
7,899,115
7,899,176
Straight line in c++
What libraries does Windows provide to draw lines? I am only interested in 2D libraries, not OpenGL or DirectX. I am working in C++.
cout << ".------------------------------------------------------------." << endl; cout << ".\n\ |\n\ |\n\ |\n\ |\n\ |\n\ |\n\ |\n\ |\n\ |\n\ |\n\ ." << endl; EDIT: Forgot the dots. EDIT 2: Diagonal: for( int i=0; i<10; ...
7,899,209
7,899,219
cout << "text" gets displayed only part of the time
I learned the hard way about using endl at the end of a cout statement to flush the buffer. What I'm confused about is why endl is only necessary sometimes. Usually I can just do cout << "test"; And it will display test. But in the middle of a long console program I'll have a similar cout statement and nothing will di...
When the buffer reaches a certain length or the program terminates normally, the buffer is flushed.
7,899,217
7,899,260
Language extensions and new keywords
What does a standard say about extending a C++ language and adding 'non standard' keywords? Do the keyword have to start with __ (double underscore) or can the be 'regular', meaning starting with a letter? If I would about to create extension to C++ and have a new keyword do I have to make it look like this: __new_k...
The standard says that identifiers with two underscores are reserved for the compiler. So if you want a safe way to add language extensions in your C++ compiler, that would be one way to do it. Be advised that if you're just writing a pre-processor, the compiler you use may conflict with what you choose. But since the ...
7,899,237
7,899,264
Function for calculating the mean of an array double[] using accumulate
It must be the most common function for what everyone has a code snippet somewhere, but I have actually spent no less than 1.5 hour searching for it on SO as well as on other C++ sites and have not found a solution. I would like to calculate the mean of a double array[] using a function. I would like to pass the array...
Try to add #include <numeric> It will bring in the 'std::accumulate' function you're looking for. Going further, you're gonna have a problem to find out the number of elements in your array. Indeed, an array cannot be passed to a function in the hope that the function will be able to know the size of the array. It wil...
7,899,242
7,899,270
Can i go to the error after executing make in VIM?
Can i go to the line of error , while compiling a C or C++ project ? Usually by executing make , and parse the error string , and go to the specific file , and the line with errors. Is there already an usable plugin ?
Yeah this is already buit into vim. After typing :make type :cwindow to bring up the error list. You can then navigate to the errors using this window.
7,899,256
7,899,340
C++ : class classname :: reference { ... }
I was learning stl and never saw this kind of class like class classname :: reference {} I searched on the net but could get good information .. class bitset::reference { friend class bitset; reference(); // no public constructor public: ~reference(); operator bool () const; ...
Did you look at the bitset class definition? There is something like this somewhere: template<size_t _Bits> class bitset { ... class reference; ... } It's much like putting the body of a funciton outside the class body. Now we are putting the body of a nested class outside of the parent class: class bitset...
7,899,269
7,899,309
Passing arrays as a reference
In C++ how can I pass an array as a reference when I don't know the size at compile time? So far, I found out that the only way to make it work is to use something like const double( &numbers ) [size] but it means that I need to know the size of the array at compile time, thus I cannot use it in an external function. ...
In C++, you should use std::vector. In C/C++, you can't pass arrays as a copy. Arrays are always passed by reference. EDIT In C++, arrays passed by reference has different meaning. In both C and C++, arrays decay into a pointer to the first element of the array. Please check the comments below.
7,899,500
7,900,025
Creating and using dynamic libraries in OS X
We have a Windows application written in C++, part of which we are trying to port to Mac OS X. Our goal is to wrap the business logic into some libraries and build a Cocoa layer on top for the controller and the GUI. We will probably have several smaller apps using the same libraries so our first thought was to use dyn...
Option 1 In this case, I would just add the directory containing the headers to the discovery paths for headers or libraries in Xcode. Depending on the layout, some approaches will be better than others. Generally, you'll use some combination of: HEADER_SEARCH_PATHS LIBRARY_SEARCH_PATHS USER_HEADER_SEARCH_PATHS or FRA...
7,899,620
7,899,630
Open-Source C or C++ Embedded relational database (copy source to deploy)
I have a cross platform project where the client gets the code, but doesn't want to resolve any dependencies. The requirements are best solved with a relational database, so it seems I need to copy the source of an embeddable relational database into my program and compile the library directly into the executable or as...
SQLite They have “amalgamation” source distribution which is one C source file, which can be included into a project and used right away.
7,899,707
7,899,749
best way to store adresses of pointer to an object of class
I have a class A whose objects are created dynamically: A *object; object = new A; there will be many objects of A in an execution. i have created a method in A to return the address of a particular object depending on the passed id. A *A::get_obj(int id) implemetation of get_obj requires itteration so i chose vector...
will this method consume more time than the vector method? Yes, it will consume a lot more time - every lookup will take several thousand times longer. This does not hurt if lookups are rare, but if they are frequent, it could be bad. this will help me reduce memory usage How many object are you expecting to manage...
7,899,838
7,899,924
fastest way to convert a std::vector to another std::vector
What is the fastest way (if there is any other) to convert a std::vector from one datatype to another (with the idea to save space)? For example: std::vector<unsigned short> ----> std::vector<bool> we obviously assume that the first vector only contains 0s and 1s. Copying element by element is highly inefficient in c...
std::vector<bool> Stop. A std::vector<bool> is... not. std::vector has a specialization for the use of the type bool, which causes certain changes in the vector. Namely, it stops acting like a std::vector. There are certain things that the standard guarantees you can do with a std::vector. And vector<bool> violates t...
7,899,932
7,899,961
How fast c++ file is fulfilled?
Possible Duplicate: How to measure execution time of command in windows command line? is there a program which counts how fast .exe file is fulfilled? For example, if I must write c++ that takes one number from input file, multiply it with 2 and outputs in output file. And if I start c++ program, I can't tell how fa...
Under Linux and other unices you can use the time command. time foo.exe real 0m0.053s user 0m0.000s sys 0m0.000s I am sure there's some equivalent for Windows as well.
7,899,973
7,900,003
What happens under the hood of vector::push_back memory wise?
My question is regarding the effect of vector::push_back, I know it adds an element in the end of the vector but what happens underneath the hood? IIRC memory objects are allocated in a sequential manner, so my question is whether vector::push_back simply allocates more memory immediately after the vector, and if so wh...
If there is enough space already allocated, the object is copy constructed from the argument in place. When there is not enough memory, the vector will grow it's internal databuffer following some kind of geometric progression (each time the new size will be k*old_size with k > 1[1]) and all objects present in the orig...
7,900,284
7,900,484
declare class template as friend
For some reasons, I'd like to write code like this: template<class T> class C : public T { friend class T; }; I think the code is clear. I want to have a class template which defines a class derived from the class passed to it as the template parameter, and to make things a little more complex, I'd like to define the ...
It is ill-formed, and is not valid C++ although it works in MSVC. The C++03 standard says this (7.1.5.3 §2): 3.4.4 describes how name lookup proceeds for the identifier in an elaborated-type-specifier. If the identifier resolves to a class-name or enum-name, the elaborated-type-specifier introduces it into the dec...
7,900,329
7,930,089
Parsing Exuberant Ctags with C++
I need to make an editor with Symbol Browser and I said I would toy with ctags. Well I read ctags format and Tried to Google and search here at SO. All I found were questions about ctags and vim and I'm zero at vim . So I decided I will play around by myself. So I took a tag file and I was totally confused! Here I have...
The first item after the ;" in each line describes the kind of the tag, that is whether it is a class, function etc. In your example c stands for class, f for function and so on. You can get the complete list with ctags --list-kinds=php. Return types are (unfortunately) not reported by ctags. You should definitely have...
7,900,520
7,900,534
Is accessing c++ member class through "this->member" faster/slower than implicit call to "member"
After some searching on our friend google, I could not get a clear view on the following point. I'm used to call class members with this->. Even if not needed, I find it more explicit as it helps when maintaining some heavy piece of algorithm with loads of vars. As I'm working on a supposed-to-be-optimised algorithm, I...
No, the call is exactly the same in both cases.
7,900,529
7,900,580
Binary Search Tree recursion insertion
I'm currently having difficulty inserting a node into a binary tree using recursion. I've been dwelling on this problem for a few days now and thought it was time I came looking for answers! Node class (.h): #ifndef STUDENT_MACROGUARD #define STUDENT_MACROGUARD #include <cstdlib> #include <string> namespace student_c...
The problem is here: if(node_ptr == NULL) { node_ptr = new student(grade, name); return; } node_ptr is a local variable, because you pass it by value. Thus, the assignment is lost when you exit the function. To fix it - pass by reference: void BTTree::insert(student* &node_ptr, const float grade, std::string n...
7,900,661
7,900,862
How to read a CMake Variable in C++ source code
I'd like to store the version number of my library in just one place. So I have defined such a variable in the CMake-file: SET(LIBINTERFACE_VERSION 1 CACHE INTEGER "Version of libInterface") With this definition I can generate a version.rc file according to Microsoft's definition, which I compile into the library ...
The easiest way to do this, is to pass the LIBINTERFACE_VERSION as a definition with add_definition: add_definitions( -DVERSION_LIBINTERFACE=${LIBINTERFACE_VERSION} ) However, you can also create a "header-file template" and use configure_file. This way, CMake will replace your @LIBINTERFACE_VERSION@. This is also a l...
7,900,677
7,900,793
Array memory allocation - paging
Not sure if the answer would be the same for Java, C# and C++, so I categorized all of them. Answer for all languages would be nice. All days I've been thinking, that if I allocate array all the cells would be in one, contiguous space. So if there isn't enough memory in one piece in system there will be raised out of m...
C++ arrays are contiguous, meaning that the memory has consecutive addresses, i.e. it's contiguous in virtual address space. It need not be contiguous in physical address space, since modern processors (or their memory subsystems) have a big map that associates virtual pages with physical pages. Processes running in us...
7,900,919
7,901,277
How to do refactoring this structure, if-else-if-else-if * 100
There is some nasty legacy code. std::string xxx = GetCommand(); // get "CommandX"; if (xxx == "Command1") { return new Command1(); } else if (xxx == "Command2") { return new Command2(); } ... else if (xxx == "Command100") { return new Command100(); } I want to improve this code structure. There were too...
Since all the functions are return new CommandNNN();, you can use a template function: template <class T> CommandBase* createCommand() { return new T(); } and bind to this function in your map: map.insert(std::make_pair("Command1", &createCommand<Command1>)); map.insert(std::make_pair("Command2", &createCommand<Co...
7,900,948
7,901,000
setlocale() returns 'C' when running as root
I'm using the following to get the system locale: currentLocale = setlocale(LC_ALL,""); This works great normally, I get (for example) en_GB.UTF-8. However, when running the same program as root, I get C. How can I get the system locale when running as root?
There is no "system locale." Each user can set the locale by itself and it may differ for each program (e.g. execute LC_ALL="en_US" locale). A return value of C means that the user has not set any locale and the default locale is active.
7,901,117
7,901,146
How do I use errno in C++
I cannot understand what the errno library in c++ is for? What types of errors are set in it and how do I know which number stands for which error? Does it affect program execution?
errno.h is part of the C subset of C++. It is used by the C library and contains error codes. If a call to a function fails, the variable "errno" is set correspondingly to the error. It will be of no use if you're using the C++ standard library. In C you have functions that translate errno codes to C-strings. If your c...
7,901,136
7,902,319
LZZ syntax error for typedef enum _foo { a } foo;
Why does LZZ tell me that the line typedef enum _foo { a } foo; has a syntax error? Test.lzz:1:19: Syntax error before '{'. Test.lzz:1:1: Discarding 'typedef'. Test.lzz:1:28: Syntax error before ';'. Test.lzz:1:28: Inserting '<identifier>' before ';'.
From the documentation: Unlike a real C++ parser, Lzz does not maintain a type and template name database. Lzz parses using context information only. However, because the C++ grammar is ambiguous this strategy is inadequate in several contexts; fortunately, Lzz can skip over most of them. This tool doesn't accept C++...
7,901,256
7,901,309
Safe to assign vector<int> to vector<double>?
To initialize variables for a certain computation I have to assign them values from an integer array. So I do: vector<double> vd; int ai[N]; // Filled somewhere else vd.assign(ai, ai+N); This works under gcc 4.6.1 Linux. But is it always correct? Or should I return to the evergreen: vd.resize(N); for(int i=0; i < N; ...
I think this is safe, since assign is a template. See http://www.cplusplus.com/reference/stl/vector/assign/. The implementation assigns doubles from ints, which basically is not different to your other solution. Checking the header in /usr/include/c++/4.6/bits/stl_vector.h it seems the constructer and assign both call ...
7,901,376
7,901,999
Polymorphism with pointers/boost::shared_ptr
Consider the following example of polymorphism in C++. To me, this is unexpected behavior, which probably lies in the fact that I am still thinking too much in Java. The question to me is now: How do I get the pointer example to call the more specific method. #include <iostream> #include <string.h> #include <boost/tr1/...
Next to the double dispatch as proposed by tokage, you could also have only 1 Process() function with the base class reference as parameter and then use polymorphism by calling virtual function of the base class inside the Process() function.
7,901,683
7,902,241
How to compile openssl for only two functions
I am trying to use openssl to encode a simple string, no need of decrypting it. I am using the functions AES_set_encrypt_key() AES_cfb128_encrypt() I need I think only the include: #include <openssl/aes.h> I couldn't find instructions in the web or in the openssl website about how to compile the source code for a v...
I understand you want to use these functions in your code. You don't need to compile OpenSSL for that. Install the package on your development machine (if developing for Windows, you can get the latest installer here). It will contain header files you need to include in your code (they will be in c:\OpenSSL-Win32\incl...
7,901,725
7,902,674
Too much CPU consumption by boost scoped_lock
I have some code which waits for write operation on Shared Memory. If no one writes it continues to wait. Test* Foo::Get() { boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock ( mutex ) ; // mutex is boost::interprocess::interprocess_mutex if ( this->check == 0 ) ...
boost::interprocess, unfortunately, uses busy-waiting for locks on many platforms (apparently including OSX). You'll want to use a lock native to your platform that actually sleeps.
7,901,758
7,901,784
Batch file launched in an exe doesn't work
Ok so I have an executable which launches my batch file and the batch file then should create an ODBC data source to my SQL server. If I run the batch file by itself it runs perfectly and creates the data source, but when I run it through my exe it runs, returns no errors but doesn't create the data source. my entire e...
Are you sure the batch file is running? Since you're not building an absolute path, I would guess it's not being found.
7,901,952
12,428,047
Windows RCP Idle Connection Cleanup
I have an application built on RCP ( server on windows xp embedded) and has client Sessions kept on the server side as business objects. Looking at :http://msdn.microsoft.com/en-us/library/windows/desktop/aa373939%28v=vs.85%29.aspx I can see that there is built in mechanism for idle connection cleanup . Is there a wa...
To answer my own question , to detect when a connection is closing I have to create a server side client context somewhere at the opening of an client session and when the connection is interrupted/lost, a Server Context Run-down Routine is called . For Example PCONTEXT_HANDLE_TYPE_rundown , where PCONTEXT_HANDLE_TYPE ...
7,902,026
7,902,395
C++: matching pipe-delimited strings with wildcards using boost::regex
Suppose I would like to match for the following pipe-delimited strings: std::string re("a|*|c"); std::string x("a|b|c"); std::string y("a|c|d"); does_match( re, x ); // want to return TRUE does_match( re, y ); // want to return FALSE what is the best way to implement does_match() using boost::regex? I think I may b...
Ok, I think I'm barking up the wrong tree by attempting to solve this with boost::regex() - boost::split() is probably more appropriate. #include <string> #include <vector> #include <boost/algorithm/string.hpp> bool does_match( const std::string& fmt, const std::string& str ) { std::vector<std::string> strs, fmts...
7,902,156
7,902,278
Creating null pointers from c++11 template parameter pack
I'm doing some metaprogramming and right now I need to test if a member function of a given type is callable with a given set of arguments, so I'm doing something like the following (which is heavily simplified by removing everything not important for this particular problem of course): template<typename T, typename......
The ... unpack "operator" can be placed outside the expression, in which case the expression is expanded. The solution would thus be, I think, (*static_cast<Args*>(0)).... EDIT: Following R. Martinho Fernandes' hint typedef decltype(std::declval<base>().my_member(std::declval<Args>()...)) type;
7,902,306
7,902,646
how to store and reference large amount of data in c++
I am using a vector of strings in order to store some data in memory. Database is not an option. More precisely an array of vector of strings. A simple scenario: I need to store the names of people living in 256 cities. Example NewYork: John, Bod, ... London: Jim, Bill... for this requirement I used vector<std::strin...
If you have C++11 and only need a single, global version of this data, you could use a data structure like this: #include <unordered_map> #include <unordered_set> #include <string> typedef std::unordered_multiset<std::string> name_set; typedef std::unordered_map<std::string, name_set> city_map; city_map city_db { {...
7,902,433
7,908,287
Passing array arguments by reference
I came across a function with this signature. void foo(char (&x)[5]) { } This is the syntax for passing a fixed size char array by reference. The fact that it requires parentheses around &x strikes me as unusual. It is probably part of the C++03 standard. What is this form called and can anyone point out a reference t...
There is nothing unusual or new about the syntax. You see it all the time in C with pointers. [] has higher precedence than &, so you need to put it in parentheses if you want to declare a reference to an array. The same thing happens with * (which has the same precedence as &): For example, to declare a pointer to an ...
7,902,452
7,903,037
May STL iterator methods throw an exception
Destructors may not throw exceptions (so stack unwinding can complete during exception handling), and must deallocate any resources allocated to the object (so no resources leak). A design for an object that contains several other objects (or is allocated several resources) might record pointers to them in an STL conta...
operator++ for a valid iterator The C++ standard (I refer to N3290 draft) does not give nothrow guarantee for increment operator of iterators. For example, std::istreambuf_iterator::operator++ effects in call to std::basic_streambuf::sbumpc. The sbumpc may call uflow which in turn may throw exception.
7,902,465
7,902,725
Minimum cpu and memory overhead data structure for editing text?
I am creating a mind mapping application, and I was wondering what would be the best data structure for the "notes" editor. Notes might be just a few symbols, might be pages long, and are being updated, edited, shuffler around and so forth. The app is intended to run on mobile platforms so processing and memory overhea...
With regards to open source, there's always emacs:-). But I suspect that you're looking for something a bit simpler. There is no one correct answer here. The traditional implementation that I've seen uses one very large buffer (std::vector<char> today), divided into three logical blocks: text before the cursor, free...
7,902,903
7,903,024
Gcc x64 function calling
As far as I know, there are two possible calling conventions for the x64 code - Microsoft x64 and AMD64. Now, gcc can be launched with the -mregparm=0 parameter, which doesn't work if we are working using the AMD64 calling convention. This happens because the AMD64 convention mandates the usage of the registers for the...
I don't know Microsoft Windows (and never used it), so I probably cannot answer your question about it. However, the AMD64 Application Binary Interface calling conventions (On Linux and other Unixes) are documented in the AMD64 ABI spec (maybe you should also find and read the equivalent document for Microsoft calling ...
7,902,916
7,904,278
Set path in CMake (C++, ImageMagick)
I'm trying to add something to a larger C++ project which is developed using CMake. In the part I'm adding, I want to use Magick++. If I'm only compiling my small example program #include <Magick++.h> int main() { Magick::Image image; return 0; } with g++ -o example example.cxx it fails since it doesn't find "M...
There is FindImageMagick.cmake module in the basic CMake distribution, so you are lucky. You should add something like this this to the CMakeLists.txt: find_package(ImageMagick COMPONENTS Magick++) After that, you can use following variables: ImageMagick_FOUND - TRUE if all components are found. Ima...
7,903,083
7,903,164
How do I prevent an implicit cast double -> int?
Question as above, more details below: I have a class Money to deal with... well, you guessed what. I am very strict about not allowing Money and double to interact(*), so the following code is not possible: Money m1( 4.50 ); double d = 1.5; Money m2 = m1 * d; // <-- compiler error Now I'm thinking about allowing mult...
You could add a declaration for a private overload of your augmented assignment operator: private: Money & operator*=( double i );
7,903,342
7,903,508
QObject inheritance Ambiguous Base
I have a simple class that stops and starts a timer when my program gains and loses focus but it gives the error tha QObject is Ambiguous base of MyApp on every signal-slot connection. Here is the relevant code: class MyApp : public QApplication, public QObject { Q_OBJECT ... } Here is my (messy) Main.cpp: ...
With your current example, you've created a split inheritance scheme, where your object ends up with dual instances of a QObject ... there is one base QObject for the QApplication, and another for the actual MyApp class. That's going to create ambiguity since accessing an inherited QObject method or data-member will n...
7,903,551
7,903,694
When to use const char * and when to use const char []
I know they are different, I know how they are different and I read all questions I could find regarding char* vs char[] But all those answers never tell when they should be used. So my question is: When do you use const char *text = "text"; and when do you use const char text[] = "text"; Is there any guideline or ru...
Both are distinctly different, For a start: The First creates a pointer. The second creates an array. Read on for more detailed explanation: The Array version: char text[] = "text"; Creates an array that is large enough to hold the string literal "text", including its NULL terminator. The array text is initialized ...
7,903,768
7,905,195
noexcept specifiers in function typedefs
Are noexcept specifiers accepted in function typedefs? as in: typedef void (*fptr)() noexcept; Intuitively, noexcept specifiers seem to make sense since they would allow some optimisations at the caller's side. I got a mixed answer from gcc 4.6.1. typedef void (*fptr)() noexcept; results in: error: ‘fptr’ de...
clang gives: test.cpp:1:25: error: exception specifications are not allowed in typedefs typedef void (*fptr)() noexcept; ^ 1 error generated. This is backed up in the C++11 standard in 15.4 [except.spec]/p2: ... An exception-specification shall not appear in a typedef declaration or alias-d...
7,903,996
9,372,993
How to make a Flyout Box using C++?
I am working with metro and I am trying to make a flyout window. I have found a class called CoreWindowFlyout, but it cannot be used for creating flyouts with other controls than buttons. Does someone know how to do this in C++?
If you are using XAML in combination with your C++ application you'll want to look at using the Popup class. In the developer preview the "light dismiss" capability isn't built-in so you will have to manage that on your own, but it will eventually have light dismiss capabilities, so using that will get you along the r...
7,904,132
7,904,223
How to initialize boost::random::discrete_distribution using std::vector?
I would like to initialize boost::random::discrete_distribution with an std::vector<double>. My problem is that if I initialize it with an array, like in the official example: double probabilities[] = { 0.5, 0.1, 0.1, 0.1, 0.1, 0.1 }; boost::random::discrete_distribution<> dist(probabilities); then it works perfe...
The class seems to have a constructor that takes an iterator range. This would be used with a vector like this: std::vector<double> probs = ...; boost::random::discrete_distribution<> dist(probs.begin(), probs.end());
7,904,191
7,904,252
Pointers in C++ Class are getting scrambled
I've got a lot of code that's driving me really crazy right now. I'm working with OpenGL, building a GUI framework which utilizes several different types of objects. I have Image classes which load *.png files and store image information in the form of a GLuint texture reference. I have Panel and Button classes with po...
Use a debugger that lets you put a watchpoint on the relevant imgMys, and then the debugger will tell you where they're being modified. That is probably the easiest way to track it down. You may also want to try valgrind, but this doesn't sound like the type of problem valgrind will find.
7,904,213
7,911,469
MSVCP100D.dll missing
When I try to debug my C++ application I get the error The program can't start because MSVCP100D.dll is missing from your computer. Try reinstalling the program to fix this problem. I found someone with a similar problem here: Remote debugging C++ on the Windows Server 2008 platform with VS2010; MSVCP100D.dll miss...
Reinstalling Visual Studio fixed the problem.
7,904,375
7,904,441
How to access the face pixel in a detected face from an image?
I have use the source code in nashruddin.com to draw a rectangle on the detected face from live video stream from my webcam. I want to change the face, or the whole rectangle as black colour. I have tried using solutions from this page: http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html#SECTION...
Well first of all, you're re-using the i variable which is a big problem. Change that topmost for loop, that's just confusing. Also, your innermost two for loops are wrong. They should be: for(int i = y; i < y + height; i++){ for(int j = x; j < x + width; j++){ Keep in mind that you're looping over absolute coordi...
7,904,423
7,912,625
How do I get Boost.LexicalCast to work?
I'm having issues with boost::lexical_cast. I am trying to use it on a class from the GLM (OpenGL Mathematics) library. To allow for lexical casting, I have implemented operator<< functions for the class in question: template <class T> std::ostream& operator<<(std::ostream& out, const glm::detail::tvec2<T>& vec) { ou...
The answer was found by another, so I'll leave it here. He mentioned something about argument dependent lookup, and suggested that the stream operators be placed in the glm::detail namepace like so: namespace glm { namespace detail { template <class T> std::ostream& operator<<(std::ostream& out, const glm::detail::tve...
7,904,429
7,904,504
Using ntohl on Struct or Union
ntohl takes a uint32_t. I have messages with many different members (of type uint32_t or uint16_t). Is it possible to properly pass in the entire received struct or union and have it converted to say uint32_t and then reinterpret_cast into my union or struct? How I have been doing it is listing, line-by-line, each ind...
No, you can't. Only in the case that your struct only contains one uint32_t variable. Besides, you must use different ntoh<X> functions depending the different variables sizes.
7,904,696
7,904,744
access list from class, in parent
I'm new to C++, and have experience with other programmas languages, but I have a question: How can I access a list from a sub class, from the parent? Here is my layout: TutorialApp.cpp with function TutorialApp::update() In that function I want to access the list mParticles2y from another class that list is made in: P...
Your code for the loop that has the errors should look more like this. It may not compile exactly since I can't compile it easily at the moment. This isn't the ideal way to go about it, but it is the minimal impact to your code. I would move this loop to the ParticleController class as a member function that returned t...
7,904,730
7,904,849
boost simple human readable date time of now
Anyone know how to get a simple date format from boost of the current time to a local system? boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time(); boost::posix_time::time_facet *facet = new boost::posix_time::time_facet("%d-%m-%Y %H:%M:%S"); I've seen examples that say to use cout.imbue bu...
you can try this code: void FormatDateTime( std::string const& format, boost::posix_time::ptime const& date_time, std::string& result) { boost::posix_time::time_facet * facet = new boost::posix_time::time_facet(format.c_str()); std::ostringstream stream; s...
7,904,941
7,904,996
How to view the machine language of a compiled c++ file?
I wrote a simple c++ program that prints "Hello World!" #include <iostream> using namespace std; int main(){ cout<<"Hello World!\n"; } I then compiled it using g++ $ g++ Desktop/sample.cpp -o Desktop/hello How would I be able to view the machine language, is it just $ less Desktop/hello ? I'm just curious to see wh...
If you compile with the -S option, it will spit out the assembler output and stop. Make sure you use the -o option to set the output file to sample.s: g++ -S -o sample.s sample.cpp
7,904,947
7,904,964
what is underlying data structure of STL list, vector and set?
what is underlying data structure of STL list, vector and set ? My solution: vector : (dynamic allocated) array list: ? set: heap (or a binary tree with all leaf nodes located as left as possible and keep min/max element on top) Right?
Based on comments, to clarify, these are the most common choices, but based on desired complexity and other factors, the backing of these implementations may vary: Vector = dynamically resizing array List = Doubly Linked List Set = Red/Black Tree (balanced Binary Search Tree) I think you might possibly be mixing up Hea...
7,905,010
7,905,091
Calling a virtual function before Implementation
So I have this kind of setup class Base { public: Base(); virtual void parse() = 0; }; Base::Base() { parse(); } class Sub : public Base { public: Sub(); void parse(); }; Sub::Sub() : Base() {} void Sub::parse() { // DO stuff } I'm wondering if there's anway I can do something similar to this, right n...
Invoking virtual member functions in a constructor (or destructor) will never make you end up in an overridden version of that function in a derived class. The reason is that base class constructors (destructors) are executed before (after) derived class' constructors (destructors). That means that the part of an obje...
7,905,024
7,905,042
CreateProcess not working
I am having problems with getting the following code to work in C++ (VC++ console app). It simply doesn't create the process, but it prints out the error text. static void main(){ char *hotkeyexe = "cmd"; PROCESS_INFORMATION pi; STARTUPINFO si; if(!CreateProcess(hotkeyexe, "", 0, 0, 0, 0, 0, 0, &si, &p...
You need to zero out STARTUPINFO. ZeroMemory(&si, sizeof(si));
7,905,025
7,905,229
"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)
I have the following code in eclipse for c++ and it's underlining string and cout and saying could not be resolved. #include <string> #include <iostream> using namespace std; int main() { string s; s = "hello world"; cout << s; return 0; } Anyone know why? edit: screenshot Edit: I have found a solu...
The problem was that I needed to have both minGW and MSYS installed and added to PATH. The problem is now fixed.
7,905,062
7,905,360
What does the push_heap function in C++ do?
I wonder what does the push_heap function which takes three parameters do? #include <iostream> #include <cassert> #include <algorithm> #include <vector> using namespace std; class HeapCompare_f { public: bool operator() ( int x, int y ) const { return x > y; ...
This function does not turn a range of values into a heap! std::push_heap(first, last [, comp]) assumes that the range [first,last-1) is already a valid heap and pushes the value at position last-1 into the heap, moving it to the correct position to keep the heap-requirement valid. It uses either the < operator to det...
7,905,172
7,905,257
C++ Constant return type of suffix increment operator
In C++, wherever I see in web an example of suffix increment operator declaration, it is always declared as T& operator++(int); and I believe this is the correct syntax of a suffix increment, isn't it? The issue is that, whenever I declare suffix increment, I declare return type with const keyword, so that it becomes ...
Suffix increment returns a temporary, not a reference (this means your first signature is wrong): T& operator++() // prefix { this->increment(); return *this; } T operator++(int) // suffix { // Almost always, you'll have this code: T tmp(*this); ++(*this); return tmp; } Some people like to const-quali...
7,905,272
7,905,344
Why is taking the address of a destructor forbidden?
C++ standard at 12.4.2 states that [...] The address of a destructor shall not be taken. [...] However, one can without any complaints by the compiler take the address of a wrapper around a class destructor, like this: struct Test { ~Test(){}; void destructor(){ this->~Test(); } }; void (Test::*...
Constructors and destructors are somewhat special. The compiler often uses different conventions when calling them (e.g. to pass extra hidden arguments). If you took the address and saved it somewhere, the compiler would lose the information that the function is a constructor or destructor, and would not know to use ...
7,905,350
7,905,473
A server program is on an infinite loop. How to check for it?
A server program is on an infinite loop. How to check for it? My solution: use GDB to check the values of condition variables that control the loop. It is ok for small program. how to do that for large program ? If the program is not running in GDB, how to detect the endless loop ? thanks
You could use some form of a watchdog timer. Have the program output a character or touch a file periodically, so if it gets stuck in a loop, a separate process can detect that the watchdog has not been updated and kill/reset the process. A lot of microcontrollers have this built into the hardware, and they will automa...
7,905,468
7,905,806
Can I create a union with formal parameter passed to a function in C++?
The function below calculates absolute value of 32-bit floating point value: __forceinline static float Abs(float x) { union { float x; int a; } u; //u.x = x; u.a &= 0x7FFFFFFF; return u.x; } union u declared in the function holds variable x, which is different from the x which is p...
Looking at the disassembly of the code compiled in release mode the difference is quite clear! I removed the inline and used two virtual function to allow the compiler to not optimize too much and let us show the differences. This is the first function. 013D1002 in al,dx union { ...
7,905,773
7,905,846
Const with smart pointers in C++
I'm writing a smart pointer implementation in C++, and I'm having some trouble with const-correctness. Below is an excerpt from the code: template <class T> class Pointer { T* pointee; public: Pointer(const Pointer<T>& other) { // must be const Pointer& for assignments pointee = other.getPointee(); } T...
Best to think of your constant smart pointer as a constant pointer to a non-constant object. This is similar to: int * const int_ptr; If you wanted a pointer to a constant object: Pointer<const int> const_int_smart_ptr; which is basically equivalent to: const int *const_int_ptr;
7,905,905
7,906,060
Howto check a type for the existence of parameterless operator()
I'm trying to check whether a functor is compatible with a given set of parametertypes and a given return type (that is, the given parametertypes can be implicitely converted to the actual parametertypes and the other way around for the return type). Currently I use the following code for this: template<typename T...
When I want to test if a given expression is valid for a type, I use a structure similar to this one: template <typename T> struct is_callable_without_parameters { private: template <typename T1> static decltype(std::declval<T1>()(), void(), 0) test(int); template <typename> static void test(...); publi...
7,905,981
7,906,002
boost: read_until "\n" reads until " "
I'm developing a tcp client using boost::asio to process incoming text, that ends with "\n". However, when I am sending text containing whitespace, it drops all characters after the first whitespace appears. I've already verified that the text I'm sending is complete. This is my code: boost::system::error_code error;...
Use std::getline instead of >>, which is what stops reading on encountering whitespace: std::istream str(&buffer); std::string s; std::getline(str, s);
7,906,083
7,906,783
Error C2248: Protected Default Constructor C++ within an class owned by another class
I'm trying to get around this error I get from Microsoft Visual Studio 10 Compiler. The error is: Some class : error C2248: cannot access protected member declared in class ''. Here is code that reproduces this error. I can't seem to figure out how to create an object that owns another object that has a protected de...
I have another constructor that takes an input parameter but can't seem to call it no matter what logical reasoning I apply. Ah, now we get to the important part (and sorry that the other answers don't seem to give you credit for understanding the protected keyword, but you do seem a bit confused the way you present...
7,906,127
7,906,269
Assignment operator with reference members
Is this a valid way to create an assignment operator with members that are references? #include <new> struct A { int &ref; A(int &Ref) : ref(Ref) { } A(const A &second) : ref(second.ref) { } A &operator =(const A &second) { if(this == &second) return *this; this->~A(); ...
It's syntactically correct. If the placement new throws, however, you end up with an object you can't destruct. Not to mention the disaster if someone derives from your class. Just don't do it. The solution is simple: if the class needs to support assignment, don't use any reference members. I have a lot of classe...
7,906,546
7,906,572
What is Node *& aNode?
In the following code: void insert(Node *& aNode, int x) { if (!aNode) { aNode = new Node(x); aNode->next = aNode; return; } Node *p = aNode; Node *prev = NULL; do { prev = p; p = p->next; if (x <= p->data && x >= prev->data) break; // For case 1) if ((prev->data > p->data) && (...
I think this code is C++, not C, and Node *&aNode is a reference to a pointer to a Node, so you would pass a Node* to the function, and function would make a reference to that (so the memory location your Node* is pointing to can change). You may find the Wikipedia article on References (C++) interesting. A simple exam...
7,906,648
7,906,690
Char array is not working in c++
I have the following code: template <typename M> struct Matrix { Matrix(int size);//(int x = defaultRows, int y = defaultCols); ~Matrix(); int rowSize; int colSize; char alpha[4]; int getSize() const; void displayAll(); M getElement(int x, int y); M** aMatrix; }; template <typename M> Matrix<M>::Matrix(int size) ...
You can't do this in C++ (well not for some time anyway): alpha = {'a', 'b', 'c', 'd'}; It looks like an initializer but it's not. Try: alpha[0] = 'a'; alpha[1] = 'b'; alpha[2] = 'c'; alpha[3] = 'd'; EDIT Not that it will help you much but C99 (along with some C++ compilers, as an extension) supports this: alpha = (...
7,907,235
7,907,245
What is intention of making a function "const"
Like this, bool isEmpty() const { return root==NULL; } This is isEmpty function, test if the BST is empty or not.
It indicates that the function does not modify any of the members of that class. Usually, the Interface/declaration(through header file) is made available to the users of the class/functions and not the implementation,So the const makes it clear to the user that the function does not modify any members. Adding the cons...
7,907,265
7,907,362
C++ to Java code translation
I have following code in C++: struct Foo { }; std::ostream& operator<<(std::ostream& os, const Foo& f) { return os << "Foo"; } Foo foo; std::cout << print("Ha! %1%, x=%2% %1% %3%") % "Hej" % 1 % foo; Because I don't think I understand that C++ code. What is appears, is that it is some kind of printf like function....
Java has String.format() See this javadoc. This allows you to use printf-style format strings. For example: System.out.println( String.format("Foo: %f\n", 3.14159) );
7,907,315
7,907,958
Is it abusive to implement the "execute-around" idiom with scoped objects?
Should scoped objects (with complimentary logic implemented in constructor and destructor) only be used for resource cleanup (RAII)? Or can I use it to implement certain aspects of the application's logic? A while ago I asked about Function hooking in C++. It turns out that Bjarne addressed this problem and the solutio...
If you pedantically consider the definition of RAII, anything you do using scoping rules and destructor invocation that doesn't involve resource deallocation simply isn't RAII. But, who cares? Maybe what you're really trying to ask is, I want X to happen every time I leave function Y. Is it abusive to use the same...
7,907,335
7,907,402
Given an array of integers, find the first integer that is unique
Given an array of integers, find the first integer that is unique. my solution: use std::map put integer (number as key, its index as value) to it one by one (O(n^2 lgn)), if have duplicate, remove the entry from the map (O(lg n)), after putting all numbers into the map, iterate the map and find the key with smallest ...
I believe that the following would be the optimal solution, at least based on time / space complexity: Step 1: Store the integers in a hash map, which holds the integer as a key and the count of the number of times it appears as the value. This is generally an O(n) operation and the insertion / updating of elements in ...
7,907,410
7,910,083
std::atomic<int> decrement and comparison
On the following code: std::atomic<int> myint; //Shared variable //(...) if( --myint == 0) { //Code block B } Is it possible that more than one thread access the block I named "Code Block B"? Please consider that overflow will not happen, that the 'if' is being executed concurrently by more than one thread, that t...
C++0x paper N2427 (atomics) states roughly the following. I've changed the wording slightly so its easier to read for the specific decrement situation, the parts I changed are in bold: Effects: Atomically replace the value in object with result of the decrement applied to the value in object and the given operand. ...
7,907,707
7,907,754
Getting a non-const iterator in Boost's multi index container
Using Boost 1_33_1, I get an error implying that my iterator is a const iterator (because it wont let me deref the result from find()). $ g++ bmi_iter_tst.cpp bmi_iter_tst.cpp: In function ‘void tst(employee_set&)’: bmi_iter_tst.cpp:32: error: invalid initialization of reference of type ‘employee&’ from expression of ...
From the MultiIndex docs on random access indices: As usual in Boost.MultiIndex, elements of random access indices are immutable and can only be modified through member functions replace and modify. This precludes the usage of many mutating algorithms that are nonetheless applicable to std::vectors. This applie...
7,907,775
7,909,949
How to load nearby pixels using pointer
Suppose i have an image matrix and i am at a particular pixel [say 4] like this: 0 1 2 3 `4` 5 6 7 8 I am trying to cycle through all pixels and am attempting to access 0,1,2, 3,5 6,7,8 whose values i am storing in the array called Pixel.... here is my attempt at it using OpenCV, kindly tell me where am i g...
Well sir, it sounds like you want to do convolution, and doing it this way when you have OpenCV at your fingertips is a bit like hammering a can opener on your Spaghettios to burst it open by blunt force. In fact, what you're doing is almost exactly the output of cv::blur(src, dst, cv::Size(3,3)) except it also includ...
7,907,943
7,909,551
c++ win32 checkbox list - multiple selection
i would like to add a list of check boxes to my win32 application, because i need a control element with multiple selection. I've searched the msdn docs and found exactly what i need in this article: https://msdn.microsoft.com/en-us/library/windows/desktop/dn742407.aspx. But i can't find any code related to it. Is this...
That screenshot is a ListView control with LVS_EX_CHECKBOXES. The documented you linked to is UI guidance, not programming documentation. It's talking about UI design, not programmatic control names.
7,907,952
7,908,052
how to use cin.ignore in a loop
the readMe.ingredients is a pointer to an array of Ingredient objects that has an overloaded >> operator. The delimiter for the >> operator is a newline character. Suppose the list of ingredients is formatted like this: 4 gal chocolate ice cream 3 gal butterscotch syrup 12 pint sliced bananas for (int count = 0; ...
nevermind I think I got it. There's a blank line after the ingredient list But wouldn't you still want in.ignore(10000,'\n') in the loop in order to go to the next line? Wouldn't it just keep assigning 4 gal chocolate ice cream to each item in the array?
7,908,216
7,908,269
Utilizing All 4 cores in c++/c
I have a main processes that will create 4 threads. If i simply run all 4 threads would the kernel utilize all 4 cores or will the program be multithreaded on a single core? if not then how would synchronization be handled on a multicore. I have a 4core intel cpu and my program is in c++ Im running this on a linux in a...
You don't really know. For one thing, the C++03 Standard doesn't know anything about threads, cores or any of that kind of stuff. So this is all platform-dependant anyway. But even from a platform point-of-view, you often still don't really know. The operating system schedules threads and jobs. The OS might -- or mi...
7,908,338
7,908,449
Creating an array of a type depending on runtime
... is what I want to do. I have the following code: ... int len = 0; char c; bool fp = false; while (infile.good()) { c = infile.get(); if (c == '\n') ++len; else if (c == '.') fp = true; } if (fp == true){ float Ai[N]; float *A...
Edit: As commented above, your compiler error comes from Ao and Ai being declared in a different scope than where you are trying to use it. This is where templates come in real handy. template<typename T> T *findMaxes(inFile) { T Ai[N]; T *Ao = new T[len]; for (int i = 0; i < L; ++i) { for ...
7,908,377
7,908,671
OpenGL - Perspective Issue
I just want to create a perspective where the eye of the camera would be, at, say: (2, 2, -2), looking right at the origin. I'm trying to use a combination of gluLookAt() and glFrustum(), but for some reason, though it is rendering, my objects look very distorted: glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glFrus...
What am I doing wrong? I don't thing you're doing wrong anything. The kind of view you want to have in your left pane is usually done using a orthographic projection. The distortion you see is just a perspective distortion; you're not looking perpendicular onto the curve (the curve lies in the XY plane, and you're lo...
7,908,596
7,908,628
define static function outside the class and access static value .h and .cc files
//foo.h class Foo { private: static int number; public: static int bar(); }; //foo.cc #include "foo.h" int Foo::bar() { return Foo::number; } this is not working. I want to define a static function outside the class definition and access a static value. undefined reference to `Foo...
You just declared the static member you need to define it too. Add this in your cpp file. int Foo::number = 0; This should be a good read: what is the difference between a definition and a declaration?
7,908,816
7,908,827
CURL HTTP PUT compliation fail
I have the following code which i copied from here: /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_...
Change the signature of read_callback to type stream as FILE*
7,908,852
7,908,904
Member vector of objects (not pointers) gets 'unset' after the pointer to (global/persisting) object goes out of scope
Would someone please take a look at the following code fragments (all from one file) and advise on the problem I will describe at the end? members: std::vector<cHasAMyClass> collected; std::vector<cHasACHasAMyClass> memberVector;//Actually an array of vectors, but simpler not to be. constructor of an inner/...
It's hard to read your code, but it looks like you are taking pointers to elements within a vector. Pointers, iterators and references to a vector are invalidated when its capacity changes. That can happen as a side effect of any function that inserts into the vector, since a new bigger internal array is created into w...
7,908,982
7,910,684
Using Boost Accumulators with Eigen::Vector types
I am having some problems combining Eigen::VectorXd types with the Boost accumulator library: #include <iostream> #include <Eigen/Core> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> using namespace boost::accumulators...
User defined type need specialize std::numeric_limits. see https://svn.boost.org/trac/boost/ticket/5491
7,909,155
7,909,194
Strange interaction between popen() and printf vs. cout in C++
It's probably a long-shot that anyone can answer this without seeing all the source code and libraries, etc., but I'll try. I have a program X written in C++ using boost-1.41. If X outputs with std::cout, then running X from another program using fp=popen("X", "r") allows X's output to be seen via fgets(buff, 1024, fp...
The reason is that you probably used std::endl with std::cout. That, in addition to writing a newline character, also flushes the output buffer. To do the same with printf you can just add fflush(stdout); after the call.
7,909,191
7,909,293
Windows thread with C++
I saw this question Simple example of threading in C++ but my problem is that I want to run this program in windows 32 and it seems that pthread is not recognized in windows!please tell me what is problem?This is my error: fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to...
Because threads are architecture dependent concept, you won't be able to use pthread without using some kind of a wrapper or use windows-specific threading functions. You have three choices Use pthread-win32 (wrapper for Win32 thread functions :http://sourceware.org/pthreads-win32/ ) Use Windows specific threading fun...
7,909,242
7,909,539
Interchanging const char* and std::string
I am refactoring an old C library, and am currently changing the external API so that it uses std::string instead of const char*. ColumnType Table::getColType(const char *name) const { int id = getColumnId(name) ; return getColType(id) ; } and int Table::getColumnId (const char * col_name) const { unsigne...
It's safe, in so far as, executed correctly, it shouldn't cause any harm. Nevertheless, I don't think I would recommend going forward with this unless you can point to a substantial benefit. What may be safer is to add a function that takes in the const string&, and does a straight pass-thru to the const char* function...
7,909,244
7,909,429
Receiving segmentation fault in C++ code
I'm using C++, code::blocks (with warnings enabled and I checked to make sure) and SFML. I've tried hunting the bug down myself but I really can't find what's wrong. I know what a segfault means but this one really has me stumped. I'm a beginner may I add but am quickly learning. I've got a basic main class void Engine...
This line in the backtrace looks suspicious: #1 004021F9 Tile::Draw(this=0x76ab8cd5, x=0, y=0, pWnd=0x3e3310) This seems to correspond to your Tile::Draw function, except the this pointer is misaligned, which suggests that it's not a valid pointer. So perhaps your std::vector<std::vector<Tile *> > has been corrupted...
7,909,312
7,909,435
Calculate whole points on a circle
I've written a small program but the answer it gives is always wrong, here is the code double radiusc; double xcenter; double ycenter; bool onthecircle(int x,int y); int main(void) { int inputwait; printf("Please enter x coordinate of your center point: "); scanf("%d",&xcenter); printf("Please ente...
In addition to the problem Ed found, 0,9 is not a valid floating-point constant; you want 0.9. (Locale settings can affect input and output representations; they don't affect language syntax.) The comma in (0,9 *radiusc*radiusc) is a comma operator, not a decimal point; you're multiplying the square of the radius by 9...
7,909,317
7,909,400
assigning random values to a matrix with reference operator(&)
Hi here is my problem i am able to input values for my matrix as such for(i=0;i<n;i++) { for(j=0;j<n;j++){ scanf("%d",&a[i][j]); how ever this is very tedious for matrices of a large order and i cant get the matrix to work with pointers and the rand function for(i=0;i<n;i++) { for(j=0;j<n;j++){ &a[i][j] = -1 +...
Apparently a is an array of int (you are using "%d" to input values with scanf). The expression you use generates doubles (ranging from -1 to 1) that when converted to int result in 0. I guess that's what you see in a. Make a an array of doubles.
7,909,374
7,909,430
A member array contains instances of a class. Can't decide where to put a method which modifies a variable of this class
There is a two dimensional array of Blocks in the class Map. I need a method to change the variable value in the class Block. class Block { Block(BlockValue blockValue = BLANK); //first solution void Block::setValue(BlockValue blockValue, Map &map); void setImage(BlockValue blockValue, int n = 0); ...
Your question is not very clear, from a clarity point of view, I'd combine both. e.g. class Block { public: // setter to set the block value void setValue(BlockValue blockValue); private: //the value to be changed BlockValue value; }; and in Map have a method to set the BlockValue for a specific l...
7,909,533
7,909,698
C++ partial template specialization
Is this answer considered "good" code or is it just an ugly hack? And I would like to know how this is forward-declared (both classes). When I just forward-declare the class with 2 template-parameters, it just always takes this one, no matter what value flag has. I would like to do this because I have 2 special member ...
In order to use specialisation its definition always has to be visible to the caller. If, for example, you have template <class Type, bool flag> struct something defined in one header and template <class Type> struct something<Type, true> : public something<Type, false> defined in the second one, to use the latter you ...
7,909,550
7,909,561
Is there a guaranteed happens-before relationship for argument evaluation to chained methods?
I want to trim a string in C++ with this code: std::string str(" Trim test "); str.erase( /* 1 */ 0, /* 2 */ str.find_first_not_of(" ") /* 3 */ ) /* 4 */ .erase( ...
Yes, the standard allow line #6 to be calculated before line #1 is executed. From the Wikipedia page on sequence points: [Sequence points occur] Before a function is entered in a function call. The order in which the arguments are evaluated is not specified, but this sequence point means that all of their side effects...
7,909,574
7,909,651
Algorithm for player to always see things a certain way in 3 player game
Say I have a table that fits 4 players: But only 3 players are used in this gane: A, B, C. on the server, the layout is like this: C B A But all players must see it both with the correct player order, ex: ABC, BCA, CAB and they must also think that no one is sitting in the top, north position, the client alwa...
If you have 4 players in a ring configuration, then store the player locations in an array on the server, and map them to the display locations on each client. Example: Absolute positions: position=[A, B, C] User A sees: A in the center, index 0. B to the right, index 0 + 1, C to the left, index 0 - 1 MOD 3 User B see...
7,909,608
7,909,649
Illegal Function, Spotify Tech Puzzle
I am trying to solve the Spotify Puzzle 'Bilateral' found here: http://www.spotify.com/us/jobs/tech/bilateral-projects/ I have run a bunch of tests on my program and I seem to get the correct output, however upon submitting it, the Puzzle Judge tells me "Illegal Function". I was wondering if someone would look at my c...
The only thing suspicious to me is: system("PAUSE"); Maybe spotify doesnt expect your program to pause once it completes.