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
71,772,165
71,774,151
Nothing dumped from json that converted from bson
I need your help about nlohmann's json library. I wrote this code. std::vector<std::uint8_t> v = nlohmann::json::to_bson(jInit); std::vector<std::uint8_t> s; for (auto& i : v) { s.push_back(v[i]); } std::ofstream ofs(s_basePath + "dump.txt"); ofs << nlohmann::json::from_bson(s).dump(); This simply converts json to...
The problem has nothing to do with json/bson. It's just that you use every uint8_t in the original bson data as an index into the very same data, which scrambles everything up. Wrong: for (auto& i : v) { s.push_back(v[i]); // `i` is not an index } The correct loop should look like this: for (auto& i : v) { s.p...
71,772,400
71,772,442
Iterate over a part of an array
Whats the best way to iterate over a part of an array? I want to iterate over the first 4 elements of an array and then separately I want to iterate over the last 4 elements of the array. Is the following code the best way to do it? Please help. void function() { int arr[8] = {a1, a2, a3, a4, b1, b2, b3, b4...
You could do: int i = 0; for ( ; i < arr_num / 2; ++i ) { // leave the initialization section empty, "i" is already 0 //... } for ( ; i < arr_num; ++i ) { // "i" already has the correct value from above loop // ... } This way i retains its value between loops, and, is more generic for different sizes of arr...
71,772,460
71,772,509
I am not able to store an element of an array into a register using x86 assembly
The following is my code in assembly: mov esi, MemberLvl mov edi, OfficerLst mov al, [esi] mov test1, al mov ah, [edi] mov test2, ah In the C++ main program, I have declared a list of type long called MemberLvl and OfficerLst, and two long types - test1 and test2. Whenever I try to run my code...
al and ah are 8-bit values (1 byte). test1 and test2 are "long" according to you, which is either 32 bit (4 bytes) or 64 bit (8 bytes), depending on your compiler / system. If you want to store the values in the respective variables, you can use movzx (if unsigned) or movsx (if signed). Also, note that if MemberLvl is...
71,772,599
71,777,358
Template specialization and selection in variadic template class
I've a variadic templated class with some template specializations. I would like, for some specialization, to enable them conditionally (with std::enable_if, so I added a additional unused template parameter). Here is a code example: #include <tuple> #include <iostream> template<int v,typename, typename...> struct A; ...
For specialization B, you need to ensure that the conditions to std::enable_if are orthogonal. In your version, if you supply v=12 both conditions v!=11 and v==12 yield true, meaning that both versions are enabled. That is the reason why you get the ambiguous instantiation error. The following compiles fine (https://go...
71,772,678
71,773,834
How to save an exception and throw it later
Say I want to create an exception object, but throw it a bit later. My use case is that the exception is generated in a thread, but I need to actually throw it from my main thread (because there's nobody to catch it in the child thread) using namespace std; runtime_error *ex = nullptr; thread myThread( [&ex]{ if ...
std::exception_ptr is the C++ facility to store exceptions. It can usually avoid an extra allocation. std::exception_ptr ex = nullptr; std::thread myThread( [&ex]{ if (something_went_wrong) { ex = std::make_exception_ptr(std::runtime_error("Something went wrong")); return; } } ); myThread.join...
71,773,132
71,773,182
Defaulted concept-constrained function never selected for instantiation
While working with C++20, I encountered an oddity which I'm unsure is a compiler defect due to C++20's infancy, or whether this is correct behavior. The problem is that a specific constrained function is either not selected correctly, or produces a compile-error -- depending entirely on the order of the definitions. Th...
Your code is correct, and indeed was the motivating example for supporting this sort of thing (see P0848, of which I am one of the authors). Clang simply doesn't implement this feature yet (as you can see here). gcc and msvc both accept your code. Note that you don't need empty anymore, just union { T val; } is suffic...
71,773,154
71,773,313
Does __global__ have overhead over __device__?
This question asks the difference between __device__ and __global__. The difference is: __device__ functions can be called only from the device, and it is executed only in the device. __global__ functions can be called from the host, and it is executed in the device. I interpret the difference between __global__ and ...
Yes, __global__ has overhead, compared to __device__, but there are additional details to be aware of. What you're proposing probably isn't a good idea. __global__ is the device code entrypoint, from host code. Initially, the GPU has no code running on it. When your host code decides that it wants to start some proc...
71,773,367
71,775,569
GetAce() failing with - ERROR_INVALID_PARAMETER
I'm attempting to do some ACL modification with some C++ code in Visual Studio. I'm stumbling into several issues, one of which is that, when I try to read the ACEs off the existing ACL using GetAce(), the call to the function fails and it returns error 87, ERROR_INVALID_PARAMETER. The ACL in question includes four ent...
I was modifying a member of one of the ACEs retrieved from the ACL directly, within the loop, which was most likely adjusting pointers or memory in such a way that broke things with memory allocation, etc. Thanks to @273K for pointing me in the right direction!
71,773,891
71,774,513
std::coroutine_handle<Promise>::done() returning unexpected value
I am trying to write a simple round-robin scheduler for coroutines. My simplified code is the following: Generator<uint64_t> Counter(uint64_t i) { for (int j = 0; j < 2; j++) { co_yield i; } } ... void RunSimple(uint64_t num_coroutines) { std::vector<std::pair<uint64_t, Generator<uint64_t>>> gens; for (ui...
Your program contains undefined behavior. The issue is your fill resumes the coroutine when !full_, regardless of whether the coroutine is at final suspend or not, which you can learn by calling h_.done(). Generator<uint64_t> Counter(uint64_t i) { for (int j = 0; j < 2; j++) { co_yield i; } // final suspend }...
71,774,376
71,774,811
Insert into a vector using an insert using lower_bound
How do I change CompareByNA to make the insert work, I assume it's wrong for the first element to insert program: https://onecompiler.com/cpp/3xycp2vju bool Company::compareByNA(const Company &a, const Company &b) { return a.getNameAddr() < b.getNameAddr(); } .. if ( binary_search(CompanyNameList.begin(), CompanyNa...
Here is your issue lower_bound(CompanyNameList.begin(), CompanyIDList.end(), cmp, Company::compareByNA); You are mixing up your lists. You probably meant to use lower_bound(CompanyNameList.begin(), CompanyNameList.end(), cmp, Company::compareByNA);
71,774,410
71,774,688
MSVS2017, Boost C++ error with namespaces
Can anyone help me out. I stumbled into a roadblock. I've modified the project properties to include the Boost header path, and Boost linker path--plus the 'not using predefined header files' options' Some how, Visual studio can't see std_in/std_out as part of the boost::process namespace. I've compile the same file on...
It's not that it can't see bp::std_in and bp::std_out. It's because you've swapped the streams. ipstream is an implementation of a reading pipe stream - a stream that you can use in a similar way as std::istreams, like std::cin. opstream is an implementation of a write pipe stream - a stream that you can use in a simi...
71,774,559
71,774,898
What does string().copy() do?
Can anyone explain what this code does? Con(const char* n){ char_number = new char[sizeof(n) + 1]; string(n).copy(char_number, sizeof(n) + 1); } I don't understand the string(n) part. What exactly does this do?
From the documentation: std::string::string copy constructor string (const string& str); Constructs a copy of str. from c-string string (const char* s); Copies the null-terminated character sequence (C-string) pointed by s. Note: .copy() is explained here.
71,774,876
71,774,994
linked list c++ difference between void function and return this
I have a question about the differences between 2 styles of coding: void *addfirst (int data){ head = new Node(int data, head); return; } and the second is: LinkedList *addfirst (int data){ head = new Node(int data, head); return this; } My prof said that nowadays most people prefer the second cho...
void *addfirst (int data){ head = new Node(int data, head); return; } The function is declared to return an object of type void*. The function returns by returning nothing. The behaviour of the program is undefined. LinkedList *addfirst (int data){ head = new Node(int data, head); return this; }...
71,775,286
71,775,376
understand the different construction of a std::string_view
Live On Coliru The string_view family of template specializations provides an efficient way to pass a read-only, exception-safe, non-owning handle to the character data of any string-like objects with the first element of the sequence at position zero. #include <iostream> #include <string_view> #include <unordered_ma...
Question 1: std::make_pair(*s2_bad, 2) will create a std::pair<std::string, int>, so the pair has a distinct temporary std::string, unrelated to the string s2_bad points to. Then, a std::string_view will be constructed from this temporary, which will be promptly destroyed. So the moment umap.emplace(std::make_pair(*s2_...
71,775,512
71,775,557
Wrong input in nested while loop
I don't no how to handle wrong input. I made an nested while loop, because if I only use the If statement and the input is wrong, it jumps to the beginning of the first while loop and not to "Do you wish to continue?". If I use a nested while loop, it somehow won't finish, even though the bool condition is satisfied. P...
It may be a lot simpler to create a function bool check_continue() { while(true) { // get your input if((go_on == 'Y') || (go_on == 'y')) return true; if((go_on == 'N') || (go_on == 'n')) return false; } }
71,775,829
71,775,904
c++ read file with accents
Good day, I am in a small project where I need to read .txt files, the problem is that some are in English and others in Spanish, the case is being presented in which some information comes with an accent and I must show it on the console with the accent. I have no problem displaying accents on console with setlocale(L...
Your error is how you control your read-loop. See: Why !.eof() inside a loop condition is always wrong. Instead, control your read-loop with the stream-state returned by your read-function, e.g. while (getline(file,text)) { std::cout << text << '\n'; } The character in question is sim...
71,776,681
71,777,052
Is it possible to pass popen() a string and have it return null?
While working on line/branch coverage for a unit test, I came across the following code bool run_command(char *command) { FILE *handle = popen(command, "r"); if (handle == nullptr) { std::cerr << "" << std::endl; return false; } I've tried many different commands such as "cat /dev/null ...
I don't think so. glibc's popen ultimately calls posix_spawn, whose documentation says that it only fails if fork() fails. And that would have nothing to do with the filename. Likewise, there are a few other ways that popen can fail before calling posix_spawn, but they aren't related to the filename; only conditions ...
71,777,048
71,777,566
OOP in C++. How to drop the states
I am writing a simple graphics editor. There are 3 buttons on the panel, by pressing which I draw a square, circle or line. There are 3 button handlers that change the state and 3 mouse event handlers in the class responsible for drawing the workspace. void Cpr111View::OnCirc() { state = 1; } void Cpr111View::OnLin...
Using this way of polymorphic calls in C++ requires to use reference sematics. I advise to read about it. E.g.: Reference and Value Semantics So it class Cpr111View, you have to keep your Figure member by pointer, or by refernce. In order to avoid having to manually manage the object, you should use a smart pointer lik...
71,777,390
71,784,149
Make QGraphicsVideoItem Fill QWidget
My goal is to create a simple video player QWidget that allows for some overlayed graphics (think subtitles or similar). I started with the naive approach, which was to use QVideoWidget with another set of QWidget on top (my overlays). Unfortunately this does not work because Qt does not allow widgets with transparent ...
I dont think QGraphicsVideoItem is good for this task. You can implement QAbstractVideoSurface that receives QVideoFrames and feeds them to QWidget that converts them to QImage, scales and draws them in paintEvent. Since you control paintEvent you can draw anything over your video, and get "fill viewport" feature for f...
71,777,564
71,778,006
Can't use std::format in c++20
I've been trying to use the std::format function included in C++20. As far as I can tell, clang 14 is supposed to support this feature, but for some reason I am receiving the following error: no member named 'format' in namespace 'std'. According to cppreference's compiler support chart, text formatting should be suppo...
According to this, text formatting should be supported by clang If you look closely, there is an asterisk in that cell: 14* Below, it says: * - hover over the version number to see notes And when you hover, it says: The paper is implemented but still marked as an incomplete feature. Not yet implemented LWG-iss...
71,777,900
71,780,892
c++ String from file to vector - more elegant way
I write a code in which I want to pass several strings from text file to string vector. Currently I do this that way: using namespace std; int main() { string list_name="LIST"; ifstream REF; REF.open(list_name.c_str()); vector<string> titles; for(auto i=0;;i++) { REF>>list_name; if(list_name=="-1"){break;} ...
The other answers are maybe too complicated or too complex. Let me first do a small review of your code. Please see my comments within the code: #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; // You should not open the full std namespace. Better to use full qualifiacat...
71,778,106
71,778,987
Specialization of non-type template argument
I have a struct template <auto& t> struct Foo { using Type = decltype(t); }; I also have a template class: template <typename T> class MyClass {}; I want to create a specialization for this struct for any arg of type MyClass: template <typename T> struct Foo <MyClass<T>& t> { using Type = int; }; I'd Like to be ...
Your code is near by the needed solution. The specialization simply needs a bit different syntax: template <typename T> class MyClass {}; template < auto value > struct Foo { void Check() { std::cout << "Default" << std::endl; } }; template <typename T, MyClass<T> value> struct Foo<value> { void Check() { s...
71,778,162
71,778,402
How to forward declare a template function in global or namespace with default argument?
template<typename T> void foo (T t, int i = 0); // declaration int main () { foo(1, 0); } // error!! template<typename T> void foo (T t, int i = 0) {} // definition Above is a minimal reproducible example for a larger problem, where many header files are involved. Attempting to forward declare with default paramete...
A default argument, like int i = 0, is seen as a definition. Repeating it is therefore an ODR-violation. Don't know exactly why, except that the standard explicitly says so Each of the following is termed a definable item: [...] (1.6) a default argument for a parameter (for a function in a given > scope) [...] No t...
71,778,286
71,778,639
try catch mechanism in c++
I honestly searched and tried to implement try - catch mechanism in c++, but I failed: I don't have enough experience yet. In android there is a convenient way to catch general exceptions, whether it's a division by zero or an array out-of-bounds, like int res; int a=1; int b=0; try{res...
C++ has a diverse range of error handling for different problems. Division by zero and many other errors (null pointer access, integer overflow, array-out-of-bounds) do not cause an exception that you can catch. You could use tools such as clang's undefined behavior sanitizer to detect some of them, but that requires s...
71,778,543
71,778,909
How can I sort function using priority queue in C++/C?
I want to array "functions" by priority E.g SetNumber1 is first SetNumber2 is second ReadNumbers is last //////////////// priority_queue < ??? > Q Q.push(ReadNumbers()); Q.push(SetNumber2()); Q.push(SetNumber1()); i want to exec in order to SetNumber1() , SetNumber2(), ReadNumbers() Thanks. and sorry about my english ...
std::priority_queue works with a compare function which can't work with the given functions. You need to define your own priorities as an enum and then you can put the pair of the prio and function in an std::multimap so all functions can be called according to their prio. You can put the pair also in a prio-q but then...
71,778,599
71,779,291
Some (but not all) targets in this export set were already defined
I create a CMakeLists.txt and the content is as followed cmake_minimum_required (VERSION 3.8) project(CTP_dll) add_library(CTPdll SHARED CTPdll.cpp) add_executable(CTPTest CTPTest.cpp) target_link_libraries(CTPTest CTPdll) find_package(OpenCV REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) target_link_libraries...
Seems you are encountering vcpkg issue #15502. There is a pull request with a fix available, which apparently was not merged yet.
71,779,078
71,779,123
How would I write this python code in c++
I'm doing a leetcode problem about squares intersecting. Here's how I was able to figure it out in Python, but how would I write it in C++? def intersections(rects): events = [] for A in rects: events.append((A.x, 'insert', A.y, A.Y)) events.append((A.X, 'remove', A.y, A.Y)) intersections = ...
I haven't touched C++ in some time... So this is merely an attempt to start with. #include <algorithm> #include <iostream> #include <vector> using namespace std; struct Rect { int x, X, y, Y; }; int intersections(vector<Rect> &rects) { vector<pair<int, pair<char, pair<int, int>>>> events; for (auto &A : ...
71,779,537
71,792,151
how to implement duplex printing via GDI Print API
I need to implement duplex printing on a printer. I set the DEVMODE structure in the printer driver with the dmDuplex parameter int dvmSize=DocumentProperties(GetForegroundWindow(),hPrinter,(LPWSTR)(printerName.c_str()),NULL,NULL,0); DEVMODE *dvmSettings = (DEVMODE*) GlobalAlloc(GPTR,dvmSize); DEVMODE *dvMode = (DEVMOD...
As far as I'm concerned, it will work. You could call the CreateDC or PrintDlgEx function to get the printer DC. If your application calls the CreateDC function, it must supply a driver and port name. To retrieve these names, call the GetPrinter or EnumPrinters function. If your application calls the PrintDlgEx functio...
71,779,939
71,780,861
C++: How to use different dynamic template in map
my header code: template <typename T> class A { } template<> class A<short>; template<> class A<float>; in my cpp, i want to use a map to contain different type a, like following code: class B { map<int, A*> a; /* how to declare a */ public: AddA(int key, int type) { ...
If you really need to have multiple types in a single map, you can use a map of std::variant. But as already mentioned in the comments, this might be a design problem. But if you need it, you can proceed with the std::map< int, std::variant<>>. Later on, if you want to access the stored element, you have to call std::v...
71,779,977
71,782,705
Contradicting definition of implicit this parameter in the standard
I am learning about classes in C++. I came across the following statement from the standard: During overload resolution, non-static cv-qualified member function of class X is treated as a function that takes an implicit parameter of type lvalue reference to cv-qualified X if it has no ref-qualifiers or if it has the l...
The implicit object parameter is not the same as this. this is a pointer referring to the object on which the member function was called while the implicit object parameter is the imagined first parameter of the member function, which is passed the object expression in the member function call (whats left of . in the m...
71,780,299
73,680,598
CppUMock for mocking open() function
Is it possible to mock the C open() function using CppUTest ? #include "CppUTest/CommandLineTestRunner.h" #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" #include <fcntl.h> extern "C" { #include "drivers/my_driver.h" } TEST_GROUP(Driver) { void teardown() { mock().clear(); } }; ...
Use compiler option --wrap to handle this scenario. For detail refer below link : How to wrap functions with the `--wrap` option correctly?
71,780,316
71,781,163
How to align text and images like the sample image provided in Qt?
I want to display the images and Texts in the PDF file generated in the manner shown in the image provided and I don't know how to go on about it. At first I tried this: for(int i=0; i<COVDATA.COV_ComponentName.size(); i++){ //------------------------------------------------------------------------------------ ...
Your coordinate computation is not working as intended. I've put together a short example illustrating how you can go about implementing a layout as you wish: QStringList Text; Text << "String 1" << "String 2" << "String 3" << "String 4" << "String 5" << "String 6" << "String 7" << "String 8"; int TextHeight = painter....
71,781,785
71,781,932
Enforce class template specializations to provide one or more methods
I'm using a "traits" pattern where I have a base case expressed as a class template template <class> struct DoCache { constexpr static bool value = false; }; and I expect users to specialize for their types: template <> struct DoCache<MyType> { constexpr static bool value = true; static void write2Cache(MyType ...
C++17: Curiously recurring template pattern It seems like a suitable use case for CRTP: template<typename T> struct DoCache { void write2Cache() { static_cast<T*>(this)->write2Cache(); } // ... }; template<typename T> void write2Cache(DoCache<T>& t) { t.write2Cache(); } struct MyType : DoCach...
71,781,811
71,822,120
How can I build amazon kinesis webrtc sdk in C on windows - missing header files
I'm trying to build WebRTC SDK in C for Embedded Devices on windows. I have configured using CMake with -DBUILD_DEPENDENCIES=0, and have installed various libraries manually such as pthreads, usrsctp, libssl etc. I don't have gstreamer installed, so I do get a message about not being able to configure one of the exampl...
Yes you will need to build the other KVS libraries that the WebRTC implementation depends on. You can find them in the .gitmodules of the project. You can also see how they are built/configured in the CMakeLists.txt
71,781,890
71,977,246
Console outputs gibberish code after re-redirecting stdout to CON
When I use C++ to invoke Python program output (By system command with parameters), it outputs gibberish code at the end of line. After that, I couldn't input any character (Include Backspace and Enter), it displays a hollow square. Console screenshot: Whole function code: (Uses file process) freopen("WCH_SYSTEM.tmp",...
After repeated inspection, I have found that freopen() can cause these encoding problems. You can redirect the output of the function (NOT FREOPEN!!!) to a temporarily file like this. DO NOT USE FREOPEN LIKE THIS! THIS MAY CAUSE UNEXPECTED BEHAVIOR. freopen("CON", mode, handle); This is correct: system(("TRANS -i \"" ...
71,782,254
71,782,608
c++ completely generic event dispatcher
I try again to explain better again what I would achieve. I would like make a thing like this (inspired to Unity's UnityEvent): Public "variables" declared in some classes: GameEvent<> OnEnemySpawn = GameEvent<>(); GameEvent<string> OnPlayerSpawn = GameEvent<string>(); GameEvent<string, float> OnEnemyDie = GameEvent<s...
What is wrong with the obvious way? void Notify(T... args) { // note: no need to write the type if it's quite long // note: & means the std::function isn't copied for (auto const& subscriber : _subscribers) { subscriber(args...); } }
71,782,644
71,787,455
Open GL Depth and Alpha issues
I am rendering two triangles in GL. The bottom two vertices of each have a set alpha value to make them transparent. I am using Depth testing and Alpha blending defined by the following calls glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LEQUAL); glDepthRange(0.0f, 1.0f); glEnable(GL_SAMPLE_ALPHA_TO_COV...
I did two things to solve this: Disable writing to depth buffer and draw triangles based on distance from the camera. Use glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); to fix blending issues. Below is the final result
71,782,754
71,784,214
How to create an interface to allow for the construction of different nested derived classes in C++?
My goal is to construct a derived classes nested class from the interface. However the nested classes don't have the same constructors. The question is how can I make an interface to create two different "sub-nested" classes. Constraints: Cannot use Heap Nested Classes' Methods cannot be called before it is constructe...
Maybe you could make the object static so it's declared in RAM at compile time (and not heap or stack).
71,783,377
71,783,639
What's the purpose of const swap() function?
While implementing a custom tuple (here), I found there is a wired swap() function that takes const parameters (cppreference): template< class... Types > constexpr void swap( const std::tuple<Types...>& lhs, const std::tuple<Types...>& rhs ) noexcept(/* see below */); and a const-qualified swap() ...
This was introduced in the "zip" proposal P2321 originally described in "A Plan for C++23 Ranges" P2214. P2321 swap for const tuple and const pair. Once tuples of references are made const-assignable, the default std::swap can be called for const tuples of references. However, that triple-move swap does the wrong thi...
71,783,833
71,784,130
QRegularExpression find and capture all quoted and non-quoated parts in string
I am fairly new to using regexes. I got a string which can contain quoted and not quoted substrings. Here are examples of how they could look: "path/to/program.exe" -a -b -c "path/to/program.exe" -a -b -c path/to/program.exe "-a" "-b" "-c" path/to/program.exe "-a" -b -c My regex looks like this: (("[^"]*")|([^"\t ]+))...
You assume that the groups you need to get value from will change their IDs with each new match, while, in fact, all the groups IDs are set in the pattern itself. I suggest removing all groups and just extract the whole match value: QString toMatch = R"del( "path/to/program.exe" -a -b -c)del"; qDebug() << "String t...
71,784,137
71,784,178
std::deque is contiguous memory container or not?
std::deque is contiguous memory container or not ? The famous book Effective STL by Scott Meyers says like below Contiguous-memory containers (also known as array-based containers] store their elements in one or more (dynamically allocated) chunks of memory, each chunk holding more than one container element. If a new...
There is no conflict between the two quotes. Scott uses the term "contiguous container" in a sense a little wider than you might have seen it used elsewhere. Scott writes (emphasize mine): Contiguous-memory containers (also known as array-based containers] store their elements in one or more (dynamically allocated) ch...
71,784,144
71,784,346
glReadPixel return fault result
I want to do the 3D-picking on OpenGl by the way of frame pick. On this way I need to use glReadPixel to get some information of the pixels on the screen currently, so I test it on the following way but get the wrong result. First , I use Callback glfwSetCursorPosCallback(window, mouse_callback)and mouse_callback(GLF...
OpenGL uses coordinates where the origin (0, 0) is the bottom-left of the window, and +Y is up. You have to convert to OpenGL's coordinate system when reading, since the cursor events use (0, 0) as the top-left of the window, and +Y is down. void mouse_callback(GLFWwindow* window, double xpos, double ypos) { int wi...
71,784,326
71,785,079
Print recursive * pattern
I have trouble printing the * pattern. They should have 2 functions: printStars() and printLine(). printStars(int n), is used to print a line of n stars; the second one, printLines(int m), is to print m pairs of lines. I have completed print half top but I could not reverse the pattern of the second half. You can't add...
here is the small change you need: void printLines(int m){ if (m < 1) return; printStars(m); cout << "\n"; printLines(m-1); printStars(m); // just add these two lines to print line again after all internal ones are printed cout << "\n"; }
71,784,364
71,796,163
Qt 6.2.4 for QNX710 on Ubuntu 20.04 - Qt version is not properly installed
I tried to build Qt 6.2.4, installed via qt-unified-linux-x64-4.3.0-1-online.run on Ubuntu 20.04 LTS in a Virtual Box. I installed Qt 6.2.4 in ~/Qt6 for Desktop gcc 64-bit and in source code. QNX 7.1 is installed in ~/qnx710. I sourced qnxsdp-env.sh: $ . ~/qnx710/qnxsdp-env.sh I added Qt6.2.4, Ninja and CMake to PATH...
The Qt version was indeed not properly installed. qmake expects a specific directory for target libraries $ ~/Qt6/6.2.4/qnx/bin/qmake -v QMake version 3.1 Using Qt version 6.2.4 in /home/werner/qnx710/target/qnx7/home/werner/Qt6/6.2.4/qnx/lib So to fix QT Creator, I simply had to create a symbolic link: $ cd ~/qnx710/...
71,784,465
71,785,634
Run Eigen Parallel with OpenMPI
I am new to Eigen and is writing some simple code to test its performance. I am using a MacBook Pro with M1 Pro chip (I do not know whether the ARM architecture causes the problem). The code is a simple Laplace equation solver #include <iostream> #include "mpi.h" #include "Eigen/Dense" #include <chrono> using namespa...
You are confusing OpenMPI with OpenMP. The gcc flag -fopenmp enables OpenMP. It is one way to parallelize an application by using special #pragma omp statements in the code. The parallelization happens on a single CPU (or, to be precise, compute node, in case the compute node has multiple CPUs). This allows to employ ...
71,784,571
71,784,913
Getter returns a rvalue?
I know it's a bad attempt but why we cannot edit the private member via the getter? class A { int a = 2; public: int GetA1() { return a; } int& GetA2() { return a; } int* GetA3() { return &a; } }; int main() { A test; test.GetA1() = 4; test.GetA2() = 4; int b = test.GetA2(); ...
It seems that the value on member's address can be changed, but the address itself not. Indeed. More generally, it isn't possible to change the address where any object is stored. This applies to all objects. Does GetA3 returns a rvalue or an unmodifiable lvalue? GetA3() is an rvalue, more specifically it is a prva...
71,784,778
71,793,829
Why JNI GetByteArrayElements does not reserve pixel stride
I need to pass a YUV_420_8888 image from Android to C++ for processing. So, I take the image planes, convert them to ByteArray, then send them to C++ function. val yBuffer: ByteBuffer = image.planes[0].buffer val uBuffer: ByteBuffer = image.planes[1].buffer val vBuffer: ByteBuffer = image.planes[2].buffer v...
According to ByteBuffer documentation: https://developer.android.com/reference/kotlin/java/nio/ByteBuffer#get_2, get copies the bytes into destination array. In this case, yByteArray, uByteArray and vByteArray are copied from the buffers. This explains why the offset in pointers is not 1.
71,785,247
71,785,515
CUDA do deprecated functions still function in newer versions?
Does the function cudaGLRegisterBufferObject (deprecated after version 3.0) still work in newer versions (ie 6.X) ? (I know that cudaGraphicsGLRegisterBuffer exists, however I'm doing some work on an old colleague's project and I don't know if a bug is caused by this, or something completely different.) Thanks in advan...
It should still work as of CUDA 11.6.2 At the moment, it is documented here so it is still present/available and should be still usable. Deprecated means that it may be dropped in a future CUDA version. When it is dropped, it is no longer usable (meaning you won't be able to compile code that uses that API, in that fu...
71,785,396
71,785,452
Concepts: require a function on a type without default constructing that type
I need to require of some type A that there exists a function f(A, A::B). I'm testing that by calling f with instances of A and A::B. Is there a less ostentatious way to test against an instance of the dependent type without requiring default constructible? template <class Container> concept CanPutData = requires (Cont...
Same way you're already getting a Container without requiring that one to be default constructible: by just sticking it in the parameter list of the requires expression: template <class Container> concept CanPutData = requires (Container container, typename Container::data_type data) { put(data, container); };
71,785,710
71,785,832
Template class with dpointer
I am trying to use the dpointer pattern in a generic class that made use of template but I cant figure how to define it correctly. template <class TNode, class TLink> class Network { private: template<class TNode, class TLink> struct Impl<TNode,TLink>; std::unique_ptr<Impl<TNode,TLink>> d_ptr; //d_pointer...
The correct way to do this would be to use different names for the template parameters of the nested class template Impl from the names of the template parameters already used for the containing class template Network, as shown below: template <class TNode, class TLink> class Network { private: //-----------------v----...
71,785,894
71,845,139
GTest Automatic Mock Class
For some time my old project used gmock_gen.py to generate automatically mocked classes (this is an old project from http://code.google.com/p/cppclean/ that it seems inactive and it depends on python2 that we don't want) My question: Is there anything on gtest environment that does the same as gmock_gen.py and supports...
It seems that the conversion to python3 is very simple. You only need to do two things and only one is required (step 2.): you can use the python tool 2to3 to convert the code from python 2 code into python 3 code (optional) change only one line to prevent an exception on the execution of the scrip: gmock_gtest/gener...
71,786,247
71,786,348
Uncertainties about OOP and the struct Keyword
class NodeType { public: int info; NodeType* link; }; I came across this when learning about linked list, and as a beginner, at line 4, pointer link is an object of class NodeType, this interpretation is definitely wrong, so can somebody please explain what does this line mean? I don't recall learning thi...
Yes, the two snippets are the same. why is there a second struct keyword at line 4? It's called an elaborated type specifier (a type with struct prepended to it, or class/union/enum; the definition class NodeType {} doesn't count as one). It's useless here and can be removed. It's only useful when a struct is mention...
71,786,521
71,786,522
Can't open dsw file in Visual Studio C++ 6.0
When I try to "Open Workplace" of my project, visual studio does nothing, solution explorer is empty. Also when I try to open my project, I occasionally see this error:
The problem was that my dsp/dsw file endings were LF. You can check your file endings in your code editor or using this git command: git ls-files --eol After converting ds/dsp files to CRLF, I was able to open the project. You can convert file endings in Unix using this command: unix2dos YouFileName.dsw
71,786,975
71,787,018
How can I seamlessly and discretely communicate new URI launch parameters to a currently running application in Windows?
Case: Click a URL in the browser and a video game that is currently running on user's desktop can ingest that data and do something. I've been working on this for some time, but I don't know if I'm on the right path. What I currently have: A clickable URI in a webpage that can have different arguments for the client to...
The OS automatically creates a console for /SUBSYSTEM:CONSOLE apps. It doesn't automatically create a window for /SUBSYSTEM:WINDOWS. So use /SUBSYSTEM:WINDOWS. Then, create the named pipe before creating the main window. If the return code tells you a new pipe was created (use FILE_FLAG_FIRST_PIPE_INSTANCE), you're ...
71,787,017
71,787,173
std::unordered_multiset exception iterating bucket
My test case is the one shown below: std::size_t t(const int &i) { return i | 0b01010101010101010101010101010101; } int main() { std::unordered_multiset<int, decltype(&t)> um(100, t); um.insert(9872934); um.insert(9024582); um.insert(2589429); um.insert(2254009); um.insert(3254082); um.inse...
The argument to the begin(bucket) function is the bucket number not the key. You need use bucket to get the bucket number that corresponds to the key auto intf = um.bucket(t(9872934)); <<<==== for (auto cb = um.begin(intf), end = um.end(intf); cb != end; ++cb) { std::cout << *cb; }
71,787,025
71,787,745
Different order of adding same type objects causes an error
Could anyone explain why adding three objects like this a+(a+a) causes problems while a+a+a and (a+a)+a does not? The Foo class has one attribute num. Adding two Foo objects returns one with sum of their num values. Here is my code. main.cpp #include <iostream> #include "Foo.h" using namespace std; int main() { Fo...
The expression (a + a) yields a prvalue of type Foo. The only possible reference parameter types this kind of value can be assigned to are Foo&& or Foo const&. The reason why (a + a) + a (or the equivalent using no brackets) works is the fact that non-const functions can be invoked on prvalues. I recommend going with t...
71,787,027
71,787,351
Requirements on returned type that may have some member functions SFINAE'd away in the function's translation unit?
Refining from Why is the destructor implicitly called? My understanding of calling convention is that functions construct their result where the caller asked them to (or in a conventional place?). With that in mind, this surprises me: #include <memory> struct X; // Incomplete type. // Placement-new a null unique_ptr ...
In your specific case there is no way that the destructor may be invoked. However, the standard specifies the situations in which the destructor is potentially invoked in more general terms. If a destructor is potentially invoked it requires a definition (even if there is no path that could call it) and this will there...
71,787,182
71,787,570
Case of using OpenMP for multi-threading of a matrix factorization calculation of an existing serial code
I came across a code that uses a low-performance series for loop for calculating so-called "Crout factorization". If you need to know more I think the concept is similar to what is described here. At first glance the code is a for loop that can simply become parallel by an omp directive: SparseMtrx *Skyline :: factoriz...
The Crout factorization is one variant of Gaussian elimination. You can characterize such algorithms by 1. their end-product 2. how they go about it. The Crout factorization computes LU where the diagonal of U is identity. Other factorizations normalize the diagonal of L, or they compute LDU with both L,U are normalize...
71,787,222
71,791,371
Error with failing to load plugin in gazebo because of undefined symbol
When I run "roslaunch" there is the error: [Err] [Plugin.hh:178] Failed to load plugin libmodel_push.so: /Robosub_Simulation/devel/lib/libmodel_push.so: undefined symbol: _ZN9ModelPush14SetJointStatesERKN5boost10shared_ptrIKN11sensor_msgs11JointState_ISaIvEEEEE Can you guys please assist us with how to solve this error...
As @Tsyvarev recommended I put "ModelPush::" before the SetJointStates function declaration. So it looks like this below: void ModelPush::SetJointStates(const sensor_msgs::JointState::ConstPtr &_js) { static ros::Time startTime = ros::Time::now(); { std::cout<<"AYo"<<std::endl; } } This got rid of the error ...
71,787,300
71,787,493
variable declaration in while loop
using namespace std; class Counter { int val; public: Counter() { val = 0; } int Next() { return ++val; } }; int main() { Counter counter; while (int c = counter.Next() <= 5) { cout << c << endl; } } When run, the program prints out 1 5 times. Thus, .Next() is returning the exp...
The <= operator has a higher precedence than the = operator. So, with while (int c = counter.Next() <= 5) The compiler interprets it as: while (int c = (counter.Next() <= 5)) which assigns the result of the logical expression to c, which will be 1 while the expression holds true. Try this instead: int c; while ((c =...
71,787,305
71,795,546
Sorting a 2-d vector but getting an unexpected output
I am trying to sort a 2 D vector and I am getting the desired output for input 'n' less than 15 but above that it is not arranged in the order that I want. If all the first column values are 0 then the second column must have increasing ordered values. #include <bits/stdc++.h> using namespace std; bool sortcol(const ve...
As others have also noted in the comments, your sortcol() always returns false because v1[0] and v2[0] are always 0. Since the predicate sortcol() tells the sorting algorithm which elements are considered to be "smaller"/"less" than other elements, no element is considered smaller than another one. This implies that al...
71,787,514
71,787,515
How to use MPE for MPI c++ project?
MPE is very useful for visualizing MPI programs, but it only provides compiler wrappers for C and Fortran: mpecc and mpef77, respectively. How can I use it if my MPI project is written in C++ and is normally compiled with mpic++, not mpicc (and so it can't be compiled with mpecc)? How do I setup (1) the MPE library its...
The answer is actually quite simple, nonetheless I struggled with it for days. Steps shown below works with MPICH 3.3.2 on Linux (Ubuntu 18) run with WSL2 - some adjustments may be necessary in different evnironments. MPE library setup for c++ You setup the MPE library normally, the same way you would for a C project ...
71,788,085
71,804,305
CMake find_package for another library in same project
I want to make a builder project that checks out sub-modules and builds them as a group, and I would like to build them in a single pass. builder submod1 submod2 #depends on submod1 submod3 #depends on submod2 For testing I downloaded ZeroMQ and cppzmq as submodules and built both with the cppzmq/demo to confi...
find_package() doesn't actually look at the global targets list, it has its own targets list that only prevents other find calls from refetching instead of creating an alias target call find_package_handle_standard_args in a Find<>.cmake module for each class so for this case a Findcppzmq.cmake include(FindPackageHandl...
71,788,243
71,788,388
How to specialize a type trait using concepts?
I am trying to use C++ concepts in order to write a type trait that will produce a different type depending on whether its template argument is a fundamental type or not: template<typename T> concept fundamental = std::is_fundamental_v<T>; template<typename T> concept non_fundamental = !std::is_fundamental_v<T>; The ...
Apparently the syntax is slightly different from what I had in mind. Here is a working solution: template<typename T> struct SomeTypeTrait {}; template<fundamental T> struct SomeTypeTrait<T> // note the extra <T> { using type = T; }; template<non_fundamental T> struct SomeTypeTrait<T> // note the extra <T> { ...
71,788,310
71,789,025
pass a list as an argument from python to C++: Segmentation fault (core dumped) when running the second time
I am coding a self-defined python module embedding with C++. test.py import my_module column_names = ['ukey', 'OrderRef', 'orderSize'] print(my_module.my_func(column_names)) my_module.cpp (partial) static PyObject * my_func(PyObject *self, PyObject *args) { Py_Initialize(); if(!Py_IsInitialized()) { std::cout<...
Py_DECREF of the input list in C++ code is not needed. PyArg_ParseTuple is just do parse only, just like some typecasting, not creating a new Python object. Py_DECREF(_list); After that, the column_names in python will become []. Then the my_func is called again, the input list is an empty list in the 2nd call. So c_c...
71,788,620
71,789,084
Translating GlobalPlatform from C to Delphi - Access violation errors
I want to use the GlobalPlatform.dll from kaoh Karsten Ohme in Delphi. So i tried to translate the headers so i can use the GlobalPlatform.dll in Delphi. The first i translated was Connection.h, i uploaded it on pastebin here. The second i translated was Security.h i uploaded it on pastebin here. First i establish a co...
In the 1st record you translated, OPGP_ERROR_STATUS, the errorMessage field is declared in the C code as: TCHAR errorMessage[ERROR_MESSAGE_LENGTH+1]; where ERROR_MESSAGE_LENGTH is defined as 256, thus this array has 257 chars max. But your translation: errorMessage : array [0..ERROR_MESSAGE_LENGTH + 1] of Char; has 2...
71,788,664
71,791,393
C++/C Importing Third Party Library to CMake
Hi I was wondering if anyone here could help me identify what I'm doing wrong while trying to add a library to my CMake project: So originally I built the library https://github.com/recp/cglm in the command line with cmake.Heres what I did I created a build folder in the desktop(mkdir build) I changed directory to ...
In general you have two approaches - Install cglm library & then make use of it in your project Build cglm as part of your project I have used both approaches & found the latter to be far better. Especially for smaller projects for these reasons - Better intellisense, you can jump to 3rd party code and even edit Eas...
71,788,764
71,788,925
Confused with references on pointers in C++
The task is to calculate the output of the following source code without a computer, which I would say is "123 234 678 678" because ref1 is a reference on the value of ptr and in the moment where the address of val2 is assigned to this pointer, then shouldn't ref1 as well refer to its value? int main() { int* ptr =...
After this declarations int& ref1 = *ptr; int& ref2 = val2; ref1 refers to val1 and ref2 refers to val2. After the declarations the references can not be changed to refer to other variables. Pay attention to that the reference ref1 does not refer to the pointer ptr. It refers the variable val1 due to dereferencing the...
71,788,928
71,789,798
How can I *directly* append to a QVariantList, stored in a QVariantMap?
I have a collection of QVariantMaps which contains QVariantLists in SOME of their entries. I need to append to the lists. These lists can grow rather large, and I have to do this for many of them, many times per second, basically the whole time the program is running. So, efficiency is pretty important here.. I'm not...
Got it! I was on the right track, but had to perform a deep dive into the Qt source to figure out how to finish this off. I now have another macro to call upon, which takes me the rest of the way: #define varPtrToListPtr( varPtr, ptrName ) \ QVariantList *ptrName( varPtr->type() == QVariant::List ? \ stati...
71,788,946
71,789,072
How to implement `ssize_t` in c++ complier correctly?
I am currently learning C++ and I saw there was a line of codes writing on the textbook: ssize_t num = index; // index could be -1 in the example of my textbook` The num is a variable to contain the index return from a traversing. However,after I copy this code to my C++ compiler, it says it can not find the definitio...
ssize_t can (and cannot) be used in C++ just as much as it can (and cannot) be used in C. There is no fundamental type by such name in either language, and there is no ssize_t type in the ISO C standard library, nor is there a std::ssize_t in the C++ standard library. ssize_t is defined in the POSIX standard. If your p...
71,789,005
71,789,258
Template class implementation has compilation issues
I am creating an object using static member function of a class. and then calling a function inside. int main(){ int a = 49; auto foo = Foo::createFoo(a); foo->study(); } Implementation for this example lets have study() display a value. Structure wise I do have constraints to have the below interface and then ...
As I wrote in the comment: Do not implement createFoo function inside the class declaration. #include <iostream> class I_Foo { public: virtual void study(void) = 0; }; class Foo : public I_Foo { public: // here just DECLARE the method... static Foo *createFoo(int x_); }; /********/ /* SNIP */ /********/ // .....
71,789,386
71,790,087
Why my code in c++ is taking too long to execute?
When I click to compile and run my code in c++, using dev c++, the code takes a while to run in the console, even though it's something very basic. The console screen opens and goes black, with the cursor blinking, the program only starts after a few seconds. How can I solve this problem? Can someone help me, please? #...
Got a similar issue some years ago at work, with the imposed antivirus. All compiled executables, even the smaller one, took several seconds to really be launched. We were forced to request some special rights to IT in order to be able to exclude from scanning our development folders. It solved the problem instantly. Y...
71,789,519
71,789,695
Unpack pointer to call object's method
If I have the following classes: class Shape { public: virtual float getArea(){} }; // A Rectangle is a Shape with a specific width and height class Rectangle : public Shape { // derived form Shape class private: float width; float height; public: Rectangle(float wid, float heigh) { width = wid; ...
Obviously, HolyBlackCat answered your question in his comment. But if you are interested in "why" - check out C++ Operator Precedence. You'd see that . -> Member access has higher priority than *a Indirection (dereference). So, unless parenthesis are used, you are trying to dereference a pointer shape with a mem...
71,790,744
71,790,825
Why this code snippet works? The parameter of the lambda should be a lvalue-reference, whereas `std::bind` pass a rvalue(i.e. `std::move(ptr)`) to it
Why does this code snippet work? #include <functional> #include <iostream> #include <memory> int main() { std::unique_ptr<int> ptr(new int(666)); std::bind([](std::unique_ptr<int> &ptr){std::cout << *ptr << std::endl;}, std::move(ptr))(); } You see the parameter of the lambda should be a lvalue-reference, wh...
std::bind() does not call the lambda, it returns a proxy that will call the lambda when the proxy is invoked later. So, just because you pass in an rvalue reference into std::bind() does not mean the proxy will pass an rvalue reference into the lambda. And in fact, if you think about it, the proxy can't do so anyway. ...
71,790,753
71,798,429
Drawing two triangles using index buffer
I am following Cherno's brilliant series on OpenGL, and I have encountered a problem. I have moved on from using a vertex buffer only, to now using a vertex buffer together with an index buffer. What I want to happen, is for my program to draw two triangles, using the given positions and indices, however when I run my ...
Unlike using Linux or Windows, a Compatibility profile OpenGL Context is not supported on a Mac. You must use a Core profile OpenGL Context. If you use a Core profile, you must create a Vertex Array Object because a core profile does not have a default Vertex Array Object. GLuint vao; glGenVertexArrays(1, &vao); glBind...
71,790,777
71,793,224
Fourth button Binary Conversion Not working
I'm going through the Inventor's Kit from Sparkfun, specifically around the Digital Trumpet. To expand on the project I'm adding a fourth button and trying to turn the buttons pressed into a binary number to give myself 16 notes from 4 buttons. Here's my code: using namespace std; //set the pins for the button and buz...
Here: toneTot |= 10; Your are not setting Bit 1, as you expected. 10d is simular to 0b00001010, so you are setting Bit3 and Bit 1. Switch it to: toneTot |= 0x02; Same think for the other Bit set in tonTot
71,790,794
71,791,206
What's the difference between an explicit call and an implicit call of the conversion function?
Consider this example: struct A{ template<class T> operator T(); // #1 }; struct B:A{ template<class U> operator U&&(); // #2 }; int main(){ B b; int a = b; // #3 b.operator int(); // #4 } According to [class.member.lookup] p7 If N is a non-dependent conversion-function-id, conversion funct...
Implementations just haven’t caught up to the new(ly clarified) rules, which had to be largely invented in 2020 since no published standard version has ever described lookup for conversion function templates in any sensible way.
71,791,129
71,791,199
Expression must have class type but it has type "*shape"
I am trying to create a vector as show below: std::vector<double> dimensions_data_vec{input_shape_pointer.get_dimensions()}; In this code, input_shape_pointer is a pointer to a shape such as a rectangle. A shape has dimensions associated with it, eg. length and width. I now have to create another, separate class which...
If input_shape_pointer is a pointer to a shape then use -> instead of .. For example, the expression input_shape_pointer.get_dimensions() should be replaced by: input_shape_pointer->get_dimensions() Note the use of -> instead of . in the above expression
71,791,358
71,804,945
Is there an easy way to tell which C++ classes are abstract from a shared object library?
I'm currently writing a library that has some abstract classes. In addition to checking that the library compiles, I'd like to make sure that all pure virtual methods have been defined in classes that are intended to be concrete. I had hoped that I could get this information from nm or objdump, but so far I haven't b...
As a programmer, I need to make sure that I have fully defined every class I expect to be instantiated. Only you can know which classes these are. if you have a list of such classes, you can generate a test program along the lines of: #include <assert.h> #include <mylib.h> int main() { assert(!std::is_abstract<Clas...
71,792,422
71,793,061
why the relative path is different when I use Cmake build and VS 2019 build?
I'm new in Cmake. And I try to use Cmake to construct my project. In my project, I need to load some resources in runtime. for instance: string inFileName = "../Resources/resource.txt"; // string inFileName = "../../Resources/resource.txt"; ifstream ifs; ifs.open(inFileName.c_str()); if (ifs) { .... } But when I use t...
When using relative paths to load files, the resolution of the final filename depends on the current working directory. The relative path is appended to that working directory. That current working directory is not necessarily the same as the path of your application; it will be the path of the surrounding environment ...
71,792,448
71,792,665
Why do C++ allocator requirements not require that construct() constructs an object of value_type?
I found this strange while I was reading this. It says value_type equals to T, but construct() constructs an object of type X, which has nothing to do with T. However, reference page of std::vector only says An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The t...
Note that a.construct(xp, args) is only optional. A std::vector merely needs allocate() to allocate memory and then it can use placement-new to construct objects in that memory. If the allocator has construct() then the vector can use it to create objects (also of type T) in memory previously obtained via allocate(). a...
71,793,094
71,793,895
Can't convert/cast between template types ( couldn’t deduce template parameter )
Whilst messing around with templates and static_assert, I came across the following problem ( Below is a shortened example the problem is the same ) template< size_t n > struct W { class X { public: /* breaks normal constructor template< size_t o > X( typename W<o>::X & ...
The underlying problem is, that in nested types the template parameter can not be deduced. You can work around the problem if you provide a helper variable ( N in my example ) and use a more general template for the converting operator. You may filter out other types as W<n>::X with SFINAE if needed. Here we go: templa...
71,793,245
71,793,321
looking for an std algorithm to replace a simple for-loop
Is there a standard algorithm in the library that does the job of the following for-loop? #include <iostream> #include <vector> #include <iterator> #include <algorithm> int main( ) { const char oldFillCharacter { '-' }; std::vector<char> vec( 10, oldFillCharacter ); // construct with 10 chars // modify so...
This loop will replace every occurrence of oldFillCharacter with newFillCharacter. If you don't want to do something more fancy std::replace looks good: std::replace(std::begin(vec), std::end(vec), oldFillCharacter, newFillCharacter); Or a bit simpler with std::ranges::replace: std::ranges::replace(vec, oldFillCharact...
71,793,510
71,798,273
Using CLion IDE, is there a way to measure performance and calculation cost of each line or part of the program while debugging?
I need to find which parts of the code are taking more CPU time and whether I can improve those parts. I can define a timer object in the code but the compilation of the code after each modification is taking too much time and I cannot continue this way. I do not use VB but I found some information on measuring and mon...
Take a look here: https://www.jetbrains.com/help/clion/cpu-profiler.html CLion has an integration for perf (on Linux) and DTrace (on MacOS). Windows unfortunately doesn't provide profiling support at the operating system level, so you'll have to install a third-party profiler and won't be able to use it from within CLi...
71,793,614
71,794,070
Printing value of private variables of a class in a loop using member functions
I'm building my first program in C++ and I'm stuck where I'm trying to print the value of fee multiple times using for loop after giving value once. By running the loop it is giving garbage value every time after giving right value at first time. I'm new to the class topic in C++. Please tell me how can I print the sam...
The problem is that you're calling the setfee member function only for the first object in the array stu. And since the array stu was default initialized meaning its elements were also default initialized, the data member fee of each of those elements inside stu has an indeterminate value. So, calling showfee on the el...
71,793,687
71,793,806
Use specialization from base class
I have a class that inherits from a base class. The derived class has a template method. The base class has a specialized version of this method: #include <iostream> class Base { public: static void print(int i) { std::cout << "Base::print\n"; } }; class Derived : public Base { public: static void print(b...
This might help: class Derived : public Base { public: using Base::print; //one of the many useful usages of the keyword 'using' //... }; See: Using-declaration in class definition
71,793,910
71,795,080
Access Java class object methos from JNI
I have an Android app in which I have implemented the connection with a WebSocket in the C++ code. Now I would like to invoke a method of an object initialized in the Java class, via C++ code with JNI. It's possible to do it? This is my Activity: public class MainActivity extends AppCompatActivity{ private MyCustomObj...
I tried to put the part of code for your use case. Pass the custom object during onCreate to JNI //MainActivity.java public class MainActivity extends AppCompatActivity { // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); } private M...
71,795,009
71,795,396
Use base class implementation when base is template type
I have a class that receives its base type as a template arg and I want my derived class to call a function, print. This function should use the derived implementation by default but if the base class has a print function it should use the base implementation. #include <iostream> class BaseWithPrint { public: st...
If you know that the base class will have some kind of print, then you can add using B::print to your derived class. If a perfect match isn't found in the derived, then it'll check the base. Demo To handle it for the case where there may be a base print, I think you need to resort to SFINAE. The best SFINAE approach is...
71,795,294
71,795,388
Why my custom constructor is not called when an object is passed as a parameter?
I have the following code: struct Entity { Entity() { std::cout << "[Entity] constructed\n"; } ~Entity() { std::cout << "[Entity] destructed\n"; } void Operation(void) { std::cout << "[Entity] operation\n"; } }; void funcCpy(Entity ent) { ent.Operation(); } int m...
https://en.cppreference.com/w/cpp/language/copy_constructor object as params will call copy constructor of class
71,795,380
71,796,588
count std::optional types in variadic template tuple
I've got a parameter pack saved as a tuple in some function traits struct. How can I find out, how many of those parameters are std::optional types? I tried to write a function to check each argument with a fold expression, but this doesn't work as I only pass a single template type which is the tuple itself. void foo1...
You can use template partial specialization to get element types of the tuple and reuse the fold-expression template<typename> struct optional_count_impl; template<typename... Ts> struct optional_count_impl<std::tuple<Ts...>> { constexpr static std::size_t count = (0 + ... + (is_optional<Ts>::value ? 1 : 0)); ...
71,795,509
71,795,648
Error writing Sec^2(x) -0.5 x in define function in C++
Okay I'm trying to make a root finder calculator and right now I was testing it out trigonometric functions. Now I'm getting errors whenever a sec is involved prompting either a "sec has not been defined" Here's what it looks like Can someone explain to me whats wrong and how can I write "Sec^2(x)-0.5"
C++ standard library doesn't provide secant function, you have to define it yourself. double sec(double x) { return 1 / cos(x); } Also, ^2 does not mean "square" in C++, it's "bitwise XOR". You need to use * or pow: sec(x) * sec(x) - 0.5; pow(sec(x), 2) - 0.5; And don't use macros, they are going to bite you. Fun...
71,795,750
71,795,802
how to brace initialize vector of custom class in C++?
Having this simple code: #include <iostream> #include <vector> #include <string> class Person{ public: Person(std::string const& name) : name(name) {} std::string const& getName() const { return name; } private: std::string name; }; int main(){ // std::vector<int> ar = {1,2,3}; std::vec...
You just need more braces: std::vector<Person> persons = { {"John"}, {"David"}, {"Peter"} };
71,795,886
71,796,501
C++ Detect private member of friend class with CRTP
I have a CRTP Base class (Bar) which is inherited by a unspecified class. This Derived class may or may not have specific member (internal_foo), and this specific member my or may not have another member (test()). In this scenario internal_foo will always be public, however test() is private, but declaring Bar as a fri...
Summary and the fix Looks like a GCC 11 bug and your second attempt should in fact work. However, I recommend rewriting action's definition in either of two ways so you don't even need the member detection idiom: // Way 1 template<class _T = T> decltype(std::declval<_T&>().internal_foo.test()) action() { static_cas...
71,796,015
71,796,104
Two versions of enable_if usage work differently
I cannot understand why do two versions of copy constructor work differently (because of enable_if). template <typename Type> struct Predicate : std::integral_constant<bool, true> { }; template <> struct Predicate<int> : std::integral_constant<bool, false> { }; template <typename FooType> struct Settings { Setting...
In the second example the template parameter OtherFooType appears only left to the scope resolution operator :: in the function parameter. Everything left of :: in a type specified by qualified name is a non-deduced context, meaning that the template argument for OtherFooType will not be deduced from the function param...
71,796,647
71,796,740
Why does std::unique_ptr<>.release() get evaluated before member function access which is in the lhs of assignment?
This results in a segmentation fault when accessing unique_ptr->get_id() as release() is run beforehand. Is the ordering not guaranteed here? #include <iostream> #include <memory> #include <unordered_map> class D { private: int id_; public: D(int id) : id_{id} { std::cout << "D::D\n"; } ~D() { ...
This is because of [expr.ass]/1 which states: [...] In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand. With respect to an indeterminately-sequenced f...
71,797,023
71,797,865
type deduction for std::function argument types with auto adds const
I have a struct with a method called call which has a const overload. The one and only argument is a std::function which either takes a int reference or a const int reference, depending on the overload. The genericCall method does exactly the same thing but uses a template parameter instead of a std::function as type. ...
The problem is that generic lambdas (auto param) are equivalent to a callable object whose operator() is templated. This means that the actual type of the lambda argument is not contained in the lambda, and only deduced when the lambda is invoked. However in your case, by having specific std::function arguments, you fo...
71,797,193
71,798,965
Upgrade OpenCV 4.5 - constants not declared
After upgrading from OpenCV 3.2 to 4.5 I get a couple of compile errors. A few constants seems to have changed names CV_ADAPTIVE_THRESH_GAUSSIAN_C CV_FILLED Error g++ -O3 -std=c++17 txtbin.cpp -o txtbin `pkg-config opencv4 --cflags --libs` In file included from txtbin.hpp:8, from txtbin.cpp:11: deskew...
It's a matter of versions. OpenCV started as a heap of C code. Those preprocessor #defines all started with CV_... as a scoping hack. OpenCV v2.0 introduced the C++ API. Constants now live in the cv namespace. The old #defines were kept in v2 and v3 so people could transition more easily. In OpenCV v4, all the old C AP...
71,797,216
71,797,386
C++ template meta-programming: find out if variadic type list contains value
I'm trying to write a function that evaluates to true if a parameter passed at run-time is contained in a list of ints set up at compile-time. I tried adapting the print example here: https://www.geeksforgeeks.org/variadic-function-templates-c/#:~:text=Variadic%20templates%20are%20class%20or,help%20to%20overcome%20this...
Your problem is that the recursive call is Contains<is...>(j) this looks for template overloads of Contains. Your base case: bool Contains(int j) { return false; } is not a template. So the final call, when the pack is empty, of: Contains<>(j) cannot find the non-template. There are a few easy fixes. The best vers...
71,797,257
73,218,764
Android, how to securely store data from C++?
I need to securely store a piece of data (a single string) on Android from a pure C++ implementation. AFAIK the way to do this is using SharedPreferences and KeyStore. SharedPreferences takes care of simple storage and KeyStore of encrypting the data. This is done trivially in Java/Kotlin, but all the C++ answers seem ...
Short answer is: no, after much fumbling around it is not worth it to try to achieve certain things from C++ on android. The solution I ended up was calling java methods (bridged used JNI) from my C++ code.
71,797,491
71,797,842
c++ replace memset with std::fill
Hello I'm trying to port some old code to new standards. I have a std::complex<double> **data_2D; And I need to set a portion of that to zero. I used to do with: memset( &( data_2D[dims[0]-delta][0] ), 0, delta*dims[1]*sizeof( std::complex<double> ) ); which gives this warning: clearing an object of non-trivial type ...
You don't need to change anything about the pointers. If you use std::fill_n you only need to be careful of the arguments being in a different order and that the number of elements, not the number of bytes, is expected: std::fill_n( &( data_2D[dims[0]-delta][0] ), delta*dims[1], 0 ); However, &...[0] has the same effe...