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,645,516
71,646,043
C++ std::fstream how to move to a certain line and column of a file
So I have been searching on how to move to a certain line and column in a file , but I can't seem to find an answer . I want something like this : std::fstream file("example.txt"); file.move_to( line number , column number );
The following function can do just you want: std::string GetLine(std::istream& fs, long long index) { std::string line; for (size_t i = 0; i <= index; i++) { std::getline(fs, line); } return line; } The above function gets the line at index (index == 0 - 1st line, index == 2 - 3rd line, etc...
71,646,113
71,648,684
C++ with OpenMP try to avoid the false sharing for tight looped array
I try to introduce OpenMP to my c++ code to improve the performance using a simple case as shown: #include <omp.h> #include <chrono> #include <iostream> #include <cmath> using std::cout; using std::endl; #define NUM 100000 int main() { double data[NUM] __attribute__ ((aligned (128)));; #ifdef _OPENMP ...
Since you're writing C++, use the C++ random number generator, which is threadsafe, unlike the C legacy one you're using. Also, you're not using your data array, so the compiler is actually at liberty to remove your loop completely. You should touch all your data once before you do the timed loop. That way you ensure ...
71,646,233
71,646,450
selecting a move-constructor in a lambda-captured object
As a test, a class has the copy-constructor defined and the move-constructor explicitly deleted so that an object cannot be move-constructed. struct foo { foo()=default; foo(const foo&) { std::cout << "foo copied\n"; } foo(foo&&)=delete; }; foo f; foo a = f; // ok foo b = move(f); // fails (expecte...
Question: why is the (deleted) foo move-constructor not selected (so that it fails to compile) ? Because the lambda's definition is defaulted and not explicitly deleted, therefore overload resolution is tuned to ignore it. [over.match.funcs.general] 8 A defaulted move special member function ([class.copy.ctor], [cla...
71,646,288
71,646,322
Null pointer check via "myPtr > 0"
In some legacy code I came across the following null pointer check. if( myPtr > 0 ) { ... } Are there any technical risks of checking for a null pointer via this if-check?
Ordered comparison between a pointer and an integer is ill-formed in C++ (even when the integer is a null pointer constant such as it is in this case). The risk is that compilers are allowed to, and do, refuse to compile such code. You can rewrite it as either of these: if(myPtr != nullptr) if(myPtr)
71,646,883
71,646,999
Why were parentheses disambiguated as a function declaration with std::istream_iterator?
auto queue = [](string str) { istringstream ss(str); //std::copy(std::istream_iterator<string>(ss), // std::istream_iterator<string>(), // std::ostream_iterator<string>(std::cout, " ")); //deque<string> q(std::istream_iterator<string>(ss), std::istream_iterator<string>{}); deq...
This line deque<string> q(std::istream_iterator<string>(ss), std::istream_iterator<string>()); is a function declaration with the return type deque<string> and two parameters of the type std::istream_iterator<string>. The first parameter has the name ss and the second parameter is unnamed. To make th...
71,647,043
71,650,683
Wrong value for the last element of the array c++
I am trying to make an array (in this case int b[]) that stores all numbers that are larger than their neighbor, int a[10] are all the elements. I'm getting everything put out correctly only the last element is some random large number do you guys have any ideas? Concole everything is alright except the #include <iost...
In your code when you get the number of inputs the array indexes will be from 0 to n-1 so the last index is n-1 but if you look at this if statement: if (a[n] > a[n - 1] && i == n - 1) { swap(a[n], b[c]); c++; } you have used a[n] as the last array index and because a[n] was...
71,647,356
71,647,864
How to implement zero-overhead Inversion of Control
Almost every OOP programmer has been exposed to the concept of Inversion of control. In C++, we can implement that principle with dynamic callbacks (i.e. functors such as lambdas and function pointers). But if we know at compile time what procedure we are to inject into the driver, theoretically I believe that there is...
"Zero Overhead" & "But if we know at compile time what procedure we are to inject into the driver, " is possible. You can use a template class to pass the functions to call like that: struct SomeInjects { static void AtInit() { std::cout << "AtInit from SomeInjects" << std::endl; } static void AtHandleInput() {...
71,647,793
71,667,289
Eigen static lib aligned_free "double free or corruption"
This is a continuation of an earlier post. But this time with a hopefully better example. This simple test crashes when setting a vector. I am using Ubuntu 20.04, gcc 9.3.0, c++17, eigen 3.3.7 main.cpp #include <iostream> #include <memory> #include "C.h" using namespace std; class B { public: C c; B() { ...
In case you compiled the library and the main executable with mismatching architecture flags (-m... flags for gcc), you can observe the crash. For example, when I compile the library with avx enabled (-mavx) and the main executable without avx, or vice versa, it crashes. The crash also occurs in Eigen 3.4.0. Moreover, ...
71,647,916
71,648,015
Does “M&M rule” applies to std::atomic data-member?
"Mutable is used to specify that the member does not affect the externally visible state of the class (as often used for mutexes, memo caches, lazy evaluation, and access instrumentation)." [Reference: cv (const and volatile) type qualifiers, mutable specifier] This sentence made me wonder: "Guideline: Remember the “M&...
You got it partly backwards. The article does not suggest to make all atomic members mutable. Instead it says: (1) For a member variable, mutable implies mutex (or equivalent): A mutable member variable is presumed to be a mutable shared variable and so must be synchronized internally—protected with a mutex, made atom...
71,647,993
71,648,455
Why does malloc produce seg fault when accessing a member reference from C++ struct?
Consider the following code example: #include <iostream> struct Foo { int x = 2; int &rx = x; }; int main() { Foo *f1 = new Foo[4]; std::cout<< f1[0].rx <<std::endl; //ok Foo *f2 = (Foo*) malloc (4 * sizeof(Foo)); std::cout<< f2[0].rx <<std::endl; //memory leak free(f2); delete...
The reason of the SEGV is because the new operator calls the class default constructor, it is where the initialization of the non-static data members is done, in this case setting x to 2 and rx to x. When you allocate the memory with malloc the default constructor is not called. So the SEGV rises because rx is never se...
71,648,068
71,648,259
Is there a C++ smart pointer that could wrap up an object to make it thread safe?
I wanted to ask if there is a smart pointer that could take in any class in its template and then any operations done with such pointer would result in a thread-safe operation. Basically an idea would be that such pointer would automatically hold an internal lock during a scope and release it when the pointer goes out ...
if there is a smart pointer that could take in any class in its template and then any operations done with such pointer would result in a thread-safe operation. No, there is no such smart pointer in the C++ standard.
71,648,632
71,648,725
Iterator becomes nvalid
ALL, std::vector<string>::iterator it; string orig; bool found = false; for( it = vec.begin(); it < vec.end() && !found; it++ ) { if( ... ) { found = true; orig = (*it); } } After I get out of the loop the iterator become invalid even if I have found = true. How do I keep the iterator? I ne...
You could decrement it in the case you found it, to undo the final it++ that you don't want. if (found) it--; Or you could use std::find_if, where ... uses value instead of *it. auto it = std::find_if(vec.begin(), vec.end(), [](std::string & value) ( return value.find("abc"); }); auto found = it != vec.end(); auto ori...
71,648,813
71,659,387
How to set a text filter for boost log?
Starting from a logging set-up with a single logging file, a second logging file should be added containing only the lines with a specific text in the message. Example: In the single logging file: "user a logged in" "user b logged in" "user a logged out" In the second logging file only the messages of user b should b...
You cannot apply filters to log record message text because message text is composed after the filtering is done. This is intentional, as this allows to avoid composing the text if the log record is to be discarded anyway. If you want to filter log records pertaining to a specific user, the way to do this is to use att...
71,648,817
71,649,016
How to call libjpeg API in an erroneous way?
I want to test my error handling code when using the libjpeg but I cannot find a suitable call which to produce an error. If I simply pass a nullptr to some of the calls expecting a pointer to a structure then the library just crashes. I want to find a statement that calls the set in the jpeg_error_mgr's error_exit fun...
I managed to produce an error when calling libjpeg's functions on jpeg_compress_struct or jpeg_decompress_struct without first calling the jpeg_create_compress or jpeg_create_decompress functions respectively.
71,650,523
71,650,682
How to for loop with iterators if vector type is parent of two child types filling vector
I have this problem: this is my loop for previously used child type std::vector<Coin>::iterator coin; for (coin = coinVec.begin(); coin != coinVec.end(); ++coin) { sf::FloatRect coinBounds = coin->getGlobalBounds(); if (viewBox.intersects(coinBounds)) { if (playerBounds.intersects(coinBounds)) ...
I find out that my code is so universal, that I dont need to separate vector elements at all. My solution here: std::vector<Collectables>::iterator collect; for (collect = collectVec.begin(); collect != collectVec.end(); ++collect) { sf::FloatRect collectBounds = collect->getGlobalBounds(); if (viewBox.inter...
71,650,689
71,650,809
The initialization of ListNode
I have a question about the initialization of ListNode, if I just announce a ListNode pointer, why can't I assign its next value like showed in the code. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; ListNode* tmp; tmp->next = nullptr;// This is wrong, why is t...
A pointer is a box that can hold the address of an object ListNode* tmp; tmp->next = nullptr;// This is wrong, why is that? Here you created the box (tmp) but did not put the address of an object in it. The second line says - "at offset 4 from the address stored in tmp please write 0", well there is no valid address...
71,650,782
71,650,907
When using C++ pointer -> is there implicit Data type conversion
I am trying to debug someone else's code. There is a struct with elements of various size including a member defined as uint16_t attempts elsewhere this element is accessed thus int x = handle->attempts; int in my system is 32 bits Is it safe to assume that 2 bytes are loaded from the position pointed to in the struct ...
int x = handle->attempts; is a declaration with an initialization. In this declaration, handle->attempts is an initializer, per the grammar in C 2018 6.7 1. An initializer is an assignment-expression, per C 2018 6.7.9 1, and so rules for expression evaluation will be used. The expression handle->attempts designates the...
71,651,028
71,651,491
Accessing private member function via Lambda
In a project, I have a C-API which uses C-style function pointers as callbacks. In one of those callbacks, I need to access a private function of an object Foo. Note that the API-call is done within a function of my class. Because of not shown code, I have a handle to my object as a void* accessible to me. Things aside...
Your code is working because Standard allows it. So first we have this (C++20 [expr.prim.lambda.closure]p2): The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression. <...> And in your example we have a block scope so in the end we hav...
71,651,184
71,652,699
C++ Return reference to vector of non-copy objects
I have class A with disabled copy semantics and class B which contains vector of A's. How can I write a member function of B that returns reference to the vector of A's?. For those knowing Rust here is what I am trying to do (expressed in the Rust language): struct A {/* ... */} struct B { data: Vec<A>, } impl B ...
As @molbdnilo stated my error was that I used auto data = b.data(); instead of auto& data = b.data();. Therefore following example is working and shows how to do what I asked: #include<vector> class A { public: A(const A&) = delete; A(A&&) = default; A& operator=(const A&) = delete; A& operator=(A&&) = ...
71,651,252
71,652,780
How to pass an HWND as a GLFWwindow*?
I have an HWND that I have been using as the target of OpenGL draw operations, and it is necessary that it be an HWND and not a GLFWwindow for other utilities of the application I'm making. The problem is, I need to load and use shaders on textures that I am rendering text to with FreeType. Unfortunately functions like...
"When in Rome"... Just leave your OpenGL window as GLFWwindow. When (if?) you really need HWND, use glfwGetWin32Window
71,651,504
71,651,639
dereferencing a pointer to set a value vs. assigning an address to the pointer?
Could someone explain the difference between the following two snippets of code? In the function below, *frame_id maybe a nullptr, it's basically the output parameter in the function. bool LRUReplacer::Victim(frame_id_t *frame_id) { long oldest_ts = std::numeric_limits<long>::max(); for (auto & it : this->LRUCache)...
In the first loop, if it.ts < oldest_ts you will assign the value of it.frame_id to the frame_id_t to which frame_id points. After the loop is done, the frame_id_t instance (*frame_id) will hold the last value that was assigned to it. In the second loop, you will instead assign the address of it.frame_id to the frame_i...
71,652,019
72,004,960
Auto-filling the HTML input field with a C++ QString value
I am finding the 'Sign in' text on the QWebEnginePage and then auto filling in the emailId in the input field if the correct page is displayed. The value of emailId is basically a QString. QString emailId = "abc@xyz.com"; What I have uptil now is the following, when the correct page is loaded, the input field is trace...
According to @eyllanesc's comment the following worked for me: QString code = QString("document.querySelectorAll('input')[0].value = '%1'").arg(emailId);
71,652,143
71,652,450
do/while loop with cin.getline parsing to string doesn't compare values to break it
So I have this type of "menu" in a do/while loop do { cout << "Press 0 to export IDs, exit to exit, or any key to continue to menu:\n"; cin.getline(choice, sizeof(choice)); if (strcmp(choice, "0") == 0) { planesManager.exportIds(idsArray, arrSize); cout << "Would you ...
You are using the same choice buffer to manage both loops. The outer loop's while check is not reached until the inner loop is finished first, and the inner loop only breaks when choice is "back". So, by the time the outer loop's while check is reached, choice will never be "exit". Try this instead: do { cout << "P...
71,652,187
71,652,691
Can't understand the requirement of the problem. (ProjectEuler problem: 11)
I am trying to solve this problem: https://projecteuler.net/problem=11 However, this part confuses me: What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid? what does in the same direction and up, down, left, right or diagonally mean? Is ...
A direction in the context of a grid is the geometrical space whose all points are on the same line. If we take a point, then we can cross it with 4 different lines: \ | / \ | / \ | / \|/ ----*---- /|\ / | \ / | \ / | \ So, how could we define these directions? There is a very simple way to do ...
71,652,425
72,105,759
How to access the files in the res folder in the imgui conan package?
I am using conan to handle dependencies, for those of you familiar with imgui, it provides a series of backends you can include. When you look at the conan package these are found in the res folder. I need to tell meson to include files in that directory, how do I instruct meson how to find these files?
I am new to conan so i dont know if there is a better solution, but i have the following in my conanfile.txt [imports] res, *glfw.* -> . which puts a bindings folder with the header and the source file in the build directory then i use them in my CMakeLists.txt with "${CMAKE_CURRENT_BINARY_DIR}/bindings/imgui_impl_glf...
71,652,807
71,653,176
Woes with std::shared_ptr<T>.use_counter()
ERROR: type should be string, got "https://en.cppreference.com/w/cpp/memory/shared_ptr/use_count states:\n\nIn multithreaded environment, the value returned by use_count is approximate (typical implementations use a memory_order_relaxed load)\n\nBut does this mean that use_count() is totally useless in a multi-threaded environment?\nConsider the following example, where the Circular class implements a circular buffer of std::shared_ptr<int>.\nOne method is supplied to users - get(), which checks whether the reference count of the next element in the std::array<std::shared_ptr<int>> is greater than 1 (which we don't want, since it means that it's being held by a user which previously called get()).\nIf it's <= 1, a copy of the std::shared_ptr<int> is returned to the user.\nIn this case, the users are two threads which do nothing at all except love to call get() on the circular buffer - that's their purpose in life.\nWhat happens in practice when I execute the program is that it runs for a few cycles (tested by adding a counter to the circular buffer class), after which it throws the exception, complaining that the reference counter for the next element is > 1.\nIs this a result of the statement that the value returned by use_count() is approximate in a multi-threaded environment?\nIs it possible to adjust the underlying mechanism to make it, uh, deterministic and behave as I would have liked it to behave?\nIf my thinking is correct - use_count() (or rather the real number of users) of the next element should never EVER increase above 1 when inside the get() function of Circular, since there are only two consumers, and every time a thread calls get(), it's already released its old (copied) std::shared_ptr<int> (which in turn means that the remaining std::shared_ptr<int> residing in Circular::ints_ should have a reference count of only 1).\n#include <mutex>\n#include <array>\n#include <memory>\n#include <exception>\n#include <thread>\n\nclass Circular {\n public:\n Circular() {\n for (auto& i : ints_) { i = std::make_shared<int>(0); }\n }\n\n std::shared_ptr<int> get() {\n std::lock_guard<std::mutex> lock_guard(guard_);\n index_ = index_ % 2; // Re-set the index pointer.\n\n if (ints_.at(index_).use_count() > 1) {\n // This shouldn't happen - right? (but it does)\n std::string excp = std::string(\"OOPSIE: \") + std::to_string(index_) + \" \" + std::to_string(ints_.at(index_).use_count());\n throw std::logic_error(excp);\n }\n\n return ints_.at(index_++);\n }\n\n private:\n std::mutex guard_;\n unsigned int index_{0};\n std::array<std::shared_ptr<int>, 2> ints_;\n};\n\nCircular circ;\nvoid func() {\n do {\n auto scoped_shared_int_pointer{circ.get()};\n }while(1);\n}\n\nint main() {\n std::thread t1(func), t2(func);\n\n t1.join(); t2.join();\n}\n\n"
use_count is for debugging only and shouldn't be used. If you want to know when nobody else has a reference to a pointer any more just let the shared pointer die and use a custom deleter to detect that and do whatever you need to do with the now unused pointer. This is an example of how you might implement this in your...
71,652,995
71,653,530
How to get each digit of a template integral type in its native base?
I am working on an implementation of Radix sort for arrays of integral types. Using the numeric_limits functions provided by the standard library, I am able to learn about the native base representation of any given integral type using numeric_limits::radix, and the maximum amount of digits in that base that the type c...
If you want to iterate through the digits of the number number expressed with radix radix, in order from least-to-greatest significant digits, then a loop like the following would work. This loop assumes that number is a type that supports division and modulus, and that these operations are purely integer operations (f...
71,653,344
71,671,281
How to overcome Stack size warning?
I would like to know the best practice concerning the following type of warning: ptxas warning : Stack size for entry function '_Z11cuda_kernelv' cannot be statically determined It appears adding the virtual keyword to the destructor of Internal, i.e. moving from __device__ ~Internal(); to __device__ virtual ~Internal...
The very short answer is that there is nothing you can do about this particular warning. In more detail: This warning is an assembler warning, not a compiler warning The NVIDIA toolchain relies on a lot of assembler level optimizations to produce performant SASS machine code that runs on the silicon. The NVIDIA compil...
71,654,148
71,669,096
Variadic template parameter pack expansion looses qualifier
Let's say I have a variadic function template taking a function pointer to a function with said variadic arguments. The following code does not compile under gcc (11.2), but compiles under clang and msvc (https://godbolt.org/z/TWbEKWb9f). #include <type_traits> void dummyFunc(const int); template<typename... Args> vo...
The cv-qualifier should always be dropped (both in determining the type of dummyFunc and when substituting the deduced argument into the callFunc signature), and I'm pretty sure all compilers agree on this. It's not really what the question is about. Let's change the example a bit: template <class... Args> struct S { ...
71,654,281
71,655,612
Can I set a default "Active Solution Platform" in Visual Studio?
The Question In Visual Studio, in the "Configuration Manager" under the Build tab, there is an option called the "Active Solution Platform." This causes problems with one of my commonly used libraries. Is there a way to set this to default to x64? Is there a way to have this setting set when I load a custom project tem...
Try to create the project in Visual Studio 2022. C++ uses x64 as Active solution platform by default in VS2022.
71,654,572
71,655,258
C++ class templates with multiple arguments
I am just learning how to use templates in c++, and I am struggling a bit. I have an example below, with comments at the points where I'm getting hung up. #include <iostream> using namespace std; template<int arrayOneSize, int arrayTwoSize> class myClass{ public: myClass(){ for(int i = 0; i < arrayOneSiz...
can't figure out how to define constructors or functions outside of class void myClass::someOtherFunction(){} The problem here is that there is no class called myClass. Instead, there are only classes called myClass<someNumber, anotherNumber>. So, in order to define someOtherFunction, it must be written something lik...
71,654,650
71,654,684
Print statement after for loop generating an additional iteration
I am very much a beginner in C++ and was just delving into for loops when I ran into a problem that I solved by winging it and not by understanding. My script adds numbers from 1 to 10 and calculates the average. The thing is that I had to introduce a new variable "number", other than "sum" and "count", to not have the...
In this loop for (count=1.0;count<=10.0;count+=1.0) { sum=sum+count; avg=sum/count; number=count; } number can not be greater than 10.0. But in this loop for (count=1.0;count<=10.0;count+=1.0) { sum=sum+count; avg=sum/count; } count is greater than 10.0 after exiting the loop due to the condition ...
71,655,186
71,655,267
Code crashes when creating new thread c++
I'm new to C++ and I'm trying to make the console print "after 5 seconds" after 5000 ms. Then print "insta log" immediately after the new thread's declaration. But doing so crashes with the following error: "Debug Error! [PROGRAM PATH] abort() has been called " This is my code: #include <iostream> #include <thread> #in...
Functions are already passed around as pointers, use thread t(f) instead of thread t(&f). Moreover, since your main() neither lasts longer than the thread or calls a t.join(), the program will end before the thread finishes it's code, so that might be another reason for a crash. In fact it is probably the reason for th...
71,655,233
71,655,659
Linking LLVM getOrInsertFunction to a external c++ function in a LLVM pass
I have written a LLVM pass that inserts a call to a external function (foo) in a C(count.c) file. Later when I link C file's object that contains foo function with LLVM instrumented c++ file, it works fine. The C file which contains foo function, looks like this. #include <stdio.h> int count = 0; void foo(int id) { ...
Yes, you need to make the C++ function as extern. foo.cpp can look like: extern "C" { void foo(int id) { count++; printf("id = $d, count = %d\n", id, count); } } extern C tells the compiler to not mangle the name of scoped functions. You can learn more about name mangling and extern C here
71,655,265
71,655,301
How can I implement a copy constructor to this program?
#include <iostream> using namespace std; class Point{ private: int x, y; public: Point(int x, int y) { this->x = x; this->y = y } Point(const Point &p) { x = p.x; y = p.y; } int getX(void) { return x; } int getY(void) { return y; } }; int main(){ Point myPt(1,2); Point myPt2 = myPt; cout <<...
If I'm understanding you correctly, you are looking for a way to make below code work: int main(){ Point myPt(1,2); Point myPt2 = myPt; myPt2(5, 5); cout << myPt.getX() << " " << myPt.getY() << endl; // prints "1 2" cout << myPt2.getX() << " " << myPt2.getY() << endl; // prints "5 5" } To all...
71,655,372
71,655,429
IDXGIOutput::GetDisplayModeList Finds No Display Modes
I am trying to get a list of all the possible resolutions for a IDXGI_OUTPUT*. To do this, I found the IDXGIOutput::GetDisplayModeList API. Unfortunately, there are almost no examples of usage that I could find online. I tried the one on MSDN, and it failed to find any display modes (num is 0) UINT num = 0; DXGI_FORMAT...
You are asking for all display modes that support the DXGI_FORMAT_R32G32B32A32_FLOAT format. This format is never supported (at least at the time of this answer posting) for "display scan-out". The only currently defined "display scan-out" DXGI formats are: DXGI_FORMAT_R16G16B16A16_FLOAT DXGI_FORMAT_R10G10B10A2_UNORM D...
71,655,419
71,656,391
How to call function/classes in c++ .so files, generated by Bazel, in Python?
Let's say I have a simple class in hello.h #ifndef LIB_HELLO_GREET_H_ #define LIB_HELLO_GREET_H_ class A{ public: int a = 0; int b = 0; int add(){ return a+b; } }; #endif with bazel build file: load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") cc_library( name = "hello", hdrs...
With cppyy, you also need to give it the header file, that is: cppyy.include("hello.h") and optionally use cppyy.add_include_path() to add the directory where hello.h resides, so that it can be found. An alternative is to use so-called "dictionaries." These package (customizable) directory locations, names of necessar...
71,655,829
71,655,866
Convert templated type into ID
I have a project where I need to have the ability to convert a given type into an ID. This code doesn't compile, but I hope it shows the functionality I am trying to achieve. class TypeIDManager { public: template <typename Type> void setTypeID(std::size_t ID) { m_data.insert({ typeid(Type), ID }); ...
That's what std::type_index is meant for: std::unordered_map<std::type_index, std::size_t> m_data; std::type_info is implicitly convertible to std::type_index via its converting constructor, so you don't need to change the way you insert into the map. However std::type_index doesn't have a default constructor which is...
71,655,871
71,655,904
QuickSort for vector<string>
I'm new to recursion and get kind of confused by it this is my first time coding Quick Sort for a string I keep getting an error. Does anyone know where I messed up? #include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; void SwapValue(string &a, string &b) { string t = a;...
This statement: while (list[l] <= (pivot)) How does that even compile? Comparing a string to an integer? I suspect you mean: while (list[l] <= list[pivot]) Similar treatment is also needed for the while (list[r] >= (pivot)) statement. And I don't think you want to use >= on the right side. while (i <= r) That won't...
71,656,015
71,656,066
Will C++ function with mixed constant value and variable enable copy elision too?
In the following code std::string OtherFunc(); std::string MyFunc() { if (condition1) return "result 1"; if (condition2) return "result 2"; return OtherFunc(); } Will MyFunc() enable copy elision (for the return string from OtherFunc())? I know I can write std::string MyFunc() { std::string ret; ...
There are no std::string copies/moves made in the first example you are showing. (since C++17) In the second variant the move from ret to the return value of the function (or whatever object is initialized from it) may be elided (named return value optimization (NRVO)), but that is not guaranteed, even in C++17. Furthe...
71,656,290
71,666,122
All possible combinations and permutations of size n algorithm
I'm trying to figure out an algorithm to have all possible combinations and permutations of size k from an array of size n. Let's have an example: Input: n = 3 => [1, 2, 3] Output should be: k = 1 => [[1], [2], [3]] k = 2 => [[1, 2], [1, 3], [2, 3], [2, 1], [3, 1], [3, 2]] k = 3 => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2...
Your task (all permutations of all combinations) can be easily solved using regular recursive function (as I did below) without any fancy algorithm. Try it online! #include <vector> #include <functional> #include <iostream> void GenCombPerm(size_t n, size_t k, auto const & outf) { std::vector<bool> used(n); st...
71,658,418
71,659,326
std::fstream / std::filesystem create file with duplicate number
I want to create a file with a number at the end of the file : filename ( number goes here ).txt. The number will tell me if there were duplicates of the file in the directory the file was created : filename.txt . Example : helloworld (1).txt Windows also has this functionality when trying to create a file duplicate. I...
Since no one is giving me any answers, I decided to spend some time on this function that does what I want , and answer my own question , its in C++ 17 for anyone who thinks this is useful : #include <filesystem> #include <regex> #include <fstream> #include <string> namespace fs = std::filesystem; // Just file "std::...
71,658,440
71,658,518
C++17 create directories automatically given a file path
#include <iostream> #include <fstream> using namespace std; int main() { ofstream fo("output/folder1/data/today/log.txt"); fo << "Hello world\n"; fo.close(); return 0; } I need to output some log data to some files with variable names. However, ofstream does not create directories along the w...
You can use this function: bool CreateDirectoryRecuresive(const std::string & dirName) { std::error_code err; if (!std::experimental::filesystem::create_directories(dirName, err)) { if (std::experimental::filesystem::exists(dirName)) { return true; // the folder probably alrea...
71,658,733
71,659,293
How do I avoid the "multiple definition of ..." Error in this case
Boardcomputer.h: #ifndef BOARDCOMPUTER_H #define BOARDCOMPUTER_H #include <Arduino.h> #include <TFT_eSPI.h> TFT_eSPI disp = TFT_eSPI(); ... #endif Boardcomputer.cpp: #include <Boardcomputer.h> ^^use disp functions^^ ... Error: .pio\build\EmmaChip\lib782\libBoardcomputer.a(Boardcomputer.cpp.o):(.bss.disp+0x0): mu...
The problem is here: #ifndef BOARDCOMPUTER_H #define BOARDCOMPUTER_H #include <Arduino.h> #include <TFT_eSPI.h> TFT_eSPI disp = TFT_eSPI(); ... #endif You define disp in a header file. Defining variables in header files is plain wrong, it cannot work (except if you include the .h file in a single .c file, bu...
71,658,794
71,658,954
Can std::string_view created in function body be returned?
Suppose you have this code #include <iostream> using namespace std; std::string_view foo(){ char arr[3]; arr[0]='0'; arr[1]='1'; arr[2]='\0'; std::string_view sv = arr; return sv; } int main(){ cout<<foo()<<endl; return 0; } Since arr is in the stack, during the creation of sv, ...
At least it's meaningless to return one. You could do so, but a std::string_view relies on the underlying string representation it provides a view on. If that one has gone out of scope, any member access to the view that results in trying to access the underlying data (so nearly all – maybe size is stored separately, b...
71,660,090
71,660,219
Understanding relationship between arrays and pointers
I was recently reading about difference between T* and T[size], T being the type, and it make me curious so I was playing around with it. int main() { int a[10]; using int10arrayPtr_t = int(*)[10]; int10arrayPtr_t acopy = a; } In the above code, int10array_t acopy = a; is an error with message error C2440:...
Array designators used in expressions with rare exceptions are implicitly converted to pointers to their first elements. So if you have for example an array T a[N]; then you may write T *p = a; because due to the implicit conversion the above declaration is equivalent to T *p = &a[0]; If you apply the address of ope...
71,660,143
71,660,341
Where can I find a reference to the function write?
I have the following code for the definition of a streambuf class. I have to adapt it to my needs. Before that, I have to understand how the code actually works. Can anyone tell me where I can find a reference to the write function in flushBuffer. It takes 3 parameters and returns an int. std::streambuf does not have ...
Can anyone tell me where I can find a reference to the write function This is Linux' ssize_t write(int fd, const void *buf, size_t count), defined in <unistd.h>. See man 2 write for more information. Note: write(1, ...) writes to file descriptor #1: standard output.
71,660,975
71,689,916
How to send ffmpeg AVPacket through WebRTC (using libdatachannel)
I'm encoding a video frame with the ffmpeg libraries, generating an AVPacket with compressed data. Thanks to some recent advice here on S/O, I am trying to send that frame over a network using the WebRTC library libdatachannel, specifically by adapting the example here: https://github.com/paullouisageneau/libdatachanne...
The input files of the streamer example for libdatachannel use 32-bit length as NAL unit separator. Therefore, the H264RtpPacketizer instance is created with H264RtpPacketizer::Separator::Length. If I'm not mistaken the ffmpeg output will have 4-byte start sequences as NAL unit prefix instead (which is actually more co...
71,661,263
71,688,947
What's consistency mapping in SLAM?
I always see "consistent mapping" or "map consistency" in SLAM papers and articles, but I have no idea about what consistent map is. I have found enter link description here, but it did not solve my problem. Furthermore, what is local consistentcy and global consistency?
During the mapping, the robot sequentially tries to locate landmarks or objects around it with precise coordinates, both locally and globally. The local consistency of the landmarks in each sequential operation means that their positions relative to the robot and the positions among themselves correspond to reality. Th...
71,661,462
71,661,721
Iterating over types in a variadic template
I have a member function that is templated with a variadic template. The member function wants to push to a container somewhere some information about the types in the variadic template, such as typeid(T) and sizeof(T). The member function should also take in a variable amount of parameters, with each parameter's type ...
Parameter pack cannot have default argument so template<typename... Ts> void bar(Ts... = Ts()...) // ill-formed What you can do is using 2 parameter-packs class foo { private: std::unordered_map<std::type_index, std::size_t> typeinfo; public: // Us... is non deducible template<typename... Us, typename... ...
71,661,744
71,661,954
How to use openmp reduction with two dimensional vector
I want to parallelised this for loop in c++ with openmp: #pragma omp parallel for reduction(+:A) for (uint k = 0; k < nInd; ++k) { for (uint l = k; l < nInd; ++l) { A.at(k).at(l) = A.at(k).at(l) + frq.at(l); A.at(l).at(k) = A.at(k).at(l); ...
I can't tell you much about the error, I can tell you that what you're doing is not what you should be doing: Using the bounds-checking A.at(i).at(j) instead of the raw A[i][j] is a bad idea here: you know the length stay constant at the entry of this loop, so just check the lengths once, and then use the faster []. It...
71,662,035
71,662,148
Creating a matrix with unique pointers and 'empty'cells
I'm quite new to coding and am running into a problem. I'm working with matrices and previously I had only integers inside them representing the state of a cell. I initiliazed my grid in the following way: const int N = 50; // Grid size // 3 vectors for 3 different antibiotics std::vector<std::vector<int> ...
If your data is a class/struct named Cell then the analog to your first example would be #include <memory> #include <vector> std::vector<std::vector<std::unique_ptr<Cell>>> grid(N, std::vector<std::unique_ptr<Cell>>(N)); In this case you can "initialize" a Cell by constructing it such as grid[i][j] = std::make_unique...
71,662,126
71,662,309
Force stl container size and declare it as a type
I want to define a std::vector with 2 elements as a type, and export it. Something looking like: template <class T> using Vec2 = std::vector<T>(2); Is it possible to force the size of a container ? If it is, how can I declare it as a type and export it in the whole code when I include its declaration file? Edit: A l...
No. This is not possible because a std::vector<int> of size 2 has the same type as a std::vector<int> of size 42. Vectors are resizable, thats basically what makes them vectors and distinguishes them from std::array. For a container of fixed size 2 you can use arrays: template <class T> using Vec2 = std::array<T,2>;
71,662,814
71,662,860
Can we watch a read/write of/to a variable in C++
I have started learning about templates in C++ and am wondering if there is a way to say print out all the read and write to a particular variable just like we can do in CMake. For example, CMake has variable_watch() which is used to log all attempts to read or modify a variable. So my question is that is there a way t...
No, you cannot do it in C++ without wrapping your variable in something else that logs for you. But it is possible to do what you need when you are debugging your code written in C++ using hardware breakpoints. You can use watch in gdb to check accesses to your variable. You can check it here or here. These types of br...
71,663,050
71,663,480
Brace initialising an inherited struct in VS2019
I have this code fragment; struct x { int thing; }; struct y : x {}; //works, but I need to use struct y struct x test1 { 1 }; //Error //"Only one level of braces is allowed on an initializer for an object of type "y" //no suitable constructor exists to convert from "int" to "y" struct y test { {1} }; //Error ...
As per the comments on the OP, VS2019 defaults to C++14. To set a project to use different language standard (C++17 in this case) you have to go to project properties->C/C++->Language->C++Language Standard. The same setting is present in VS2017. Thanks to the commenters who helped with this.
71,663,246
71,664,212
Exporting Eigen csr_matrix to python via Pybind11 without converting to scipy.sparse.csc/csr matrix
I would like to export the eigen csr sparse matrix to python in order to perform benchmarks. I'm well aware that the scipy.sparse csr matrix is following the canonical format of a csr matrix, while eigen has a different representation, and that's specifically what I would like to play with. However, when exporting the ...
o.k., posting questions seems to help. Although I struggled with this problem for some time now, only after posting the question I found a solution, namely, I have to include a PYBIND11_MAKE_OPAQUE(TpSpMatrix_csr); at the top of my pybind interface file. I can now call my test function as desired. I hope that this ma...
71,663,765
71,664,421
What exactly is Synchronize-With relationship?
I've been reading this post of Jeff Preshing about The Synchronizes-With Relation, and also the "Release-Acquire Ordering" section in the std::memory_order page from cpp reference, and I don't really understand: It seems that there is some kind of promise by the standard that I don't understand why it's necessary. Let'...
This ptr.store(p, std::memory_order_release) (L1) guarantees that anything done prior to this line in this particular thread (T1) will be visible to other threads as long as those other threads are reading ptr in a correct fashion (in this case, using std::memory_order_acquire). This guarantee works only with this pair...
71,664,281
71,664,937
How to concatenate two dynamic char arrays?
I have two char arrays defined like this: char* str = new char[size]; How can I concatenate these two without creating an additional array? I wrote the code below but it doesn't work: void append(char* str1, int size1, char* str2, int size2) { char* temp = str1; str1 = new char[size1+size2]; for (int i = 0...
The problem of my code was not passing the str1 pointer by reference. Here is the corrected code: void append(char*& str1, int size1, char* str2, int size2) { char* temp = str1; str1 = new char[size1+size2]; for (int i = 0; i < size1; i++) { *(str1+i) = *(temp+i); } int j = 0; for (in...
71,664,385
71,665,926
Directory structure for a C++ template library
I am creating a C++ template library which I intend to use as a vital component in a number of future projects. Due to the size of the library, I am dividing the code between a number of files, some of which are forward declarations and prototypes and some of which are "implementations." Some classes in the library are...
There are a few examples of header only libraries which put everything in the include directory. When it comes to private implementations, there may be a sub-directory or namespace which makes this intent clear to the consumer (something like internal, details, or impl). Adding an accompanying namespace should help sep...
71,664,439
71,676,754
how to share common resource amongst objects in c++
In C++, I frequently run into this problem and always left confused. Suppose there are multiple levels of classes. Each level is instantiating the class which is a level below. E.g. below level1 instantiates level2_a and b(there are more in real case). Now some operation the leaf level object needs to perform. Simple e...
Usually, I set up the logger in the base class, through a co-class that is often a singleton. I obviously always define some basic loggers: Null logger (don't print anything), Console logger (standard output / error), File logger (merged stdout/stderr or not). It's obvious that, in fact, it's the same class but insta...
71,664,795
71,665,063
Does syntax exist to call an unconstrained function that is hidden by a constrained function?
I understand that with concepts, a constrained function (regardless how "loose" the constraint actually is) is always a better match than an unconstrained function. But is there any syntax to selectively call the unconstrained version of f() as in the sample code below? If not, would it be a good idea for compilers t...
Different overloads of a function are meant to all do the same thing. They may do it in different ways or on different kinds of objects, but at a conceptual level, all overloads of a function are supposed to do the same thing. This includes constrained functions. By putting a constrained overload in a function overload...
71,665,474
71,677,814
Sanitize strings expected to be in UTF-8, but which sometimes are not, in C++
We are loading SQLite DBs, into PostgreSQL. SQLite expects UTF-8 strings, but is rather lenient, not enforcing UTF-8-ness. While PostgreSQL is strict, and will fail the transaction with such strings. During tests, once in a while, invalid strings do actually happen, so we must do something. I'd like to detect such stri...
I ended up using https://github.com/nemtrif/utfcpp, as suggested by Alan Birtles, since UTFCPP is well documented, and appears stable. That library is header-only, and I wrapped it as shown below. bool isUtf8(std::string_view text, size_t* p_invalid_offset) { size_t local_invalid = 0; size_t& invalid = p_invali...
71,665,487
71,665,905
Disabling PlaySound() that is included by LibCURL
I've been developing with raylib for quite a while now. I've gotten libcurl to work, but it doesn't work with windows.h, because of the functions names overriding others. However, there is a workaround, by mentioning these defines (in curl.h): #define NOGDICAPMASKS - this disables CC_, LC_, PC_, CP_ TC_ RC_ #define NO...
The #defines you mention are Win32 SDK defines. They instruct windows.h (more accurately, various other Win32 headers that windows.h itself #includes) to not define/declare various symbols. The #define you are looking for to omit a declaration of PlaySound(A|W) (in mmsystem.h) is: #define MMNOSOUND Here is the full t...
71,665,563
71,665,779
how to use hDevMode from PRINTDLGA
how to cast HGLOBAL to DEVMODE? I tried like this: PRINTDLG pd; pd.hDevMode = NULL; if(PrintDlg(&pd)){ DEVMODE* test=(DEVMODE*)pd.hDevMode;
Per the PRINTDLGA documentation: hDevMode Type: HGLOBAL A handle to a movable global memory object that contains a DEVMODE structure. So, use GlobalLock() to access the DEVMODE, eg: PRINTDLG pd = {}; pd.lStructSize = sizeof(pd); ... if (PrintDlg(&pd)){ DEVMODE* test = (DEVMODE*) GlobalLock(pd.hDevMode); // u...
71,666,177
71,666,326
Replacing random_shuffle with shuffle: How to make a random number generator with a given distribution
I am moving from C++11 to C++17 and I have to replace random_shuffle with shuffle. But I am facing the following issue: I need to shuffle the contents of a vector using a random number generator with a particular distribution. In my case this is a std::piecewise_linear_distribution. But I don't know how to create a Uni...
How can I make this generator have the distribution I want? You don't. std::shuffle requires a uniform random bit generator because it is defined as follows: Permutes the elements in the range [first, last) such that each possible permutation of those elements has equal probability of appearance. Emphasis added. Wh...
71,666,268
71,666,660
Stopping multiple threads at once
What do I miss in the program below with threads waiting for a condition_variable_any to determine when to stop ? In the program listed below, the threads stop in an impredictable way; some before the call to notify_all and some don't stop at all. The condition variable used is defined as below: static std::mutex inter...
A condition_variable is meant to signal threads when a condition changes (ie, such as when a shared variable changes value). But your code has no condition. You are trying to use the condition_variable itself as a quit signal, and that is not what it is meant for. notify_all() will only wake up threads that are acti...
71,666,420
71,687,655
what is raylib required libraries in arch linux instead of mesa and
How to install raylib required libraries in the arch. All required libraries are for Debian. what are raylib required libraries for arch? I installed raylib and created a CMakeLists.txt file for creating an executable file after running cmake and making the executable file created, but when I ran it, I got this error I...
I solved the problem with remove glfw-wayland and installing glfw-x11 sudo pacman -S glfw-x11
71,666,712
71,798,486
How to use glClearTexImage for packed depth/stencil textures?
Is it possible to use glClearTexImage to clear a packed depth/stencil texture in OpenGL? And if so, how? I'm using a multisample texture with pixel format GL_FLOAT_32_UNSIGNED_INT_24_8_REV. Attempting to clear the texture with glClearTexImage(textureId, 0, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, GL_FLOAT, nullptr); yields ...
I have mixed up the internal format and the data type, which is why I used the wrong parameters. The packed depth/stencil texture can be cleared with glClearTexImage(textureId, 0, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, nullptr);
71,666,733
71,667,207
Initializing a c++ array with another one
struct AType { const byte data[4]; AType(const byte d[]):data{d[0],d[1],d[2],d[3]} {} ... }; const byte SERIALNR[4] = {0,0,9,0xFF}; AType SNr {SERIALNR}; This works, but I consider it a bit ugly. Is there a syntax with a shorter initializer list? And: How to do it, if that magic 4 were a template parameter? Th...
I think you can do this using a combination std::array and std::initializer_list. Also you can have the size of the array to be a template parameter: using byte = unsigned char; template <int S> struct AType { std::array<byte, S> data; AType(const std::array<byte, S> &d) : data(d) {} AType(const std::initializer...
71,666,989
71,667,252
how to call a function when an asynchronous task is already done?
I have a set of classes look like this: class A { public: std::unique_ptr<B> b; void triggerAsynchronously() { // this work is submitted to a queue. b->getC()->signalAsync(); } }; class B { public: std::shared_ptr<C> c; std::shared_ptr<C> getC() const { return c; } void d...
You need to be very precise with what you are asking for. You say Once C::signalAsync() is executed and done with its work, it should notify A::b::doSomethingWithSignalFromClassC() 'Notify' implies that a thread is waiting somewhere to be woken up to do something - this is complex But you could also mean, I want sing...
71,667,367
71,667,418
Converting German Letters to Uppercase won't work
What is wrong with this code? It does not make them to uppercase, as I want to, if there is a letter in a string such as å, ä or ö. Is there something I'm missing? Is there any way in C++ to make German letters to uppercase in some way with the library? string makeUpperCase(string c) { transform(c.begin(), c.end(),...
You are searching for uppercase letters and replacing them with lowercase letters. If you want to make the letters to uppercase, you have to do the opposite. string makeUpperCase(string c) { transform(c.begin(), c.end(), c.begin(), ::toupper); while(c.find("ä") != string::npos) { ...
71,667,709
71,669,226
Addition of Matrix in C++ using OOP
the following code is not giving the correct output. Matrix data is displaying perfectly, but after the addition of two objects M1 and M2, it did not display the correct output. If I use setData to input data in the matrix, data is stored perfectly, but the addition is not performing correctly. kindly suggest to me how...
Copy constructor and assignment operator were both broken. Let's take a quick stroll to see what went wrong Matrix::Matrix (const Matrix &ref){ // noOfRows and noOfColumns have not been initialized. Their values are unknown so // the rest of this function is a crapshoot. Could do anything. Allocate(); ...
71,668,756
71,670,478
Convert spatstat functions to C++ to circumvent memory-limitation
I am using spatstat to estimate the risk of pest introduction and spread from roads, highways, and other roadways. However, I believe I am running into memory-limitation issues; my data is at a continental scale and my computer only has 16 GB of memory. The warning message I receive when running spatstat's as.owin() an...
Firstly I strongly agree with the poster who said that the quick fix is not to edit the code but to throw more computing resources at the existing code. It can be fiddly to use a cloud computing service, but it will take much more time to re-implement, test, and validate a completely new source code. But anyway: The fi...
71,669,328
71,669,558
Unpacking a container of variant into a variant of containers, combined with the inner variant types
Some code will help making sense: #include <variant> #include <vector> #include <string> using MyType = std::variant<int, float, string>; using ContainerOfMyType = std::vector<MyType>; using MySuperType = std::variant<MyType, ContainerOfMyType>; Instead of having MySuperType being a std::variant of another std::varia...
I would like to declare a new variant type that contains all these base types, plus vector of each of these base types. Template partial specialization should be enough #include <variant> #include <vector> template<class Var> struct MySuper; template<class... Args> struct MySuper<std::variant<Args...>> { using ty...
71,669,426
71,669,456
Why don't I have access to the private values of a class through a friend function?
I create a class, and in the class I declare a friend function so that I can later change a private value with an if..else statement, though I can't even change it without the if..else. #include <iostream> using namespace std; class A { private: float money; friend...
The problem is not with _setMoney() being a friend or not. If that were the issue, your code would not even compile. The real issue is that you are passing the a object in main() by value to _setmoney(), so you are passing in a copy of the object, and are then modifying the copy rather than the original object. Simply...
71,669,791
71,684,475
Android Asset FileNotFound Exception Using Kotlin and Android NDK C++
I am trying to read .obj files in the assets/ folder by passing the AssetManager object from my Kotlin script to the JNI interface, where I can use C++ to parse the .obj files and add it to my OpenGL scene. But the app is not finding any files in my assets folder. I grab the AssetManager and attempt to pass it to my JN...
The issue was I grabbed my asset manager using manager = Resources.getSystem().assets which only gets me access to system resources, not application resources. Instead, I should have passed my context from my surface view class to the renderer class //Surface View Class class glSurfaceView(context: Context, attrs: Att...
71,670,476
71,675,622
How do I cast a typename variable parameter as a string
The problem: I am trying to create a function capable of finding the largest number if the array is an integer, double, float, etc. If the array given is a string it returns the string in the string with the most letters. However, I don't know how to cast list [0] and list[i] as strings. #include <isostream> #include...
if (typeid(list) == typeid(string*)) is the wrong tool. You need compile time branch, either with if constexpr template<typename U> U maxNumber(U list[], int size) { if constexpr (std::is_same_v<U, std::string>) { auto less_by_size = [](const auto& lhs, const auto rhs){ return lhs.size() < rhs....
71,670,859
71,671,030
Is it OK to share a QLineEdit between Layouts?
I'm debugging some code that uses the same QLineEdit between two layout boxes. Is this legal? It looks like the 2nd layout box is grabbing control, and they don't render in the first layout. But I can't find any documentation to say whether this is a valid use-case, and (perhaps) something else is wrong. Pseudocode: ...
It's safe to do, but it won't result in the QLineEdit appearing in both locations. If you look in the QLayout::addChildWidget(QWidget * w) method of qlayout.cpp, you'll see this code: void QLayout::addChildWidget(QWidget *w) { QWidget *mw = parentWidget(); QWidget *pw = w->parentWidget(); if (pw && w->tes...
71,670,869
71,671,085
Why does left justification not work in the first iteration of a loop?
#include <iostream> int main(){ using namespace std; string s1("Hello1"); string s2("Hello2"); for(int i = 0; i < 3; i++){ cout.width(20); cout<<"Some String:"<<left<<s1<<endl; cout.width(20); cout<<"Another String:"<<left<<s2<<endl; ...
std::left is a "sticky" manipulator, meaning you just set it once. By default, padded strings will be right-justified, which is what happens when you output "Some String:" before ever applying the std::left manipulator. See the documentation which states: The initial default for standard streams is equivalent to right...
71,671,194
71,671,208
Error while using auto as the function return type
I am learning C++ using the resources listed here. In particular, i read that we can use the auto type specifier as the return type of a function. So to get clarity over the concept, i tried the following example: header.h #pragma once struct S { auto f(); }; source.cpp #include "header.h" auto S::f() { ret...
The problem is that the function definition must be visible at any point where the function(with auto return type as in your case) is used. Since you've defined(implemented) that member function inside a source file(.cpp), it is not visible when the call expression s.f() is encountered. To solve this you can put the im...
71,671,400
71,671,469
Print a #define macro using std::cout
I am trying to do this #define _TEST_ test #include <iostream> int main() { std::cout << "_TEST_" << std::endl; } As far as my understanding, I expect this output. test However, the output I get is _TEST_ Why am I doing wrong here?
"_TEST_" is a string literal and not a macro. So no macro replacement will be done due to "_TEST_". To achieve your expected output you need to remove the surrounding double quotes and also change the macro to as shown below //-------------vvvvvv--->double quotes added here #define _TEST_ "test" #include <iostream> i...
71,671,604
71,671,702
Selection Sort Implementation with C++ incorrect
really new to C++, trying to instantiate some basic algorithms with it. Having trouble returning the correct result for selection sort. Here is my code #include <iostream> #include <array> #include <vector> using namespace std; // Selection Sort : int findMin(vector<int> &arr, int a) { int m = a; for (int i ...
The warning is very real, and it alludes to the problem that's breaking your sort as well. You are currently returning m inside your loop body. What that means is that if the loop is entered, then the function will return m on the very first time around the loop. It only has a chance to check the first element. And o...
71,671,923
71,673,426
Why is the trailing return type necessary in this lambda expression?
Consider the following code: #include <iostream> #include <type_traits> #include <functional> #include <utility> template <class F> constexpr decltype(auto) curry(F&& f) { if constexpr (std::is_invocable_v<decltype(f)>) { return std::invoke(f); } else { return [f = std::forw...
If you explicitly give the return type and std::is_invocable_v<decltype(f), decltype(arg), decltype(args)...> is false SFINAE applies and a test for whether or not the lambda is callable will simply result in false. However without explicit return type, the return type will need to be deduced (in this case because of s...
71,671,963
71,672,233
Array reference binding vs. array-to-pointer conversion with templates
This code sample fails to compile due to ambiguous overload resolution void g(char (&t)[4]) {} void g(char *t) {} int main() { char a[] = "123"; g(a); } and careful reading of overload resolution rules makes it clear why it fails. No problems here. If we formally transform it into a template version template <typ...
The second overload is more specialized than the first one during partial ordering of function templates. According to [temp.deduct.partial]/5 the reference on T &t of the first overload is ignored during template argument deduction performed for partial ordering. The following paragraphs distinguish based on reference...
71,672,091
71,675,220
How to implement a get<T>() similar to that in nlohmann/json?
I'm writing a json library that has the same usage as nlohmann/json. But I'm having trouble understanding nlohmann's get() function. So I implemented a get() myself, but I think that my method is not very good, do you have any good solutions or suggest? #include <vector> #include <iostream> #include <vector> #include <...
Your way works, but requires default constructible types (so no void, reference, ...), types which do "nothing" (a RAII object using global mutex would be problematic for example). Even a log might be strange. You should care about conversion/promotion with overloading resolution (get<char> is ambiguous from your type...
71,672,597
71,672,773
Can't find where this std::logic_error is coming from
My application works just fine when I have defined the CAMERA_NAME environment variable, but as soon as I remove that variable from my docker-compose file, the container will return a very useless error message that doesn't give me information such as what variable/line the error is occurring on: basler-hd | termin...
To see where the error is from you could use a debugger to step through the code line by line to find where something unexpected is happening. If it's NULL, I am setting it to a value before I move on. camera_name_ is a pointer. It is not a string. It can point to a c-string. Here: camera_name_ = generate_uuid_v4().c...
71,672,731
71,673,172
Screen capture via WinAPI (security)
Is it possible to determine that now my screen (or window of my C++ program) is being captured by any of the running programs on the PC?
It seems there is no way to detect a screen capture until now But you can use SetWindowDisplayAffinity to protect the window content from being captured or copied only when the Desktop Window Manager(DWM) is composing the desktop.
71,673,569
71,674,748
How to call the base class method in C++?
I am working on a C++ program. For one of the use case, I have a class which is derived from its template class. So, I'm wondering how we can call the base class method inside the derived class method? Example: template <typename base> struct derived : public base { void aFunction() { // need to call a ...
If you want to explicitly use the base's member, make the type explicit like you found: template <typename base> struct derived : public base { void aFunction() { base::function(); } }; If you would rather have the usual unqualified-lookup behaviour, make this explicit instead: template <typename b...
71,673,918
71,673,954
how to find the ways of handling pointer difference between ptr and ->
what is the difference of pointers between and which is better in terms of memory management void Loo(){ Song* pSong = new Song(…); //… string s = pSong->duration; } and void Hoo(){ unique_ptr<Song> song2(new Song(…)); //… string s = song2->duration; }
In the first case you need to call delete yourself and make sure it happens on all program control paths. That is easier said than done. It's tempting to write delete pSong; just before the closing brace of the function and be done with it. But what happens, say, if string s = song2->duration throws an exception? (Yes ...
71,673,959
71,674,296
icpc error in compiling over-aligned dynamic allocated variables
I am trying to compile a code in C++, that uses over-aligned variables. If I try to compile the following code (a MWE) #include <new> #include <iostream> int main() { alignas(32) double *r = new (std::align_val_t{32}) double[3]; std::cout << "alignof(r) is " << alignof(r) << '\n'; return 0; } everything r...
It seems that icpc fails to conform with the standard with aligned allocations. Quoting from the documentations for version 2021.5: In this release of the compiler, all that is necessary in order to get correct dynamic allocation for aligned data is to include a new header: #include <aligned_new> After this header is ...
71,674,624
71,675,039
OpenSSL how to request client certificate, but don't verify it
I want to setup openssl c/c++ server request certificate from client but don't verify it. I already use this piece of code to query certificate from client: /** Force the client-side have a certificate **/ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); SSL_CTX_set_verify_depth(ctx,...
You should read the manual. It states: void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb verify_callback); [...] The return value of verify_callback controls the strategy of the further verification process. If verify_callback returns 0, the verification process is immediately stopped with "verification f...
71,674,793
71,675,874
Automatic generate member functions depending on inherited class template
I am just thinking about a way to check an object to be valid in a automated way. I have a couple of hardware related objects (like class A), which can be deleted by external (physical) events. To detect this I have used shared/weak pointer. But now I am struggling with the checking of the weak pointer. Since this is d...
I would protect the full user function call: class A { public: void func1() {} //many more functions }; template <typename T> class Validator { public: #if 1 // template way, but no-expressive signature template <typename F> void do_job(F f) #else // type-erasure way, expressive, but with some overhead...
71,675,005
71,675,068
Default arguments for member function of templated class
Let's say I have something like this bit of (duplicated) code that I'd like to refactor using a template: #include <iostream> #include <algorithm> #include <set> struct IntFoo { auto f(int arg, std::set<int> s = {1, 2, 3}) { return std::find(s.begin(), s.end(), arg) != s.end(); } }; struct FloatFoo { auto f...
You can use parameter pack for specifying default arguments, e.g. template<typename T, T... defaults> struct Foo { auto f(T arg, std::set<T> s = {defaults...}){ return std::find(s.begin(), s.end(), arg) != s.end(); } }; using IntFoo = Foo<int, 1, 2, 3>; // specify default arguments when defining t...
71,675,063
71,675,372
C++ What is the behavior of a try-catch statement if an exception is thrown, and that exception does not match the type of exception caught?
I'm interested to know more about how the following code logic behaves: try { // might, or might not do this: throw ExceptionTypeA; function_which_might_throw_exception_type_a(); do_A(); // do we do A? } catch(ExceptionTypeB) { // B will never be done do_not_do_B(); } // C is always done (Edit...
Will the function do_A be called? In short – no. When an exception is thrown inside a try block, that block will be exited immediately. If the type of exception thrown is not handled by a corresponding catch block, then it will be treated much like an exception thrown outside a try block would be (possibly causing a ...
71,675,252
71,675,755
Cannot increment value-initialized map/set iterator
I'm trying to increment key of nodes after the index j in a map, but I got some error while incrementing the iterator to the next node, here's my code : typedef map<int, string> My_map; My_map my_map; my_map[0] = "la base"; my_map[1] = "le premier"; int j = 1; My_map::reverse_iterator first_it(my_map.rbegin()); f...
In the documentation for std::map::extract it mentions the side-effects: Extracting a node invalidates only the iterators to the extracted element. Pointers and references to the extracted element remain valid, but cannot be used while element is owned by a node handle: they become usable if the element is inserted in...
71,676,830
71,677,107
I can see only one USB string when I try to print all the USB devices (WinAPI)
I try to print a message whenever a new USB device is connected to my PC, but I don't want to create an application which just catches and treats the events triggered by the windows' kernel. So I used some specific functions in order to print the active USB devices and then, whenever a new device is plugged in, a signa...
The format used by CM_Get_Device_Interface_ListA to return a list of items is a double-null-terminated list (see also Why double-null-terminated strings instead of an array of pointers to strings? for rationale). This isn't explicitly spelled out in the documentation, but can be inferred from the argument type of Buffe...
71,676,854
71,808,528
Thread protected variables from inside a threaded function
I writing a simple raytracer plugin for a software that generates the pixels from a multithreaded function. the pseudo code is Scene* scene; void engine_(int y, int, x, pixel& out){ // this function is threaded for each orizontal line y Buffer* line; my_render_engine(y, scene, buffered_line); // here is where I'm acc...
I've managed to solve the issue by creating a map containing the needed data for each thread and a thread::id. the data is the World class which contains pointers for the shared read-access data and a copy for what is not (hopefully is thread safe, but I'm not entirely sure). const std::thread::id tID = std::th...
71,676,871
71,677,508
How to build a 32 bit linux module remotely from visual studio?
I have been trying to create a cross-platform project. Both 32 bit and 64 bit binaries (dlls) need to be built. I am using Visual Studio and selecting x86-Release or x64-Release solves the problem for windows. But for linux it is always building 64 bit binaries. After searching, i found that g++ multilib needs to be in...
As mentioned in comments, it was found that CMAKE_SIZEOF_VOID_P is not able to detect if m32 flag is passed. So i modified the code like this if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(OUTPUT_BITNESS 64) else() set(OUTPUT_BITNESS 32) endif() if(FORCE_32) set_target_properties(PROJECT_NAME PROPERTIES COMPILE_FLAGS ...
71,677,049
71,677,211
Flatten a multidimensional vector in c++
I want to write a generic function in c++ to flatten any multidimensional vector provided. The signature of the method is as follows: template <class U, class T> void flatten(U* out, T& inp, int* dims, int n){ // out is the flattened output // inp is some multidimensional vector<vector...<U>> // dims is an array ...
Your code is unecessarily complicated due to manually managing the memory and manually passing sizes around. Both is obsolete when you use std::vector. Even if you do want a raw C-array as result you can nevertheless use a std::vector and later copy its contents to properly allocated C-array. I would use a recursive ap...
71,677,242
71,696,216
how to mirror a HBITMAP
how to flip a HBITMAP horizontally?As an option, I thought to get an array of colors from BITMAP and write them to another BITMAP, but somehow it's too busy. Are there built-in functions or other options to do this?
You can use StretchBlt with a negative dimension as below: HBITMAP FlipBitmapHorizontally(HBITMAP hbm) { BITMAP bm; GetObject(hbm, sizeof(BITMAP), &bm); int wd = bm.bmWidth; int hgt = bm.bmHeight; HDC hdcScr = GetDC(NULL); HDC hdcFlipped = CreateCompatibleDC(hdcScr); HBITMAP hbmFlipped = Cr...