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
65,471,497
65,471,632
How are you supposed to use a controller with a URDF
I'm trying to use the LQR Controller to move the wheels on this really simple URDF linked here I'm trying to understand how to use the LQR controller for a model loaded from a URDF so this is a mix of the LQR example and the PR2 Example systems::DiagramBuilder<double> builder; auto pair = AddMultibodyPlantSceneGrap...
There are a few problems here. The first, and the one generating the error, is the fact that you've passed a plant_context (only) into the LinearQuadraticRegulator. Because your system has collision geometry, you need a SceneGraph to be connected for the dynamics to be evaluated. You would want to pass the diagram c...
65,471,709
65,472,718
Simulate pressing a key for x milliseconds
I'm currently working on a project that requires to be able to simulate the pressure of a key during a certain period of time. I'm using the keybd_event function to simulate pressing and releasing the key. But if I add a timer between pressing and releasing the key in this way (example with the 'v' key) : #include "win...
keybd_event has been deprecated, you should use SendInput instead. The simulation api cannot directly simulate the repeat of keystrokes. You may need to simulate repeated keystrokes by detecting the keyboard repeat-delay & repeat-speed setting with SystemParametersInfo(SPI_GETKEYBOARDDELAY&SPI_GETKEYBOARDSPEED) and sim...
65,472,035
65,472,056
Checking for three-way-comparison operator support at compile time
I'd like to conditionally enable operator <=> overloads in my code depending on whether or not it is supported given the current version of the compiler and its command line options. For example, I'd like the following code to compile as C++14, 17, and 20 (this is essentially a sequel to this solution to a question I a...
This is what feature-test macros are for. There is a standing document that defines all the macros and their values; those are the macros and values that you check for, that all vendors agree to abide by. Three-way-comparison specifically is a bit tricky because this is a feature that requires both language and library...
65,472,126
65,472,307
How do I know whether my code has compiled?
I am learning to code in C++ mostly through self-study. I am using the Microsoft Visual Studio IDE. I'm used to very simple IDEs (think MATLAB) where you basically press "run," whereas visual studio gives me options to clean, build, etcetera. Anyway, my question is how do I know whether my code has compiled successfull...
In Visual Studio you get a message at the end of the output in the Output Tab like this: ========== Build: 22 succeeded, 0 failed, 2 up-to-date, 4 skipped ========== This message is displayed after every build of your solution. I usually check this at the end of each build to verify that the build has worked. If any p...
65,472,414
65,472,454
linking hpp and cpp issues with g++ compiler
I am relatively new to c++ and have a solid C and Object Oriented background. So I have the following code written. I have Person.hpp which is as follows: class Person { private: struct h { char *name; unsigned char age; }; struct h entities; public: ...
You have a destructor declared here in your header file: public: unsigned char age(); char *name(); Person(char *name, unsigned char a); ~Person(); // <===== Declared here But you haven't provided any definitions for it. However, the destructor is called after your main function returns (you can learn mo...
65,472,617
65,473,024
How to correcly check whether a pointer belongs within an allocated block?
After reading many questions about pointer comparison, I've come to realize that many of my custom allocators does a comparison that's unspecified behavior. An example could be something like this: template <int N, int CAPACITY> class BucketList { struct Bucket { Bucket* next { nullptr }; // The ne...
The short answer is no. A good explanation is here. Some work-around solutions could be: Return a custom object that has a reference to the allocated base pointer. As equality comparison isn't unspecified, you should be able to compare it to the base pointer of the collection. The custom object could implement the int...
65,472,996
65,672,076
Template distinguishing between maps and sets
In creating a code common for set, unordered_set, map, and unordered_map, I need the few methods, where the handling is actually different. My problem is getting the compiler to deduce, which implementation to use. Consider the example: #include <map> #include <unordered_set> #include <string> #include <iostream> usin...
First of all, the actual solution, that works with compiler-versions currently found in the wild -- tested with gcc-4.4.7 (stock compiler on RedHat6), gcc-8.3.1, and clang-10 is: template<class...> // or just <class> if genericity is not needed struct std_void { typedef void type; }; template<template<typename......
65,473,143
65,476,432
Is there any way to read from files faster?
I am trying to create a program that looks through all the permutations of a string and then prints out all the valid words. I can get all the permutations, but checking if a word is in a dictionary text files takes around 3 seconds. When I tried 7 letters it took 47:19. Is there any way to read from a file faster? Any...
There are ways to reduce number of read operations, and number of permutations tested: Store dictionary in memory associate word letters to all possible permutation (anagrammer). iterate over combination instead of permutation so std::unordered_map<std::string, std::vector<std::string>> read_dictionary() { std::i...
65,473,838
65,474,077
How to obfuscate or delete exported names in the binary
I am using namespaces and classes to implement a simple calculator with add member function. int main(int argc, char* argv[]) { std::shared_ptr<Container::Calculator> O1 = std::make_shared<Container::Calculator>(); auto result = O1->Add(1, 2); std::printf("The final result of the calculation: %d", result)...
Turning off RTTI in the project Properties / C/C++ / Language / Enable Run-Time Type Information by setting it to No (/GR-) removes the need to save the internal namespace and class names in the compiled binaries, and those names are no longer visible in release builds. However, as noted on the /GR page: You usually n...
65,474,198
65,474,496
Array of arrays initialized as const float* instead of const float **
I came across this code float range[] = { 0, 256 }; const float* histRange = { range }; For me, { range } means 'array of arrays' since the variable range is an array of float. Therefore, for me, it would make more sense. const float** histRange = { range }; But the compiler (VC++ from VS2019) doesn't like it (expect...
Text enclosed by braces is not an expression, and doesn't have a type. A braced list is only allowed in certain contexts, and in each case the language definition specifies the semantics of the larger context featuring that braced list. In the line: const float* histRange = { range }; we are initializing a scalar, not...
65,474,466
65,475,531
How do you Deflate data and put it into a vector?
With zstr, a header-only C++ zlib wrapper library, I’m trying to Deflate a std::string and put it into a std::vector<unsigned char>. zstr::ostream deflating_stream(std::cout); deflating_stream.write(content.data(), content.size()); The above code works: it prints the Deflate’d. The problem is, I’m not familiar with C+...
Something like this works: #include <iostream> #include <sstream> #include <vector> #include <string> #include <algorithm> #include "zstr.hpp" int main() { std::string text{"some text\n"}; std::stringbuf buffer; zstr::ostream compressor{&buffer}; // Must flush to get complete gzip data in buffer compressor...
65,474,896
65,475,240
Counting times that a number repeats without array(c++)
I need a program to get 100 numbers between 0-20 and count the repition of the most repeated number. Here is what I got for less amount for input (10 instead of 100) but ofc it's wrong. #include <iostream> using namespace std; int main() { int num, x,c; for(int i=1; i<=10; i++) { cin >> num; i...
Assuming you mean the longest continuous sequence, here's one way you can do it: #include <iostream> int main() { int max_val = 0, max_len = 0; // Overall longest int cur_val = 0, cur_len = 0; // Current for (int i = 0; i < 10; ++i) { int val; std::cin >> val; // read 1 number if (val == cur_v...
65,475,349
65,475,608
Wrong extended characters are represented
I couldn't find any related answer to my question and I want to have a string like "╔══╗" but wrong characters are represented instead of them. I found the issue and that was because of signed characters and that values of each character is different with ascii table value of element. How can I do that with char in c++...
use std::wstring(included in <string>) and L"...": #include <string> int main(/**/) { std::wstring wstr = L"╔══════════════╗"; } NOTE: There is no good cross-platform way of printing such a string. See How to print a wstring?, How to print a wstring on MacOs or Unix?, C++ wide character locale doesn't work.
65,475,435
65,475,506
Using undo stack for a command which is running asynchronously and is emitting signals
I have a command inherited from QUndoCommand: class ImportEntityCommand : public QUndoCommand { // ... private: QString m_importedEntityName; Importer *m_importer; // ... } The redo method kicks off a QProcess: void ImportEntityCommand::redo() { if (/* Import is already done before */) { /...
I'm inhering my ImportEntityCommand class from QUndoCommand which in turn inherits from QObject, I guess. QUndoCommand does not inherit from QObject see: https://doc.qt.io/qt-5/qundocommand.html Compared to a QWidget for example, that does inherit from QObject. https://doc.qt.io/qt-5/qwidget.html If you want your imp...
65,475,615
65,475,745
Why does this SFINAE not work with enable_if when one conditional branch is inherited from the base class?
#include <bits/stdc++.h> #include <type_traits> // Type your code here, or load an example. template <typename Types> class C1 { public: using A=typename Types::A; using B=typename Types::B; template <typename Dummy = void> inline typename std::enable_if<std::is_same<A, B>::value, Dummy>::type f() { }...
As always with such problems, it falls down to the very definition of SFINAE. The S stands for "substitution", which happens into the template that we are trying to instantiate. That template is the member f, and not C. Even though C is a template also, and both A and B are dependent types in C, they are not dependent ...
65,475,688
65,536,866
Understanding "Expression does not compute the number of elements in this array"
Using Apple Clang 12.0.0 to compile this code: int my_array[10]; int arr_size = sizeof(my_array) / sizeof(decltype(my_array[0])); And getting this warning/error: Expression does not compute the number of elements in this array; element type is 'int', not 'decltype(my_array[0])' (aka 'int &') Note, this is simplified c...
This is a partial answer. First of all it is not surprising that decltype(my_array[0]) is of type int& and not int. Just remember that you can assign to it and change the value at my_array[0]. Secondly, your code should be correct anyway because for sizeof When applied to a reference type, the result is the size of th...
65,475,786
66,795,264
_VACPP_HASH_FUNCTION_CHECK error while trying to compile C++ code with LANGLVL(*EXTENDED0X) at IBMi7.4
I'm trying to compile simple C++ program with unordered_map using LANGLVL(*EXTENDED0X) at pub400.com: #include <stdlib.h> #include <stdio.h> #include <unordered_map> #include <string> int main(int argc, char* argv[]) { printf("Hello world!\n"); std::tr1::unordered_map<long long, std::string> test; test[123] = st...
It's an internal error in their /QIBM/include/std/xhashtbl, you could actually fix it yourself, you just need to exclude the whole _HashFunctionCheck function via ifdef check regarding _VACPP_HASH_FUNCTION_CHECK. They fixed it on zOS (or AIX?) a long time ago but forgot to port it for IBM i.
65,476,018
65,476,904
Find file size using a CRT routine
So I'm currently using this code to open a specified file: FILE* stream; stream = fopen("file.txt", "w+"); My goal is to get the size of this file but I could not find any explicit function that determined the file size in the CRT runtime library. I only found GetFileSize or GetFileSizeEx but these functions are in th...
This is what I came up with, however @Remy Lebeau's way works as well. struct _stat fd; if(_fstat(_fileno(stream), &fd) != 0) return -1; DWORD fsize = fd.st_size;
65,476,286
65,478,050
f(123) = 1! + 2! + 3! .I wrote a code for this type of function to work, have a look at it. My code is not giving desired result
#include <iostream> #include <cmath> using namespace std; int main() { int a=123,c,h=0,fact=1,sum=0; for(int i=1;a>10;i++) { a/=pow(10,i); h++; } for(h;h>=0;h--) { c=a/pow(10,h); for(int j=1;j<=c;j++) { fact*=j; } sum+=fact; ...
#include <iostream> #include <cmath> using namespace std; // Factorial function: // we just get: n * (n-1) * (n-2) ... * 1 // return type is long double because number may be big // if we use it not only for one digit long double get_factorial(int n){ if (n == 1) return 1; // for 1 factorial is 1 else...
65,476,557
65,476,886
What's the difference between a while loop in one or two statements?
I am confused understanding the difference between these two loops and their results : State 1: int n = 10; while (n>0) { cout << n << ", " << --n; } State 2 : int n = 10; while (n>0) { cout << n << ", "; --n; } I do not understand why should the result differentiate? ...
There is no difference in the values, just in the number of times they are occurring because of being printed a different number of times. The first one outputs, with "()" added for clarity: (10, 9)(9, 8)(8, 7)(7, 6)(6, 5)(5, 4)(4, 3)(3, 2)(2, 1)(1, 0) Note that there are pairs of numbers without a "," in between, crea...
65,477,074
65,478,753
How to interrupt blocking accept() call in C++?
I'm trying to exit an accept() call after a timeout occurs using an alarm() signal. The signal registers as excepted but isn't interrupting the blocking accept() process. How can I make the signal break the loop or interrupt the blocking process? volatile sig_atomic_t time_out_flag = false; void handleSig(int sig) { ...
The issue is that signal() installs signal handlers in such a way that syscalls like accept() are resumed after a signal is caught*. Use sigaction() instead to disable that behavior: #include <cerrno> #include <cstdlib> #include <cstring> #include <iostream> #include <thread> #include <signal.h> #include <unistd.h> /...
65,477,269
65,477,592
Is polymorphism the best way to achieve this? (regarding function calls in derived classes)
I have a program that has four classes: Vehicle (Base) Automobile (Derived from Vehicle) Car (Derived from Automobile) Truck (Derived from Automobile) At run-time, the user generates a Automobile object which is either a "Car" or "Truck" using a factory function: Automobile *Automobile::make_automobile(std::string ch...
I have solved this issue using virtual functions with local overrides. So now, the "Automobile" class all four functions (in virtual form), which by default do nothing. However, when called on an object, the local override performs the correct functionality. Below is an example, and it all works. That makes it necess...
65,477,272
65,478,130
OpenSSL Certificate "unable to get local issuer certificate"
I just started using Poco C++ libraries and i just compiled the NetSSL-OpenSSL download example. When using it with an http site, everything works, but when i use it with an https site, following error occurs: >download.exe https://api.github.com WARNING: Certificate verification failed -------------------------------...
I just managed to do it, for anyone interested: Since i only need to access the Github API, i only need to verify the certificate used by github, which is DigiCert. I visited this page https://www.digicert.com/kb/digicert-root-certificates.htm and downloaded the file DigiCertHighAssuranceEVRootCA.crt.pem, copied it nex...
65,477,605
65,477,751
How to pair 2D array and integer in the output of the function?
I'm struggling to create multi-variable output from a function: I want to return 2D array sites(16x15) and the integer number N. I tried: std::make_tuple here std:make_pair here My problem is that I probably do not know how to define a 2D array in the declaration of the function std::pair <int [][],int> correctly. Pi...
You can go with std::array. It is more C++-ish and you don't need to care about memory allocation/deallocation. std::pair <std::array<std::array<int, 15>, 16>, int> sites_diamond() { std::array<std::array<int, 15>, 16> sites; // ... return std::make_pair(sites, N); } and then the usage would be: auto resul...
65,477,716
65,479,075
Function returning different values on different configuration
here's a snippet of my code: int fastcmp(const void* ptr1, const void* ptr2, size_t size) { if (ptr1 == ptr2) return 0; if (!ptr1 || !ptr2) return -1; size_t remain = size; if (size >= 8) { remain = size % 8; size_t work = size / 8 + 1; auto p1 = (const uint64_t*) ((const ui...
In fastcmp just replace size_t work = size / 8 + 1; by size_t work = size / 8; and while(--work > 0) { by while(work-- != 0) { else you look at indexes n..1 rather than n..0 so you do not detect difference in the remain+0..7 characters ( note size_t is non signed ) note you suppose you can read an uint64_t from...
65,477,773
65,487,566
Error C2440 '<function-style-cast>': cannot convert from 'char' to 'std::string'
I am trying to iterate over an std::tuple and retrieve the true amount of space (bytes) it takes up. To handle std::string I need to use the .length() function but I am unable to compile, and I get the following error: Error C2440 '': cannot convert from 'char' to 'std::string' I have also tried using std::is_same (a...
Something like this, perhaps: template <typename T> size_t LengthOf(const T&) { return sizeof(T); } template <typename ... Params> size_t LengthOf(const std::basic_string<Params...>& s) { return s.length(); } template <typename Tup> size_t iterate_tuple_types(const Tup& t) { auto sum_length = [](const auto&... args...
65,477,898
65,479,195
Move operator destroying original pointer
I am trying to have a pointer to a memory location. Then, if I modify the original the assigned variable who points to the same location must be also affected by the change. But, the thing is, there are two function calls, that happen on line: a = Data("New data"); Data(const char* cdata) constructor is called. Data ...
There are a few issues with your class Data. First, it never calls delete[] local_data, so it will leak memory. Add a destructor: ~Data() { delete[] local_data; } Then ensure your move assignment operator works correctly. Don't use std::move(data.data()), this does not in fact set the pointer in the object that is...
65,478,164
65,478,273
Forward the same argument to variadic tuple constructor in C++
TL;DR below I am trying to write some C++ code using a package for multicore processing. The package has a nice sender class that I use to send messages between the threads. It looks something like this: // structs provided by the package struct GlobalVarsContainer { // some global vars }; template<typename ...Ts>...
You can create dummy structure to allow your pack expansion: template <typename> struct tag{}; template<typename ...Ts> struct Bar { Bar(Foo f){}; }; template<typename ...Ts> struct BarContainer{ BarContainer(Foo f) : bars{(tag<Ts>{}, f)...} {} std::tuple<Bar<int,Ts>...> bars; } Demo
65,478,673
65,478,770
another solution for if function for less writing
Hello I am looking for a solution to a function for writing less and clutering the code :D The question is: is there another function or another use of IF function to write less code? because I will need to write from up to 50 line of IF functions Adding a code of how I am doing it and is there another way of doing it ...
if (TESTAS == 30 && soilmoisturepercent == TESTAS) { digitalWrite(LED_PIN, HIGH); // turn on led 5 seconds delay(5000); digitalWrite(LED_PIN, LOW); } else if (TESTAS == 29 && soilmoisturepercent == TESTAS) { digitalWrite(LED_PIN, HIGH); // turn on led 5 seconds delay(5000); digitalWrit...
65,478,756
65,479,018
pthread_cond_timedwait doesn't work even if I use absolute time
I'm using this code to try to get the mainthread to wait around for a bit, but it doesn't work at all. The code is as follows. #include <string> #include <cstring> #include <string.h> #include <iostream> #include <pthread.h> #include <sys/time.h> using namespace std; int64_t get_current_millis(void) { struct timev...
The correct answer is given by @Mat. Thank all. It' really nice of all of you.
65,479,096
65,479,523
I believe [dcl.typedef]/1 has a defect, otherwise what am I missing?
[decl.pre]/10: If the decl-specifier-seq contains the typedef specifier, the declaration is called a typedef declaration and each declarator-id is declared to be a typedef-name, synonymous with its associated type ([dcl.typedef]). [Note 4: Such a declarator-id is an identifier ([class.conv.fct]). — end note] If the de...
There are exceptions to this rule described below that allows you to write such constructions: typedef const signed short int si; [dcl.type.general/2] As a general rule, at most one defining-type-specifier is allowed in the complete decl-specifier-seq of a declaration or in a defining-type-specifier-seq, and at most ...
65,479,486
65,479,565
Can someone pinpoint where I am wrong?
I am trying to make a calculator for my grades average, and I cant seem to find where I am wrong. #include <iostream> #include <conio.h> #include <cmath> using namespace std; int main() { string subject[17] = {"Biology", "French"}; //"Sport", "Ed.Antreprenoriala", "Geografie", "Mate", "TIC", "Psihologie", "Romana",...
you need to add sumaNote = 0; within the i loop.
65,479,507
65,482,208
OutputDebugString an int in win32
I am new to win32 api and as a part of my learning, I want to print out the coordinates of my mouse (LOWORD(lParam), HIWORD(lParam)). How do I do that? The OutputDebugString only gets LPCWSTR value, so do I need to convert the int to that? or there is a better way to do that?
OutputDebugString only knows how to send strings of text to the debugger. OutputDebugString("This works because this is a string.\n"); int x = GetMouseXCoordinate(); OutputDebugString(x); // This doesn't work because x isn't a string. If you want to print something that's not already a string of text, you'll first ha...
65,479,725
65,479,788
How I can insert an array of floats returned by a lambda into a vector of floats?
I'm trying to make the following code to work auto createMyArray = []() { float foo[] = {0.0f, 1.5f, 2.0f}; return foo; }; auto myArray = createMyArray(); std::vector<float> myVector; // fatal error: no matching function for call to 'begin' myVector.insert(myVector.end(), std::begin(myArray), std::end(myArray));...
The modern C++ way of dealing with such arrays is to use std::array. That should avoid the problems you are facing. Using a native C array like you do gets you into allocation-related problems which you should avoid. The compiler warning you are seeing is not to be taken lightly (like any warning). It tells you that fo...
65,479,999
65,480,192
Xcode/clang no longer compiling C++14 code after updating Xcode: "no member named make_shared"
I am no longer able to build my C++ project after coming back to it after a while (I've since updated macOS and Xcode), either from Xcode or by calling clang on the command line. I am getting an error on every use of std::shared_ptr::make_shared in my code. I want to emphasize this used to compile and run fine and I do...
I can't find any way to call make_shared as a static method at all. Also checked your code in other in older versions of Clang. Doesn't seem that it can work... Maybe just: auto test = std::make_shared<test_c>(test_s); UPD Wait. Indeed it worked in in clang of version 9. Looks it really was updated to disable this fea...
65,480,282
65,480,338
Check if same list element contains true or false
Let's say that I have a list std::list<MyClass> myList like this: ID Valid -------------- 1000 true 1000 false 1000 true 2000 false 2000 false 3000 true 3000 true And this boolean value comes from a function bool isExpired(MyClass &a). How can I check if one group of elements have equal or di...
You don't want to use ||, you want to use &&, which means that you have to default to true: std::map<long, bool> status; for(const auto &it : myList) { auto entry = status.find(it.ID); if (entry != status.end()) { entry->second = entry->second && isExpired(it); } else { status[it.ID] = true;...
65,480,285
65,480,537
Is SFINAE on unspecializable std templates ill-formed?
Is the following legal? template<typename T> std::enable_if_t<false, T> foo() {} Usually, we have [temp.res] The program is ill-formed, no diagnostic required, if: no valid specialization can be generated for a template [...] and the template is not instantiated [...] Clearly, no valid specialization can be genera...
The question is whether the prohibition on specializing std::enable_if makes it illegal? I would say that yes, it does. For starters, since such specialization would lead to undefined behavior, we can completely ignore the possibility of this ever happening. The contract is breached there, so discussing legality furt...
65,480,819
65,480,881
Determining what data type a templated struct holds
So I have a data structure that looks a bit like this #include <vector> template<typename T> struct Vector { std::vector<T> v; }; typedef Vector<int> Vi; typedef Vector<float> Vf; typedef Vector<double> Vd; template<typename T> struct Matrix { std::vector<T> m; }; typedef Matrix<Vi> Mi; typedef Matrix<Vf> Mf...
You can retrieve the type using declval and decltype: template<typename T> struct Matrix { std::vector<T> m; using type = typename decltype(std::declval<T>().v)::value_type; }; Or you can use an intermediate structure to extract the type from Vector, see : template <class V> struct VectorType; template <clas...
65,481,144
65,481,210
Difference between std::move() and std::add_rvalue_reference()
Can somebody explain the difference between std::move() and std::add_rvalue_reference()? Do both serve the same purpose? If yes, what is the advantage of one over the other?
std::move is a cast on an object, std::add_rvalue_reference manipulates a type, other than both dealing with r-value references they aren't really related.
65,481,361
65,482,131
How to use C++20 concepts to check some constraints in the template itself
Sorry for the ambiguous title, I couldn't find the right words to phrase it. I'm trying to force a class to define some functions/operators to be correct. for example ForwardIterator is required to have some operators otherwise I should get a compiler error. I have asked the question here and I was given a method with ...
In CRTP, derived class in incomplete, so checking its property is not possible. One way to check interface with traits/concept is simply static_assert after the class: template <typename T> concept is_ForwardIterator= requires(T x, T y) { x == y; // ... }; struct MyCustomIterator { bool operator ==(const M...
65,481,648
65,481,706
reading binary file leaves some bytes unread
I have a binary file containing an image whose dimensions are (1908,1908,3) without any header. Each pixel is a single byte, so there should be 1908 x 1908 x 3 = 10,921,392 bytes. I've used the following function to read the file, using iterators. std::unique_ptr<std::vector<char>> SaliencyMapperTester::readImage(std::...
You should be using std::istreambuf_iterator to read the file in this manner. This is equivalent to using read. std::istream_iterator is equivalent to using the >> formatted extraction operator to read from the file. That will not be very useful, in this case.
65,481,930
65,482,025
How to change a value of an object which is contained in an QVector-array on heap in a simple way?
Modifying objects which are contained in an QVector array on stack can be done like this //widget.cpp //extract from widget constructor: QVector<MyClass> myClassObjectsStack; myClassObjectsStack.push_back(MyClass()); int index = 0; myClassObjectsStack[index].firstName = "Michael"; When QVector array is on heap I do no...
Here's how you do it: (*myClassObjectsHeap)[index].firstName = "Ella"; You should consider using std::vector instead since it's superior in every way. You can see this talk as a nice discussion on that.
65,482,288
65,482,334
why am I getting free(): invalid pointer error after program ends
Can somebody explain why I'm getting this error after program ends? free(): invalid pointer This is my code: #include <iostream> #include <memory> int main() { int a = 3; std::unique_ptr<int> up(&a); std::cout << a << std::endl; std::cout << *up << std::endl; std::cout << &a << std::end...
std::unique_ptr<int> up(&a); The whole and entire purpose of std::unique_ptr, the only reason it exists, is so that when it goes out of scope and gets destroyed it automatically deletes whatever it's pointing to (assuming that it hasn't been moved from). a was instantiated in function local scope, and not dynamic scop...
65,482,464
65,483,698
Balanced paranthesis question based on stack
Here is the question: A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS". You are give...
This kind of problem won't work by the logic for checking valid parenthesis. Example: The test case where input string = (?)? will fail in your case. But it is a valid string as it can take the form (()). So now, how do you approach such a problem? Let's figure out what are all the possible input strings can look like....
65,483,235
65,483,598
C++ structure for time with TZ, but without date?
Are there any structures in the C++ std::chrono spec to represent a time, along with a time zone, but without the date? The issue is that I want to be able to filter records which have unix time (time_t), and return all records which have times between "10:00 EST" and "11:00 EST". This would require converting the time...
C++20 introduces time zone support for chrono. It isn't shipping yet, but there's a free, open-source preview library. It does require some installation for the time zone support. There is no ready made data-structure for {time-of-day, time_zone}. However you could easily build your own by storing time-of-day as a c...
65,483,444
65,486,395
TCP/IP connection over global internet connection (C/C++)
Essentially I've been trying to relay messages between two computers using c/c++ using standard socket programming. Everything works fine on LAN. The issue is making the connection using something like external ip address. I searched online and saw methods that mention ensuring the router is configured for "port forwar...
here is some methods we usually use to solve the problem. If you can use a server in WLAN as relay or central controller, it's quite simple. The computers connect to the server, the server change messages for them and can do many more operations. If you don't want to use a server, then here is a problem: NAT devices ...
65,483,820
65,484,192
Is a vector of arrays contiguous?
If I create std::vector<std::array<double, 2>> points; std::vector<double> points2; I know that points2 will be a contiguous chunk of memory holding doubles in the heap. I think that points will be a contiguous chunk of memory of double* to the stack? But will those array be contiguous in the stack? Let's say that I a...
Is a vector of arrays contiguous? No, it is not. std::array may contain padding or even additional members at the end. More details, e.g., here: Is the data in nested std::arrays guaranteed to be contiguous? Is the size of std::array defined by standard But I believe this is very unlikely to happen and you can sim...
65,483,903
65,488,301
C++ GDIPlus Bitmap lockbits results WrongState(8)
I'm trying to get rect. of diffent area between two Bitmap* objects. When i pass 2 bitmap* it can run lockbits for first frame but it cannot do it for second bitmap. Rect GetRecDifference(Bitmap* currentFrame, Bitmap* previousFrame) { if (previousFrame == NULL) { previousFrame = currentFrame; } else { retur...
The problem is that you are trying to lock the same image twice, this previousFrame = currentFrame; means that both your pointers are pointing to the same image. Instead you need a scheme that keeps two images in memory at once. Something like the following Bitmap* current = NULL; Bitmap* previous = NULL; while (somet...
65,484,387
65,486,676
Get unmanaged DLL path to load Python independent of the version
I looked for a way to retrieve the path to a dll that is installed in the user's computer, but where the path could change depending on where they decided to install it. Couldn't find anything, so I wrote this with my own findings (feel free to add your own). Some background: I'm writing a module that loads Python into...
I don't think there is a nice way to allow for different Python minor versions (eg 3.6 or 3.8) unless you define a stable ABI for Python. However from my experience is that this makes for a poor subset of Python that doesn't support things like PyMemoryView. I would also suggest using delay load linker flags if you can...
65,484,619
65,484,840
Casting static_cast on dynamically-created element of smartpointers vector
I'm learning C++ and I'm facing a problem. I have created a vector of smartpointers containing dynamically-created objects of a derived class but I am unable to cast a static_cast on one of these objects. I have tried several approaches but it didn't work. this is my code: class Person {}; class Walker : public Person ...
You need to unwrap the raw pointer out of the unique_ptr first: auto walkers = static_cast<Walker*>(ptr.get()); Note that the ownership of the pointer still belongs to ptr, which is a std::unique_ptr<Person> still. You can transfer the ownership like this: std::unique_ptr<Walker> walkers(static_cast<Walker*>(ptr.relea...
65,484,705
65,484,809
Is srand a reliable source of encryption pads?
I'm looking to encrypt license keys on an audio software plugin. The biggest risk to the integrity of the license keys is small-time crackers decompiling the code and looking for the encryption key. My solution is to store an arbitrary number in the code and feed it to an algorithm that will obfuscate the encryption ke...
srand and rand will produce the same sequence of numbers when you use the same implementation. Change compilers, even to a newer version of the same compiler, and there are no guarantees, But the new random number generators, introduced in C++11 and defined in <random>, are requires to generate the same sequence of num...
65,485,237
65,485,724
Is specializing std::hash outside namespace std unsafe?
I know that we can only add code to namespace std that is a template specialization of templates defined there otherwise the behavior is undefined. I have implemented this code from C++ primer: //namespace std //{ template <> class std::hash<Sales_data> // class hash<Sales_data> { public: usin...
Is specializing std::hash outside namespace std unsafe? No. template<> class std::hash<Sales_data> { ... }; in the global namespace will result in the same as namespace std { template<> class hash<Sales_data> { ... }; } in the global namespace. Shouldn't I do this or it is erroneous to do so? It's fine to do so - ...
65,485,511
65,485,604
C++: Do functions within structs get copied with the struct?
In a struct (or class), I know that I can add a function and then call it later. struct State { int turnsLeft; void nextTurn() { turnsLeft--; } }; State s1{1}; State s2{2}; s1.nextTurn(); My question is, how do these functions relate to how much space the struct takes up? I know a int is 4 bytes an...
I suppose I need to start with a disclaimer: what I say below applies to all known implementations. In theory somebody could to things differently (but in this case it's so unlikely that it's hardly worth considering even as an intellectual exercise). Member functions will only affect the size of the class in one way: ...
65,486,070
65,486,135
Question about std::function when using with static member function
Why both PassFxn(&X::StaticMemberDoIt); and PassFxn(std::bind(&X::StaticMemberDoIt, _1, _2, _3)); are right? Is there is an implicit conversion when invoking PassFxn(&X::StaticMemberDoIt); since the declaration is void PassFxn(std::function<int(float, std::string, std::string)> func) other than void PassFxn(int(*func)(...
For regular functions (and so static method), inherited syntax from C allows both f and &f as function pointer. Both function pointer, and result of std::bind are callable, and so valid argument to std::function (and as first argument of std::bind).
65,486,081
65,486,167
Read a specific line and column C++
I have a .txt file that contains: Gabriel 18 2002 Joseph 89 1931 How can I read the last column of the first line? Like 2002 I don't know how I can do that with C++, in Shell programming have the sed and awk
In C++ you'd normally do this by reading the entire line, finding (for example) the last space or tab character in the line, and then creating a substring containing the data after that: std::getline(infile, line); int pos = line.find_last_of(" \t"); std::string last_column; if (pos == std::string::npos) // wasn...
65,486,542
65,486,734
Google Test test name confusion
I'm really confused by what SquareTest and PosZeroNeg is representing in this example. I would expect that they are strings being passed into a function, but they aren't? I'm new to c++ so I'm not even sure what to look up since I've never seen anything like this. CLion is showing those "variable string" things as vali...
TEST is a macro with two arguments, the macro produces the test case SquareTest.PosZeroNeg. It may depend on an implementation, but in this particular example this days, SquareTest names a class and PosZeroNeg names a (static) class method, both are generated by the macro, and SquareTest.PosZeroNeg maps these class an...
65,486,760
65,487,131
Intrinsic benefit of using a LinkedList class to point to head Node vs. just using Node*
We can define a LinkedListNode as below: template <typename T> struct LinkedListNode { T val; LinkedListNode* next; LinkedListNode() : val{}, next(nullptr) {} LinkedListNode(T x) : val{ x }, next(nullptr) {} LinkedListNode(T x, LinkedListNode* next) : val{ x }, next(next) {} }; If we want to define...
Defining an actual LinkedList type allows you to directly support operations that would be relatively difficult to support by just passing around a pointer to a node. One comment has already mentioned storing the size of the linked list as a member, so you can have a function return the size of the linked list in const...
65,486,924
65,488,241
How should I get platform specific jni headers in linux for cross-build?
I'm new to the Jni environment and I want to cross compile the shared library builds using the docker so the Jar can be packed easily from any platform and can include the required shared libraries. I had more attempts to do via CMake and Meson build system but never succeed in them, so I shifted to docker, luckily I f...
Found OpenJDK headers in the github repository. Although that's not properly arranged as one in the JDK installation, its worth hardcoding those paths or use a simple bash/python script :) Hopefully its helpful. Since its nowhere written or guided to be used. Many blog posts just download extract the whole jdk for all ...
65,487,148
65,487,956
Class Destructors not being called in the expected reverse order from which they were initialized in
I was testing out smart pointers and how they work and I ran into an "issue". Here is the code which I will be talking about: #include <iostream> #include <memory> class B; // forward declaration class A { private: std::shared_ptr<B> b_ptr; public: void set_B(std::shared_ptr<B> &b) { b_ptr = b; ...
A owns a reference to B. Your main scope owns a reference to A and B. When main ends it drops the B reference, then the A. The B reference drops the reference count to 1. The A to 0. As destructor then runs. After the body of the destructor runs, each member is destroyed. As reference to B goes away. Bs destructor...
65,487,162
65,487,198
Polymorphism with C++
I am trying to achieve Polymorphism whereby a specific method of the derived class is called based on the instance passed to the function. I'm not sure if this is possible. Any guidance would be much appericated. This is the code: #include <iostream> using namespace std; class Animal { public: void speak() { ...
Sure you can. I recommend making Animal an "abstract" base class. Declare the functions virtual and make them "pure" by setting them to 0 (forcing derived classes to override them to be able to be instantiated.) class Animal { public: virtual ~Animal() = default; // allows polymorphic destruction too virtual v...
65,487,173
65,487,528
expected initializer before imprimircadena
#include <iostream> using namespace std; class String { public : String :: String(char* ch); public : ~String (); private : char* text; size_t sizeoftext; public : void imprimircadena(); }; String :: String (char* ch) { sizeoftext = strlen(ch); //pido la ...
Syntax while defining method is incorrect Plz check my definition of method void String:: imprimircadena() // class name should be before :: { for (int i = 0 ; i < sizeoftext ; i++) cout<< text[i]; cout<<endl; }; There are lot of basics mistakes you have done. Please first learn basic syntax of c+...
65,487,583
65,487,987
Is __thread guaranteed to be zero initalized?
I have two variables. One is __thread the other is static __thread. If I had a constructor all I'd do is zero all the member variables. I also happen to use this class only outside of function bodies. Will my variables be zero initalized skipping the need for me to write a constructor? To clarify. I have a class that ...
Thread-local variables are zero initialized before any other constructors. If you have no constructors, then only the zero initialization is done. In case of a class type, this means all members are set to zero. Zero initialization is performed in the following situations: For every named variable with static or thre...
65,487,608
65,488,309
why does the pow function seem to be glitching?
For the below code: int digsum(ll num) { //function to calculate sum of digits if (num < 0) num = abs(num); int ans = 0; while (num != 0) { ans = ans + num % 10; num = num / 10; } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int a, b, c, cnt...
My psychic powers suggest that your standard library's implementation of pow is not precise. I recall a discussion on SO a while back on this topic. Remember, pow returns a floating point value. I can't repro it, but it's entirely possibly your invocation of pow(19,3) returns 6858.999999999 or similar due to the way...
65,487,678
65,487,788
Using a class/struct member delared inside 'if' conditional outside
I am attempting to recreate some "R" scripts in C++, just for the fun of it. Have used C decades ago but not recently. Now what I have is a bit of code where I am reading data from a binary file and placing the data into a structure (or class) with an unknown number of array structures (for the file reading side). Not ...
If you need it to live longer than the scope of the if, then declare it in the outer scope where you need it to continue living. After you added this line to deal with the warning: traverse stations[1]; // removes 'stations was not declared' error on line 35. You left the declaration of stations inside the if. That h...
65,487,728
65,487,873
istream compile error in C++ using Visual Studio
I’m using Visual Studio and I'm reacquainting myself with C++ before taking a few classes. This is an old script that used to compile, but now istream is giving me a few syntax errors. If anyone can lead me in the right direction, that would be great. Fraction.h friend istream& operator >> (istream& in, const Fractio...
Because it takes reference to CONST type. const Fraction& f, it must not be (just remove "const" in the both declaration and definition), the stream input operator is about to modify this object. Instead, const should be used in the stream output operator (e.g. std::ostream& operator<<(std::ostream& os, const Fraction&...
65,487,825
65,487,880
Sum of rows and column in a Matrix
the problem arises when I use a different number of rows and columns, for example, 2 by 3 otherwise, it is running okay. the sum of column outputs garbage values I can't seem to understand where the bug is. #include <iostream> #include <conio.h> using namespace std; int main () { int a[10][10]; ...
You are not iterating correctly to get your columns sum, column and row are switched up. change to: for (i = 0; i < column; i++) // <----- { for (j = 0; j < row; j++) // <----- s = s + a[j][i]; cout << "Sum of Column " << i + 1 << " is: " << s; s = 0; cout << endl; } Consider a 3x4 matrix: 1 2 ...
65,487,918
65,488,033
CodeSignal: Execution time limit exceeded with c++
I am trying to solve the programming problem firstDuplicate on codesignal. The problem is "Given an array a that contains only numbers in the range 1 to a.length, find the first duplicate number for which the second occurrence has minimal index". Example: For a = [2, 1, 3, 5, 3, 2] the output should be firstDuplicate(a...
Anytime you get asked a question about "find the duplicate", "find the missing element", or "find the thing that should be there", your first instinct should be use a hash table. In C++, there are the unordered_map and unordered_set classes that are for such types of coding exercises. The unordered_set is effectively...
65,488,215
65,490,157
Proper way to facilitate MOVE operation when overriding operator on C++
I'm not really familiar with how move works in C++, and I need some help to clarify my understanding. I'm want to overload the operator+, and I'm have a couple of questions about it. ap_n operator+(const ap_n& n, const ap_n& m) { ap_n tmp {n}; return tmp += m; } My first question is how to make temporary obje...
how to make temporary objects movable By defining move constructor/assignment to your type. Is the return value supposed to be a reference as ap_n&? Not for operator+ when you return new object. operator += on the other hand returns reference to lhs, so returns ap_n&. How can I make my return value usable for move...
65,488,589
65,488,670
While Loop when to use OR or AND?
I need help with this simple question. I'm starting to learn more about while loops and I'm not sure what I'm doing wrong. Here's a snippet of the code that I'm working on, so when I'm using or in while loop the loop executes indefinitely. But when I use AND the loop stops can somebody please explain? Shouldn't OR be ...
You have phrased your condition (option != 'Q' or 'q') like you speak it. "option not upperQ or lowerQ". That is understood by the compiler as "option is not upperQ; or q", where "q" is a non zero thing. Nonzeros are interpreted as "true". So the whole thing always evaluates to "true", always, even for option having a ...
65,488,850
65,489,556
Terminating with uncaught exception of type std::out_of_range aborted error
I'm trying to make a program that turns a string into a char array. My code looks something just like this (this is just a part of my code): #include <iostream> #include <string> using namespace std; int main() { string Word; cout << "Type A String And I'll Turn It Into A Char Array ' : "; cin >> Word; ...
You are writing out of the range of char_word variable. //First make enough space for char_word int length = word.length()+1; char Char_word[ length ]; for( int i = 0; i < length - 1; i++) Char_word[i] = word.at(i); Char_word[length-1] = '\0'; //very important Reading or writing beyond the range is a bad thing in...
65,489,063
65,504,582
I can't modify variables I declared in C++ with UPROPERTY(EditAnywhere) using Blueprint (UE4)
I'm new to UE4 but I have some basic understanding to C++ and I've been developing a FPS Shooter Game which is kinda challenging to me. And here I am, with a problem that is still remain unsolved to me. So here's a part my code: FPSCharacter.h: #pragma once ... #include "Weapon.h" #include "CoreMinimal.h" #include "Ga...
You should add Instanced keyword to UPROPERTY specifiers of weapon variables. That way, an instance of an object will be created and assigned to a property, that saves correctly You might also need to add EditInlineNew as a UCLASS specifier to your weapon class. FPSCharacter.h UCLASS() class GAME_API AFPSCharacter : pu...
65,489,236
65,489,938
How's the Copy & Swap idiom really supposed to work, seriously! My code fails
I have been hearing about this, very advertised way of implementing an assign operator=() in C++. EDIT: MVP(s), https://onlinegdb.com/meN5a_I2I (Version 1) https://onlinegdb.com/HybpyOO6P (Version 2) Version 2: a.out: main.cpp:52: int main(): Assertion `ptr == a.data()' failed. ...
The main problem is that you seem to misunderstand how modifications to a.local_data are propagated (or not, as is what happens) to ptr. Lets draw this up, statement by statement: First we have Data a("Some data"); Which gives us something like +--------------+ +-------------+ | a.local_data | --> | "Some data" |...
65,489,397
65,489,510
How do I initialize non-static class members and not get the C2864 error?
I'm making a thingy and today I got the C2864 Error. I am new to C++ so I'm actually kind of lost. #ifndef MONSTER_ZOMBIE_H #define MONSTER_ZOMBIE_H // class definition class CZombie : public CBaseMonster { public: virtual void Spawn(void); virtual void Precache(void); virtual void HandleAnimEvent(MonsterE...
The code you are trying only becomes legal with C++11. So change your compiler options to be at least C++11 (not sure if this is possible with Visual Studio 2010, you really should upgrade your compiler as well). Or do things the old fashioned way with a constructor. class CZombie : public CBaseMonster { public: CZ...
65,489,524
65,489,654
Binary '<' : 'const_Ty' does not define this operator or a conversion to a type acceptable to the predefined operator
I am getting the same error in my own code. This is a small example. Where is the problem? #include <set> using namespace std; class Table{}; struct MyStruct { set<Table> arr; }; int main() { MyStruct a; Table t; a.arr.insert(t); // Here it gives C2676 error }
std::set is an ordered container. For custom types you are expected to provide an ordering for your type. The simple way to do that is to define operator< for your type. // return true if table x should go before table y in the set bool operator<(const Table& x, const Table& y) { ... } Because you didn't do that (...
65,489,856
65,490,110
Is there any way can know if the thread is created success or failure?
I am using std::thread to create a thread, but looks like there is no API can tell if this operation success or failure. Is there any way to know this information?
The constructor of std::thread throws an exception in the case of a failure. https://en.cppreference.com/w/cpp/thread/thread/thread Exceptions 3) std::system_error if the thread could not be started. The exception may represent the error condition std::errc::resource_unavailable_try_again or another implementation-spe...
65,490,292
65,490,544
How to filter std::list and remove non-matching items comparing to another list?
I am trying to remove elements which are not matching with elements from another list. For example I have std::list<MyClass> mainList which contains something like this: ID Number ------------- 1 100 2 200 3 200 4 100 5 300 And I have one more std::list<long> itemsForFiltering which ...
To make it more efficient, you can start by creating an unordered set of the items to filter: #include <unordered_set> using namespace std; ... auto itemsForFilteringSet = unordered_set<long>{itemsForFiltering}; Now you can filter using mainList.remove_if([&](MyClass &val) { return itemsForFilteringSet.find(val)...
65,490,377
65,490,530
Behaviour of map emplace vs try_emplace?
Let's say I have an unordered_map: std::unordered_map<Key, BigObject> big_objects; where BigObject is like: struct BigObject { BigObject(P1, P2, P3); // <--- expensive /*...*/ }; and I have a Key k, and a set of arguments for BigObjects constructor P1 p1, P2 p2 and P3 p3. If big_objects already contains k I w...
Yes, it is correct, this is the reason why try_emplace exists, it doesn't touch its arguments if the key is already present. Cppreference try_emplace Unlike insert or emplace, these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are mov...
65,491,395
65,491,521
What this template syntax "typename = T" mean?
Sometimes I see syntax like this. template<typename T,typename = int> int foo(){ //... } what part typename = int mean? Where it can be used?
foo has two template arguments. The first is called T and the second is unnamed and defaults to int. In your piece of code alone there is no reason to use the second argument. Unnamed template arguments often come up with SFINAE. An example from cppreference: // primary template handles non-referenceable types: templat...
65,491,424
65,491,469
error:no matching fucntion for call to 'Square::Square(SquareColor&,Location*)'
I'm trying to make a chess game in C++ and I have an error I can't resolve where the error is: for(auto file : all_E) { Square newSquare= new Square(currentColor, new Location(file,i)); boardSquares[i][column]=newSquare; } These are the Square and Location Classes class Square { SquareColor...
You are constructing a pointer (Location*), not an object (Location), which is why the constructor does not match. Remove the new: Square newSquare = Square(currentColor, Location(file,i));
65,491,682
65,961,415
Wt++ TableView and QueryModel
I have a problem with tableView and queryModel this is my error: lo.C: In constructor ‘HelloApplication::HelloApplication(const Wt::WEnvironment&)’: hello.C:162:48: error: no matching function for call to ‘Wt::WTableView::setModel(std::remove_reference<Wt::Dbo::QueryModel<Wt::Dbo::ptr<Utente> >*&>::type)’ tableVie...
Wt::WTableView::setModel expects a shared pointer, i.e. std::shared_ptr<Wt::WAbstractItemModel>, not a raw pointer to your item model. So, you should replace auto *modelDataTable = new Wt::Dbo::QueryModel<Wt::Dbo::ptr<Utente>>(); by auto modelDataTable = std::make_shared<Wt::Dbo::QueryModel<Wt::Dbo::ptr<Utente>> >(); ...
65,492,062
65,492,126
Why assignment operator = doesn't return the value of pointer but the dereference value?
From What does an assignment return? : An assignment expression has the value of the left operand after the assignment and this code: #include <iostream> using namespace std; int main() { int a[5] = { 0,1,2 }; int* a_ptr = a; int b = (*a_ptr++ = 3); //int *b won't compile cout << b << endl; //3 ...
The left operand is *a_ptr++. As per the operator precedence, it's evaluated as *(a_ptr++) where the post-increment is sequenced as a side effect, after the execution of the statement. The value of the operand is the result of the statement. So, it's equivalent to int b = (*a_ptr = 3); a_ptr++; That said, in genera...
65,492,409
67,802,411
audio file ds2 format to wav conversion in CentOS
I am trying to convert ds2 format audio file to wav in a python / c++ based solution. Basically, I want to read ds2 audio in Linux with any codec. I tried ffmpeg and pydub, but failed. Is there any other library or solution which can handle this conversion on linux? ffmpeg -i audio_input.DS2 -acodec dss_sp -ar 16000 -...
On linux with wine there is also switch from nch.com.au, free for personal use only. The graphical interface works fine on my Fedora desktop and you can use cli for automation Here a example with output in ~/Musics by default /usr/bin/wine /home/mylogin/.wine/dosdevices/c\:/Program\ Files\ \(x86\)/NCH\ Software/Switch/...
65,492,441
65,492,520
cv::rotate appears to have no effect
I want to rotate a cv::Mat 90 degrees clockwise. I've written the following snippet: cv::Mat m = populate_somehow(); cv::Mat rot; cv::rotate(m,rot,ROTATE_BY_90_CW); std::cout << rot.total()*rot.elemSize() << std::endl; cv::imwrite("dump0.bmp",m); cv::imwrite("dump1.bmp",rot); The first image, ...
I think you have wrong rotateCode, try use cv::ROTATE_90_CLOCKWISE.
65,492,568
65,492,616
How to take multiple lines Input in char arrays without overwriting using getline()
I am a beginner in c++. I am basically trying to take input from user in multiple lines using getline(). But it is overwriting the input every time. Is there any way to get input in char array and not overwrite the previous line or some way to take input in string array and convert it into char array? #include<iostream...
You need to do two things: Open the destination file before you start asking for user input. In the loop where you ask user input, after every input, dump (append) the buffer content to the destination file. Something like (pseudocode, not tested) int main() { int lines; char sentence[1000]; cout << "Enter Numb...
65,492,605
65,495,047
how to connect firebase with libcurl
I want to connect my code to firebase with using libcurl library and read datas i have function like this static size_t my_write(void* buffer, size_t size, size_t nmemb, void* param) { std::string& text = *static_cast<std::string*>(param); size_t totalsize = size * nmemb; text.append(static_cast<char*>(buffer), t...
Schannel error code 0x80092013 means Revocation Server Offline. In your case the Firebase CRL, http://crl.pki.goog/GTS1O1.crl as specified in the server certificate, could not be fetched. That could be due to a misconfiguration of the Windows trust store, DNS, firewall, proxy, corporate network, or alike. As a temporar...
65,493,128
65,856,888
How to use wstringstream and getline with wchar_t?
I have a pipe-delimited string that I want to put into the vector named result. However, it won't compile on getline. If I remove the pipe-delimiter character in getline, then it compiles: #include <sstream> using namespace std; wstringstream ss(L"1,2,3|4,5,6|7,8,9|"); vector<wstring> result; wstring substr; while (ss...
Your code does not compile because getline requires that the delimiter and the stream use the same character type. Your string stream ss uses wchar_t, but '|' is evaluated by the compiler as a char. The solution is to use the appropriate character literal, like this: #include <sstream> #include <iostream> using namespa...
65,493,539
65,493,614
Compare each character of two strings. New and looking for input
I'm currently in a class for C++ Development at WGU, and I'm presented with an exercise based on Simon Says. Basically, simonPattern is a string of 10 Characters (R, G, B, Y), and userInput would be the input at each step of the game. The chapter is on break and continue statements, but the exercise didn't provide any ...
You didn't need all those variables — you already had arrays to work with! And the beauty of the arrays it that you can use other variables to index into them, which allows you to collapse all that repeated logic into another loop. Your program could have been written like this: #include <iostream> #include <string> us...
65,493,579
65,494,002
I'm having some issue with arithmetic operators in string
I am a beginner and I am practicing C++ on UVa. Problem link: P458 My IDE is showing an error in line 15 decoded = decoded + (s[i] - 7); My code: #include <iostream> #include <string> using namespace std; int main() { string s; while (cin >> s) { string decoded; int len = s.length(); ...
Please explain why this is happening? std::string has a method overload std::string::operator+= that accepts type char. That what makes this line: decoded += (s[i] - 7); to compile. But when you write: decoded = decoded + (s[i] - 7); that requires (s[i] - 7) to be implicitly converted to std::string or something th...
65,493,709
65,493,880
Convert char** to int C++
So I have an array of symbols which has another array of symbols in it (if i'm not wrong). What I need to do is to change third element (words[2]). This third element will definitely be a number. I have to increase this number by 15 percent. Therefore, I need to convert words[2] to int? Function: void create(char* str)...
you need to convert a char* to int like below. (int) casting won't work int a = atoi(words[2]); // make sure words[2] is null terminated
65,493,935
65,494,321
Error with going through map elements with a class pointer as values
I have a class that i'm using for a trie class Node { public: map<char,Node*> node; bool flag = false; }; int main(){ Node table; for(auto x: table){} return 0; } I'm trying to iterate through it's elements but I keep getting errors I checked stack for solutions and tried to use the iterator map m...
Node is not an iterable class. It's just a regular class, that happens to have a std::map as a member. What you want is to access the map object within `Node: for (auto x : table->node) Also, in the code you showed us, table is never initialized. I am assuming that in your real code, it is, but if not, fix that too....
65,494,545
65,494,657
Auto parameter type in lambda causes "Use 'template' keyword to treat..." error
I have this code struct TestClass { template <typename T> T get() { return 0; } }; void invoke(const std::function<void(const TestClass& c)>& func) { func(TestClass()); } Now if I use invoke as following there is no problems invoke([](TestClass tc) { tc.get<int>(); }); But if I change...
Now that you have a template type (in the form of auto) instead of a concrete type TestClass, the get function is dependent, and therefore you need to qualify it with the template keyword: tc.template get<int>();
65,494,838
65,496,195
How to change the value of wxDatePickerCtrl?
I have tried this, But I am not able to get date displayed on the datePickerCtrl. Here SDOB is a wxDatePickerCtrl. SDOB->SetValue(Rs.GetDate(3)); But I am able to get the date onto a label or text field by doing wxStaticText11->SetLabel(Rs.GetDate(3).FormatDate()); But for my purpose I would like to get it onto the d...
You're using the correct function for setting wxDatePickerCtrl value, so if you don't see what you expect, the date you pass to it must be invalid or otherwise different from what you think it is. Generally speaking, when asking about why something doesn't work you should explain both how do you expect it to work and w...
65,495,025
65,495,332
How can I add different names to a vector using classes?
#include <iostream> #include <string> #include <vector> class Enemy { private: std::string rank = "Boss"; std::string rank2 = "Miniboss"; public: std::string type; std::string get_rank(){ return rank; } std::string get_rank2(){ return rank2; } }; int add_enemy(std::...
So the reason that both Orcs are added is because by the time you run add_enemy, you've already added them. All the enemies should be using the add_enemy function instead of push_back: int main() { Enemy enemy; enemy.type = "Dragon"; std::cout << enemy.type << " is a " << enemy.get_rank() << std::endl; ...
65,495,122
65,495,712
How to change color of Rect within an image if it contains a certain value
I have several ROIs on my image. For each ROI, if it contains a black pixel, I want to color the whole ROI black. Here is my code so far: int j = 0; // this loop sets the ROI rows while (j < 10) { // this loop sets the ROI columns for (int i=0; i<width-1; i+=mini_box_width){ ...
You can select a region of your image with your Rect minibox by calling your image with the rectangle: i.e. region = frameRGB(minibox), see the docs for Mat::operator()(const Rect& roi) Then you can check if there's a black pixel inside your region with cv::countNonZero(region == cv::Scalar(0, 0, 0)) (docs). If there's...
65,495,390
65,495,432
C++ convert from int to byte array, then convert that byte array back to int, cause overflow
I'm making a multiplayer game where I use CSocket to send data between server and clients, and I need to transfer raw bytes. So I tested out how to convert from integer to byte array and reverse, this is what I tested: int test1 = 257; byte bytes[4]; copy(&test1, &test1 + 3, bytes); int test2; copy(bytes, bytes + 3, &...
Here's your code fixed int test1 = 257; byte bytes[4]; copy((char*)&test1, (char*)&test1 + 4, bytes); int test2; copy(bytes, bytes + 4, (char*)&test2); cout << "Test " << test2 << endl; I convert all the pointers to char pointers, and I use +4 not +3. +3 only copies three bytes so it fails to copy the last byte.
65,495,523
65,496,905
Time complexity of operations on Order Statistics Tree and 1D points problem
I ran into the following interview question: We need a data structure to keep n points on the X-axis such that we get efficient implementations of Insert(x), Delete(x) and Find (a, b) (giving the number of points in the interval [a, b]). Assume that the maximum number returned by Find(a, b) is k. We can create a data...
The answer is indeed (1). The idea of an AVL tree is fine, and your conclusions are right. But you can extend the AVL tree such that each node has one extra property: the number of values that precede the node's own value. You would have to take care in the AVL operations (including rotations) that this extra property ...
65,495,822
65,496,333
How to infer the template parameter from instantiation of function template?
I know how to infer the template parameter from an instantiation of a class template: template <typename T> struct foo {}; template <typename T> struct foo_param; template <typename T> struct foo_param< foo<T> > { using type = T; }; But I am lost at doing the same for a function template. The naive template <typ...
I don't think it's possible what do you want. Not passing through the type of the function, at least, because the type of bar<T> is exactly the same for every type: a returning void function with no-argumens. You can verify this with a simple static_assert() static_assert( std::is_same_v<decltype(bar<int>), decltype(ba...
65,495,929
65,496,097
C++ Long integer display
#include <iostream> #include <map> using namespace std; map<pair<int, int>, int> d; auto trav(int m, int n) { if (d.find(make_pair(m, n)) != d.end()) return d[make_pair(m, n)]; if (m == 0 || n == 0) return 0; if (m == 1 && n == 1) return 1; d[make_pair(m, n)] = trav(m - 1, n) + trav(m, n - 1); ...
The cast here is too late: cout << long int(trav(18, 18)) << endl; As everything in trav is calculated with ints the possible overlflow happens before the cast. Once the overflow happened casting afterwards is of no use. I do get correct looking results when I change the calculations to use long int: #include <iostrea...
65,496,071
65,499,026
Signed variant of size_t in standard C++ library
Is there a signed variant of size_t in standard C++? Meaning exactly same bit size as size_t but signed. Of course I can do: #include <type_traits> using signed_size_t = std::make_signed_t<std::size_t>; but maybe there is already similar definition in standard library, not to invent extra type name? I know there are s...
There is one place where the "signed version of std::size_t" (and also the unsigned version of std::ptrdiff_t) comes up in the standard: The printf format specifier %zu is for std::size_t objects. %zd is for objects of, as the C standard which the C++ standard refers to says, "the corresponding signed integer type [of ...
65,496,175
65,529,195
std::for_each with std::execution::par_unseq not working on GCC but working with MSVC
I wanted to parallelize a for loop and found out about std::for_each as well as its execution policies. Surprisingly it didn't parallelize when using GCC: #include <iostream> #include <algorithm> #include <execution> #include <chrono> #include <thread> #include <random> int main() { std::vector<int> foo; foo.r...
I solved it by firstly upgrading my WSL Ubuntu distribution from version 18.04 to 20.04 since after running sudo apt install gcc libtbb-dev to install TBB I still got the following error: #error Intel(R) Threading Building Blocks 2018 is required; older versions are not supported. This is caused by TBB being too old. N...