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
63,718,805
63,727,877
Parameter passing bug in Boost.Log
I've been experimenting with Boost.Log for the first time and quickly ran into problems. The following simple code does not work correctly for me #include <boost/log/common.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/sources/logger.hpp> namespace logging = boost::log; namespace src = boost::lo...
You're exactly right. It is a bug. Reducing it all the way: std::cerr << (kw::file_name = "first.log")[kw::file_name | boost::filesystem::path()] << std::endl; Prints "". A slightly more informative test-bed: Live On Coliru #include <boost/log/utility/setup/file.hpp> #include <iostream> int main() { namespace kw...
63,719,178
63,719,422
Flip least significant one-bit by using negation of a size_t
I've recently encountered a piece of code that supposedly works fine, but I don't quite understand why. size_t a = 19; std::cout<<std::bitset<8>(a)<<std::endl; a ^= a & -a; std::cout<<std::bitset<8>(a)<<std::endl; This piece of code will invert the least significant bit of a given unsigned integer. I would prefer to j...
a & -a gives you the least significant 1-bit set in a. For an odd number it is indeed 1, but that's not the case in general of course. Making an unsigned negative is a well-defined and occasionally useful notation: -a for positive a is -a + 2N where N is the number of bits in the type. An alternative to writing size_t ...
63,719,365
63,719,656
HorizontalHeaderView not calling headerData() of QAbstractTableModel's child
According to HorizontalHeaderView's doc, If the model is a QAbstractTableModel, then the header will display the model's horizontal headerData(); otherwise, the model's data(). but It's not even calling it in my case. but QTableView from widgets module seems to work just fine. here is my main.qml:- import QtQuick 2.15 ...
The problem is caused by a naming conflict between the Button's display property and the role. The solution is to access the role through the model explicitly: // ... delegate: Button { text: model.display } // ...
63,719,439
63,719,746
Linker error: undefined reference to fdt_path_offset
I am trying to leverage libfdt for parsing device tree blob files. You can install libfdt on any Ubuntu by: sudo apt-get install libfdt-dev I write simple test program to use one of the APIs: #include <vector> #include <iostream> #include <libfdt.h> #include <fstream> std::vector<char> read_binary(const std::string& f...
libfdt is C software that doesn't care about C++. Functions written in C should be declared with extern "C" in order to be usable in C++. A lot of C libraries have their user-facing headers wrapped in #ifdef __cplusplus extern "C" { #endif // declarations ... #ifdef __cplusplus } #endif as a convenience for C++ deve...
63,719,548
63,719,596
Unclear struct definition in a C++ header file
I am relatively new to C++, coming from a Python background. I have the following header file: struct Example { int n_example; float random_number; float second_random_number; Example(int n_example, float random_number, float second_random_number); }; I do not get what the second to last line do (i.e, Example(in...
this here Example(int n_example, float random_number, float second_randon_number); is the declaration of the constructor, you can call that and pass the parameters every time you want to construct a new instance of the class Example... like int main() { Example foo(0, 3.14f, 2.77f); } the only thing you are miss...
63,719,711
63,719,838
std::compare_exchange int with #define value
I want to use std::compare_exchange_strong for some std::atomic<int> For compilation reasons (int &) I am forced to introduce int _OLD_VALUE = OLD_VALUE. Is there a more elegant way to achieve this? Here is my example #include <atomic> #include <stdio.h> #define OLD_VALUE 16 #define NEW_VALUE 744 #define OTHER_VALUE ...
No. The reason being is that the previous value of the variable is exchanged so the expected value is overwritten if the compare mismatches. To see what's going on under the hood, look at the GCC built-ins: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html You will note there is a __atomic_exchange_n i...
63,719,935
63,721,201
Include multiple library dependency in same project JNI
I'm trying to build an android app using JNI. The following is my C++ code structure: main -cpp -native-lib.cpp -dependency.h -dependency.cpp In my native-lib.cpp I'm including dependency.h. In my Cmake, I'm creating a shared library (.so) for dependency and native-lib so that I can load them in my Java ...
On Android, you only need to explicitly loadLibrary("dependency") if the platform is older than API 21. As for CMake, target_link_libraries(native-lib dependency) should work, but you may need to clean the project if the CMake caches don't get properly updated.
63,720,745
63,721,023
Is leaving debug sections in the source code a good practise?
I am working together with a senior C++ developer. In most of his code he includes debug sections. It looks like this: void do_something() { int var = 10 #ifndef NODEBUG trace("Function Start %s", __FUNCTION__); #endif while (someCondition) { var += 1 #ifndef NODEBUG trace ("Var = %d \n", var...
It's not generally a bad practice to add code within debug sections. As long as this code doesn't fundamentally change the behavior of your function, it doesn't add much complexity and can give you useful information. However, it does decrease readability. It is very rare that you really need a dedicated code section t...
63,721,279
63,722,323
How to add Qt sources to QtCreator in Ubuntu?
Edit The answers to this post either say compile yourself - which I don't want do to - or install qtbase5-dbg which is not part of Ubuntu releases anymore. So is there no way to achieve this without this package? And shouldn't there be different debug symbols for each Qt 5.X version? I'm trying to add Qt sources - whi...
A few minor versions ago, Qt added "Qt debug information files" to the maintenance tool. They contain the debug information of the libraries. Which means, if you debug and want to step into human readable Qt library code you have to install them.
63,721,577
63,721,703
How to join an array of threads in C++?
I am learning how to use threads in C++. I need to create an array of threats, start executing all of the threats and subsequently join them. I am getting an error however, can someone help me please? The skeleton of my code is: #include <iostream> #include <thread> using namespace std; int Numbers[100000][1000]; thre...
Unhandled exception at 0x76BF40B2 in Learn.exe: Microsoft C++ exception: std::system_error at memory location 0x1DF3F4E0. That mostly because you created an insane number of threads thread Threads[10000][1000]; Most systems cannot support that number of threads. This is a typical max number of threads that a Linux s...
63,721,847
63,722,041
Converting from cartesian coordinates to polar coordinates and from polar to cartesian using reference
Im trying to make a simple converter using reference to convert between cartesian and polar the problem is it gives me wrong answers and sometimes 0 ,0 . I want to know what's the problem and how can i fix it . this is the code : #include <iostream> #include <cmath> using namespace std; void cartesianToPolar(int x,int...
Results of both of your functions should be floats, not ints: void cartesianToPolar(float x, float y, float &r, float &q ) { r = sqrt(x * x + y * y); q = atan(y / x); } void polarToCartesian(float r, float q, float &x, float &y) { x = r * cos(q); y = r * sin(q); } The values you were computing were correct, b...
63,721,860
63,721,892
How to get the last index in a for loop
i am coding in a language similar to c++ known as mql5.(for mt5 trading platform) they have many similarities... i have a for loop as shown below: void OnTick() // this functon basically executes the code after every price change. { for (int i = 0; i<5; i++) //the for loop function { Print(i); //this pri...
All you need to do is pull i outside the loop: void OnTick() { int i = 0; for (; i < 5; i++) { Print(i); } // i is now one past the last index int last = i - 1; } If you know that you loop 5 times in advance, you could also obtain the last index using: int last = 5 - 1;
63,721,872
63,736,888
How to use jsoncpp from fetchcontent
I'm making one program that is basically a stresstest for a couple of different machines, and I have to write the testresults to a jsonformat. Because I don't want to manually install jsoncpp on every machine I decided to use Fetchcontent in the CMakeLists file: cmake_minimum_required(VERSION 3.15) project(Programma) ...
While being built, the project jsoncpp doesn't provide jsoncpp target. Instead, it provides separate targets for different kind of library: jsoncpp_static for STATIC library, jsoncpp_lib for SHARED library, jsoncpp_object for OBJECT library. By default, all 3 library kinds are built, so you may choose any of them for...
63,722,641
63,722,864
Create a vector with repeated entries of each Element
I want to expand a given vector by repeating every entry three times. For example, if the vector is [5,7]. The output vector should be [5 5 5 7 7 7] #include<iostream.h> #include<vector.h> int main(void) { std::vector<int> x; x.push_back(5); x.push_back(7); x.insert(x.end(), x.begin(), x.begin() + 1); ret...
A simple approach is to loop over the vector and create a new one: std::vector<int> vec{5, 7}; // create a new vector std::vector<int> new_vec; new_vec.reserve(vec.size() * 3); for (auto elem : vec) { for (std::size_t i = 0; i < 3; ++i) { new_vec.push_back(elem); } }
63,723,508
63,723,931
Is it possible to make OpenCV matricies with manual input?
I am trying to store the location of four specific points and then putting it into the cv::fillPoly function. Currently my locations are stored in a multidimensional array is there a way to convert this or make it straight into a format it accepts? int PointLocationArray[4][2] = {{point1_x, point1_y}, {point2_x, point2...
A very simple way is to start with a flat array and then reshape the matrix: static const std::vector<double> data = { 1.0, 2.0, 1.0, 2.0 }; // two points Mat ret = Mat(data).reshape(2, 2); Note: This way, ret is a wrapper around data. If you would like to copy the data instead, use Mat(data, true). Another way is to ...
63,724,059
63,724,155
Does GCC support C++20 std::format?
If it doesn't, do you know what compiler or version will? See cppreference/format.
Does gcc support C++20 std::format? Not yet! There's no compiler support yet, not even gcc 11. See Text formatting in Library features. Compiler support for C++20 library features
63,724,182
63,754,006
Can you access the object representation of any object through a char*?
I have stumbled upon a reddit thread in which a user has found an interesting detail of the C++ standard. The thread has not spawned much constructive discussion, therefore I will retell my understanding of the problem here: OP wants to reimplement memcpy in a standard-compliant way They attempt to do so by using rein...
This video, linked in the comments (now chat) by @KonradRudolph is likely the answer to the problem. At around the 40min mark, Timur Doumler, who is a member of the ISO C++ commitee, discusses the possibility of accessing byte representations. The summary is that any attempt of accessing byte representation except memc...
63,724,203
63,724,450
Getting this error: request for member 'at' in 'array3', which is of pointer type
The function apply_all is supposed to multiple all the elements of array2 (of size2) to all the elements of array1 (of size1) and store them at a dynamically created vector (of size1*size2) The compiler mention this line for error: array3.at(i)=array1.at(k)*array2.at(j); #include <iostream> #include <vector> using name...
Allocating vectors is just crazy. Most of the advantages of using a vector (like not having to manually manage memory) disappear in an instant. Create your vector on the stack instead, like this vector<int> apply_all(vector<int>&array1,size_t &size1,vector<int>&array2,size_t &size2) { vector<int> array3(size1*size2...
63,724,412
63,724,548
Why are my two tuples containing strings, created the same way, not equal?
I'm compiling the following program using Microsoft Visual C++, as a C++20 program: #include <iostream> #include <tuple> int main() { auto t1 = std::make_tuple("one", "two", "three"); auto t2 = std::make_tuple("one", "two", "three"); std::cout << "(t1 == t2) is " << std::boolalpha << (t1 == t2) << "\n...
You are comparing pointers to buffers of characters, not strings. Sometimes the compiler will turn two different "one"s into the same buffer, sometimes it will not. In your case, it isn't. Probably a debug build. Add #include <string_view>, then using namespace std::literals; auto t1 = std::make_tuple("one"sv, "two"s...
63,724,679
63,728,530
Wrong GCC 9 (and higher) optimization of memcmp with -fno-inline
There is a small func function which compares a memory block against a static const zeroed array. Here is a primitive example to illustrate the problem: #include <cstring> #include <memory> #define MAX_BYTES (256) inline int my_memcmp(const void * mem1, const void * mem2, const size_t size) { const auto *first =...
This is GCC bug 95189, https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95189 Basically, GCC can emit specialized code for memcmp if one of the buffers has known contents, but this specialization doesn't work correctly if it encounters a zero byte (because it's special for other functions such as strcmp). It appears alread...
63,724,778
63,734,742
Something strange when generating random matrices ( Eigen Library )
My intention is to stack, in tmp, matrices generated as orth(randn(lenghtDim, dimsSubsp(iK)))' (in Matlab notation) I simulate nresample times this procedure and every time I compute the squared norm of tmp and save it in normVal. I tried different ways to generate these random matrices but their norm value is always t...
EDIT: Haha, I know what it is now. You are performing an SVD and looking at U, which is always (regardless of the input) a unitary matrix. A unitary matrix has the property that U^T * U == I, which implies that the norm (and squared norm) of each of its columns are exactly 1. Therefore, the squared norm of the matrix i...
63,724,956
63,725,001
How can I fix " no suitable constructor exists to convert from const char"?
I am new to c++ and I have an error. When I created a new object the compiler giving to me " no suitable constructor exists to convert from const char[16] to stringex "and "no suitable constructor exists to convert from const char[14] to stringex " #include <iostream> using namespace std; #include <stdlib.h> ...
What is converted from string literals are const char*, so char[] (without const) cannot accept that. You should add a constructor like Stringex(const char* s) { strcpy(str, s); } Avoiding buffer overrun by, for example, using strncpy() instead of strcpy() will improve your code more.
63,725,259
63,727,171
Index of Boost cmake components
I am using boost quite often, but every time I try to use it I have doubts about what is the name of Boost module, which I should add in cmake. For example in my last project I wanted to use boost::concurrent::sync_queue and I can't find anywhere what is the name of the module. I finally found it by accident, by locati...
From CMake\share\cmake-3.*\Modules\FindBoost.cmake: FindBoost --------- Find Boost include dirs and libraries Use this module by invoking find_package with the form:: find_package(Boost [version] [EXACT] # Minimum or EXACT version e.g. 1.67.0 [REQUIRED] # Fail with error if Boost is not fo...
63,725,273
63,725,503
What is the nfunction of .WillOnce(Return(n)) in google mock?
EXPECT_CALL(turtle, GetX()) .WillOnce(Return(100)) What is the function of the above action .WillOnce(Return(100))? Does it verify that the value 100 is returned exactly once from GetX()? Or does it make the function GetX() to return the value 100?
As explained in the gmock docs, this will make the test fail if method GetX on the mock turtle is NOT executed exactly once (see "Cardinalities: How Many Times Will It Be Called"). Otherwise the test will pass (unless it will fail in some other point) and the GetX method will return 100 wherever it was called.
63,725,308
63,733,111
Aws::S3::S3Client constructor very slow
I'm trying to use the AWS C++ SDK to generate a signed URL for S3, however the Aws::S3::S3Client constructor seems very slow. In the following example: #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> int main() { Aws::SDKOptions options; Aws::InitAPI(options); printf("1\n"); Aws::S3::S3Client c...
When not running on AWS, set: AWS_EC2_METADATA_DISABLED=true to disable the metadata API which is what's causing the delay.
63,725,475
63,726,091
C++ const_iterator to iterator for forward_list
As per this question, and assuming I have a mutable reference to the container itself, the constness of an iterator can be safely removed using: foo::const_iterator cit = ... ; foo::iterator it = c.erase( cit, cit ); However, this doesn't seem to work for forward_list's equivalent, erase_after, as per this code:: #inc...
although I think it's tricky and STL should provide a normal way to do that, there is also a solution by insert_after, because: iterator insert_after(const_iterator position, size_type n, const T& x); Preconditions: position is before_­begin() or is a dereferenceable iterator in the range [begin(), end()). Effects: I...
63,725,509
63,731,352
Is it acceptable for a derived function to not make use of all available parameters?
I have an overridden member function that does not make use of all the parameters it is passed? Does this indicate a design flaw?
It is always a good idea to watch for unused parameters. Compilers typically will rise a warning and this is definitely meant as a hint to watch out for potential problems. If your interface is too broad and pass more or less often unneeded parameters, it can be seen as a design problem. But there are tons of examples,...
63,725,780
63,733,899
c++ compile-time associative array
I think this question may just be more about my weakness with doing anything nontrivial with templates more than the problem itself, but I would like to implement a template class that is used like so: MyArray<std::string, 1, 3, 7> a; a[1] = "hello"; a[3] = "world"; a[7] = "!"; // runtime error // a[4] = "?"; Under t...
ok, if you don't mind the possible huge space cost, you can do it like this: template<typename T, size_t Head, size_t... Tails> class MagicArray{ std::array<T, 1 + sizeof...(Tails)> data; static constexpr size_t max(size_t a, size_t b) noexcept{ return (a < b) ? b : a; } template<typename head, ...
63,725,847
63,725,916
C++ ensuring arithmetic result involving literals is 64 bits not 32 bits
I have encountered issues in the past multiplying literals by one billion, where the result should be 64-bits but was converted to 32 bits due to the presence of literals. What is the best (safest & simplest) practice when multiplying numbers which will probably exceed 2^32? I have this equation: const uint64_t x = 1'0...
You can use a suffix on the first literal to promote it to the correct size. In this case you can use const uint64_t x = 1'000'000'000ull * 60 * 5; to make 1'000'000'000 an unsigned long long which is at least 64 bits wide. This also has the affect of promoting 60 and 5 to be unsigned long long's as well when the mu...
63,725,881
63,726,780
How to delete a user-specified data node in a linked list?
In the function void eliminarXdato() the user will be asked to write a number and if that number is the same as one found in the linked list structure cedula it will delete them. The problem is probably logical, it just crashes and abruptly ends the program whenever i try to initialize said function so i dont get any c...
Fixed it myself, bye. void eliminarXdato(){ aux=cab; // initialize stuff int tkn = 0; cout<<"Ingrese la cedula a eliminar: \n"; cin>> tkn; if (aux != NULL && aux->cedula == tkn) { cab = aux->nxt; free(aux); // free function } while (aux != NUL...
63,726,114
63,726,476
Is it safe and portable to cast pointer to any type to char pointer for arithmetic?
Considering the following snippet, and for both C and C++ languages, is: int t[2] = { 0, 1 }; *( (int *)( (char *)t + sizeof(int) ) ) = 2; always equivalent to: int t[2] = { 0, 1 }; t[1] = 2; ? It might sound weird but I imagined some reasons why it could be false on some platforms: char pointer increment could go i...
Is it safe and portable to cast pointer to any type to char pointer for arithmetic? Any type --> No. (Non-null) function pointers cast to char * is UB and then math applied is UB. A char * may even be too small to encode a function pointer.
63,726,311
63,726,884
Locally visible typedef for function parameter and function body
I want to know if there is any way to typedef locally for use with function parameters and function body. Like in the following case: // typedef: solution 1, visible everywhere in the namespace void func(/*really long type*/ param1, /*many more params of same/different type*/) { // typedef: solution 2, cannot use...
You could do the following: namespace inner { using type = really_long_type; // typedef works as well void func(type t, /* ... */) { // ... } } using inner::func;
63,726,415
63,726,469
Find if std::list contains element from another std::list
I have two lists: std::list<MyClass1> listClass1; std::list<MyClass2> listClass2; For sake of simplicity lets say that they have these elements: listClass1 {id: 1, name: "Test1"} {id: 2, name: "Test2"} {id: 3, name: "Test3"} {id: 4, name: "Test4"} {id: 5, name: "Test5"} listClass2 {id: 1, name: "Test2"} {id: 2, nam...
You can store one (larger of the two would be better) of the list's names into a set<string> and iterate over the other list and see if the set contains that element. That should reduce your running time from O(m * n) to O(m * log(n)). P.S.: I believe using a hash table can further reduce that log(n) factor.
63,726,513
64,039,538
CfSetInSyncState fails with ERROR_NOT_A_CLOUD_FILE after a file update
I am using the Cloud Mirror sample and I am having problems to set a file sync state after I edit a .txt file with WordPad app. When I try to set the file sync state to in sync state (CF_IN_SYNC_STATE_IN_SYNC) I am getting the error ERROR_NOT_A_CLOUD_FILE. But when I use the Notepad app I can change the file sync state...
After some tests and taking account the Rita Han - MSFT answer I couldn't set the file reparse point, like I posted in this question. But I can use the CfSetInSyncState without errors using the CfConvertToPlaceholder function to convert the file to a placeholder again, because after a txt file modification with some ap...
63,726,569
63,726,683
How can I overload a postfix operator in C++?
How can I properly make prefix and postfix operators for any type? For example, I have this enum class: enum class Traffic_light { green, yellow, red }; I try to create the operator overloads like: Traffic_light operator++(int) { return Traffic_light::green; } Traffic_light operator++() { return Traffic_ligh...
Since you need to make the operators non-member functions, you need to pass a Traffic_light argument to the operators: Traffic_light operator++(Traffic_light const&, int) { return Traffic_light::green; } Traffic_light operator++(Traffic_light const&) { return Traffic_light::red; } Note that these are returni...
63,726,754
63,726,799
Compile and run at the same time with a single line command in windows
In macOS whenever I compile and execute my code I use g++ name.cpp && ./a.out but in Windows it doesn't work for compile and run i use g++ name.cpp ./a.exe I'm using command prompt. g++ name.cpp && ./a.exe doesn't work. But i want to use a single line command like i used to do in macOS
In Windows, backslash (or yen mark on some font) is used as separator of directory. g++ name.cpp && .\a.exe worked on Command Prompt (but not on PowerShell).
63,726,932
63,726,969
Array values reset problem with dynamic allocation
Trying to create a little program using class, dynamic allocation,... This is the "problematic" code: void Social::calc_pop(double years) const { double var = births - deaths; double* pop = new double; pop[0] = pop_0; for (int i = 0; i < years; i++) { pop[i+1] = pop[i] + var; std::co...
This code: double* pop = new double; allocates a single double, but then you are treating pop like an array, which invokes undefined behavior when you index into it at any position other than 0. Instead, you need to allocate an array: double* pop = new double[years + 1]; Note that you need to make years an int, or ca...
63,727,311
63,727,749
dynamic 4d array c++ with dynamic borders
I try to make a 4D- array, seemed to work fine if the Dimensions WxXxYxZ are fixed like W= 7; X=5, Y=10, Z= 2. But my code needs to work for Dimensions with varring borders: int chainCount = 10; int * beadCount = new int[N];// N >= chainCount // for example: beadCount = { 5, 7, 8, ... , 12} //4D array: double **** r...
May I suggest a better way to look at this? Treat the object as a container whose key is a "4-tuple" (w,x,y,z). If a particular "dimension" has a range-constraint, that's easy to implement. If you need to iterate through the tuples, you can do that too. But the container only stores the values that are actually set –...
63,727,438
63,727,534
Is noexcept useless when not throwing is zero-cost?
Is the noexcept specifier useless if your implementation has a zero-cost (if nothing is thrown) exception model? What is an example where lacking noexcept has a consequence?
Is the noexcept specifier useless if your implementation has a zero-cost (if nothing is thrown) exception model? No, noexcept would be useful even if exceptions had no performance impact at all. One example is that noexcept can signal which algorithm can be used. For example algorithms that use std::move_if_noexcept ...
63,727,702
63,728,734
Arduino ESP edit big JSON file - wear leveling
I have a "big" JSON file about 1000 objects. Using https://arduinojson.org/ to serialize / deserialize. void ConfigFile_Save_Variable(String VarName, String VarValue) { Serial.print("ConfigFile_Save_Variable: "); Serial.print(VarName); Serial.print("="); Serial.print(VarValue); File configFile = SPIFFS.open("/co...
The best way to handle this is to break up the JSON - write each top level object to its own file. You already have the labels for the objects, use those as filenames prefixed with /config/ or /c/ if you need more space for the label name. Let's look at why what you're asking for from SPIFFs doesn't work. JSON is seria...
63,727,795
63,727,920
How to pass a c++20 view to a funciton
I want to make a function which takes a generator as a parameter. Consider: void function_which_takes_generator(type_i_dont_know view); struct Pair { int a, b; } int main() { std::vector<Pair> pairs = //init to something function_which_takes_generator(pairs | transform([]{auto pair} { pair.x })); } What...
You write a function template, not a function template <typename View> void function_which_takes_generator(View view) { // ... } Note you need the definition, not just a declaration, visible at the call site.
63,727,815
63,727,915
Why Doesn't A Character Array Give an Unsigned Result
In this project I am supposed to receive a packet, and cast a part of it to an unsigned integer and get both Big-Endian and Little-Endian results. Originally, I wanted to just cast a pointer inside the byte array (packet) to an unsigned integer type that would automatically put the value received in Big-Endian form, li...
Well, I daresay you want to use %u not %d in that printf() format-string! %d assumes that the value is signed, so if the most-significant bit is 1 you get a minus sign.
63,727,975
63,734,562
When should one explicitly attribute noexcept?
When should one add the noexcept attribute to a function? i.e. when is the compiler not able to tell a function throws? Should everything be marked or is there a way to tell? I'm not a fan of premature optimization, and I'm not a fan of premature attribution. I don't know of a way to "profile" the need of noexcept the ...
The C++ Core Guidelines recommends basically use it everywhere that the code doesn't throw. This is mostly important for libraries because code checkers use the functions you call to see if it's noexcept, otherwise you get a cascade of warnings. That said, the most important recommendations are to make swap, move, and ...
63,728,042
63,728,582
What are the underlying types of pointers to 1D/2D arrays, and why is double dereferencing needed?
Say I initialise arrays and variables as such: int arr1d[3] = { 1, 2, 3 }; int* arrptr = arr1d; int (*ptr1d)[3] = &arr1d; int arr2d[2][3] = { {1, 2, 3}, {4, 5, 6} }; int (*ptr2d)[3] = arr2d; So, arr1d is an array of 3 integers. Under the hood, arr1d is a pointer to the first element of the array, i.e. &arr1d[0]. Henc...
int arr1d[3] = { 1, 2, 3 }; So, arr1d is an array of 3 integers. Correct. Under the hood, arr1d is a pointer to the first element of the array, i.e. &arr1d[0] It is unclear what you mean by "under the hood", but in the C++ language an array is an array. It is not a pointer type. Saying that arr1d is &arr1d[0] is w...
63,728,238
63,728,416
How to use the bisection method in boost C++ for a function with multiple arguments
I have below function in C++ #include <cmath> #include <utility> #include <iostream> #include <boost/math/tools/roots.hpp> double my_fn(double x, double y) { return x*x - y - 1; }; int main() { double min_x = 0.0; // min value of domain of x double max_x = 10.0; // max value of domain of x double y =...
#include <cmath> #include <utility> #include <iostream> #include <boost/math/tools/roots.hpp> double my_fn(double x, double y) { return x*x - y - 1; }; int main() { double min_x = 0.0; // min value of domain of x double max_x = 10.0; // max value of domain of x double y = 1; auto x = boost::math:...
63,728,262
63,728,611
How do you assign struct to a void in gsl integration
I want to use gsl package for numerical integration, which may look easy. However, my function is multi-parameters. I use a struct data type for the parameters of the function. Here is my code to integrate the function f=a*x+b as an example which contains the parameters a and b. #include <stdio.h> #include <math.h> #in...
You've done the casting wrong. This: struct parameters alpha = *(struct parameters *) params; ...should be written as below if you want to copy params to alpha: struct parameters alpha = *((struct parameters *) params); ...but you later use alpha as a pointer, so it should really be this: struct parameters* alpha = (...
63,728,368
63,728,469
How to avoid this nasty concept trap (depending on order)
The following code depends on whether the concept is defined before or after the class. The intent is to check, whether a Quantity can be constructed from a T. I have stripped this down, only showing the test for copy construction. template <typename T> concept is_compatible = requires( T & t ) { Quantity( t ); }; // n...
There might be a "good reason" for this, "because compilers work a certain way", but I find this pretty flawed. Concepts wouldn't be as useful without it. You wouldn't be able to check that a function call expression relying on ADL is valid. Your concept is satisfied by this pair of declarations namespace ns { st...
63,728,479
63,728,890
How do I diagnose the streaming operator problem: no match for 'operator<<'
I really didn't want to resort to this but I literally have no clue as to why my code isn't compiling (gcc).. ('template argument deduction/substitution failed' etc.) Error message: error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const EAN_code') header file #ifndef HEADER_H #define...
The problem is here: return o << qty << " x " << item_number; specifically: << item_number item_number is of type EAN_code and you have not provided an operator<< overload for it. Use a similar pattern to what you've already done for Order_item I suggest you change the question title to something like "how to find C...
63,728,715
63,732,547
Why I cannot use the operator [] on a pointer of std::array< int, 3 > to index value?
Code: void function(array<int,3> * ptr) { int temp = ptr[2]; // Error int temp = (*ptr)[2]; // Can work! } int main(void) { array<int,3> arr={1,2,3}; function(&arr); return 0; } I have no idea why the pointer cannot work like this: int *a = new int[...
You are dealing with pointer arithmetic. Inside of function(), you have a std::array<int,3>* pointer to an array of std::array objects (in your example, &arr can be treated as a pointer to an array of 1 std::array object). Applying an index offset to a typed pointer will advance the pointer by a byte count equal to the...
63,729,073
63,729,162
How to start a thread from one object's method by calling another method?
I have read various articles on C++ threading, among others GeeksForGeeks article. I have also read this quection but none of these has an answer for my need. In my project, (which is too complex to mention here), I would need something along the lines: #include <iostream> #include <thread> using namespace std; class ...
The easiest way to call member functions and pass arguments is to use a lambda expression: Threads[i][j] = std::thread([this, i, j](){ this->DoOperation(i, j); }); The variables listed in [] are captured and their values can be used by the code inside {}. The lambda itself has a unique anonymous type, but can be impli...
63,729,246
63,731,206
STL algorithms for pairwise comparison and tracking max/longest sequence
Consider this fairly easy algorithmic problem: Given an array of (unsorted) numbers, find the length of the longest sequence of adjacent numbers that are increasing. For example, if we have {1,4,2,3,5}, we expect the result to be 3 since {2,3,5} gives the longest increasing sequence of adjacent/contiguous elements. No...
In both your code snippets, you are iterating through a range (in the first version, with an index-based-loop, and in the second with a range-for loop). This is not really the kind of code you should be writing if you want to use the standard algorithms, which work with iterators into the range. Instead of thinking of...
63,729,430
63,733,092
How to recreate a file using tcpdump and c++?
I have the pcap file for duration when the text file was downloading. How can I recreate the original file from this pcap file using python or c++. I don't know much about network programming and am trying to do this to enhance my understanding. Any help is appreciated.
This depends on what the pcap file looks like. Assuming that the text file is in the data field inside of the tcp layer, you can use tshark like so: $ myfile="traffic.pcap" $ tshark -r $myfile -T fields -e data > myfile.txt If data is not the right field, use wireshark to look at the packets to see which is. If the da...
63,729,721
63,736,182
Converting minutes into days, hours, minutes and seconds
I'm in a beginner level C++ class and I'm having some trouble figuring out why I'm getting the wrong output when I convert minutes into days, hours, minutes and seconds in C++. I had a friend help me and she was able to get the correct output in Python using the same math, but for some reason in C++ I can't get the cor...
As other users already pointed out, when you write inputMinutes = decimalMinutes; you convert a double into a int, loosing all the information about the decimal part. You have to separate this part from the integer part of your decimalMinutes variable, then multiply it by 60 to get the seconds. See the below code. #inc...
63,729,836
63,730,132
returning template class from member function
I'm trying to implement engine using ECS pattern and i want to have entity class template that would be used to represent in-game objects: template<typename...components> class entity { //... }; and entity_manager class that would manage lifetime of entities: class entity_manager { public: template<typename......
You don't put a template argument list after the name of a function in its declaration. Simply: template<typename...components> entity<components...> create_entity();
63,729,847
63,729,905
Sending your c++ project
I have coded an app in c++ using the SFML library. I configured it into code blocks to run the program. Let's say I now want to send this app to my friend, what's the best way I can do this so that he doesn't have to go through downloading a lot of stuff to run it? I am using the MinGW compiler.
Create an installer or package. For example; On RedHat Linux you'd want to create a RPM package. On Windows you want to create a MSI file. Whatever you do, the package you create should bundle up everything your application needs to run and put it into the correct location(s) on the target system. This includes your ex...
63,730,007
63,730,185
c++ initialize array of function pointers with variable (compiletime) number of entries
For an embedded solution I want to define an array of void(*relay)(void) functions which I use as callback relays for a library which only accepts stateless void(*f)(void) callbacks. The relays will then call the actual std::function callbacks. The code below works nicely. However, I'm looking for a possibility to chan...
I don't think it's possible with a plain array. You'll need to use something like std::array to be able to return it from a helper function/lambda. Here's a C++20 solution with a lambda template: constexpr std::array<void(*)(), nrOfRelays> relays = []<std::size_t ...I>(std::index_sequence<I...>) { return st...
63,730,124
63,730,186
Perfect forwarding of pair.second using a lambda
Why this snippet doesn't compile? #include <iostream> #include <vector> #include <ranges> #include <unordered_map> namespace vw = std::ranges::views; int main() { auto get_second = [](auto&& pair) constexpr noexcept -> decltype(auto) { return std::forward<decltype(pair)>(pair).second; }; ...
Shouldn't -> decltype(auto) evaluate to std::pair<double, char>&? No. Here's a much simpler example: struct X { int i; }; X x{42}; decltype(auto) i = x.i; Is i an int or an int&? It's an int. decltype(auto) derives its type by applying decltype(...) to the right-hand side. decltype(x.i) just gives you the type ...
63,730,742
63,797,335
Qt generated project code finds shared library file but still getting undefined references during build
I was given source code for a third party library for controlling a printer. I built a shared object from that. I was able to successfully use that shared object to run a simple program in C. I tried to integrate it with an existing Qt GUI that I built, but I was getting undefined reference errors. So, I made a new, cl...
Trying to compile the sample code as a C++ program instead of a C program gave me the clue I needed. I needed to include extern "C" around the API header. My Qt program compiles now.
63,730,745
63,730,826
Difference between two template code patterns where in one case a number is assigned whereas in the other the keyword typename is used
In the following code, what is the difference between the following two template lines. > 1. template<class T, std::enable_if_t<std::is_integral<T>::value, int> = 0> > 2. template<class T, typename = std::enable_if_t<std::is_integral<T>::value>> Both the above lines are working fine, I just wanted to kno...
They are both working fine, if you write a single function. But when you want two alternative functions, this way template <typename T, typename = std::enable_if_t<true == std::is_integral_v<T>>> void foo (T const &) { std::cout << "is integral" << std::endl; } template <typename T, typename = std::enable_if_t<false ...
63,730,953
63,731,659
Operator [ ] overloading with const and non const versions
I started learning C++ not long ago and I've got an issue. I know that a lot of similar questions has been asked about this topic. However, I didn't deeply understand something which is why I am here. So, my question is: why do I need to provide 2 versions of the [] operator? isn't the const version sufficient? For e...
Whether or not you need two overloads depends on what interface you want to provide. If you want to be able to modify elements even in const instances of Array, then yes, the single int& operator[](int index) const; is enough. This is what std::unique_ptr does. But if you want elements of const Arrays to be read-only, ...
63,731,028
63,731,072
std::accumulate using the view std::ranges::views::values
Is there any way to make that code compile, or I have to create my own lambda as fourth parameter of std::accumulate? #include <iostream> #include <ranges> #include <unordered_map> #include <numeric> namespace rv = std::ranges::views; int main() { std::unordered_map<unsigned, unsigned> m = {{5, 3}}; auto...
The error that gcc throws, if I understood it correctly, basically says that begin and end yields different types Indeed. In Ranges terms, elements_view's iterator and sentinel are different types. Before C++20, these types had to be the same, and lots of code is written assuming this. Unfortunately, we do not yet ha...
63,731,036
63,731,108
Define C++ conversion operator only if template arg is not const
I'm writing custom conversion operator from CContainer<CLASS> to CContainer<const CLASS>. The code looks like this: template<class T> class CContainer { public: operator CContainer<const T>() const { /* here goes the code */ } }; and technicaly it works well, but some compilers print warnings like operator CContai...
A possible solution is use SFINAE to enable the operator only when T is different from T const. For example (caution: code not tested) template <typename U = T, typename std::enable_if<false == std::is_same<U, T const>::value, int>::type = 0> operator CContainer<U const>() const { /* here goes the code */ } or, as...
63,731,161
63,734,385
Register Windows Runtime Component (c++winrt) in native c++ application
Native c++ application is using c++/winrt classes to instantiate and use winrt::Windows::Media::Audio::AudioGraph. Inside AudioGraph there is possibility to add effects to graph nodes. There are some already created effects (like echo effect) but there is also possibility to create custom audio effect. Custom audio eff...
This article solves this problem: https://blogs.windows.com/windowsdeveloper/2019/04/30/enhancing-non-packaged-desktop-apps-using-windows-runtime-components/ It is possible to use Registration-free WinRT (starting from Windows 10 1903) by modifying application manifest file (and not Windows Runtime Component Package ma...
63,731,226
63,732,314
c++ throw with try catch all always hits terminate in C++ 11 14 and 17
I keep getting terminate called for anything I throw using GCC 9.2, even if it is caught. terminate called after throwing an instance of 'char const*' terminate called recursively I have tested -std=c++17, -std=c++14, -std=c++11 Example test: #include <iostream> int main() { try { throw "not found"; } c...
It seems there is a bug or exception handling isn't working on version 9.2 of GCC (ARM only?) compiler. I tried with version 8.3-2019.03 - arm-linux-gnueabihf - Linux x86 compiler and they are working just fine. No other changes were necessary, other than the compile switch. https://developer.arm.com/tools-and-software...
63,731,983
63,732,690
How do I broadcast a WM_SETTINGCHANGE message?
The purpose is to firstly make a modification in the registry for my touchpad and then apply them by sending a WM_SETTINGCHANGE broadcast. Here is the link I have been looking on mostly: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-settingchange The registry I wanted to modify is: HKEY_CURRENT_USER\Softwa...
As stated in the documentation you linked to: Applications should send WM_SETTINGCHANGE to all top-level windows when they make changes to system parameters. (This message cannot be sent directly to a window.) To send the WM_SETTINGCHANGE message to all top-level windows, use the SendMessageTimeout function with the h...
63,732,175
63,732,510
C++ not reports error or warning with data type mismatch
Does C++ automatically cast data type based on function definition? I have following code: #include <iostream> using namespace std; void print_value(int i) { cout << "Here is an integer: " << i << endl; } int main() { int i = 5; float f = 3.3; print_value(i); print_value(f); return 0; } When...
When calling a function with a parameter T2 using a value of type T1 an implicit conversion is performed, if possible. All arithmetic types in C++ can be implicitly converted to one-another, although not always without loss of precision. Also see Implicit conversions. The particular conversion which takes place in your...
63,732,278
63,732,335
error: no match for call to ‘(std::string {aka std::basic_string}) ()’
my code: #include <stdio.h> #include <iostream> #include <string> using namespace std; class Person { public: string name; int age; }; void print (Person* person) { cout << person->name << "is " << person -> age << " years old" << endl; } int main() { Person person; person.name = "Ha...
You need to delete the parentheses after person. Because you try to access variable that named "name", however when you put that parenthesses think that it is a function. So that you need to do like this; #include <stdio.h> #include <iostream> #include <string> using namespace std; class Person { public: ...
63,733,353
63,734,947
What is the time complexity of this segment tree algorithm?
class SegTreeNode { public: int start; int end; int min; SegTreeNode *left; SegTreeNode *right; SegTreeNode(int start, int end) { this->start = start; this->end = end; left = right = NULL; } }; class Solution { public: int largestRectangleArea(vector<int>& heights) { if (heights.size() ...
Your reasoning is right. But why did you complicate the code so much by using Segment tree. It can be done using stacks also. Refer this:maximize-the-rectangular-area-under-histogram
63,733,643
63,733,672
console throws ; error with curly bracket initialization
When I run this hello world function: #include <iostream> /* welcome to your first c++ tutorial! Congrats lets have some fun :) */ int main() { std::cout << "hello world\n"; int e{ 2 }; std::cout << e; return 0; } I get this error: [Running] cd "/Users/tbarton/Documents/GitHub/c++ practice files/" &...
Maybe your compiler is older and not setup for c++11 (or higher). You could try: g++ main.cpp -o main -std=c++11 See your same code working here: https://godbolt.org/z/77oc5Y And here is the same code running -std=c++98: https://godbolt.org/z/aEszPb (with the error you are seeing) update since the above links might sto...
63,733,835
63,734,303
Lower bound in Set STL in c++
I understand that set is implemented as tree structure internally in c++ . So, how does lower_bound gets performed on it? I mean I understand for vector that you pick the middle element using the start and end indexes and perform binary search, but how does it get implemented for tree like structures?
Finding the lower_bound in a set is almost the same as searching for an element in the set. At the end of the search (navigating the tree) you've either found the node where the element is, or you find an element that is greater than the one you're looking for, but there aren't any nodes with a lower value in its subtr...
63,733,848
63,733,947
Python embed into C++
I have python codes ebmedded into C++. Do I need to release memory(Py_XDECREF) PyObject* pValue and PyObject *pArgs? When I do Py_XDECREF(pArgs) and Py_XDECREF(pValue) I have Segmentation Fault (Core dumped). I think python side is still using those variables and c++ try to release memory. What is the best practice for...
PyTuple_SetItem steals a reference to the item. You don't need to decref the item, because you no longer own a reference to it. You do need to decref the tuple. If you still get segfaults after that, you have some other bug.
63,734,015
63,734,100
My C++ program is deleted when I close my file explorer
I'm not exactly sure why my C++ programs are deleted in Visual Studio Code when I close my file explorer (that has the folder containing my C++ programs open). I get something like so: I'm not exactly sure what's wrong since my programs run just fine when the file explorer isn't closed. Does anyone know how to fix thi...
When you "open" a file from inside a zip archive, the Explorer temporarily extract the file. When you close the Explorer the temporary files are deleted. If you want to keep the files, you need to extract (copy out) the files from the archive to a permanent location.
63,734,295
63,735,911
Is it possible to access the arguments from an std::bind object?
Please consider the following scenario. A hypothetical pop-up menu class that displays some actions, and when one of them is selected it will call the passed in action which is in form of an std::function: PopupMenu::PopupMenu(std::function<void(RowItem*)> editRowFunction, RowItem *item) : _editRowFunction(editRowF...
std::bind(&EditorWidget::editRow, editorWidget, item) std::bind here is creating a functional object that takes a pointer to a member function EditorWidget::editRow, bound to an object editorWidget, using the parameter item. What you've done is actually fix the parameter to the function EditorWidget::editRow with th...
63,734,393
63,734,463
C++ how to print the first 10 and last 10 elements of an array?
im trying to print the first 10 and the last 10 elements of an array. My attempt below returns the following in an infinite loop Word: Count 0 void printarrayString(std::string arr[], int size) { int i; int j; std::cout << "***first 10 elements***" << std::endl; for (i = 10; i < size; i++)//print firs...
You have got the indices wrong. In C++ (and even in most programming languages) the base, or first element is located at index 0 (ever wonder why?). So, to print the first n elements, you need to iterate from i = 0 to i = n - 1, aka for(int i = 0; i < n; i++) and to print the previous n elements, you need to iterate fr...
63,734,847
63,734,884
findChild does not find menu just added to a QMenuBar
Here is my code snippet: void MainWindow::on_TestButton_triggered() { QMenu *m = menuBar()->addMenu("TestMenu"); auto *found = menuBar()->findChild<QMenu *>("TestMenu"); if ( !found ) MessageBox(NULL, "not found", "s", MB_OK); } It always produces the MessageBox. What can I do instead to get a po...
findChild uses the objectName to do the search but in your case QMenu does not have an objectName, so the solution is to set the objetctName: QMenu *m = menuBar()->addMenu("TestMenu") m->setObjetctName("TestMenu");
63,734,977
63,864,074
Issue Building C++ package with cmake: using Python .dylib, using 2.7 rather rather than 3.8, OS X
I'm trying to build a C++ "Plug-in" that is part of "Orthanc" (Open Source Project). I've been doing that on both UBUNTU and OS X, but I'm having trouble using a version of Python other than the system installed version (High Sierra, Python 2.7) on OS X. I've tried installing Python 3.8 using the OS X package from th...
Just a follow up to my question. I found that if I explicitly defined that paths for -DPYTHON_LIBRARY= and -DPYTHON_INCLUDE_DIR in the cmake, then it compiles fine and I can use various versions of Python on OS X if I want. I would imagine there is another more elegant way, but this works pretty well. cmake -DPYTHON_...
63,735,752
63,735,789
What is the meaning of comparing strings with >=
I am studying C++. I am surprised that it can compare strings. The following code compiles and runs successfully for strings a and b. if (b >= a) {} What does it mean?
All comparisons of std::string are lexicographical. See std::basic_string::operator>=. You can find an excellent answer which explains this in detail here: Using the less than comparison operator for strings. The operators < and >= are not equivalent, but the principle is the same.
63,736,126
63,736,162
Can we define two functions with same name but different parameters?
I am confused when we need to define another function we can give it a different name. But on LeetCode discussion, I found a popular post in which there are two functions with same name, but having different parameters. int longestPalindromeSubseq(string s) { return longestPalindromeSubseq(0,s.size()-1,s); } int l...
I am confused when we need to define another function we can give it a different name. The is the one of the most basic feature of C++: function overloading. In C you can't have two functions with the same name, at all. In C++, it's entirely possible as long as the function function signature is different, ie two fun...
63,736,553
63,736,728
MinGW treats second declaration of an object in a class as a Constructor
I am trying to write a class (let's call it Bar) that takes an object of another class (Foo) as an argument to the constructor. I also have an object of class Foo declared as an attribute of Bar. Here is some example code: #include <iostream> class Foo { public: Foo(int i) { std::cout << i; } }; class...
It's not the declaration that is treated as constructor call, but the member fooObject1 needs to be initialized in some way in Bar's constructor. So the compiler generates some code to call the default constructor Foo::Foo(). But that does not exist, so you get an error. One solution is to explicitly initialize the mem...
63,736,800
63,782,008
CMAKE: Wrong linker (g++) is used in executable to CUDA library link
I have a static CUDA-based library (mixture of .cu and .cpp files) which I am trying to link against a test file test.cu which will include a lib_file_1.cuh from the library. Thus I want to link my .cu executable to my CUDA library, and up until now g++ is used instead of nvcc in the linker step. How do I fix this? Bec...
Apparently, adding set_target_properties(my_library PROPERTIES CUDA_SEPARABLE_COMPILATION ON) to the CMakeLists.txt in root/my_library did the trick. I did try the option globally with set(CUDA_SEPARABLE_COMPILATION ON) in the CMakeLists.txt in the root directory, but that did not work. I dont know why.
63,736,935
63,737,670
How do I link the library correctly using cmake?
I have laid out my project directory below,so when I do cmake build I get a linker error which I wasn't able to figure out. I get a linker error that LIBD cannot be found, although LIBB is successfully formed and APP executable only needs LIBB why is it throwing a linker error that it needs LIBD when trying to build AP...
link_directories is scoped to the file containing it, in your case source/CMakeLists.txt, so apps/CMakeLists.txt does not know where to find LIBD. You should create an IMPORTED CMake target in the main CMakeLists.txt instead and link to that where you need it: add_library(LIBD IMPORTED) set_target_properties(LIBD PROPE...
63,737,086
63,737,411
C++ template metaprogramming for argument dispatch
I'm reading the source code of spconv, a sparse convolution library wrote by c++ (and cuda), in the source code I found a complicate template usage, and I summarize it as a minimum working example below: #include <iostream> #include <sstream> template<class... T> struct mp_list { }; template<class T, T... I> using mp...
So the first part, (minus useless part) // list of type template<class... T> struct mp_list { }; // list of type, which are integral_constant // so we can see it like a list of constexpr T // since we can use ::value on each type template<class T, T... I> using mp_list_c = mp_list<std::integral_constant<T, I>...>; t...
63,737,788
63,737,888
Can unused function-arguments become optimized away?
I'm trying to ensure an object - wrapped by a shared_ptr - is alive as long as a function is executed by passing it as value. However inside the function the object is not used at all, so I just want to use it for 'pinning': void doSomething(std::shared_ptr<Foo>) { // Perform some operations unrelated to the passed...
You don't need to worry - the lifetime of the function argument at the call site is guaranteed to survive the function call. (This is why things like foo(s.c_str()) for a std::string s work.) A compiler is not allowed to break that rule, subject to as if rule flexibility.
63,738,216
63,752,404
How to spawn 10 spheres in C++
Say I have chosen First Person template in UE IDE, and I am expected to create 10 spheres at distance of 1500 units. Also when one shoots some sphere then the sphere disappears. How do I create spheres in C++?
You would normally use the SpawnActor method in the UWorld class. You can find more info about the method here, but essentially you would get a reference to the world, call SpawnActor using that UWorld reference while passing in four parameters: the actor you want to spawn, which is usually of type TSubclassOf<AActor> ...
63,738,404
63,738,654
c++ libcurl and SSL setup for https read file
For my desktop sofware (Windows 7 - 10) I check version with read file on server and get information from it (read txt file). This is done, but i am not sure if I use SSL right setup and If need security for that simple thing (I am not sure how SSL works, I used some example from libcurl examples). I only read txt file...
Disabling SSL certificate validation opens you up to man/monster in the middle attacks. It only encrypts traffic for people who are passively intercepting your communication. Either get a commercial verifiable certificate, a free one from Let's encrypt, or a self-signed certificate where you explicitly trust the CA you...
63,738,539
63,739,565
Compile time size of data member std::array in non-class template (C++14)
Compile-time inspection std::array data member for its (compile time) size I need to statically assert that the compile-time size of a non-constexpr data member of type std::array, say arr_, of a non-template class is equal to a given (externally provided) constant. The static assertion will be done from inside the cla...
The standard provides a static version of array::size under the name tuple_size: #include <array> #include <tuple> // for std::tuple_size_v static_assert(std::tuple_size<decltype(arr_)>::value == kAnotherArraySize, ""); static_assert(std::tuple_size_v<decltype(arr_)> == kAnotherArraySize); // C++17
63,738,572
63,774,311
AES IV into file with FileSource and FileSink
I have the need to crypt big files (multi GB) with crypto++. I managed to find an example on the documentation that helped me create the 2 followings functions : bool AESEncryptFile(const std::string& clearfile, const std::string& encfile, const std::string& key) { try { byte iv[CryptoPP::AES::BLOCKSIZ...
Thanks to all the differents comments here is what i managed to do. As suggested by @Sam Mason i put the iv at the beginning of the file : So before starting to encrypt i 'm putting the iv at the beginning of the file: CryptoPP::ArraySource(iv, sizeof(iv), true, new CryptoPP::Redirector(sink) ); // Encrypt And the...
63,738,738
63,742,674
unable to write /proc/sys/kernel/ns_last_pid file
I want to edit the ns_last_pid file present in /proc/sys/kernel, but i'm getting the error of Read-only file system. How to resolve this? This is what i've written to open the file. int fd = open("/proc/sys/kernel/ns_last_pid", O_RDWR | O_CREAT, 0644); if (fd < 0) { cout<<strerror(errno)<<"\...
For a program to change kernel files, it should be owned by root sudo chown root program // program is the executable(the binary) set the setuid bit on the executable to execute a program with superuser access. with this it will run as root even if we execute it as any user on our machine. sudo chmod u+s program Co...
63,739,112
63,739,368
How to make a constructor similar to multidimensional vectors?
For a vector type, we can do this: vector<vector<int>> v = {{1, 2, 3}, {4, 5, 6}}; I'm trying to do the same for a custom class SomeClass, so that I can do: SomeClass a = {{1, 2, 3}, {4, 5, 6}}; How do I write the constructor for SomeClass to achieve this?
What you're looking for is std::initializer_list for which you can find a good documentation here. If you define your SomeClass as follows: template <typename T> class SomeClass { public: SomeClass(std::initializer_list<std::initializer_list<T>> param) { //... } }; Then you will...
63,739,198
63,739,496
Iterator or std::iota with regular C++ Array?
Is there a way to achieve the same effect as this, std::list<int> l(10); std::iota(l.begin(), l.end(), -4); With a regular int a[]? Or, is the following the only way around: for (iterator itr = begin; itr != end; ++itr) /* ... visit *itr here ... */
C++11 added std::begin and std::end. Since then there is no difference: std::list<int> l(10); std::iota(std::begin(l),std::end(l), -4); int a[10]; std::iota(std::begin(a),std::end(a), -4);
63,739,658
63,739,933
Get a std::list::iterator from std::reference_wrapper
I'm coding a Fibonacci heap data structure (https://en.wikipedia.org/wiki/Fibonacci_heap) in C++. This data structure consists of several heaps, with roots connected in a doubly-linked list. Each node has a doubly-linked list of its children. A whole heap has a doubly-linked list of leaf nodes, to support fast pruning....
Using a std::list<Node*> would not cause any double deletes, as long as you don't manually delete nodes, and let the actual unique_ptr pointers in child_list members handle that. You would just need to be careful to avoid using a dangling pointer after a Node has been destroyed. But this way still doesn't give a good w...
63,739,728
63,739,778
How do C++ compiler interpret comparison logic in string/character?
When we compare numbers in a string/character format, how does the c++ compiler interpret it? The example below will make it clear. #include <iostream> using namespace std; int main() { // your code goes here if ('1'<'2') cout<<"true"; return 0; } The output is true What is happening inside the compi...
'1' is a char type in C++ with an implementation defined value - although the ASCII value of the character 1 is common, and it cannot be negative. The expression arr['a'] is defined as per pointer arithmetic: *(arr + 'a'). If this is outside the bounds of the array then the behaviour of the program is undefined. Note t...
63,739,935
63,740,805
Why do we access the value of the bytes pointed at by the char* instead of the value of the pointers?
From previous questions in the topic, I've understood that the pointer points to the first character of a string, and expects the following characters to take part of the string until a null character. My question is how does this declaration for example work: const char* name = "abc"; As far as I understand, the va...
const char* name = "abc"; is basically short for: // compiler makes up a random name static const char _abc_string_235o8v3tiue[4] = {'a', 'b', 'c', '\0'}; const char* name = _abc_string_235o8v3tiue; which is short for: // compiler makes up a random name static const char _abc_string_235o8v3tiue[4] = {'a', 'b', 'c', ...
63,740,056
63,767,646
Variadic macros with zero arguments doesn't compile even with ##__VA_ARGS__
If I try to compile the following code: template <typename... TArgs> void Dummy(const TArgs &...args) { } #define DUMMY(...) Dummy("Hello", ##__VA_ARGS__) int main() { DUMMY(); } I get the following compilation error: g++ -std=c++17 -O3 -Wall main.cpp && ./a.out main.cpp: In function 'int main()': main.cpp:6:48:...
An important fact about C/C++ macros is that it is impossible to invoke them with no parameters, because a macro parameter is allowed to be an empty token sequence. Consequently, DUMMY() invokes the macro DUMMY with a single empty parameter, not with zero parameters. This explains why the second example works, and it a...
63,740,250
63,740,300
std:find() for sorted vs unsorted
Consider two integer vectors v1 and v2, where v1 is sorted and v2 is not sorted. What would be the time complexities to search for an element in these two vectors using find()?
std::find() performs linear search, i.e., it goes element by element until it finds the value it's looking for. It is linear regardless of whether or not the collection is sorted. If you have a sorted vector, you may want to consider performing binary search with std::lower_bound() instead. This will be logarithmic in ...
63,740,618
63,741,431
Need for std::decay in noexcept operator?
The following code requires using std::decay inside noexcept operator in gcc, but not in clang. template<typename... Ts> class B; template<typename T> class B<T> { T t; public: template<typename U> constexpr B(U&& t) // without decay - strange behavior in gcc, see main below <=== noexcept(noexcept...
Following the remark by @Marek R it seems to be a bug in gcc. A bug was opened on gcc. The following case also fails with gcc and not with clang: template<typename T, typename U> auto convert(U&& t) { // fails on gcc: return T{std::forward<U>(t)}; // works ok if it is not brace initialization: // return...
63,740,929
63,740,954
Where is getline() function coming from?
I am starting learning C++ a little while ago. Came to know about header files and preprocessor statements. I know that std::cin and std::cout are the objects/Function is declared in standard library IOSTREAM. But when taking input as a string and to read the whole line. We have to getline() function or at least the in...
You have to include the header <string> to use the function std::getline. It is implementation defined whether the header <iostream> includes the header <string>. In this call using unqualified name getline getline(std::cin, str); the compiler applies the argument dependent lookup ADL (the first argument std::cin is d...
63,740,935
63,742,606
C++ Qt inherit from custom widget
I'm working on a project with Qt and C++. Now my Question is: Is inheritance possible in UI classes? For example: This is the Widget I want to inherit from //windowA.h namespace Ui { class WindowA; } class WindowA : public QWidget { Q_OBJECT public: explicit WindowA(QWidget *parent = nullptr); ~AddWin...
If I understand your question correctly, all you need to do is change what text you set on the button in your constructor: WindowB::WindowB(QWidget *parent) : WindowA(parent) { button->setText("Something else!"); }
63,740,938
63,741,533
Using pointer to inner class object as outer class constructor argument in C++
Like I said in the title, I can't pass an inner class object as argument for outer class' constructor. Below is the class header; class Corner { public: Corner(cv::Mat imageMat, int flag, feat::Corner::cornerDetectorHarris* cdh = nullptr); ... class cornerDetectorHarris {...}; ... }; Visual Studio Co...
Simply declare the inner class before any methods that depend on it. You can of course even define the methods in the header if you so wish. Not really sure why you would do it this way though; why not simply have cornerDetectorHarris declared outside and before Corner? There is some useful discussion on the topic her...
63,741,179
63,792,812
How to pass a callback to EM_ASM for c++?
I do not know how to pass the value asynchronously to EM_ASM, here's how I try to do it (but JS says it's not a function): const auto testFunc = [] (const char* data) { printf("data: %s\n", data); } EM_ASM_( { var funcResult = ($0); var text = "data"; var lengthBytes = lengthBytesUTF8(text) + 1; var...
I don't know about passing callbacks, but if what you want to do is to return a value from JS, then the docs have such an example: you have to use EM_ASM_INT instead: int x = EM_ASM_INT({ console.log('I received: ' + $0); return $0 + 1; }, 100); printf("%d\n", x); The API reference has another example for returnin...