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,003,865
71,004,279
Function as template argument that has a different structure depending on method
I am writing a routine to find the numerical roots of a function in C++. Depending on the algorithm, I can supply either the function or both the function and derivative. For example, I have two separate routines template <typename T, typename Func> T Bisection(Func func, T x) { // algorithm details... auto f = func(x); // more details... } template <typename T, typename Func> T Newton(Func func, T x) { // algorithm details... auto [f, df] = func(x); // more details... } Note that one method assumes that the Func type will be a simple one-variable function, whereas the other assumes it is some structure that contains both the function 'f' and the derivative 'df'. Both of these routines seem to work for my tests so far. I would like to write a master routine which accepts a parameter method, which selects either of these with a switch statement. What I have in mind is: enum Method { Bisection, Newton }; template <typename T, typename Func> T find_root(Func func, T x, Method method) { switch(method) { case Bisection: return Bisection(func, x); case Newton: return Newton(func, x); default: // do other stuff... } } This does not compile. If I write a routine with method = Bisection for example, I get error error: cannot decompose non-array non-class type 'const float' because the Newton method needs a different structure for the binding, even though I am not using it. Is there a generic way I can circumvent this to allow for a uniform master method? I have another method which the user supplies the function and first and second derivative, so that structure has three components.
The problem is that in your case you are instantiating both functions for the types that doesn't fit the implementation. You may try if constexpr, but for this case you need to move the method parameter the template parameters: enum class Method { Bisection, Newton }; template <Method method, typename T, typename Func> T find_root(Func func, T x) { if constexpr (method == Method::Bisection) { return Bisection(func, x); } else if constexpr (method == Method::Newton) { return Newton(func, x); } else { } } In this case the compiler will not instantiate the functions for the branches where expression is false (note that for the compiler to eliminate the false branches the expression needs to depend on the template parameters).
71,004,156
71,004,219
How to pass struct array arguments to a function the right way?
Source Code: #include <iostream> using namespace std; struct Employee { string name; int age; float salary; }; void displayData(Employee); int main() { Employee employee[3]; int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]); for(int i = 0; i < sizeOfEmployee; i++) { cout << "Enter name for employee " << i + 1 << ": "; cin >> employee->name; cout << "Enter age for employee " << i + 1 << ": "; cin >> employee->age; cout << "Enter salary for employee " << i + 1 << ": "; cin >> employee->salary; } for(int i = 0; i < sizeOfEmployee; i++) { displayData(employee[i]); } } void displayData(Employee employee) { cout << "DISPLAYING INFORMATION" << endl; cout << "Name: " << employee.name << endl; cout << "Age: " << employee.age << endl; cout << "Salary: " << employee.salary << endl; } My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted. CODE OUTPUT: In what way could i possibly get all the data i've stored into the array and display it?
You are reading data into a pointer to the first element of the array. To read into n-th element your code should be using indexing, like cin >> employee[i].name;. However... "Naked" arrays are a source of many errors, subtle bugs, and generally unsafe code. Consider using std::array instead - this will eliminate the need for code like int sizeOfEmployee = sizeof(... and will nicely encapsulate that array as a parameter to a function: #include <array> int main() { std::array<Employee, 3> employee; for(int i = 0; i < employee.size(); i++) { cout << "Enter name for employee " << i + 1 << ": "; cin >> employee[i].name; // the rest of that for loop... } // and the second loop becomes: for(const auto& e: employee) { displayData(e); }
71,004,340
71,004,714
How to optimize mesh normals calculation?
I am making an application for real time mesh deformation and I need to calculate normals a huge number of times. Now the problem is I found with some profiling this bit of code is taking largest cpu time so how can I possibly optimize this? void Mesh::RecalculateNormals() { for (int i = 0; i < indexCount; i += 3) { const int ia = indices[i]; const int ib = indices[i + 1]; const int ic = indices[i + 2]; const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position); const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position); const glm::vec3 no = cross(e1, e2); vert[ia].normal += glm::vec4(no, 0.0); vert[ib].normal += glm::vec4(no, 0.0); vert[ic].normal += glm::vec4(no, 0.0); } for (int i = 0; i < vertexCount; i++) vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f); } Also before this function is called I must loop through all vertices and clewr the previous normals by setting normals to vec3(0). How can I speed this up? Could there be a better algorithm? Or is GLM slow?
There is three main ways to optimize this code: using SIMD instructions, using multiple threads and working on the memory access pattern. None of them is a silver-bullet. Using SIMD instructions is not trivial in your case due to the indices-based indirect data-dependent read in memory in the first loop. That being said, recent SIMD instruction sets like AVX-2/AVX-512 on x86-64 processors and SVE on ARM ones provides instructions to perform gather loads. Once the values are loaded in SIMD registers, you can compute the cross product very quickly. The thing is the last indices-based indirect data-dependent stores in the first loop require scatter store instruction which are only available on very recent processors supporting AVX-512 (x86-64) and SVE (ARM). You can extract the values from SIMD registers so to store them serially but this will certainly quite inefficient. Hopefully, the second loop can be much more easily vectorized but you certainly need to reorder the normal data structure in a way that is more SIMD-friendly (see AoS vs SoA and Data-oriented design). In the end, I expect the SIMD implementation not much faster for the first loop as long as scater instructions are not used, and certainly significantly faster for the second one. Actually, I expect the SIMD implementation of the first loop not to be a lot faster even with gather/scatter instructions since such instructions tend to be quite inefficiently implemented and also because I expect the first loop of your code to cause a lot of cache misses (see the next sections). Using multiple thread is also not trivial. Indeed, while the first part of the first loop can be trivially parallelized, the second part performing the accumulation of the normal cannot. One solution is to use atomic adds. Another solution is to use a per-thread array of normal vectors. A faster solution is to use partitioning methods so to split the mesh in independent parts (each threads can safely perform the accumulation, except for possibly-shared vect items). Note that efficiently partitioning a mesh so to balance the work between many threads is far from being simple and AFAIK it has been the subject of many past research papers. The best solution is very dependent of the number of threads, the size of the overall vert buffer in memory and your performance/complexity requirements. The second loop can be trivially parallelized. The simplest solution to parallelize the loops is to use OpenMP (few pragma are enough to parallelize the loops although an efficient implementation can be quite complex). Regarding the input data, the first loop can be very inefficient. Indeed, ia, ib and ic can refer to very different indices causing predictable vert[...] loads/stores in memory. If the structure is big, the loads/stores will cause cache misses. Such cache misses can be very slow is the data structure does not fit in RAM due to the huge latency of the RAM. The best solution to fix this problem is to improve the locality of the memory accesses. Reordering vert items and/or indices can help a lot to improve locality and so performance. Again, partitioning methods can be used to do that. A naive first start is to sort vert so that ia is sorted while updating ib and ic indices so they are still valid. This can be computed using key-value arg-sort. If the mesh is dynamic, the problem becomes very complex to solve efficiently. Octrees and k-D trees could help to improve the locality of the computation without introducing a (too) big overhead. Note that you may not need to recompute all the normals regarding the previous operations. If so, you can track the one that needs to be recomputed and only perform an incremental update. Finally, please check compilers optimizations are enabled. Moreover, note that you can use the (unsafe) fash-math flags so to improve the auto-vectorization of your code. You should also check the SIMD instruction set used and that the glm calls are inlined by the compiler.
71,004,636
71,004,658
how to complement the values of std::vector<bool> using range for loop taking element by reference
I need to complement the values of std::vector<bool>. So I thought of using range for loop taking elements by reference. But the compiler is giving me the below error error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference' 13 | for (auto& bit : rep) This is my sample code #include <iostream> #include <vector> int main() { std::vector<bool> rep; rep.push_back(true); rep.push_back(false); rep.push_back(true); rep.push_back(false); rep.push_back(true); rep.push_back(false); for (auto& bit : rep) bit = !bit; }
you can bind them (the returned proxy object) to rvalue reference for (auto&& bit : rep) bit = !bit; godbolt
71,004,642
71,005,010
I want to change the location of .sln and .vcxproj
below one is the current project structure. - project - bin - obj - include - src * a.cpp * project.sln * project.vcxproj But I want to create new directory "project". And move .sln and .vcxproj file into "project" directory. - project - bin - obj - include - project * project.sln * project.vcxproj - src * a.cpp Here problem occurred. Because <ItemGroup> components of vcxproj do not update itself, so .sln cannot load all of my files. In other words, originally a.cpp is written as "src/a.cpp" in .vcxproj file. but after moving .vcxproj, it still remains as "src/a.cpp" not "../src/a.cpp". I also saw VS 2010, change location of project file. But I could not find the automatic way to update vcxproj when it is moved. Is there any way to achieve it ? or I have to change all of components of .vcxproj manually?
Visual Studio just allows to save the solution file .sln at another location. Just select the Solution in the Solution Explorer, go to menu item File -> Save >MySolution.sln> As... and save it under another name and/or location. The project file .vcxproj itself cannot be relocated by a Visual Studio option/menu item. Therefore this has to be done manually and all the pathes to source, resource files etc. shall be updated by the help of a powerful text editor, e.g. Notepad++ PSPad TextPad just doing a search and replace. Checked with Visual Studio version 16, hence VS 2019. Maybe this option will be available in a future version of Visual Studio.
71,004,667
71,005,153
Short way to constrain template parameter without boiler plate code for a struct
consider this example: #include <iostream> template <typename T, std::size_t I> struct Foo { }; template <typename T> struct specializes_foo : std::false_type {}; template <typename T, std::size_t I> struct specializes_foo<Foo<T, I>> : std::true_type {}; template <typename T> concept foo = specializes_foo<T>::value; int main() { std::cout << foo<int> << "\n"; std::cout << foo<Foo<int,3>> << "\n"; } is there a shorter way in C++20? I know that you could do a concept for "specializes template", e.g.: // checks if a type T specializes a given template class template_class // note: This only works with typename template parameters. // e.g.: specializes<std::array<int, 3>, std::array> will yield a compilation error. // workaround: add a specialization for std::array. namespace specializes_impl { template <typename T, template <typename...> typename> struct is_specialization_of : std::false_type {}; template <typename... Args, template <typename...> typename template_class> struct is_specialization_of<template_class<Args...>, template_class> : std::true_type {}; } template <typename T, template <typename...> typename template_class> inline constexpr bool is_specialization_of_v = specializes_impl::is_specialization_of<T,template_class>::value; template <typename T, template <typename...> typename template_class> using is_specialization_of_t = specializes_impl::is_specialization_of<T,template_class>::type; template<typename T, template <typename...> typename template_class> concept specializes = is_specialization_of_v<T, template_class>; However, this fails with non-type template parameters such as "size_t". Is there a way so I could, for example just write: void test(Foo auto xy); I know that since C++20 there came a couple of other ways to constrain template parameters of a function, however, is there a short way to say "I dont care how it specializes the struct as long as it does"?
Nope. There's no way to write a generic is_specialization_of that works for both templates with all type parameters and stuff like std::array (i.e. your Foo), because there's no way to write a template that takes a parameter of any kind. There's a proposal for a language feature that would allow that (P1985), but it's still just a proposal and it won't be in C++23. But it directly allows for a solution for this. Likewise, the reflection proposal (P1240) would allow for a way to do this (except that you'd have to spell the concept Specializes<^Foo> instead of Specializes<Foo>). Until one of these things happens, you're either writing a bespoke concept for your template, or rewriting your template to only take type parameters.
71,004,750
71,088,878
Arduino IR Transmittor not working with my TV
I try to do my DIY project with Arduino and IR transmitter. I connected and written code as per mentioned in web. but it is not working properly. connections: first IR pin connected to Ground second IR pin connected to TX #include <IRremote.h> IRsend irsend; void setup() {} void loop() { irsend.sendRC5(0x1FC1, 32); delay(5000); } This is my code in Arduino for checking in serial monitor i used below code #include <IRremote.h> const int RECV_PIN = 2; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { Serial.begin(9600); irrecv.enableIRIn(); irrecv.blink13(true); } void loop() { if (irrecv.decode(&results)) { if (results.decode_type == NEC) { Serial.print("NEC: "); } else if (results.decode_type == SONY) { Serial.print("SONY: "); } else if (results.decode_type == RC5) { Serial.print("RC5: "); } else if (results.decode_type == RC6) { Serial.print("RC6: "); } else if (results.decode_type == UNKNOWN) { Serial.print("UNKNOWN: "); } Serial.println(results.value, HEX); irrecv.resume(); } } reference: https://www.pjrc.com/teensy/td_libs_IRremote.html results- serial monitor: from remote: RC5: 1FC1 from Arduino: RC5: 1FC1 both are same. but still my TV not working with Arduino but working with original remote what could be the issue?
I got answer, even it shows warning, I can control my TV and other by below code. instead of RC5 I used NEC #include <IRremote.h> IRsend irsend; void setup() {} void loop() { irsend.sendNEC(0x1FC1, 32); delay(5000); }
71,005,029
71,005,071
Program works on GCC 7.5 on PC but not on online compiler
I have the following program that compiles successfully on my machine using GCC 7.5.0 but when i try out the program here the program doesn't work. class Foo { friend void ::error() { } }; int main() { return 0; } The error here says: Compilation failed due to following error(s). 3 | friend void ::error() { } | ^ My question what is the problem here and how can i solve it.
The problem is that a qualified friend declaration cannot be a definition. In your example, since the name error is qualified(because it has ::) so the corresponding friend declaration cannot be a definition. This seems to be a bug in GCC 7.5.0. For example, for gcc 7.5.0 the program works but for gcc 8.4.0 and higher it doesn't work. One way to solve thiswould be to remove the body { } of the error function and make it a declaration by adding semicolon ; as shown below: //forward declare function error() void error(); class Foo { friend void ::error();//removed the body { } . This is now a declaration and not a definition }; int main() { return 0; } //definition of function error void error() { } Note you can also put the definition of function error() before the definition of class Foo as shown here. Another way to solve this would be to remove the :: and make error an unqualified name as shown here
71,005,607
71,005,680
how to index a numeric value to return a string
I have this enum enum CombatType_t { COMBAT_ICEDAMAGE = 1 << 9, // 512 COMBAT_HOLYDAMAGE = 1 << 10, // 1024 COMBAT_DEATHDAMAGE = 1 << 11, // 2048 }; Basically, im trying to make a new array/list to be able to index an string by using a specific number to index CombatType_t Something as the following: enum AbsorbType_t { "elementIce" = 512, "elementHoly" = 1024, "elementDeath" = 2048 } In Lua, for example I could make an associative table local t = { [512] = "elementIce"; } And then, to index i could simply do t[512] which returns "elementIce" How can I do this in C++?
In C++, the standard way to make an associative table is std::map: #include<iostream> #include<map> #include<string> ... std::map<unsigned, std::string> absorbType = { {512, "elementIce"}, {1024, "elementHoly"}, {2048, "elementDeath"} }; // Access by index std::cout << "512->" << absorbType[512] << std::endl;
71,005,801
71,014,967
Simplify chained expression in ANTLR listener
I have an ANTLR listener for C++ where I want to get the name of a member declarator. Currently, I'm using this approach: def enterMemberDeclarator(self, ctx: CPP14Parser.MemberDeclaratorContext): id = ctx.declarator().pointerDeclarator().noPointerDeclarator().noPointerDeclarator().declaratorid().idExpression().unqualifiedId() which is just a horrible expression. I feel like there should be some way of getting the id immediately without having to go down that rabbit hole. Additionally, some of these expressions might be None so I fear that I would have to make even more effort to get to the result... The grammar is from here
ANTLR4 supports XPath expressions to find specific nodes (see the documentation). That's somewhat easier to read than your expression, especially when you have to check for null: ids = XPath.findAll(ctx, "/declarator/pointerDeclarator/noPointerDeclarator/noPointerDeclarator/declaratorid/idExpression/unqualifiedId") (this is just pseudo code, I don't know python well).
71,005,923
71,011,823
SIMD code for mesh normals calculation not working (Trying to convert C++ to SIMD)
C++ Code void Mesh::RecalculateNormals() { for (int i = 0; i < indexCount; i += 3) { const int ia = indices[i]; const int ib = indices[i + 1]; const int ic = indices[i + 2]; const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position); const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position); const glm::vec3 no = cross(e1, e2); vert[ia].normal += glm::vec4(no, 0.0); vert[ib].normal += glm::vec4(no, 0.0); vert[ic].normal += glm::vec4(no, 0.0); } for (int i = 0; i < vertexCount; i++) vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f); } New Code with SIMD // From : https://geometrian.com/programming/tutorials/cross-product/index.php [[nodiscard]] inline static __m128 cross_product(__m128 const& vec0, __m128 const& vec1) { __m128 tmp0 = _mm_shuffle_ps(vec0, vec0, _MM_SHUFFLE(3, 0, 2, 1)); __m128 tmp1 = _mm_shuffle_ps(vec1, vec1, _MM_SHUFFLE(3, 1, 0, 2)); __m128 tmp2 = _mm_mul_ps(tmp0, vec1); __m128 tmp3 = _mm_mul_ps(tmp0, tmp1); __m128 tmp4 = _mm_shuffle_ps(tmp2, tmp2, _MM_SHUFFLE(3, 0, 2, 1)); return _mm_sub_ps(tmp3, tmp4); } void normalize(const glm::vec4& lpInput, glm::vec4& lpOutput) { const __m128& vInput = reinterpret_cast<const __m128&>(lpInput); // load input vector (x, y, z, a) __m128 vSquared = _mm_mul_ps(vInput, vInput); // square the input values __m128 vHalfSum = _mm_hadd_ps(vSquared, vSquared); __m128 vSum = _mm_hadd_ps(vHalfSum, vHalfSum); // compute the sum of values float fInvSqrt; _mm_store_ss(&fInvSqrt, _mm_rsqrt_ss(vSum)); // compute the inverse sqrt __m128 vNormalized = _mm_mul_ps(vInput, _mm_set1_ps(fInvSqrt)); // normalize the input vector lpOutput = reinterpret_cast<const glm::vec4&>(vNormalized); // store normalized vector (x, y, z, a) } void Mesh::RecalculateNormals() { float result[4]; glm::vec4 tmp; for (int i = 0; i < indexCount; i += 3) { const int ia = indices[i]; const int ib = indices[i + 1]; const int ic = indices[i + 2]; __m128 iav = _mm_set_ps(vert[ia].position.x, vert[ia].position.y, vert[ia].position.z, 0.0f); __m128 ibv = _mm_set_ps(vert[ib].position.x, vert[ib].position.y, vert[ib].position.z, 0.0f); __m128 icv = _mm_set_ps(vert[ic].position.x, vert[ic].position.y, vert[ic].position.z, 0.0f); __m128 e1i = _mm_sub_ps(iav, ibv); __m128 e2i = _mm_sub_ps(icv, ibv); //const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position); //const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position); //const glm::vec3 no = cross(e1, e2); __m128 no = cross_product(e1i, e2i); //vert[ia].normal += glm::vec4(no, 0.0); //vert[ib].normal += glm::vec4(no, 0.0); //vert[ic].normal += glm::vec4(no, 0.0); _mm_storeu_ps(result, no); tmp = glm::make_vec4(result); vert[ia].normal += tmp; vert[ib].normal += tmp; vert[ic].normal += tmp; } for (int i = 0; i < vertexCount; i++) vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f); } But its not working. Please can anyone help finding the problems. (I am very new to SIMD)
Your correctness problem is probably caused by Intel screwing up the order of their _mm_set_ps and similar intrinsics. To create a vector with x, y, z floats in the first 3 lanes, write either _mm_set_ps( 0, z, y, x ) or _mm_setr_ps( x, y, z, 0 ). Here’s better primitive functions you gonna need for that. That code assumes you have at least SSE 4.1, that thing is introduced in the Intel Core 2 in 2007, and according to Steam survey the market penetration is 98.89% by now. // Load an FP32 3D vector from memory inline __m128 loadFloat3( const glm::vec3& pos ) { static_assert( sizeof( glm::vec3 ) == 12, "Expected to be 12 bytes (3 floats)" ); __m128 low = _mm_castpd_ps( _mm_load_sd( (const double*)&pos ) ); // Modern compilers are optimizing the following 2 intrinsics into a single insertps with a memory operand __m128 high = _mm_load_ss( ( (const float*)&pos ) + 2 ); return _mm_insert_ps( low, high, 0x27 ); } // Store an FP32 3D vector to memory inline void storeFloat3( glm::vec3& pos, __m128 vec ) { _mm_store_sd( (double*)&pos, _mm_castps_pd( vec ) ); ( (int*)( &pos ) )[ 2 ] = _mm_extract_ps( vec, 2 ); } // Zero out W lane, and store an FP32 vector to memory inline void storeFloat4( glm::vec4& pos, __m128 vec ) { static_assert( sizeof( glm::vec4 ) == 16, "Expected to be 16 bytes" ); vec = _mm_insert_ps( vec, vec, 0b1000 ); _mm_storeu_ps( (float*)&pos, vec ); } // Normalize a 3D vector; if the source is zero, will instead return a zero vector inline __m128 vector3Normalize( __m128 vec ) { // Compute x^2 + y^2 + z^2, broadcast the result to all 4 lanes __m128 dp = _mm_dp_ps( vec, vec, 0b01111111 ); // res = vec / sqrt( dp ) __m128 res = _mm_div_ps( vec, _mm_sqrt_ps( dp ) ); // Compare for dp > 0 __m128 positiveLength = _mm_cmpgt_ps( dp, _mm_setzero_ps() ); // Zero out the vector if the dot product was zero return _mm_and_ps( res, positiveLength ); } // Copy-pasted from there: https://github.com/microsoft/DirectXMath/blob/jan2021/Inc/DirectXMathVector.inl#L9506-L9519 // MIT license #ifdef __AVX__ #define XM_PERMUTE_PS( v, c ) _mm_permute_ps( v, c ) #else #define XM_PERMUTE_PS( v, c ) _mm_shuffle_ps( v, v, c ) #endif #ifdef __AVX2__ #define XM_FNMADD_PS( a, b, c ) _mm_fnmadd_ps((a), (b), (c)) #else #define XM_FNMADD_PS( a, b, c ) _mm_sub_ps((c), _mm_mul_ps((a), (b))) #endif inline __m128 vector3Cross( __m128 V1, __m128 V2 ) { // y1,z1,x1,w1 __m128 vTemp1 = XM_PERMUTE_PS( V1, _MM_SHUFFLE( 3, 0, 2, 1 ) ); // z2,x2,y2,w2 __m128 vTemp2 = XM_PERMUTE_PS( V2, _MM_SHUFFLE( 3, 1, 0, 2 ) ); // Perform the left operation __m128 vResult = _mm_mul_ps( vTemp1, vTemp2 ); // z1, x1, y1, w1 vTemp1 = XM_PERMUTE_PS( vTemp1, _MM_SHUFFLE( 3, 0, 2, 1 ) ); // y2, z2, x2, w2 vTemp2 = XM_PERMUTE_PS( vTemp2, _MM_SHUFFLE( 3, 1, 0, 2 ) ); // Perform the right operation vResult = XM_FNMADD_PS( vTemp1, vTemp2, vResult ); return vResult; } You should not expect high quality results with that algorithm. It computes per-vertex normals by accumulating triangle normals weighted by triangle’s area. This means if your mesh has both small and large triangles, the normals of the small triangles will be ignored, which is suboptimal. A better way is weighting normals by triangle’s angles at vertices. See this article for more information.
71,006,057
71,006,413
C++ wprintf format specifier for char16_t for printing unicode string
I have the following code successfully compiled: #include <io.h> #include <fcntl.h> #include <iostream> #include <cstddef> #include <cstdio> int main() { _setmode(_fileno(stdout), _O_U16TEXT); char16_t chinese[] = u"\u4e66\u4e2d\u81ea\u6709\u9ec4\u91d1\u5c4b"; wprintf(L"String written with unicode codes: %ls \n", chinese); wchar_t arabic[] = L"أَبْجَدِيَّة عَرَبِيَّة"; wprintf(L"String written with L-String: %ls \n", arabic); std::wcout << std::endl; std::system("PAUSE"); } It prints: String written with unicode codes: 书中自有黄金屋 String written with L-String: أَبْجَدِيَّة عَرَبِيَّة However, the compiler issues a warning for chinese case (not for arabic case): warning C4477: 'wprintf' : format string '%ls' requires an argument of type 'wchar_t *', but variadic argument 1 has type 'char16_t *' What would be then the correct wprintf format string?
wchar_t is not the same as char16_t. wchar_t are 2 byte characters on windows, but (usually) 4 byte characters on linux. This is like the int vs. int16_t problem. The standard does not define wchar_t. So the question is not what format specifier to use with wprintf. It's rather how to convert a char16_t string to a wchar_t string. Under Windows you might get away with simply casting a char16_t to a wchar_t, which is what happens implicitly with wprintf, since it does not actually validate it's parameters. The warning C4477 is just a little help by the (Visual Studio?) compiler hinting at your problem. But on other platforms you have to actually convert the string. So the best solution would be something like this: wprintf("%ls", boost::utf16_to_wchar_t(chinese)); (I am just throwing in boost here, since they have conversion functions. I don't know the exact function to use). Or alternatively use wchar_t escape sequences and define your chinese as a wchar_t* string.
71,006,098
71,006,331
Why does this OpenGL + WIN32 code produce Vertical lines?
To be clear, I've extensively tested this code and found the issue is somewhere with the code written prior to the WGL code. It's precisely in the WIN32 code. Now I think it could partially be caused by calling gluOrth2D but even then, that shouldn't be the primary cause as far I as I understand. I may figure this out myself just by messing with stuff but considering this issue (that occured in a much larger project) has taken up a lot of my time I thought it was worth posting this encase anyone else runs into the same problem. I'm hoping for an explanation as well as fix/correction. #include <GL/glew.h> #include <glfw3.h> #define GLFW_EXPOSE_NATIVE_WGL #define GLFW_EXPOSE_NATIVE_WIN32 #include <glfw3native.h> constexpr int width = 1000, height = 1000; bool running = true; LRESULT CALLBACK WIN32_processMessage(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { return DefWindowProcA(hwnd, msg, wparam, lparam); } int main() { HINSTANCE hinst = GetModuleHandleA(NULL); HICON icon = LoadIcon(hinst, IDI_APPLICATION); WNDCLASSA* wc = (WNDCLASSA*)memset(malloc(sizeof(WNDCLASSA)), 0, sizeof(WNDCLASSA)); if (wc == NULL) { return -1; } wc->style = CS_DBLCLKS; wc->lpfnWndProc = WIN32_processMessage; wc->cbClsExtra = 0; wc->cbWndExtra = 0; wc->hInstance = hinst; wc->hIcon = icon; wc->hCursor = LoadCursor(NULL, IDC_ARROW); wc->hbrBackground = NULL; wc->lpszClassName = "toast_window_class"; if (!RegisterClassA(wc)) { return 1; } UINT32 windowX = 100; UINT32 windowY = 100; UINT32 windowWidth = width; UINT32 windowHeight = height; UINT32 windowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION; UINT32 windowExStyle = WS_EX_APPWINDOW; windowStyle |= WS_MAXIMIZEBOX; windowStyle |= WS_MINIMIZEBOX; windowStyle |= WS_THICKFRAME; RECT borderRect = { 0,0,0,0 }; AdjustWindowRectEx(&borderRect, windowStyle, 0, windowExStyle); windowX += borderRect.left; windowY += borderRect.top; windowWidth += borderRect.right - borderRect.left; windowWidth += borderRect.bottom - borderRect.top; HWND window = CreateWindowExA(windowExStyle, "toast_window_class", (LPCSTR)"test", windowStyle, windowX, windowY, windowWidth, windowHeight, 0, 0, hinst, 0); if (window == 0) { return 2; } bool shouldActivate = true; const int showWindowCommandFlags = shouldActivate ? SW_SHOW : SW_SHOWNOACTIVATE; ShowWindow(window, showWindowCommandFlags); // WGL ----------------------------------------------------------- HDC device = GetDC(window); PIXELFORMATDESCRIPTOR pfd; pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cAlphaBits = 0; pfd.cAccumBits = 0; pfd.cDepthBits = 0; pfd.cStencilBits = 0; pfd.cAuxBuffers = 0; pfd.iLayerType = PFD_MAIN_PLANE; SetPixelFormat(device, ChoosePixelFormat(device, &pfd), &pfd); HGLRC render = wglCreateContext(device); wglMakeCurrent(device, render); // GLEW --------------------------------------------------------- const GLint res = glewInit(); if (GLEW_OK != res) { return 1; } // setup OpenGL -------------------------------------------------- gluOrtho2D(0, width, 0, height); // main loop ----------------------------------------------------- while (running) { glClear(GL_COLOR_BUFFER_BIT); // rendering glBegin(GL_POINTS); for (int x = 10; x < width - 10; ++x) { for (int y = 10; y < height - 10; ++y) { glVertex2f(x, y); } } glEnd(); SwapBuffers(device); } return 0; }
Don't use GL_POINTS for drawing an image pixel-by-pixel. For one, it's probably the most inefficient way (on any system, in any configuration) to go about, due to the way OpenGL, its implementations, and modern GPU do work. Instead – if using OpenGL – create a 2D array of the desired size, fill in the pixel values to your desire, then load the picture into a texture and draw a textured quad, or better yet a rectangle covering triangle which you crop using glScissor. Back to your point-to-point drawing problems. The issue you're running is essentially rounding errors and the way OpenGL is transforming between modelview space, over projection space into NDC and finally the viewport. BTW, you're not calling glViewport, so any adjustments in window size are not taken into account. The call to glOrtho2D will setup the transformation matrix (in your case the modelview, since you didn't bother to switch to the projection matrix) so that coordinates in the range [0; width]×[0; height] will map to NDC coordinates [-1; 1]×[-1; 1]. These ranges are closed, i.e. they do include their limiting values. However pixels in a pixel grid are addressed in a range over the integer numbers with the end of the range being open (i.e. ℤ²∩[0; width(×[0; height(). And that means, that if you use the viewport extents for an orthogonal projection without adjustment, there'll be an ever so slight difference between pixel indices and OpenGL coordinates. I'll leave it to you, as an exercise, to figure out the math for what kind of adjustment to make (hint, you'll have to subtract a certain fractional value of the viewport extents to some of the glOrtho parameters). Now for certain window sizes you won't notice this problem, because for all "pixel" locations you put into OpenGL the round off will happen to coerce them toward your desired pixel locations. But for other window sizes, for certain coordinate values, the round off goes the other way, and you're left with columns and/or rows untouched. Which leads to the lines you're seeing sometimes.
71,006,368
71,006,458
Why does gcc throw warning about conditionally-supported offsetof?
I have two structures in c++ struct Vertex { float x,y,z; float nx, ny, nz; }; struct SkinnedVertex : public Vertex { uint32_t j0, j1, j2, j3; float w0, w1, w2, w3; } Now, when I use offsetof to get offset of Vertex, everything is fine but if I use offsetof in SkinnedVertex, I get the following warning when compiling with GCC: warning: offsetof within non-standard-layout type ‘SkinnedVertex’ is conditionally-supported My guess is that this happens because I am inheriting SkinnedVertex from Vertex, which makes this a non-standard-layout. But why does this happen? Does inheritance add additional information that makes this a non standard layout? Is thee a way to enforce it so that both of these structures are in standard layout? EDIT: Changed jN types to uint32_t (was float)
https://en.cppreference.com/w/cpp/named_req/StandardLayoutType A standard layout type requires all data members be in the same type. Standard layout is conservative in definition. Additional types could be made standard layout. The fact that a type is not standard layout doesn't mean there is a good reason that it isn't. It just means the standard committee and compilers haven't done the work to justify it. I mean, you could make classes with virtual functions standard layout if the committee really wanted (like, standardize how vtables work). One concern is that the committee doesn't want to needlessly break existing code. So they try to standardize existing practice unless there is a good reason. If two compilers disagree on layout of a class, that makes standardizing their layout more costly and/or generate less benefits. Standard layout is technically just a flag; semantically it means different compilers with similar options (like packing) are going to compile compatible data layouts.
71,006,407
71,010,303
Generically wrap member function of object to modify return type
Version restriction: C++17. I'm trying to create a type capable of accepting a callable object of any type and wrapping one of its member functions (in this case, operator()) to take the same arguments, but modify (cast) the return type. An example follows: template <typename Ret, typename Callable> struct ReturnConverter : Callable { ReturnConverter(Callable cb) : Callable(cb) { } Ret operator()(argsof(Callable::operator()) args) // magic happens here { return static_cast<Ret>(Callable::operator()(std::forward<??>(args)); // how to forward? } }; template <typename Ret, typename Callable> auto make_converter(Callable cb) { return ReturnConverter<Ret, Callable>(cb); } int main() { auto callable = []() { return 1.0f; }; auto converted = make_converter<int>(callable); auto x = converted(); // decltype(x) = int } ReturnConverter can take an object and override that object's operator() to cast whatever it returns to Ret. The problem is expressing the argument types of the wrapping function - they should be exactly the same as those of Callable::operator(). Using a variadic template with std::forward does not satisfy this goal, as it would modify the signature of the function (operator() now becomes a template where it wasn't before). How can I express the argsof operator I've highlighted above? Motivation: I'd like to modify the std::visit overload technique demonstrated in this article to be able to specify the desired return type from multiple lambda functors, so that I don't have to strictly match the return type in every lambda, for instance: std::variant<int, float, void*> v = ...; auto stringify = overload( [](int x) { return "int: " + std::to_string(x); }, [](float x) { return "float: " + std::to_string(x); }, [](auto v) { return "invalid type!"; } // error! const char* != std::string ); std::visit(stringify, v); With the change above, I'd be able to write something like auto stringify = overload<std::string>(...);
I don't see a way to respond to your exact answer but... considering the "Motivation" of the question... I propose a wrapper for overload (a class that inherit from a class with one or more operator(), call the appropriate operator() from the base class and cast the return value to type Ret) template <typename Ret, typename Wrpd> struct wrp_overload : public Wrpd { template <typename ... Args> Ret operator() (Args && ... as) { return Wrpd::operator()(std::forward<Args...>(as)...); } }; and, given the Ret type isn't deducible from the argument (the overload class) and that CTAD doesn't permit to explicit a template argumend, seems to me that a make_wrp_overload() function is required template <typename Ret, typename ... Cs> auto make_wrp_overload (Cs && ... cs) { return wrp_overload<Ret, overload<Cs...>>{{std::forward<Cs>(cs)...}}; } so your std::visit() call become std::visit(make_wrp_overload<std::string>( [](int x) { return "int: " + std::to_string(x); }, [](float x) { return "float: " + std::to_string(x); }, [](auto v) { return "invalid type!"; } ), package); The following is a full compiling C++17 example #include <iostream> #include <variant> template <typename ... Ts> struct overload : public Ts... { using Ts::operator()...; }; // not required anymore (also C++17) //template <typename ... Ts> overload(Ts...) -> overload<Ts...>; template <typename Ret, typename Wrpd> struct wrp_overload : public Wrpd { template <typename ... Args> Ret operator() (Args && ... as) { return Wrpd::operator()(std::forward<Args...>(as)...); } }; template <typename Ret, typename ... Cs> auto make_wrp_overload (Cs && ... cs) { return wrp_overload<Ret, overload<Cs...>>{{std::forward<Cs>(cs)...}}; } int main() { std::variant<int, float, void*> package; std::visit(make_wrp_overload<std::string>( [](int x) { return "int: " + std::to_string(x); }, [](float x) { return "float: " + std::to_string(x); }, [](auto v) { return "(no more) invalid type"; } ), package); }
71,007,105
71,185,220
CMake undefined reference when using fmt from vcpkg
I'm pretty new at VSCode CMake and vcpkg, but I get in trouble when setting up environment. Here's CMakeList.txt cmake_minimum_required(VERSION 3.0.0) project(temp VERSION 0.1.0) set(CMAKE_TOOLCHAIN_FILE "C:/vcpkg/scripts/buildsystems/vcpkg.cmake") set(VCPKG_TARGET_TRIPLET "x64-windows") #include("C:/Users/dell/vcpkg/scripts/buildsystems/vcpkg.cmake") #include(FetchContent) #FetchContent_Declare(fmt # GIT_REPOSITORY https://github.com/fmtlib/fmt.git # GIT_TAG master #) #FetchContent_MakeAvailable(fmt) add_executable(temp C++/temp/temp.cpp) SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/C++/temp) find_package(fmt CONFIG REQUIRED) target_link_libraries(temp PRIVATE fmt::fmt) Here's my example for fmt: #include <iostream> #include "fmt/format.h" int main() { fmt::print("This is a string {}", "world"); } Here's error CMake gave: [main] Building folder: VS Code Project [build] Starting build [proc] Executing command: "C:\Program Files\CMake\bin\cmake.EXE" --build "c:/Users/dell/Desktop/VS Code Project/build" --config Debug --target all -j 14 -- [build] Consolidate compiler generated dependencies of target temp [build] [ 50%] Building CXX object CMakeFiles/temp.dir/C++/temp/temp.cpp.obj [build] [100%] Linking CXX executable ..\C++\temp\temp.exe [build] E:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles\temp.dir/objects.a(temp.cpp.obj): in function `void fmt::v8::print<char const (&) [6]>(fmt::v8::basic_format_string<char, fmt::v8::type_identity<char const (&) [6]>::type>, char const (&) [6])': [build] C:/Users/dell/vcpkg/installed/x64-windows/include/fmt/core.h:3208: undefined reference to `__imp__ZN3fmt2v86vprintENS0_17basic_string_viewIcEENS0_17basic_format_argsINS0_20basic_format_contextINS0_8appenderEcEEEE' [build] collect2.exe: error: ld returned 1 exit status [build] mingw32-make[2]: *** [CMakeFiles\temp.dir\build.make:100: ../C++/temp/temp.exe] Error 1 [build] mingw32-make[1]: *** [CMakeFiles\Makefile2:82: CMakeFiles/temp.dir/all] Error 2 [build] mingw32-make: *** [Makefile:110: all] Error 2 [build] Build finished with exit code 2 But building with FetchContent works fine, what happened ?
The main reason of this is that I should use "fmt-header-only" instead of "fmt"
71,007,434
71,007,466
What does "operator MyType () {}" mean in C++
I see a function member in a c++ class: class bar{ //.. } class foo{ public: foo(){}; //... operator bar(){ return bar(); } } it's not an operator overloading, can anyone explain it to me ?
It is a user-defined conversion operator which constructs a bar object from the foo object. The purpose is to enable type casting from foo to bar.
71,007,972
71,008,040
process exited due to signal 6/11 c++
I didn't have any problems with compiling my program, but I have a big one when I try to use a bot to check output data. It says: "process exited due to signal 6" or "process exited due to signal 11". I thought it was a matter of dynamic arrays (i have two in this program) but both are deleted at the end. I would be very grateful for any tip! #include <iostream> using namespace std; void input_data (int p_n, int **p_arr); void output_data (int p_n, int **p_arr); void check_salary(int p_n, int **p_arr); int main() { int n; cin >> n; int** arr = new int*[n]; for(int i = 0; i < n; ++i){ arr[i] = new int[2];} input_data(n, arr); check_salary(n, arr); output_data(n, arr); for(int i=0; i<n; i++) { delete [] arr[i]; } delete[] arr; return 0; } void check_salary(int p_n, int **p_arr) { bool fit, flag, exist; int *used = new int(p_n); int boss, salary, i_temp, i_salarless, min_sal ,i_used = 0,boss_salary, id; for (int i=0; i<p_n; i++) { if(p_arr[i][1] != 0) { used[i_used]=p_arr[i][1]; i_used++; } } do{ flag = false; exist=false; for (int i=0; i<p_n; i++) { i_salarless = 0; id = i+1; boss = p_arr[i][0]; salary=p_arr[i][1]; boss_salary = p_arr[boss-1][1]; if(salary==0) { if(boss==id){ p_arr[i][1] = p_n; flag = true; }else if(boss_salary>0){ for (int j=0; j<p_n; j++) { if (p_arr[j][0]==boss && p_arr[j][1] == 0){i_salarless++;} } if (i_salarless == 1){ do{ --boss_salary; exist = false; for (int i=0; i< i_used; i++){ { if(boss_salary == used[i]){exist = true;} } } }while(exist); p_arr[i][1]= boss_salary; used[i_used]= p_arr[i][1]; i_used++; flag = true; } } }else{} } } while(flag); delete []used; } void output_data (int p_n, int **p_arr) { for (int i=0; i<p_n; i++) { cout<< p_arr[i][1] << "\n"; } } void input_data (int p_n, int **p_arr) { for (int i=0; i<p_n; i++) { for (int j=0; j<2; j++) { cin>> p_arr[i][j]; } } }
I think the main issue is that you are doing int *used = new int(p_n);, this will create a pointer to an integer that has initial value equal to p_n. But, the problem comes here: used[i_used]=p_arr[i][1]; -- this may lead to a segmentation fault, as you may end up using memory outside the valid bounds. I'm not sure about the algorithm, but based on the code, I think you should use this instead: used = new int[p_n]; // assuming p_n > 0
71,009,055
71,018,413
Extract all icons of a file
First of all, I want to access all icons (16x16...256x256 and larger) in a ".exe" file. As a result of my research, I found such code: #ifndef __ICON_LIST_H__ #define __ICON_LIST_H__ #include <windows.h> #include <vector> class IconFile: public std::vector<HICON>{ public: IconFile(){}; IconFile(std::string i_filename){ addIconsFromFile(i_filename); }; int addIconsFromFile(std::string i_fileName){ int iCount=0; HANDLE file = CreateFile( i_fileName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(file!=INVALID_HANDLE_VALUE){ int size = GetFileSize(file,NULL); DWORD actRead; BYTE* buffer = new BYTE[size]; ReadFile(file, buffer, size, &actRead, NULL); CloseHandle(file); int ind = -1; for(int p = 0; p< size-4; ++p){ if(buffer[p]==40 && buffer[p+1]==0 && buffer[p+2]==0 && buffer[p+3]==0){ HICON icon = CreateIconFromResourceEx(&buffer[p], size-p, true, 0x00030000,0,0,0); if(icon){ ++iCount; this->push_back(icon); } } } delete[] buffer; } return iCount; }; }; #endif //__ICON_LIST_H__ This code works fine but doesn't show 256x256 or larger icon, Code output: std::vector(0x8ef2013, 0x64ce1867, 0x24681219) Currently, this is the icon list of the file: How can I get the 256x256 icon?
Use LoadLibraryEx to load the file, EnumResourceNames to enumerate icons, and CreateIconFromResourceEx to lead each icon. Note that driving a class from std::vector and other C++ Standard Library containers is not recommended. The example below uses LR_SHARED, you might want to change that. #include <windows.h> #include <vector> BOOL CALLBACK EnumIcons(HMODULE hmodule, LPCTSTR type, LPTSTR lpszName, LONG_PTR ptr) { if (!ptr) return FALSE; auto pvec = (std::vector<HICON>*)ptr; auto hRes = FindResource(hmodule, lpszName, type); if (!hRes) return TRUE; auto size = SizeofResource(hmodule, hRes); auto hg = LoadResource(hmodule, hRes); if (!hg) return TRUE; auto bytes = (BYTE*)LockResource(hg); auto hicon = CreateIconFromResourceEx(bytes, size, TRUE, 0x00030000, 0, 0, LR_SHARED); if (hicon) pvec->push_back(hicon); return TRUE; } int main() { std::vector<HICON> vec; const char* modulepath = "file.exe"; HMODULE hmodule = LoadLibraryEx(modulepath, NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE); if (!hmodule) return 0; EnumResourceNames(hmodule, RT_ICON,(ENUMRESNAMEPROC)EnumIcons,(LONG_PTR)&vec); for (auto e : vec) { ICONINFOEX ii = { sizeof(ii) }; if (!GetIconInfoEx(e, &ii) || !ii.hbmColor) continue; BITMAP bm; GetObject(ii.hbmColor, sizeof(bm), &bm); printf("%d %d %d\n", bm.bmWidth, bm.bmHeight, bm.bmBitsPixel); } //free icons... return 0; }
71,009,740
71,009,867
Initializing from a pair in constructur intializer list
I have a function f returning a pair of objects of classes A and B: auto f() -> std::pair<A,B>; Furthermore, I have a class C that has A and B as members: class C { public: C(); private: A a; B b; }; In the constructor of C, I want to use the member initalizer list and initialize with the output of f: C(): a(f().first), b(f().second) {} This calls f twice though and it is a quite complicated function. Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.
Improving on the idea from AnkitKumar's answer: class C { A a; B b; C(std::pair<A,B> &&pair) : a(std::move(pair.first)), b(std::move(pair.second)) {} public: C() : C(f()) {} };
71,009,831
71,009,896
Can I test deadlock in googletest?
I have a small class that creates multiple threads. When I call stop() method, it sets a flag for stopping threads and joins on the thread until they are stopped. Here is the code of stop() method: void stop() { running_flag_ = false; for (auto& th : threads_) { if (th.joinable()) th.join(); } } I wonder if there is a way to test if this method works as expected, meaning this method should always return. I don't think dead test is really suitable here. Any idea if there is a way to test this?
When you have a deadlock some threads are waiting on locks until they are released. There is no way to recover process form such state, without adding extra code. The only way to overcome this problem is to detect timeout and crash unit test application when timeout accrues. Some times ago I used this code to detect issue so build machine do not hang to long: class TerminateOnDeadlockGuard final { public: using Clock = std::chrono::system_clock; using Duration = Clock::duration; explicit TerminateOnDeadlockGuard(Duration timeout = std::chrono::seconds{30}); ~TerminateOnDeadlockGuard(); private: void waitForCompletion(); private: const Duration m_timeout; std::mutex m_mutex; std::condition_variable m_wasCompleted; std::condition_variable m_guardStarted; std::thread m_guardThread; }; //--------- TerminateOnDeadlockGuard::TerminateOnDeadlockGuard(Duration timeout) : m_timeout{timeout} { m_guardThread = std::thread(&TerminateOnDeadlockGuard::waitForCompletion, this); std::unique_lock lock{m_mutex}; m_guardStarted.wait(lock); } TerminateOnDeadlockGuard::~TerminateOnDeadlockGuard() { m_wasCompleted.notify_one(); m_guardThread.join(); } void TerminateOnDeadlockGuard::waitForCompletion() { std::unique_lock lock{m_mutex}; m_guardStarted.notify_one(); if (std::cv_status::timeout == m_wasCompleted.wait_for(lock, m_timeout)) { std::cerr << "Test timeout!!!" << std::endl; std::exit(-1); // you can use `abort` here to create crash log. } } Usage: TEST(SomeTestSuite, myTest) { TerminateOnDeadlockGuard guardDeadLock; // test code here } Now there is google death test which could come to the rescue. This forks process at let child process to terminate. using namespace std::chrono_literals; class NoDeadLockTest : public ::testing::Test { public: void someTest() { TerminateOnDeadlockGuard guardDeadLock{5s}; actualTest(); std::exit(::testing::Test::HasFailure() ? 2 : 0); } void actualTest() { #if VERSION == 0 ASSERT_TRUE(true); #elif VERSION == 1 ASSERT_TRUE(false); #elif VERSION == 2 std::this_thread::sleep_for(10s); #endif } }; TEST_F(NoDeadLockTest, myTest) { EXPECT_EXIT(someTest(), testing::ExitedWithCode(0), ""); } I've checked this on godbolt and it is far from perfect: https://godbolt.org/z/nasros577 but shows there is hope if some extra effort is done. I relay recommend to use some tool to detect the dead locks and fix code. I used thread sanitizer - I've tried it and it is very effective.
71,010,116
71,010,265
Index-based assignment in the loop for Pair, C++
I am new to C++. I want to assign the values to my tuple inside the loop. The following does not work. #include<utility> std::pair<int, int> myPair; int main() { for(int i=0; i<2; i++) { std::get<i>(myPair) = i; } } How could I do it correctly?
Do you have a reason to insist on doing this in a loop? If not, you can just assign to mypair.first and mypair.second. #include<utility> std::pair<int, int> myPair; int main() { myPair.first = 1; myPair.second = 2; } A very useful website to check what's available for standard library types is cppreference.com Maybe you actually want a std::vector? #include <vector> int get_next_value(int); // Not defined in this example. // You get your values from somewhere... // note that global variables like this might not be the best idea. std::vector<int> values; int main() { for (int i=0; i < 2; ++i) { values.push_back(get_next_value(i)); } }
71,010,149
71,011,980
I can't figure out why hash[0] is being assigned the value 1 in the output . Any help would be appreciated
This is my code:- #include<iostream> #include<string> using namespace std; int main() { string magazine="aab"; string ransomNote="aa"; int hash[123]={}; int i; for(i=0;i<=magazine.length();i++) { hash[magazine[i]]++; } for(i=0;i<123;i++) { cout<<hash[i]<<" "; } cout<<endl; } The output is:- 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
In c++ chars are almost the same thing as integers and they are stored as integers. So when you are performing hash[magazine[i]]++; what really happens is that the magazine[3] (which is the NULL character) will be promoted to an int (Source: cpp reference: Implicit Conversions, the equivalent of which is 0 based on the cpp reference: ASCII codes. Thus, the statement hash[3] = 0 is true. That said, the below code which is similar to the code used in the example string x = hash[magazine[3]]++; //first x is assigned with the value of hash[magazine[3]], then hash[magazine[3]] is incremented. cout << "output: " << x << "\n"; will produce output: 0. That happens because the hash[0] is assigned with the value of hash[magazine[3]] before the increment operator.Equivalently, the increment (++ operator) will be evaluated after the rest of the expression is -- after the assignment has been done. If you want to avoid this behavior, you can do the below: string x = ++hash[magazine[3]]; //first hash[magazine[0]] is incremented, then it is assigned to x. cout << "output: " << x << "\n"; which will produce output: 1. However, hash[magazine[i]]++ is inside a loop. This means that after the loop concludes, the expression has already been evaluated and the hash array contains the new values, thus, hash[0] will be equal to 1. Cheers,
71,010,294
71,010,787
Different results between clang/gcc and MSVC for templated constructor in base class
I stumbled over the following piece of code. The "DerivedFoo" case produces different results on MSVC than on clang or gcc. Namely, clang 13 and gcc 11.2 call the copy constructor of Foo while MSVC v19.29 calls the templated constructor. I am using C++17. Considering the non-derived case ("Foo") where all compilers agree to call the templated constructor, I think that this is a bug in clang and gcc and that MSVC is correct? Or am I interpreting things wrong and clang/gcc are correct? Can anyone shed some light on what might be going on? Code (https://godbolt.org/z/bbjasrraj): #include <iostream> using namespace std; struct Foo { Foo() { cout << "\tFoo default constructor\n"; } Foo(Foo const &) { cout << "\tFoo COPY constructor\n"; } Foo(Foo &&) { cout << "\tFoo move constructor\n"; } template <class U> Foo(U &&) { cout << "\tFoo TEMPLATED constructor\n"; } }; struct DerivedFoo : Foo { using Foo::Foo; }; int main() { cout << "Foo:\n"; Foo f1; Foo f2(f1); cout << "\nConst Foo:\n"; Foo const cf1; Foo cf2(cf1); cout << "\nDerivedFoo:\n"; DerivedFoo d1; DerivedFoo d2(d1); cout << "\nConst DerivedFoo:\n"; DerivedFoo const cd1; DerivedFoo cd2(cd1); } Result for clang and gcc: Foo: Foo default constructor Foo TEMPLATED constructor Const Foo: Foo default constructor Foo COPY constructor DerivedFoo: Foo default constructor Foo COPY constructor <<<<< This is different Const DerivedFoo: Foo default constructor Foo COPY constructor Result for MSVC: Foo: Foo default constructor Foo TEMPLATED constructor Const Foo: Foo default constructor Foo COPY constructor DerivedFoo: Foo default constructor Foo TEMPLATED constructor <<<<< This is different Const DerivedFoo: Foo default constructor Foo COPY constructor
It is correct that the constructor template is generally a better match for the constructor call with argument of type DerivedFoo& or Foo& than the copy constructors are, since it doesn't require a const conversion. However, [over.match.funcs.general]/8 essentially (almost) says, in more general wording, that an inherited constructor that would have the form of a move or copy constructor is excluded from overload resolution, even if it is instantiated from a constructor template. Therefore the template constructor will not be considered. Therefore the implicit copy constructor of DerivedFoo will be chosen by overload resolution for DerivedFoo d2(d1); and this will call Foo(Foo const &); to construct the base class subobject. This wording is a consequence of CWG 2356, which was resolved after C++17, but I think it is supposed to be a defect report against older versions as well. (I don't really know though.) So GCC and Clang are correct here. Also note that MSVC behaves according to the defect report as well since version 19.30 if the conformance mode (/permissive-) is used.
71,010,520
71,012,791
Rcpp wrapper for algorithm to generate r x c contingency tables
I'm trying to use this C++ implementation of an algorithm for efficiently generating r x c contingency tables with fixed margins: https://people.sc.fsu.edu/%7Ejburkardt/cpp_src/asa159/asa159.html I'm working in Rcpp and am trying to create a function that I can utilize in R. I'm aware that there's a C implementation of this algorithm in R. That doesn't work for me because I need to be able to utilize this function within Rcpp. As an intermediate step, I'm just trying to wrap this algorithm and export it to R. Seems simple but I've struggled mighty with this. The original function is defined as follows: void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key, int *seed, int matrix[], int *ierror ) This is a link directly to the algorithm: https://people.sc.fsu.edu/%7Ejburkardt/cpp_src/asa159/asa159.cpp I don't need the error handling and couldn't figure out how to deal with the void type so I altered the algorithm slightly and ended up with this: int* rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key, int *seed, int matrix[]) I've made several attempts. Here's one example. This will compile, but when I try to run the function in R, it crashes. #include <Rcpp.h> #include "asa159.h" using namespace Rcpp; //[[Rcpp::export]] IntegerVector rcont2_cpp(int nrow, int ncol, IntegerVector nrowt_r, IntegerVector ncolt_r, bool key_r, int seed_r) { std::vector<int> nrowt_rr = as< std::vector<int> >(nrowt_r); std::vector<int> ncolt_rr = as< std::vector<int> >(ncolt_r); int* nrowt = &nrowt_rr[0]; int* ncolt = &ncolt_rr[0]; int matrix[nrow * ncol]; bool *key = &key_r; int *seed = &seed_r; int* out = rcont2(nrow, ncol, nrowt, ncolt, key, seed, matrix); int len_out = *(&out + 1) - out; std::vector<int> value_vec(out, out + len_out); return wrap(value_vec); } I assume I'm making some elementary mistakes here. Thank you in advance to anyone who has time to take a look.
This is actually an excellent question, and I too have had good luck with the nice and very comprehensive site full of routines by John Burkardt at FSU. But nothing is life is entirely free, and one needs to know a little bit about how C and C++ work to integrate such routines into R via Rcpp. My version of the final file is much shorter: we just ship rowsums and colsums to it, and get the desired matrix back. We also add the R call for the example at the bottom (a nice trick!) Code #include <Rcpp.h> #include <asa159.cpp> // [[Rcpp::export]] Rcpp::IntegerMatrix rcont2_cpp(Rcpp::IntegerVector rowsums, Rcpp::IntegerVector colsums) { int nrow = rowsums.length(); int ncol = colsums.length(); Rcpp::IntegerMatrix matrix(nrow, ncol); rcont2(nrow, ncol, rowsums.begin(), colsums.begin(), matrix.begin()); return matrix; } /*** R rs <- c(6, 5) cs <- c(3, 4, 4) rcont2_cpp(rs, cs) rcont2_cpp(rs, cs) // different answer as randomized algo rcont2_cpp(rs, cs) // different answer as randomized algo */ Output This contains three example calls. > sourceCpp("rcont2.cpp") > rs <- c(6, 5) > cs <- c(3, 4, 4) > rcont2_cpp(rs, cs) [,1] [,2] [,3] [1,] 3 1 2 [2,] 0 3 2 > rcont2_cpp(rs, cs) [,1] [,2] [,3] [1,] 1 3 2 [2,] 2 1 2 > rcont2_cpp(rs, cs) [,1] [,2] [,3] [1,] 1 2 3 [2,] 2 2 1 > Diff to original asa159.cpp The change to the original asa159.cpp is fairly small: we use R's own RNG, and we simplify the calling interface. Propagation of error condition via Rcpp::stop() is left as an exercise, as they say :) --- asa159.orig.cpp 2020-01-30 08:20:42.000000000 -0600 +++ asa159.cpp 2022-02-06 19:52:20.999042887 -0600 @@ -428,8 +428,8 @@ } //****************************************************************************80 -void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], bool *key, - int *seed, int matrix[], int *ierror ) +void rcont2 ( int nrow, int ncol, int nrowt[], int ncolt[], /*bool *key, */ + /*int *seed,*/ int matrix[] /*, int *ierror*/ ) //****************************************************************************80 // @@ -517,6 +517,10 @@ double x; double y; + bool keyflag = false; // added + bool *key = &keyflag; // added + int ierr = 0; // added + int *ierror = &ierr; // added *ierror = 0; // // On user's signal, set up the factorial table. @@ -638,7 +642,7 @@ // // Generate a pseudo-random number. // - r = r8_uniform_01 ( seed ); + r = R::runif(0,1); //r8_uniform_01 ( seed ); // // Compute the conditional expected value of MATRIX(L,M). // @@ -740,7 +744,7 @@ break; } - r = r8_uniform_01 ( seed ); + r = R::runif(0,1); // r8_uniform_01 ( seed ); r = sumprb * r; }
71,010,802
71,010,871
Will destructor delete built-in types and pointer objects?
I'm a c++ beginner and now reading the C++ Primer. I have some problem about the destrucor: in chapter 13.1.3: "In a destructor, there is nothing akin to the constructor initializer list to control how members are destroyed; the destruction part is implicit. What happens when a member is destroyed depends on the type of the member. Members of class type are destroyed by running the member’s own destructor. The built-in types do not have destructors, so nothing is done to destroy members of built-in type." So if I have such a class: class Foo { ~Foo() { delete pi; } int *pi; int i; }; When an instance of Foo is going to be destroyed, according to the above text, the built in type variable int i will not be destroyed? Then how it will exist since the object to which it belongs has been destroyed. In chapter 13.1.4: "The HasPtr class that we have used in the exercises is a good example (§ 13.1.1,p.499). That class allocates dynamic memory in its constructor. The synthesized destructor will not delete a data member that is a pointer. Therefore, this class needs to define a destructor to free the memory allocated by its constructor." I understand that the synthesized destructor does not de-allocate the memory that has been allocated by new and is pointed to by plain pointers, but here in the text, it indicates that the pointer object itself is also not deleted by the synthesized pointer. Still the example of class Foo, does that mean that after an object of Foo class is destroyed, the pointer pi will not be destroyed ( so becomes an invalid pointer )?
What the spec means is that no code is run to clean up int i. It simply ceases to exist. Its memory is part of Foo and whenever a Foo instance is released, then i goes with it. For pointers the same is true, the pointer itself will simply disappear (it's really just another number), but the pointer might point at something that needs to also be released. The compiler doesn't know if that is the case, so you have to write a destructor. This is why things like std::shared_ptr exist; they are clever pointers (aka 'smart') and the compiler does know if it points at something that needs to be released and will generate the correct code to do so. This is why you should always use smart pointers instead of 'naked' ones (like int *p).
71,010,829
71,010,912
How to delete the extra spacing in code after it is printed?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue? please help! Here's an example picture of the output. **UPDATE: Thanks Drew for helping me with the alignment! //extracted code.. #include <iostream> int main() { int day = 0; if (day > 9) { std::cout << day << '\n'; } else { std::cout << day << '\n' << " "; } }
Change every (day > 9) to (day >= 9 ). You are using that condition to decide how much whitespace should appear after the number. Demo
71,010,919
71,011,103
Pointer to base virtual function vs direct call of base virtual function
Why do these two behave differently? (obj.*lpfn)(); vs obj.Base::fn(); I know when we directly call virtual member function (obj.fn()) it will do a virtual dispatch(find correct 'fn' implementation for type of obj, and call it). But why does a pointer to member function call that is set to Base implementation((obj.*lpfn)()) lead to virtual dispatch, and why does the same expression, except directly called (obj.Base::fn()) not do virtual dispatch? If anything, I would expect them both to do call base implementation of Print function(no virtualization) #include <iostream> class Base { public: virtual void Print() { std::cout << "Base::Print();\n"; } }; class Derived : public Base { public: void Print() override { std::cout << "Derived::Print();\n"; } }; int main() { Derived d; auto lpfn = &Base::Print; (d.*lpfn)(); d.Base::Print(); } Output: Derived::Print(); Base::Print();
From the C++ standard: [expr.call]/1 For a call to a non-static member function, the postfix expression shall be an implicit (12.2.2, 12.2.3) or explicit class member access (8.2.5) whose id-expression is a function member name, or a pointer-to-member expression (8.5) selecting a function member; the call is as a member of the class object referred to by the object expression... If the selected function is non-virtual, or if the id-expression in the class member access expression is a qualified-id, that function is called. Otherwise, its final overrider (13.3) in the dynamic type of the object expression is called; such a call is referred to as a virtual function call. Thus, there are only two cases where virtual dispatch is not performed for a call of a non-static member function: 1) the function is not virtual to begin with, or 2) the function is named with a qualified name, as in obj.Base::fn(). In all other cases - including the case of calling via a pointer-to-member - the final overrider is called.
71,011,343
71,011,579
Maximum number of codepoints in a grapheme cluster
I am using the C++ ICU library. I wish to split a utf-8 string into approximately equal chunks. However, I want the chunks to be demarcated at grapheme cluster boundaries. I do not wish to convert my entire string into utf-16 to do this for both memory and speed efficiency. Instead, I want to translate a small number of utf-8 codepoints close to my estimated chunk boundaries into utf-16. I can then use ICU's BreakIterator to work out the exact boundaries. Is there a hard upper limit of the number of codepoints that can make up a grapheme cluster? If so, what is it? I need to know this in order to determine the minimum codepoints that I need to translate from utf-8 to utf-16.
Is there a hard upper limit of the number of codepoints that can make up a grapheme cluster? No. There is no hard upper limit for how many code points a grapheme clusters - i.e. a user-perceived character - consists of. You could for example repeatedly add ZERO WIDTH JOINER with a joined character.
71,011,550
71,011,953
How to write statement that deletes extra space in C++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue? //extracted... if (day >= 9) { std::cout << day; } else std::cout << day << " "; std::cout << " "; } }
In the section else { if (day >= 9) { std::cout << day; } else std::cout << day << " "; std::cout << " "; } You seem to have accidentally omitted the braces around the final else clause. It probably should read: else { if (day >= 9) { std::cout << day; } else { std::cout << day << " "; std::cout << " "; } } This ensures that the dangling std::cout << " "; mentioned by @Igor-Tandetnik is part of the else clause, as you seem to have intended.
71,011,580
71,011,622
Check distance between labels when importing binary file gnu-assembler
I have the following macro to embed binary data from filename: #define INCBIN(identifier, filename) \ asm(".pushsection .rodata\n" \ "\t.local " #identifier "_begin\n" \ "\t.type " #identifier "_begin, @object\n" \ "\t.align 16\n" #identifier "_begin:\n" \ "\t.incbin \"" filename "\"\n\n" \ \ "\t.local " #identifier "_end\n" \ "\t.type " #identifier "_end, @object\n" \ "\t.align 1\n" #identifier "_end:\n" \ "\t.byte 0\n" \ "\t.popsection\n"); \ \ extern std::byte const identifier##_begin[]; \ extern std::byte const identifier##_end[] I would like to be able to claim that it is an uint32_t instead of an std::byte. This would require the file to have an integer multiple of 4 bytes. Alignment is already taken care of by the macro (align to 16). Can I trigger a compile-time error if the file has a bad size? That is, add some compile-time assert to the assembly.
If you just .p2align 2 after the file, it will round the total size up to a multiple of 4 bytes, regardless of how many bytes .incbin assembled to. (Since the file started at an aligned position). If you want to check instead of pad, that's possible at assemble time, using assembler directives. Obviously not at compile-time proper, since that just translates C++ to asm to later be fed to the assembler. (In GCC, those steps are actually separate, not all part of the same compiler process. But logically still sequential in other implementations.) The distance between two labels in the same file is an assemble-time constant that you can use in GAS expressions like (b-a)&3. If you use .rept -((b-a)&3), you'll have a 0 or negative repeat count, the latter of which is an assemble-time error, according to the file size % 4 being non-zero. (Fun fact: the Linux kernel uses a trick like this in C to do static asserts by generating an array with 0 or negative size). Or even better, .error can be controlled by .rept or other GAS directives like .ifgt. (.rept would repeat the error message (b-a)%4 times, vs. if-greater-than-zero repeating it only once.) .p2align 2 a: .incbin "bin" # .p2align 2 b: .ifgt (b-a)&3 # true if remainder > 0 .error "asm static_assert failed: file size not a multiple of 4" .endif $ echo xyz > bin # size 4 $ gcc -c foo.s $ echo >> bin # size 5 $ gcc -c foo.s foo.s: Assembler messages: foo.s:9: Error: asm static_assert failed: file size not a multiple of 4 Tested with GNU assembler (GNU Binutils) 2.36.1 I'll leave it up to you to stuff that back into your inline asm macro, with the filename in the .error string.
71,011,881
71,020,477
Why does pthread_join not take a thread pointer?
Pretty self explanatory question. For example, the header for pthread_create shows it takes a pointer to a thread: int WINPTHREAD_API pthread_create(pthread_t *th, const pthread_attr_t *attr, void *(* func)(void *), void *arg); OK, makes sense, you allocate a pthread in memory then pass a pointer to pthread_create so it gets initialized... but now looking at the header for pthread_join: int WINPTHREAD_API pthread_join(pthread_t t, void **res); It takes a copy of the pthread_t. I just don't get why it doesn't take a pointer to that already existing thread, rather than copying it and passing it over; it seems like if anything, doing so would cause more problems and more memory use. Am I missing something? I read the manpage, it doesn't seem to offer a reason to this.
It takes a copy of the pthread_t. Yes. I just don't get why it doesn't take a pointer to that already existing thread, pthread_t is a thread identifier. The specs consistently refer to it that way. Copying it does not duplicate the thread itself, nor consume more memory than one pthread_t occupies. rather than copying it and passing it over; it seems like if anything, doing so would cause more problems and more memory use. It does not necessarily cause more memory use, as a pthread_t is not necessarily larger than a pointer. It might be a pointer, or an integer. Even if it is a structure, however, there is no reason to think that it so large that passing it by value presents a significant problem, because the specifics are under control of the pthreads implementation. Why would implementers shoot themselves in the foot that way? Note well that passing a structure by value is not inherently less efficient than passing a pointer. As for problems other than excessive memory use, you would have to be more specific, but I don't see any issues inherent in accessing a copy of a thread identifier directly vs. accessing a common identifier object indirectly, for the purposes of those functions that accept a pthread_t by value. Am I missing something? I suspect that your concerns are tied up in a misunderstanding of type pthread_t as somehow carrying data supporting thread operation as opposed to simply identifying a thread. You may also be supposing that pthreads is a library, with a particular implementation, whereas in fact, it is first and foremost a specification, designed to afford multiple implementations. This is part of the reason for defining abstract data type pthread_t instead of specifying int or struct something * -- implementations can choose what actual type to use. Perhaps you are also focusing too closely on the API functions. Even if in some particular implementation, passing a pthread_t by value to, say, pthread_join() were less efficient than passing a pointer to one, how much of an impact do you suppose that would actually have? pthread_join() is called infrequently, and only in cases where the caller is prepared to block. What does it matter if argument passing consumes a few more nanoseconds than it might otherwise do? I read the manpage, it doesn't seem to offer a reason to this. Few manual pages provide rationale for function design, but I think the most likely explanation is essentially that form follows function. Those functions that receive a pthread_t by value do so because they do not need or want to modify the caller's value. The functions' designs reflect that.
71,011,962
71,011,994
Create STATIC and SHARED libraries with Clang
What is the minimal commmand line way to create an static and a dynamic library with Clang under Linux and Windows, and then, link it against an executable? Suppose the project contains a main.cpp file with the main function, an lib_header.h file under /include/project_name and a lib_source.c or lib_source.cpp under /src Thanks
For both static and dynamic libraries, you first compile the source files individually: clang -c -o lib_source.o lib_source.c -fPIC For the static library on Linux, archive all .o files together: ar r library.a lib_source.o For the shared library, link with the -shared flag: clang -shared -o library.so lib_source.o
71,012,034
71,012,042
Pointer still able to call member function, after it was set to NULL and delete being called on it
#include<stdio.h> class test2 { public: void testFunc() { printf("test"); } test2(){} ~test2(){} }; class test1 : test2 { public: test1(){ link = new test2();} ~test1(){ delete link; link = NULL; } test2* link = NULL; private: }; int main() { test1 *ptr = new test1(); delete ptr; ptr->link->testFunc(); return 0; } I want to delete the test2 object after calling the deconstructor of test1. Yet, Im still able, after calling delete and setting link to NULL, to call the member function "testFunc" and print "test" with the link pointer. Why is this possible?
If a program accesses an object outside of its lifetime, then the behaviour of the program is undefined. Your program accesses an object outside of its lifetime. The behaviour of your program is undefined. The behaviour that you observed is because the behaviour is undefined. You could have observed any other behaviour because it is undefined, but you didn't observe other behaviour because it's undefined.
71,012,139
71,012,201
How to delete spacing after row is complete in c++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. So far my project works, but I am noticing an extra space after the last row is completed. How do I fix this extra spacing issue? please help! There's a space at the bottom... and this only seems to happen when the last row is full and no date is carried over. // Extracted.. #include <iostream> if (day >= 9) { std::cout << day; } else { std::cout << day << " "; } if (day != days_per) { std::cout << " "; } }
I think this will fix it: That's the block dealing with the last day of the week (Saturday). Print it always. If it is the last day of the month, don't do anything else. Otherwise: 1) print a newline, and 2) if the next day has 1 digit (current day < 9), print a space. [Demo] if (++count > 6) { count = 0; std::cout << day; if (day != days_per) { std::cout << '\n'; if (day < 9) { std::cout << " "; } } }
71,012,424
71,012,468
Finding Max element of the list of lists in c++ (conversion of python function)
I wanted to convert the following function python to c++: def find_max_value(list): max_value_list = [] for i in list: max_value_list.append(i[0]) return max(max_value_list) The inputs are the : [[90.272948, 210.999601, 90.31622, 349.000214, 4.042645], [520.293431, 349.000041, 520.285479, 211.000041, 2.007837], [237.026305, 263.076182, 237.629826, 247.023679, 4.523158]] The Output is 520.293431. I have tried but getting some errors. Could you please mention where I'm doing wrong? std::list<int> find_max_value(std::list<int> a(std::list<double> b)){ std::list<int> max_value_list; for (std::list<int>::iterator i = *a.begin(); i!=*a.end(); ++i){ max_value_list.push_back(i.front()); return std::max_element(i); } } Those are the errors: Thanks in advance!!!
I'm going to guess you are looking for something like this: double find_max_value(const std::list<std::list<double>>& a){ return std::max_element(a.begin(), a.end(), [](const std::list<double>& lhs, const std::list<double>& rhs) { return lhs.front() < rhs.front(); } )->front(); } This assumes none of the lists involved are empty.
71,012,708
71,012,821
How to print the multiples correctly?
I am trying to display the multiples of a user-inputted number given 6 user-inputted numbers. I think I am sort of close, but I am stuck. For example, if someone enters "4" and then their 6-number sequence is "23 45 12 16 51 8", it should return 12 16 8 because those are the multiples of the first inputted "4". So far I have the following: #include <iostream> using namespace std; //Display multiples of a number that appear within a sequence of numbers. //E.g. input is looking for multiples of 5 in the following sequence of 6 numbers: 6 10 9 3 25 79 → output: 10 25 int main() { int userNum; int seq1, seq2, seq3, seq4, seq5, seq6; cout << "Enter a number: " << userNum; cin >> userNum; cout << "Enter a sequence of 6 numbers: " << seq1 << " " << seq2 << " " << seq3 << " " << seq4 << " " << seq5 << " " << seq6; cin >> seq1; cin >> seq2; cin >> seq3; cin >> seq4; cin >> seq5; cin >> seq6; int sequence[] = {seq1, seq2, seq3, seq4, seq5, seq6}; int total; for (int sequence[] = seq1; i < 6; i++) { if (i % userNum == 0) { return total; } } cout << "Multiples in the sequence are: " << total; }
You print userNum and seq1 to seq6 before you've assigned values to them. That makes the program have undefined behavior. Your for loop has invalid syntax and you also return instead of printing the matching values. A fix could look like this: for (int i = 0; i < 6; i++) { if (sequence[i] % userNum == 0) { std::cout << sequence[i] << ' '; } } You don't actually need the variables seq1 to seq6. Just input directly into sequence. You can also use range-based for loops to make looping over the elements in sequence easier. Example: #include <array> // std::size #include <iostream> int main() { int userNum; std::cout << "Enter a number: "; std::cin >> userNum; int sequence[6]; std::cout << "Enter a sequence of " << std::size(sequence) << " numbers: "; for(int& num : sequence) { // a range-based for loop std::cin >> num; // assign to all 6 elements in a loop } std::cout << "Multiples in the sequence are: "; for(int num : sequence) { // another range-based for loop if(num % userNum == 0) { std::cout << num << ' '; } } std::cout << '\n'; }
71,012,740
71,012,798
passing std::plus as an argument
How do I pass std::plus as an argument across functions? #include<functional> #include<iostream> template < class T, typename F > T fn(T a, T b, F f) { return f<T>()(a,b); } template<class T> struct X { template < typename F> T foo(T a, T b, F f) { return fn<T, F>(a,b,f); } }; int main() { int a = 1; int b = 1; X<int> f; std::cout<< f.foo(a,b, std::plus<int>); return 0; } https://onlinegdb.com/g5NZc2x9V main.cpp:7:21: error: expected primary-expression before ‘)’ token
If you want to pass std::plus as a runtime argument you have to actually construct one. You can't pass a type as an argument. Trying to pass a naked std::plus<int> is akin to writing a class name or type name there i.e. you would not expect foo(a,b, int) to compile if it expects the third argument to be an int value. #include <functional> #include <iostream> template < class T, typename F > T fn(T a, T b, F f) { return f(a, b); } template<class T> struct X { template < typename F> T foo(T a, T b, F f) { return fn<T, F>(a, b, f); } }; int main() { int a = 1; int b = 1; X<int> f; std::cout << f.foo(a, b, std::plus<int>()); return 0; }
71,013,366
71,013,537
Equivalent in C++ to the pack function in PHP pack('H*', $tagIdAsHex);
I have this PHP code: $tagId = 1; // the original value of tag $tagIdAsHex = sprintf("%02X", $tagId); // the tag value in hex format $tagAsHexBytes = pack('H*', $tagIdAsHex); // the packed hex value of tag packed into string as a conversion How can I translate that to C++? byte tagId = 1; auto hexedTag = IntToHex(tagId); //C++ Builder ??
The PHP code shown is simply converting the integer 1 into a hex-encoded string containing "01", and is then parsing that hex string into a binary string holding a single byte 0x01. In C, you can use sscanf() in a loop to parse a hex string. In standard C++, you can use std::hex and std::setw() to parse a hex string from any std::istream, such as std::istringstream, using operator>> in a loop. In C++Builder specifically, you can use its RTL's HexToBin() function to parse a hex string into a pre-allocated byte array.
71,013,555
71,013,589
Default and Parameterized constructors and object declaration
I've written this code: #include<iostream> using namespace std; class Student { public: string name; int age; Student() { cout<<"Default constructor"<<endl; } Student(string name, int age) { this->name=name; this->age=age; cout<<"Parameterized constructor"<<endl; } }; int main() { system("clear"); Student s1={"abc", 20}; return 0; } Result: Parameterized constructor Conclusion: Defining object s1 like this Student s1={"abc", 20} calls parameterized constructor of class Testing out conclusion: #include<iostream> using namespace std; class Student { public: string name; int age; }; int main() { system("clear"); Student s1={"abc", 20}; return 0; } But compiling the code above doesn't give any errors. Questions: Why there is no errors even if we don't define any parameterized constructor inside class ? When we define class data members as private, we get some error: 5.cpp:12:12: error: no matching constructor for initialization of 'Student' Student s1={"abc", 20}; ^ ~~~~~~~~~~~ 5.cpp:5:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided class Student { ^ 5.cpp:5:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided 5.cpp:5:7: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided 1 error generated. Why we are getting this error now and not when data members were public ? :)
For the 1st case, Student has user-declared constructors, Student s1={"abc", 20}; performs list-initialization, as the effect, the appropriate constructor Student::Student(string, int) is selected to construct s1. If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, ... For the 2nd case, Student has no user-declared constructors, it's an aggregate and Student s1={"abc", 20}; performs aggregate-initialization, as the effect the data member name and age are initialized from "abc" and 20 directly. An aggregate is one of the following types: ... ... class type (typically, struct or union), that has ... no user-declared or inherited constructors ... Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list. If you make data members private, Student is not aggregate again. Student s1={"abc", 20}; still performs list-initialization and causes the error since no appropriate constructor exists. An aggregate is one of the following types: ... ... class type (typically, struct or union), that has no private or protected direct (since C++17)non-static data members ...
71,013,605
71,013,852
How can I initialize an std::array of a class without a default constructor?
Let's say I have a class without a default constructor called Foo. If I were using an std::vector, I could do this: std::vector<Foo> vec(100, Foo(5)); This would create a vector of 100 elements, each with value Foo(5). How do I do the same with std::array<Foo, 100>? I obviously do not want to list out Foo(5) explicitly 100 times in an initializer list. And yet I cannot wait till after the array is constructed to initialize it, since the lack of default constructor will produce a compiler error. Bonus points for a solution that allows me to avoid the copy constructor as well, by supplying explicit constructor arguments similar to "placement new" or emplace functions.
With copy constructor, something along these lines: template <typename T, size_t... Is> std::array<T, sizeof...(Is)> MakeArrayHelper( const T& val, std::index_sequence<Is...>) { return {(static_cast<void>(Is), val) ...}; } template <typename T, size_t N> std::array<T, N> MakeArray(const T& val) { return MakeArrayHelper<T>(val, std::make_index_sequence<N>{}); } std::array<Foo, 100> arr = MakeArray<Foo, 100>(Foo(5)); Actually, this can be done without copy constructor after all. This solution relies heavily on C++17's mandatory copy elision. template <typename T, size_t... Is, typename... Args> std::array<T, sizeof...(Is)> MakeArrayHelper( std::index_sequence<Is...>, Args&&... args) { return {(static_cast<void>(Is), T{std::forward<Args>(args)...}) ...}; } template <typename T, size_t N, typename... Args> std::array<T, N> MakeArray(Args&&... args) { return MakeArrayHelper<T>(std::make_index_sequence<N>{}, std::forward<Args>(args)...); } Demo
71,013,618
71,013,778
Understanding the Sub-expression overflow reasoning
I am trying to understand the reasoning behind this particular suggestion in Visual Studio 2022, as it doesn't seem to make sense to me. Here's the simple code: static constexpr uint32_t MAX_ELEMENTS = 100000; const std::vector<int> A{ some random ints }; std::vector<bool> found(MAX_ELEMENTS); for (int value : A) { if (value > 0 && value <= MAX_ELEMENTS) found[value - 1] = true; // Problem it complains about is the value - 1. } It suggests that a "sub-expression may overflow before being added to a wider type". Now obviously the condition-if prevents this from ever happening, but what's the reasoning here? Now if this was a Spectre thing, I could understand that the compiler would add a memory fence to stop any speculative execution of the statement after the if, but I don't think that's the answer here. My only thinking is that it has to do with the subscript operator on the vector; that its index is of a type larger than int and is implicitly cast to size_t? Just seems a little unintuitive that the below is an issue: found[value - 1] and its perfectly fine to do this, int a = value - 1; found[a]; when the end result is the same. What am I missing here in terms of understanding?
In this case, it is a false positive, as you suspected. This is a rule that sometimes gets used in stricter code bases. (This particular warning is an error in MISRA, for example.) A lot of warnings are like this... the compiler writers are trying to detect a situation where the behavior of the program is unexpected or unintentional, but the warnings are not always correct. For example, uint64_t x = 0xffffffffu << 16; On a system with 32-bit int, the standard is very clear what the value of this is supposed to be... it's supposed to be: uint64_t x = 0xffff0000u; However, it does look like someone meant to write this instead: uint64_t x = (uint64_t)0xffff0000 << 16; That's what the warning is trying to catch. That's the reasoning behind this rule. In your case, the compiler is doing a bad job of it. You can see a more detailed justification for the warning in the compiler documentation: Warning C26451. Spectre has nothing to do with it. It's perfectly fine... To do this: int a = value - 1; found[a]; In this case the "intent" is more obvious, because the programmer has explicitly written out "int" as the type. Solutions This is a code style issue, so there are a few different solutions and you pick whatever one you feel comfortable with. Leave the warning on (noisy, may distract you from real warnings) Assign the expression to an int first (verbose) Disable the warning across the code base (if you don't think it's helpful) Disable the warning around this location with a #pragma warning (very verbose)
71,013,640
71,013,722
WinAPI equivalent for Linux/POSIX pthread_wait/pthread_post
I have an application which takes care of some syncronization problems, it relies heavily on the POSIX functions, sem_wait, pthread_join and sem_post, I'd like to know what are the winapi equivalents for these?
sem_wait() -> WaitForSingleObject() on a Semaphore object pthread_join() -> WaitForSingleObject() on a Thread object sem_post()-> ReleaseSemaphore() on a Semaphore object See Using Semaphore Objects in MSDN's documentation.
71,014,380
71,014,489
What I need write this second SFINAE constructor?
I wanted to activate a class with parameter packs when all types in the parameter pack is distinct. I wrote a small helper function like this that works with no problem: template<typename T, typename... Ts> constexpr bool has_duplicate_types() { if constexpr (sizeof...(Ts) == 0) return false; else return ((std::is_same_v<std::decay_t<T>, std::decay_t<Ts>> || ...) || has_duplicate_types<Ts...>()); } When I tried to activate my class using SFINAE, I tried several method and the working one was this: template<typename T, typename dummy = void, typename... Ts> struct XYZ_imp { XYZ_imp() { std::cout << "ok\n"; } }; template<typename T, typename... Ts> struct XYZ_imp<T, std::enable_if_t<has_duplicate_types<T, Ts...>()>, Ts...> { XYZ_imp() = delete; }; template<typename T, typename... Ts> using XYZ = XYZ_imp<T, void, Ts...>; But as you see, it is too much code. But when I tried to write it like this: template<typename T, typename... Ts> struct XYZ { template<typename U = T, std::enable_if_t<has_duplicate_types<U, Ts...>(), int> = 0> XYZ() = delete; }; I don't know why it is not working. It works as expected when there is a similar type like XYZ<int,int> and it says constructor is deleted, but when types differ like XYZ<int,double>, I get following error: no matching function for call to 'XYZ<int, double>::XYZ()' If I write another SFINAE constructor like this: template<typename T, typename... Ts> struct XYZ { template<typename U = T, std::enable_if_t<has_duplicate_types<U, Ts...>(), int> = 0> XYZ() = delete; template<typename U = T, std::enable_if_t<!has_duplicate_types<U, Ts...>(), int> = 0> XYZ() { std::cout << "ok\n"; } }; It will work, but I have no idea why I need to write 2nd one and it does not pick defaulted one without it automatically. Any idea why?
If I write another SFINAE constructor like this: ... It will work, but I have no idea why I need to write 2nd one and it does not pick defaulted one without it automatically. The compiler doesn't generate the default constructor if you define any custom constructor, even if that constructor is disabled by SFINAE. And since you need to write the non-=deleted constructor, you might as well remove the =deleted one: template<typename T, typename... Ts> struct XYZ { template <typename U = T, std::enable_if_t<!has_duplicate_types<U, Ts...>(), int> = 0> XYZ() { std::cout << "ok\n"; } };
71,015,806
71,020,162
Firestore authentication for multiple devices
I'm developing linux c++ desktop application that connects to Firebase. The app will be deployed on multiple devices. Is it possible to perform REST authentication (Sign in with email / password) for all of these devices using one common e-mail address or will it trigger a security alert when more than one sign in operations are performed at the same time? Is there any better solution to solve this problem?
A user can sign in to Firebase Authentication from multiple devices. There is no inherent limit to the number of devices a single user can sign in from.
71,015,864
71,016,004
Can we add a const to an inherited virtual member function
I am learning inheritance in C++. So for clearing my doubts i am trying out different examples. One such example which i don't understand is given below: struct Base { virtual void func(int a) { std::cout<<"base version called"<<std::endl; } }; struct Derived: Base { void func(int a) const //note the const here: Is this a new function or this function overrides the old virtual from base { std::cout<<"derived version called"<<std::endl; } }; Note that i have added const for the func member function inside struct Derived. My question is that: is this member function func inside Derive a new(separate from func inside Base) function or does this func in Derived overrides the old virtual func from Base? PS: My question is not about the meaning of const here since i know that in this context it means a const member function which means that that the object to which this pointer points is treated as const object. My question is whether func inside Derived a different function that the one inside Base.
The member function func inside Derived is a separate/different non-virtual member function from the virtual func inside Base, as explained below. Explanation You can confirm this: by adding the specifier override after const of func in Derived as shown here you will see the error saying marked override, but does not override This confirm that the func in Derived does not override the virtual from func from Base. struct Derived: Base { void func(int a) const override //added keyword override. This gives error now { std::cout<<"derived version called"<<std::endl; } }; moreover, by adding the specifier final after the const of func in Derived as shown here you will see the error saying marked final, but is not virtual This confirm that the func in Derived is a non-virtual member function. struct Derived: Base { void func(int a) const final //added keyword final. This gives error now { std::cout<<"derived version called"<<std::endl; } }; Combining these two points, we come to the conclusion that func inside Derived is a non-virtual member function that is separate from the virtual member function func inside Base. We say that func that belongs to Derived hides the virtual func in Base. So effectively, Derived has two functions named func. One that it inherits from Base which is implicitly virtual and second that it defines which is a nonvirtual. Also note that there is another way of confirming that the func inside Derived is a nonvirtual member function by just declaring it and not defining it as shown here because we must define a virtual member function. On the other hand if the member function is nonvirtual we can have its declaration without having its definition as long as we do not call that member function. struct Derived: Base { void func(int a) const; //note this is a declaration and not a definition. This works as long as you do not call this function. You cannot do this with a virtual member function };
71,015,912
71,032,215
HID USB ReadFile() missing packets during large downloads
I implemented a HID USB PC application which seems to work fine for connecting, readin and writing to an external USB device. The problem is when attemping to read large data files, some packets get lost. Here is the code im using: DWORD result; uint8_t u8_dataBuffer[size] = { 0 }; DWORD bytesRead; ReadFile(Handle, u8_dataBuffer, size + 1, &bytesRead, (LPOVERLAPPED)&m_HidOverlapped)) result = WaitForSingleObject(Handle, 6000); switch (result) { case WAIT_OBJECT_0: { break; } case WAIT_TIMEOUT: { result = CancelIo(Handle); CloseHandle(Handle); deviceFound = false; break; } default: { break; } }
HID reports are saved in a ring buffer. So if you don't fast enough to read all pending input reports - they could be lost. Size of this buffer could be changed via HidD_SetNumInputBuffers call or IOCTL_SET_NUM_DEVICE_INPUT_BUFFERS IOCTL on HID device handle. By default, the HID class driver maintains an input report ring buffer that holds 32 reports. See Troubleshooting HID Reports#Dropped HID Reports for additional info.
71,016,630
71,016,716
"Invalid use of non-static data member" when initializing static member from global variable
class A { int x; static int i; }; int x = 10; int A::i = x; When I compile the code above, it get the error <source>:8:12: error: invalid use of non-static data member 'A::x' 8 | int A::i = x; | ^ <source>:2:9: note: declared here 2 | int x; | ^ What's causing this error?
This is a peculiar language quirk - the scope resolution on the left, in int A::i, affects the lookup scope on the right, so that actually refers to the x member of A. Either rename one of the variables, or specify the scope of the desired x explicitly: int A::i = ::x;
71,016,677
71,016,935
When does std::format throw an exception?
I am using OutputDebugStringA() to output diagnostic info from my program that I can read with DbgView. Today I am using std::stringstream to format messages: int value = 5; std::stringstream ss; ss << "value=" << value; OutputDebugStringA(ss.str().c_str()); This is rather verbose and I am looking into using std::format() instead: int value = 5; OutputDebugStringA(std::format("value={0}",value).c_str()); which seems nice. My only worry is that std::format may throw an exception. But under which circumstances? It would be really bad if some diagnostic or error checking code I write itself throws an exception that messes up the execution of my program. EDIT: example that throws an exception: std::string s = std::format("value={},{}", value);
My only worry is that std::format may throw an exception. But under which circumstances? From [format.err.report]: Formatting functions throw format_­error if an argument fmt is passed that is not a format string for args. They propagate exceptions thrown by operations of formatter specializations and iterators. Failure to allocate storage is reported by throwing an exception as described in [res.on.exception.handling]. In short, format_error will be thrown when your format string is not valid for format arguments.
71,017,753
71,018,114
benefits for setting dependency interface in cmake target_link_libraries
I use CMake in my C++ project for a while, and my project is an application (not a library) consisting of multiple sub modules, where each module depends on other internal modules in the same project, and depends on multiple third party libraries as well, and each of them is built using CMake. Currently, we use PUBLIC in target_link_libraries when specifying these dependencies. I read some articles/documentations [1][2][3] about this topic, and know the general difference between PUBLIC/INTERFACE/PRIVATE, and know that it is recommended to specify different visibility as detailed as possible. But since I am building an application but not a library, I am not worried that internal APIs are "leaked" accidentally, is there any other benefit that we should choose to use non PUBLIC visibility like PRIVATE? For example, besides affecting linking's speed, does it affect compilation speed? If linking doesn't take too much time, does it still make sense to optimize compilation speed by exploring this option? Does it affect the size of the binary in the end? Or is there any other benefit for controlling this behavior? Thanks. [1] https://cmake.org/cmake/help/latest/command/target_link_libraries.html [2] https://leimao.github.io/blog/CMake-Public-Private-Interface/ [3] https://cmake.org/pipermail/cmake/2016-May/063400.html
You should absolutely always use a visibility specifier with target_link_libraries. Whether or not target_link_libraries(target lib) is considered to be PRIVATE or PUBLIC by default depends on whether or not you use visibility specifiers elsewhere in the CMakeLists.txt. This risk of changing the visibility of a library simply by adding a different library should really be all the justification anyone needs to just use the maintainer-recommended best practices. Having too many public dependencies will eventually lead to pointlessly long link lines, which can indeed bloat link times as the linker will need to determine that a symbol is not relevant. Worse, it's possible that one library that didn't need to be public will win a symbol conflict incorrectly and cause trouble. There's simply no reason to intentionally set up an inaccurate dependency model. Finally, for executables, which visibility specifier to use is usually simple to choose: 99% of the time, it will be PRIVATE. However, this is not always the case. If you are building a plugin system, say, you might have ENABLE_EXPORTS set on your executable. In this case, libraries may in fact link to the executable target and visibility becomes relevant again.
71,018,062
71,019,037
Save a PCL specific view as image
I am new to C++ and the use of the Pointcloud Library PCL (https://pointclouds.org/). At the moment I am able to generate a viewer of the point cloud by using the <pcl::visualization::PCLVisualizer> and I was wondering if it would be possible to save an image of the current viewer "view". Imagine I have a picture like the following: At the moment I just take a screenshot manually of what it looks like. However, since I will be processing many point clouds, I would like to have a way to convert this "viewer view" to an image.
Of course I posted the question after researching online. However, I could not find the super easy solution available already in PCL. You just need to use the function: void pcl::visualization::PCLVisualizer::saveScreenshot ( const std::string & file ) Documentation here I hope this will be helpful for someone else in the same situation.
71,018,897
71,042,174
Yocto recipe to compile C++ program with usb.h include
I would like to compile a c++ program in my yocto toolchain. For this, I added a new recipe that should compile the program and install it into the image. My issue is that I have to include some kernel headers like `usb.h`` recipe.bb SUMMARY = "Simple helloworld application" SECTION = "examples" LICENSE = "MIT" LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302" SRC_URI += "file://dcdc-nuc.h \ file://dcdc-nuc.cpp \ file://dcdc-nuc-console.cpp \ " S = "${WORKDIR}" TARGET_CC_ARCH += "${LDFLAGS}" do_compile() { ${CXX} ${BUILD_CXXFLAGS} dcdc-nuc-console.cpp -o dcdc-nuc } do_install() { install -d ${D}${bindir} install -m 0755 dcdc-nuc ${D}${bindir} } Current message | In file included from dcdc-nuc-console.cpp:23: | dcdc-nuc.h:23:10: fatal error: linux/usb.h: No such file or directory | 23 | #include <usb.h> | | ^~~~~~~ | compilation terminated. | WARNING: exit code 1 from a shell command. I know that I have to make the compile aware of the kernel headers but I'm not able to find any hint on how to do this. Thanks for all the help in advance!
I believe you need to add libusb as a dependence to your recipe. Add the following line to your recipe: DEPENDS = "libusb"
71,019,078
71,019,832
Efficient overflow-immune arithmetic mean in C/C++
The arithmetic mean of two unsigned integers is defined as: mean = (a+b)/2 Directly implementing this in C/C++ may overflow and produce a wrong result. A correct implementation would avoid this. One way of coding it could be: mean = a/2 + b/2 + (a%2 + b%2)/2 But this produces rather a lot of code with typical compilers. In assembler, this usually can be done much more efficiently. For example, the x86 can do this in the following way (assembler pseudo code, I hope you get the point): ADD a,b ; addition, leaving the overflow condition in the carry bit RCR a,1 ; rotate right through carry, effectively a division by 2 After those two instructions, the result is in a, and the remainder of the division is in the carry bit. If correct rounding is desired, a third ADC instruction would have to add the carry into the result. Note that the RCR instruction is used, which rotates a register through the carry. In our case, it is a rotate by one position, so that the previous carry becomes the most significant bit in the register, and the new carry holds the previous LSB from the register. It seems that MSVC doesn't even offer an intrinsic for this instruction. Is there a known C/C++ pattern that can be expected to be recognized by an optimizing compiler so that it produces such efficient code? Or, more generally, is there a rational way how to program in C/C++ source level so that the carry bit is being used by the compiler to optimize the generated code? EDIT: A 1-hour lecture about std::midpoint: https://www.youtube.com/watch?v=sBtAGxBh-XI Wow! EDIT2: Great discussion on Microsoft blog
The following method avoids overflow and should result in fairly efficient assembly (example) without depending on non-standard features: mean = (a&b) + (a^b)/2;
71,019,328
71,019,867
Mismatch in integer calculation results between C++ and Python (random number generator)
I needed a pseudo random number generation scheme (independent of standard libraries) for one of my projects and I tried a simple LCG based RNG. It seems to work fine except that it produces different values in C++ and Python. I am giving the relevant code for both below. I am not able to find the error. Any help will be greatly appreciated! (c++) // file: lgc.cc // compile and run with: g++ lgc.cc -o lgc && ./lgc #include <cstdio> #include <cstdint> #include <vector> using namespace std; uint64_t LGC(uint64_t x) { uint64_t A = 1103515245; uint64_t C = 12345; uint64_t M = (1 << 31); return (A * x + C) % M; } int main(int argc, char* argv[]) { for (auto x : {485288831, 485288832, 10, 16, 255, 756}) { uint64_t y = LGC(x); printf("%u %u\n", (uint32_t)x, (uint32_t) y); } return 0; } (python) # file: lgc.py # run with: python3 lgc.py def LGC(x): A = 1103515245; C = 12345; M = int(2 ** 31); return (A * x + C) % M; for x in [485288831, 485288832, 10, 16, 255, 756]: y = LGC(x) print(x, y) (Results: c++) 485288831 3822790476 485288832 631338425 10 2445230203 16 476387081 255 2223525580 756 1033882141 (Results: python) 485288831 1675306828 485288832 631338425 10 297746555 16 476387081 255 76041932 756 1033882141
The problem is with the shift in: uint64_t M = (1 << 31); the (1<<31) is a negative number -2147483648 for 32 bit integers because this is signed integer math. To fix you can use uint64_t M = (1U << 31); to make the shift use unsigned 32 bit integers. You could also use uint64_t M = (1UL << 31); to have the calculation use 64 bit unsigned integers The following link shows printing the output of: (1 << 31), (1U << 31) and (1UL << 31) on a system with 32 bit int: https://ideone.com/vU0eyX
71,020,122
71,129,303
Detecting circles with DIPlib
I'm trying to detect the circles in this image: and then drawing such circles in another blank image using DIPlib in C++. Following the advices of Cris Luengo I've changed the code and now looks like this: #include <iostream> #include <vector> #include <diplib.h> #include <dipviewer.h> #include <diplib/file_io.h> #include <diplib/display.h> #include <diplib/color.h> #include <diplib/linear.h> #include <diplib/detection.h> #include <diplib/generation.h> using namespace std; int main() { try{ //read image dip::Image img; dip::ImageReadTIFF(img,"circle.tif"); dip::ColorSpaceManager csm; img = csm.Convert(img, "grey"); //circle detection //first convert the image in binary dip::Image bin_img = img<128; //Now calculate the gradient vector of the images dip::Image gv=dip::Gradient(img); //Apply the Hough transform to find the cicles dip::FloatCoordinateArray circles; circles=dip::FindHoughCircles(bin_img,gv,{},0.0,0.2); //Draw circles dip::Image detec_img= g_img.Similar(dip::DT_UINT8); for(auto i: circles){ dip::FloatArray center; center.push_back(i[0]); center.push_back(i[1]); dip::dfloat diameter=i[2]*2; dip::DrawBandlimitedBall(detec_img,diameter,center, {255}, "empty"); center.clear(); } dip::ImageWriteTIFF(detec_img, "detected.tif"); I also changed the parameters of the FindHoughCircles function because there are two concentric circles in the image so the distance between centers has to be 0.0 but the program is unable to detect it. This is the result:
The documentation for dip::FindHoughCircles reads: Finds circles in 2D binary images using the 2-1 Hough transform. First, circle centers are computed using dip::HoughTransformCircleCenters, and then a radius is calculated for each center. Note that only a single radius is returned per center coordinates. That is, this function is not able to find concentric circles. One workaround could be to run the function twice, with different limits for the circle sizes. In DIPlib, all allocated images (either through the dip::Image constructor, though img.Forge(), through img.Similar(), etc.) are not initialized. You need to explicitly set the pixels to zero before you start drawing in it: detec_img.Fill(0). Your output image has some very nice display of previous memory use in the bottom half, I wonder what computations lead to that! :)
71,020,324
71,022,902
Function log2l has no function body
I am new to Vivado HLS ( using Vivado HLS 2018.3 ). I am writing this code to generate a 16-bit CRC (Cyclic Redundancy Check) using a 128-bit message and 17-bit generator polynomial. Here in the source code, I am using log2l() in order to find out the number of bits. This code runs smoothly during C Simulation but during C Synthesis, it throws the error : Function 'log2l' has no function body Please see the full source code below : #include "header.h" #include "ap_int.h" using namespace std; int crc(ap_int<128> dword,ap_int<17> gen){ int l_gen = floor(log2l(gen) + 1); ap_int<136> dividend = dword << (l_gen-1); // shft specifies the no. of least significant bits not being XORed int shft = (int) (floor(log2l(dividend))+1) - l_gen; ap_int<16> rem; //rem variable stores the CRC value while (shft >= 0){ // bitwise XOR the MSBs of dividend with generator // replace the operated MSBs from the dividend with // remainder generated rem = (dividend >> shft) ^ gen;// // (dividend & ((1 << shft) - 1)) : bits of dividend that were not XORed dividend = (dividend & ((1 << shft) - 1)) | (rem << shft); // new dividend // change shft variable shft = (int) (floor(log2l(dividend))+1) - l_gen; } // finally, AND the initial dividend with the remainder (=dividend) ap_int<144> codeword; //128 bit message plus 16 bit CRC = 144 bit codeword = (dword << (l_gen - 1)) | dividend; cout << "Remainder: " << dividend << endl; cout << "Codeword to be sent : " << codeword << endl; return 0 ; } The test bench that I am using is : #include "header.h" #include "ap_int.h" using namespace std; int crc(ap_int<128> , ap_int<17> ); int main() { ap_int<128>dataword ; ap_int<17> generator; dataword = 36; generator = 13; crc(dataword, generator); cout<<" Majid wins"; return 0; } The header file is : #include<iostream> #include<math.h> #include "ap_fixed.h" #include "hls_stream.h" In C simulation, the output that I get is : Remainder: 1 Codeword to be sent : 289 Majid wins I am using only three files : source , testbench and header. Please tell me why this code is not working in C Synthesis. Also if you find anything amiss in my code, please tell me. Thanks !
I suspect it has something to do with the inclusion of the math library. I guess Vivado HLS has some configurations or flags to supply in compilation and then in synthesis regarding the use of mathematical functions. Nevertheless, a simple and effective workaround would be to implement floor(log2(x)) yourself, something that looks as follows: template <typename T> unsigned int mylog2 (T val) { #pragma HLS PIPELINE II=1 if (val == 0) return (1 << (val::size-1)); // A very big number, assuming T is always ap_int<> if (val == 1) return 0; unsigned int ret = 0; while (val > 1) { val >>= 1; ret++; } return ret; } I'm pretty sure that Vivado will optimize the function and generate a proper hardware module. Reference: How to do an integer log2() in C++? Edit: I added a Pipeline pragma in order to be sure to obtain a 1-cycle hardware module.
71,020,560
71,021,030
Is OutputDebugString thread safe?
In my code I call these methods at various places to send diagnostic output to DbgView: inline void dbg_info(std::string s) { std::stringstream ss; ss << "INFO:" << std::this_thread::get_id() << ": " << s << std::endl; OutputDebugStringA(ss.str().c_str()); } inline void dbg_err(std::string s) { std::stringstream ss; ss << "ERROR:" << std::this_thread::get_id() << ": " << s << std::endl; OutputDebugStringA(ss.str().c_str()); } Is the method OutputDebugStringA() thread safe or could it mix messages from multiple threads being output at the same time? If not would it be sufficient and a good idea to create a static member variable of std::mutex and lock this in my two methods above?
Yes it is thread safe. It uses a mutex and events. Implementation details here.
71,020,873
71,020,903
Error main: malloc.c:2401: sysmalloc: Assertion Doing a simple C++ fibonacci assignment
I am working on this assignment and i trying to figure this out. When i input any other numbers between 1 to 10 except 6. The fibonacci_fast(n) outputs an error main: malloc.c:2401: sysmalloc: Assertion. However, when i use an array to replace the vector or just uncomment the std::cout. It will work fine. Can anyone enlighten me what's the error that i have made. #include <iostream> #include <cassert> #include <vector> #include <algorithm> int fibonacci_naive(int n) { if (n <= 1) return n; return fibonacci_naive(n - 1) + fibonacci_naive(n - 2); } int fibonacci_fast(int n) { std::vector<int> numbers{0,n}; numbers[0] =0; numbers[1] =1; int ans=0; if (n <= 1) { return n; } //std::cout<<std::endl; //int numbers[n]; for(int i=2;i<=n;i++) { numbers[i] = numbers[i-1] + numbers[i-2]; } ans = numbers[n]; return ans; } void test_solution() { assert(fibonacci_fast(3) == 2); assert(fibonacci_fast(10) == 55); for (int n = 0; n < 20; ++n) assert(fibonacci_fast(n) == fibonacci_naive(n)); } int main() { int n = 0; std::cin >> n; //std::cout << fibonacci_naive(n) << '\n'; //test_solution(); std::cout << fibonacci_fast(n) << std::endl; return 0; }
std::vector<int> numbers{0,n}; creates a vector of size 2, not of size n. You probably want to use std::vector<int> numbers(n, 0).
71,021,297
71,021,457
std::set elements' reference and pointer invariance after insertion
I came across a paragraph on cppreference that I don't think I understand: No iterators or references are invalidated. [If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid. (since C++17)] I expect that No iterators or references to already existing objects within the set are invalidated means that the following is correct: std::set<person> set{person{"Kate", "Oceanic"}}; const auto &kate = *set.cbegin(); std::cout << kate.flight << std::endl; // this does not invalidate reference to Kate set.insert(person{"John", "Oceanic815"}); std::cout << kate.flight << std::endl; But I don't get what the part for C++17 means: ...pointers and references to the element obtained while it is held in the node handle are invalidated, ... Does node handle refer to an iterator? ... and pointers and references obtained to that element before it was extracted become valid What does exactly become mean here? The full example: #include <set> #include <string> #include <iostream> struct person { std::string name; std::string flight; bool operator<(const person& other) const { return name < other.name; } }; int main() { std::set<person> set{person{"Kate", "Oceanic"}}; const auto &kate = *set.cbegin(); std::cout << kate.flight << std::endl; // this does not invalidate Kate set.insert(person{"John", "Oceanic815"}); std::cout << kate.flight << std::endl; // is new Kate created within the same address? set.insert(person{"Kate", "Oceanic815"}); std::cout << kate.flight << std::endl; return 0; }
Does node handle refer to an iterator? No. A "node handle", introduced in C++17, refers to the data structure internal to a std::set used to hold a single element. It's what the std::set will allocate from the free store to hold the element and any related data structures, such as pointers and flags. A handle to this structure allows elements to be removed from a set (via std::set::extract) without triggering a memory deallocation, and added to a set without triggering a memory allocation. and pointers and references obtained to that element before it was extracted become valid What does exactly become mean here? It means that pointers and references to an element in a node handle are invalid when they are extracted, but they are valid once again when that same node handle is inserted back into a set.
71,021,339
71,021,440
C++: [[maybe_noreturn]]
As far as I am aware, there is no [[maybe_noreturn]] attribute in C++. I have a function which looks like this: void func() { try { do_something(); } catch (const std::exception& e) { std::exit(1); } } If I would mark func as [[noreturn]] I'd run into UB for the happy case. Is it UB when I do not return from a function that is not marked as [[noreturn]]? Or are there other language constructs, compiler extensions or libraries that implement something like [[maybe_noreturn]]?
Is it UB when I do not return from a function that is not marked as [[noreturn]]? No, it's well defined to terminate the program from a function regardless whether it has [[noreturn]] attribute or not. Using [[noreturn]] is optional when it is appropriate - i.e. when a function terminates unconditionally - but it is always recommended in such cases. No such attribute as [[maybe_noreturn]] is needed. If it were necessary, then you would find that you would have to declare any function potentially calling [[maybe_noreturn]] function to also be [[maybe_noreturn]], and then functions that call those functions, all the way to the top of the call chain.
71,021,818
71,022,125
Compiler insists rename() function is of type void
I'm trying to write a program capable of renaming files, but I'm encountering a weird issue. When I write this: string oldname, newname; rename(oldname, newname); Everything works fine. The file is renamed and there are no problems. But then when I go ahead and try this: int result; result = rename(oldname, newname); if(result) //stuff else //other stuff The "=" gets a fresh new red underline and I get an error "a value of type "void" cannot be assigned to an entity of type "int"". I also tried if(rename(oldname, newname)) //stuff Then I just get "expression must have bool type (or be convertible to bool)" Microsoft's documentation says that the rename function returns 0 if successful and nonzero if not successful. After a lot of googling I found countless examples of code that use the second or third snippet without issue, and none of it has helped me understand what might be different in my situation. The language standard is C++17. I can't think of any other relevant details, but just in case, here is a snippet of the actual code with all the "includes": #include <windows.h> #include <stdlib.h> #include <tchar.h> #include <vector> #include <string> #include <filesystem> #include <fstream> #include <time.h> #include <iostream> #include <codecvt> #include <locale> #include <sstream> #include <windowsx.h> #include <Shlobj.h> using namespace std; using namespace std::filesystem; tmp_wstr = oldname + L"\n\nwill be renamed to:\n\n" + newname + L"\n\nWould you like to proceed?"; msgboxID = MessageBox(NULL, tmp_wstr.c_str(), L"Renaming...", MB_YESNO | MB_SYSTEMMODAL); switch (msgboxID) { case IDYES: result = rename(oldname, newname); if (result) { error = true; msgboxID = MessageBox(NULL, L"Unable to rename", NULL, MB_OK | MB_SYSTEMMODAL); } else error = false; break; case IDNO: error = true; break; } Here oldname and newname are wstring instead of string, but I have tried using string and the error persists.
You are expecting to call the C standard library function rename() with signature: int rename(const char*, const char*); But that function would not be a viable overload for rename(oldname, newname) if oldname and newname are of type std::(w)string, since std::(w)string is not implicitly convertible to const char*. So, you must be calling a different function named rename(). Since you used: using namespace std::filesystem; you are, in fact, calling the following overload of the C++ standard library function std::filesystem::rename() with signature: void rename(const std::filesystem::path&, const std::filesystem::path&); which is viable with your arguments, since std::filesystem::path is constructible from std::(w)string. This function has a void return type, explaining the error messages. As explained in the link, it doesn't return a status code, but instead throws an exception if there is an error.
71,021,895
71,022,137
How to unravel type dependency? (X uses undefined class Y)
I'm trying to implement simplistic fast memory management for my delegate type, but encountered circular dependency which I can't solve myself. // Size of single bucket of delegates static constexpr size_t _alloc_buffer_bucket_size = 128; template <typename TFunc, typename... Args> struct bucket; template <typename TFunc, typename... Args> class Delegate final : public IDelegate { . . . static void* operator new (size_t size) { auto bckt = _current_bucket; // gives compilation error here } private: // Size of single bucket of delegates static constexpr size_t _alloc_buffer_bucket_size = 128; struct bucket { // stores currently occupied slots in bucket. size_t allocated_slots = 0; // when this bucket is filling with values, this size_t current_slot = 0; std::array<Delegate<TFunc, Args...>, _alloc_buffer_bucket_size> slots = {}; }; // Vector of buckets. inline static std::vector<bucket*> _alloc_buffer = { new bucket(), }; // This is a pointer to currently filling bucket. New delegates are added here // by delegate allocator. // When this bucket reaches _alloc_buffer_bucket_size of items, this pointer is // replaced with either newly allocated bucket or existing and empty bucket. inline static bucket* _current_bucket = &(_alloc_buffer[0]); }; This gives me "'Delegate<void (*)(void)>::bucket::slots' uses undefined class 'std::array<Delegate<void (*)(void)>,128>'". How can I break this circular dependency? I've tried using more pointers, moving bucket outside of Delegate scope, but this error remains.
By moving the definition of the bucket struct outside of the scope of Delegate and assigning the _alloc_buffer and _current_bucket variables outside of the class scope, we can achieve compilation. I was able to get it compiling as such: // Size of single bucket of delegates static constexpr std::size_t _alloc_buffer_bucket_size = 128; template <typename TFunc, typename... Args> struct bucket; template <typename TFunc, typename... Args> class Delegate final : public IDelegate { public: Delegate() = default; static void* operator new (std::size_t size) { auto bckt = _current_bucket; // gives compilation error here return nullptr; // added to get rid of the error } private: // Vector of buckets. static std::vector<bucket<TFunc, Args...>*> _alloc_buffer; // This is a pointer to currently filling bucket. New delegates are added here // by delegate allocator. // When this bucket reaches _alloc_buffer_bucket_size of items, this pointer is // replaced with either newly allocated bucket or existing and empty bucket. static bucket<TFunc, Args...>* _current_bucket; }; template <typename TFunc, typename... Args> struct bucket { // stores currently occupied slots in bucket. std::size_t allocated_slots = 0; // when this bucket is filling with values, this std::size_t current_slot = 0; std::array<Delegate<TFunc, Args...>, _alloc_buffer_bucket_size> slots = {}; }; template <typename TFunc, typename... Args> std::vector<bucket<TFunc, Args...>*> Delegate<TFunc, Args...>::_alloc_buffer = { new bucket<TFunc, Args...>(), }; template <typename TFunc, typename... Args> bucket<TFunc, Args...>* Delegate<TFunc, Args...>::_current_bucket = &(_alloc_buffer[0]); By splitting up the declaration and definition of the static variables and by splitting out the bucket type, the Delegate class is defined by the time we go to actually use it. See it in action here: https://godbolt.org/z/bx7hh1av9 Edit: Tested this minimum sample on MSVC and Clang.
71,022,354
71,026,288
how to use c++ ->() operator to get a baseclasses private member? so I can access derived?
I am attempting to access a derived class TMAConnection after receiving it via a baseclass factory method template <> class cpool::ConnectionPoolFactory<TMAConnection> { public: static std::unique_ptr<cpool::ConnectionPool> create( const std::uint16_t num_connections, const char* tma_gw_host, const int tma_gw_port) { std::vector< std::unique_ptr<cpool::Connection> > connections; for ( std::uint16_t k = 0; k < num_connections; ++k ) { // cannot use std::make_unique, because constructor is hidden connections.emplace_back( std::unique_ptr<TMAConnection>( new TMAConnection{tma_gw_host, tma_gw_port} ) ); } return std::unique_ptr<cpool::ConnectionPool>( new cpool::ConnectionPool{std::move( connections )} ); } }; My trouble comes trying to access the derived classes functions and members.. such as TestCPPClient member, or querySymbols function... class TMAConnection final : public cpool::Connection { public: TMAConnection(const char* hostname, const int port){ this->gateway_host=hostname; this->gateway_port=port; } bool heart_beat() override { return connected; } bool is_healthy() override { return connected; } bool connect() override { connected = true; return connected; } void disconnect() override { connected = false; } void querySymbols(std::vector<tmaapi::CD> & empty_contract_vect, std::vector<std::string> & queries_list) { this->tma_client.query_matching_tickers(empty_contract_vect, queries_list); std::vector<std::string> empty_vec; } TestCppClient tma_client; private: TMAConnection(){} friend cpool::ConnectionPoolFactory<TMAConnection>; bool connected = false; const char* gateway_host; int gateway_port; uint16_t tma_client_id; }; When I look look at the ConnectionProxy code.. it seems i can get the member or derived class with an operator -> but no avail so far https://github.com/malikkirchner/connection-pool/blob/master/src/pool.cpp#L61-L63 Connection* ConnectionPool::ConnectionProxy::operator->() { return m_connection; } Connection& ConnectionPool::ConnectionProxy::operator*() { return *m_connection; } Here's where I try to call create to get a connection.. but then fail to get my derived class pointer cpool::ConnectionPool::ConnectionProxy proxy_conn = this->tma_conn_pool->get_connection(); proxy_conn->is_healthy(); // this works fine if i don't cast.. since it's in the base class proxy_conn->querySymbols(empty_contract_vect, sub_batch_vector); // this fails I tried adding a dynamic cast.. doesn't seem to work cpool::ConnectionPool::ConnectionProxy proxy_conn = this->tma_conn_pool->get_connection(); TMAConnection* x = dynamic_cast<TMAConnection*>(&proxy_conn)); x->is_healthy(); x->querySymbols(empty_contract_vect, sub_batch_vector); /home/server/src/server.cpp:48:64: error: cannot dynamic_cast ‘& proxy_conn’ (of type ‘class cpool::ConnectionPool::ConnectionProxy*’) to type ‘class TMAConnection*’ (source type is not polymorphic) 48 | TMAConnection* x = dynamic_cast<TMAConnection*>(&proxy_conn)); How can I get a pointer to my derived class? is my factory wrong? thank you EDIT: I tried @typewriters suggestion to use auto .. still didn't work auto proxy_conn = this->tma_conn_pool->get_connection(); TMAConnection* x = dynamic_cast<TMAConnection*>(&proxy_conn)); error: cannot dynamic_cast ‘& proxy_conn’ (of type ‘class cpool::ConnectionPool::ConnectionProxy*’) to type ‘class TMAConnection*’ (source type is not polymorphic)
ConnectionPool::get_connection() returns a ConnectionProxy which is not a Connection object directly, but holds one: A ConnectionProxy allows you to access the underlying connection object. // create a pool auto pool = ... // get a ConnectionProxy auto proxy = pool->get_connection(); // cast to your type if(auto conn = dynamic_cast<TMAConnection*>(proxy.operator->())) { // success! }
71,022,720
71,022,877
What the value of "chrono::steady_clock::now().time_since_epoch().count()" represents?
cout << chrono::steady_clock::now().time_since_epoch().count() << "\n"; // it prints a 14-digit value Is is the number of nanoseconds passed since 1970?
Is is the number of nanoseconds passed since 1970? Very unlikely. It is the number of some duration unit passed since some time. Neither the unit nor the epoch is standardized. This may not sound useful, and a single reading of std::chrono::steady_clock::now() arguably isn't very useful. (Beyond, say, seeding a random number generator perhaps) steady_clock readings are intended to be compared against other steady_clock readings. It is useful for measuring elapsed time. The count() is only useful if you cast the duration to a known duration period.
71,022,852
71,022,923
c++ template with partially fixed argument list
Consider a case like the following: template<typename T> class A { ... }; template<typename T, typename DataType = std::vector<A<T>>> class B { .... DataType data; ... } In my case the DataType type can be any std "container", but it must always be specialized with type A. The use of A should be transparent from outside class B, however in the definition of B without the default type for DataType one should explicitly specify e.g. B<int, std::deque<A<int>>. I'd like to remove this possibility and achieve something like: template<typename T, typename container = std::vector> class B{ using DataType = container<A<T>>; ... } so that I would specialize B like B<int, std::vector>. Of course it cannot be exactly like this because container in this case should a complete type and then must be specialized. Is there a way to achieve this with c++14?
You can do it with template template parameter, e.g. template<typename T, template <typename...> typename container = std::vector> class B { using DataType = container<A<T>>; ... }; Then use it like B<int> (i.e. B<int, std::vector>) or B<int, std::deque>.
71,022,928
71,023,359
Why doesn't std::integral_constant<lambda> work the same way as std::integral_constant<function-ptr>?
(related to this question). I am trying to combine unique_ptr and lambda via std::integral_constant (taking address of most std functions is outlawed in C++20, I am figuring out a convenient way to wrap them in lambda). I noticed weird behaviour of std::integral_constant that I can't explain (godbolt): #include <type_traits> template<auto L, class T = decltype(L)> using constant = std::integral_constant<T, L>; void dummy(void*); int main() { using C1 = constant<&dummy>; using C2 = constant<[](void* p){ dummy(p); }>; C1()()(nullptr); // #1 works as expected C2()()(nullptr); // #2 works as expected C1()(nullptr); // #3 unexpectedly works C2()(nullptr); // #4 fails as expected return 0; } Can someone explain why line #3 compiles? This is what std::unique_ptr uses under cover (when you use std::integral_constant as deleter) and this is why my attempts to use lambda instead of function address fail. P.S. Line #4 fails with following message: <source>: In function 'int main()': <source>:17:17: error: no match for call to '(C2 {aka std::integral_constant<const main()::<lambda(void*)>, <lambda closure object>main()::<lambda(void*)>{}>}) (std::nullptr_t)' 17 | C2()(nullptr); // #4 fails as expected
When performing a function call on an object, not only the call operators are considered. There is a special exception if a non-explicit conversion function to a function pointer type (or function reference type) with suitable cvref-qualifiers exists. In these situations [over.call.object]/2 says that an additional overload is generated, a surrogate call function which takes the converted implicit object pointer as first argument and the function pointer/reference's parameters as further parameters. If this overload is chosen, it will use the conversion function to convert this to the function pointer/reference and then call it with the remaining provided arguments. std::integral_constant has a non-explicit conversion function to value_type and so if value_type is a function pointer/reference, and only then, will this surrogate call exist, which essentially forwards the object function call to a call to the stored function pointer/reference.
71,023,144
71,024,534
How to build header only C++ library within Bazel workspace?
I'm working on a C++ project and I need Numpy like arrays and functionalities in C++. I found some alternatives like xtensor, NumCpp etc. These are header only libraries. The problem is I'm experimenting with Bazel for the first time so, I don't have any idea about how do I add header only library to Bazel workspace. There are some suggestions like genrule-environment, rules-foreign-cc suggested on other questions around Bazel. I've added http_archive to WORKSPACE file, but I'm not sure what to add in BUILD file. WORKSPACE file load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") all_content = """filegroup(name = "all", srcs = glob(["**"]), visibility = ["//visibility:public"])""" http_archive( name = "xtensor", build_file_content = all_content, strip_prefix = "xtensor-master", urls = ["https://github.com/xtensor-stack/xtensor/archive/refs/heads/master.zip"], ) http_archive( name = "NumCpp", build_file_content = all_content, strip_prefix = "NumCpp-master", urls = ["https://github.com/dpilger26/NumCpp/archive/refs/heads/master.zip"], ) http_archive( name = "rules_foreign_cc", sha256 = "c2cdcf55ffaf49366725639e45dedd449b8c3fe22b54e31625eb80ce3a240f1e", strip_prefix = "rules_foreign_cc-0.1.0", url = "https://github.com/bazelbuild/rules_foreign_cc/archive/0.1.0.zip", ) load("@rules_foreign_cc//:workspace_definitions.bzl", "rules_foreign_cc_dependencies") rules_foreign_cc_dependencies() I've tried to follow documentation, but failed every time. Some help would be appreciated.
For simple things like header-only libraries, I would write BUILD files yourself, without using rules_foreign_cc. Just write a cc_library with no srcs. Something like this: http_archive( name = "xtensor", build_file_content = all_content, strip_prefix = "xtensor-master", urls = ["https://github.com/xtensor-stack/xtensor/archive/refs/heads/master.zip"], build_file_content = """ cc_library( name = "xtensor", visibility = ["//visibility:public"], hdrs = glob(["xtensor/*.hpp"]), defines = [ "XTENSOR_ENABLE_ASSERT", ], deps = [ "@tbb", ], ) """, ) @xtensor will be your Bazel repository. The build_file_content will be used to create a BUILD.bazel file in it. That means your code can depend on it via @xtensor//:xtensor, which can be shortened to just @xtensor. You can also put that in a separate file (say build/BUILD.xtensor.bazel) and then use build_file = "@build//:BUILD.xtensor.bazel" instead of putting it inline in WORKSPACE via build_file_content. rules_foreign_cc is going to generate something equivalent if you get it set up, but that seems like a lot more trouble to me than just writing it yourself. I set defines and deps based on a scan through the CMakeLists.txt, you'll want to customize based on how you want it configured. The only other thing I see that CMakeLists doing (beyond finding dependencies and setting some -D flags, which translate as shown above) is generating a single file that #includes all the others. If you want to do that, I'd do something like this (in the BUILD file for @xtensor): genrule( name = "gen_single_include", outs = ["xtensor.hpp"], cmd = "\n".join([ "cat > $@ <<'END'", "#ifndef XTENSOR", "#define XTENSOR", ] + ["#include \"%s\"" % h[len("xtensor/"):] for h in glob(["xtensor/*.hpp"]) if h not in [ "xtensor/xexpression_holder.hpp", "xtensor/xjson.hpp", "xtensor/xmime.hpp", "xtensor/xnpy.hpp", ]] + [ "#endif", "END", ]), I may not have gotten everything perfect here, but the idea is to build up the file using cat to copy stdin to it, a bash here document to feed the content in, and Python-style list comprehensions to actually build up the content.
71,023,177
71,023,375
My code is outputting an extra line why is this?
This code I've been working on is so close to being done. However, it keeps printing out an extra line in the output. There is only supposed to be 5 lines in the output but there is six and I can't figure out why this is happening. This is my book.h file this file cannot be changed in order to complete the code. #include <string> using namespace std; enum Type { UNKNOWN = -1, PAPERBACK, HARDBACK }; const string TYPE_WORDS[] = { "Paperback", "Hardback" }; class Book { public: //default constructor - not actually used but should be implemented anyway Book(); //constructor Book( const string& name, Type type, int pages, float ounces ); //destructor ~Book(){}; string formatReportLine(); //return a string with all the info for the book float getWeightLbs(); //calculate and return the weight of the book in lbs string getTypeName(); //return the string which correlates with the book type //accessors string getName(){ return bName; }; Type getType(){ return bType; }; int getPages(){ return bPages; }; float getOunces(){ return bOunces; }; private: string bName; //name of the book Type bType; //the type of book (Type is an enumerated type) int bPages; //how many pages the book contains float bOunces; //how much the book weighs in ounces }; This is the main.cpp file this file can be changed but should only have code added not taken out. #include <iostream> #include <fstream> #include <string> #include "book.h" using namespace std; int main() { const string FILENAME("books.txt"); const int INT_MAX = 1; ifstream input(FILENAME); if( input.good() ) { while( !input.eof() ) { string name; int type; int pages; float ounces; getline( input, name ); input >> type >> pages >> ounces; input.ignore(INT_MAX, '\n'); //ignore the newline char at the end of the line //create Book object here! Book myBook(name,(Type)type, pages, ounces); //write out report line for book here! cout << myBook.formatReportLine(); } } else { cout << "File not found: " << FILENAME << endl; } system("pause"); return 0; } This is the book.cpp file this is where the most change will be done file has some functions but most code will have to be added. #include <iostream> #include <fstream> #include <string> #include "book.h" #include "sstream" Book::Book() { } Book::Book( const string& name, Type type, int pages, float ounces ) { bName = name; bType = type; bPages = pages; bOunces = ounces; } float Book::getWeightLbs() { float answer; answer = bOunces / 16; return answer; } string Book::getTypeName() { string typeName = ""; if(bType == PAPERBACK) typeName = TYPE_WORDS[bType]; else if (bType == HARDBACK) typeName = TYPE_WORDS[bType]; else typeName = "Unknown"; return typeName; } string Book::formatReportLine() { stringstream sout; sout << bName << " | Type: " << getTypeName() << " Pages: " << bPages << " Weight(lbs): " << getWeightLbs() << endl; return sout.str(); } This is the book.txt file that the code is getting its data from. The Human Use of Human Beings 0 200 8.0 Utopia 0 176 4.8 Hackers 0 520 22.4 The Information 1 544 33.6 Sterling's Gold 1 176 8.0 This is what it is currently outputting. The extra line at the end that reads " | Type: Hardback Pages: 176 Weight(lbs): 0.5" should not be there and I can't figure out why it is outputting like that. The Human Use of Human Beings | Type: Paperback Pages: 200 Weight(lbs): 0.5 Utopia | Type: Paperback Pages: 176 Weight(lbs): 0.3 Hackers | Type: Paperback Pages: 520 Weight(lbs): 1.4 The Information | Type: Hardback Pages: 544 Weight(lbs): 2.1 Sterling's Gold | Type: Hardback Pages: 176 Weight(lbs): 0.5 | Type: Hardback Pages: 176 Weight(lbs): 0.5
There's probably a blank line at the end of the data file. Put in if (name.empty()) { continue; } just before you construct the book object. Also as @Eljay said in comments you shouldn't iterate over a file by doing while (!file.eof()): see here.
71,023,187
71,023,946
Can I use std::next on user defined class
If I have a user-defined class : class MyColl { int *data ; public : class Itr { int operator*() {} void operator++() bool operator != (const Itr &oth) } ; Itr begin() {} Itr end() {} } ; Can I use std::next on objects of MyColl If yes, then what needs to be done
// How to implement a forward iterator for your collection class template <typename T> class MyCollection { public: struct MyCollectionIterator { // These five typedefs tell other things about your iterator using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T&; explicit MyCollectionIterator( ... ) ... {} // These five methods implement the minimum required behavior of a forward iterator reference operator * () const {...} iterator & operator ++ () {...} iterator operator ++ (int) {...} bool operator == ( iterator that ) {...} bool operator != ( iterator that ) {...} }; MyCollectionIterator begin() { return MyCollectionIterator(...); } MyCollectionIterator end() { return MyCollectionIterator(...); } }; There are other iterator types beyond a forward iterator. If possible, you should implement the most capable iterator type you can: if not random access, then bidirectional, and if not bidirectional, then forward. Iterators have been an increasingly frightening thing to look at in C++ (see docs here), but the basic idea is simply a class that knows how to pretend to be a pointer sufficient to access your collection’s data. To do that it must provide certain kinds of information and capabilities. That little table of iterator types in the linked docs will help you when adding the required functionality to your iterator class.
71,023,392
71,023,704
Can I pass a built-in array to std::ostream_iterator without an array-to-pointer decay?
I have overloaded operator<< to print a built-in array const int (&arr)[N]: template <size_t N> std::ostream& operator<<(std::ostream& os, const int (&arr)[N]) { os << "{ "; bool first{true}; for (int i : arr) { os << (first ? "" : ", ") << i; first = false; } return os << " }"; } I can use it to print a const int (&)[5] array to std::cout: int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}}; for (const auto& subarr : arr) { std::cout << subarr << "\n"; } // Outputs: // // { 3, 4, 6, 1, 1 } // { 6, 3, 4, 5, 1 } // { 6, 1, 2, 3, 3 } However, when I try to print the same array via a std::copy to std::ostream_iterator<const int (&)[5]>, I just get the array address printed out: std::copy(std::cbegin(arr), std::cend(arr), std::ostream_iterator<const int (&)[5]>{std::cout, "\n"}); // Outputs: // // 0x7ffec4f84db0 // 0x7ffec4f84dc4 // 0x7ffec4f84dd8 I suppose the array is decaying to a pointer at the ostream_iterator end. If so, is there a way to avoid that? [Demo] for a working version. There are many questions in this site regarding array-to-pointer decay, but I haven't seen one that was helping with this case. Actually, this answer says: [...] you can also prevent decay in your original version of f if you explicitly specify the template agument T as a reference-to-array type f<int (&)[27]>(array); But that doesn't seem to be happening when constructing the ostream_iterator.
This has nothing to do with array-to-pointer decay and everything to do with how name lookup works. In this version: for (const auto& subarr : arr) { std::cout << subarr << "\n"; } your operator<< is a candidate because regular unqualified lookup will find it. But that's not what ostream_iterator does, its implementation internally will do something like this: template <typename T> void whatever(std::ostream& os, T const& arg) { os << arg; } And that os << arg call is going to not find your operator<< candidate by unqualified lookup (it won't have been declared at the point of definition of the header) and it's not going to find your operator<< by argument-dependent lookup (since it's not in an associated namespace of either argument). Since your function isn't a candidate, instead the one selected is the pointer one - which is why it formats the way it does. One (bad, don't do this) solution would be to put your operator<< overload inside of namespace std, which would cause argument-dependent lookup to be able to actually find it. But don't do this, since you're not allowed to add things to namespace std (and, generally speaking, shouldn't add your things to other people's namespaces). So the better solution would be to instead create your own type that formats the way you want it to, since then you can just add an operator<< that properly associates with it - in a way that doesn't involve messing with std.
71,023,590
71,023,659
how to pass pointer to constructor in c++
have a derived class that needs to take a pointer as a constructor for the base class. how do you do this in c++, i tried it but it gave me a bug. #include <iostream> using namespace std; class Base { protected: int *num; public: Base(int *num); virtual void print(); }; Base::Base(int *num){ this->num = num; }; class Derived : public Base { public: Derived(int *num) : Base(*num); void print(); }; Derived::print(){ cout << "int value : " << *(this->num); }; int main(){ int num = 5; int *p = &num; Derived derived(p); derived.print(); return 0; }
In the constructor initializer list of Derived you have to write Base(num) instead of Base(*num) as shown below: Derived(int *num): Base(num) { //code here } Note that you don't have to dereference the pointer num which you were doing while using it in the constructor initializer list. When you dereference num, you got an int. And so you were passing that int to the Base constructor.
71,024,043
71,226,322
Problem finding multiplicative inverse c++
I need to find the multiplicative inverse to some number e modulo ph. e is a prime number, ph is the result of the Euler function of some number. In the example e = 65537; ph = 3616319324. The pre-calculated correct value is 2373062985. On my own and with the help of the Internet, I wrote several functions to get this number. Functions using the extended Euler algorithm produce the same incorrect result, close to the maximum possible of variable type. A function based on Euler's theorem also gives an incorrect result, but different from the previous ones. What could be the problem here? #include <iostream> #include <tuple> #include <vector> uint32_t xgcd1(uint32_t a, uint32_t b, uint64_t& x, uint64_t& y) { x = 1, y = 0; uint64_t x1 = 0, y1 = 1; uint32_t a1 = a, b1 = b; while (b1) { int q = a1 / b1; std::tie(x, x1) = std::make_tuple(x1, x - q * x1); std::tie(y, y1) = std::make_tuple(y1, y - q * y1); std::tie(a1, b1) = std::make_tuple(b1, a1 - q * b1); } return a1; } uint32_t xgcd2(uint32_t a, uint32_t b, uint64_t& x, uint64_t& y) { if (b == 0) { x = 1; y = 0; return a; } uint64_t x1{}, y1{}; uint32_t gcd = xgcd2(b, a % b, x1, y1); x = y1; y = x1 - (a / b) * y1; return gcd; } std::vector<int64_t> euler(uint32_t x, uint32_t y) { std::vector<int64_t> modInverse(x + 1, 0); modInverse[1] = 1; for (int64_t i = 2; i <= x; i++) { modInverse[i] = (-(y / i) * modInverse[y % i]) % y + y; } return modInverse; } int main() { unsigned long ph = 3616319324; unsigned long e = 65537; uint64_t res1{}, y{}; xgcd1(e, ph, res1, y); uint64_t res2{}; xgcd2(e, ph, res2, y); uint64_t res3 = euler(e, ph)[e]; std::cout << "e: " << e << '\n'; std::cout << "ph: " << ph << '\n'; std::cout << "right result: 2373062985\n"; std::cout << "res1 xgcd iterative: " << res1 << '\n'; std::cout << "res2 xgcd: " << res2 << '\n'; std::cout << "res3 euler: " << res3 << '\n'; return 0; }
The solution was to change the types from unsigned to signed. Also, if the result is negative, you need to add ph to it. And here's working code: #include <iostream> #include <tuple> #include <vector> int32_t xgcd1(int64_t a, int64_t b, int64_t& x, int64_t& y) { x = 1, y = 0; int64_t x1 = 0, y1 = 1; int64_t a1 = a, b1 = b; while (b1) { int q = a1 / b1; std::tie(x, x1) = std::make_tuple(x1, x - q * x1); std::tie(y, y1) = std::make_tuple(y1, y - q * y1); std::tie(a1, b1) = std::make_tuple(b1, a1 - q * b1); } return a1; } int64_t xgcd2(int64_t a, int64_t b, int64_t& x, int64_t& y) { if (b == 0) { x = 1; y = 0; return a; } int64_t x1{}, y1{}; int64_t gcd = xgcd2(b, a % b, x1, y1); x = y1; y = x1 - (a / b) * y1; return gcd; } int main() { unsigned long ph = 3616319324; unsigned long e = 65537; int64_t res1{}, y{}; xgcd1(e, ph, res1, y); int64_t res2{}; xgcd2(e, ph, res2, y); std::cout << "e: " << e << '\n'; std::cout << "ph: " << ph << '\n'; std::cout << "right result: 2373062985\n"; if (res1 < 0) // if negative add ph res1 += ph; if (res2 < 0) res2 += ph; std::cout << "res1 xgcd iterative: " << res1 << '\n'; std::cout << "res2 xgcd: " << res2 << '\n'; return 0; }
71,024,774
71,024,801
Validating Input C++
int num = 0; while(true){ cout << "enter num: "; cin >> num; if(!(num)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "num must be an int" << endl; }else if(num <= 0){ cout << "num must be greater than 0" << endl; }else if(static_cast<double>(static_cast<int>(num)) != num){ cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "num must be an int" << endl; }else{ break; }; }; I've been looking through SO and I found some threads that addressed similar issues, but nothing that is specific to what I'm trying to achieve. I'm only trying to accept integer inputs, no decimals, no strings, no characters. If I enter in a negative number or 0, it'll throw me an error saying "num must be greater than 0." If I enter in a, it'll throw me an error saying "num must be an int." If I enter 1.0, it'll throw me an error saying "num must be an int." The problems I'm running into with this is when I enter in 0 for example, instead of executing the conditional statement that checks (num <= 0), it runs the conditional statement that says (!(num)). The other problem I'm running into is when I enter in a value that has a decimal, like 2.0, it'll truncate the numbers after the decimal and send in 2 as the value, completely glossing over the check to see if it's a decimal value and telling the program that it's a valid integer when it's not. Does anyone have a solution for this, or an article link that solves problem like mines? Thank you!
This: cin >> num; if(!(num)) Should be this: if (!(cin >> num)) You are checking the value of num when you should instead be checking the error state of cin. operator>> returns a reference to the input stream, which is then implicitly convertible to bool, where false means the stream encountered an error. Also, this is completely useless: else if(static_cast<double>(static_cast<int>(num)) != num) Casting an int value to an int is a no-op, and casting an int value to a double back to an int will get you the original int value. num is an int, it can't read in anything else. So, by the time your code reaches this point, you know num must be holding a valid int value. However, if the user had actually entered a floating-point number instead, operator>> would have stopped reading at the decimal point, leaving it and the remaining fractional value in cin's input buffer for later reading. Also, the 2nd call to cin.ignore() is wrong. By that point, operator>> was able to read in an int value, it just wasn't satisfactory to you. So don't ignore subsequent input yet. If you really need to differentiate between integer and floating-point input, you will have to read in the input as a string first, and then parse it to see what it actually holds, eg: int num = 0; string s; size_t pos; while (true){ cout << "enter num: "; if (!(cin >> s)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "input error, try again" << endl; } else{ try{ num = stoi(s, &pos); if (pos != s.size()) throw invalid_argument(""); if (num > 0){ break; } cout << "num must be greater than 0" << endl; } catch (const exception &){ cout << "num must be an int" << endl; } } } Online Demo
71,025,541
71,025,581
Access protected member function in C++
There are two external class (A and B)that I cannot change. I would like to access protected member of the class A:: doSomething in C (which I can do edit). Is there any way to access it. I understand its not good practice but I did not find any other way of doing it. // External code starts struct A { friend class B; protected: void doSomething() { std::cout << "A" << std::endl; } }; struct B { protected: void doSomething() { A a; a.doSomething(); } }; // External code ends // This will not compile as doSomething is a protected member. struct C : B { protected: void doSomethingElse() { A a; a.doSomething(); } };
Friendship is not transitive, so inheriting from B doesn't help with this. Inherit from A and form a pointer-to-member to doSomething: struct Helper : A { static constexpr auto ptr = &Helper::doSomething; }; Use that pointer to call a function on a: void doSomethingElse() { A a; (a.*Helper::ptr)(); }
71,025,562
71,025,776
my data in the console is displayed in the wrong sequence
Why is my data in the console displayed in the wrong sequence? I have the following code: #include <iostream> template <typename T, typename T2> T2 printArr(const T* array, int i) { for (int j = 0; j < i; j++) { std::cout << array[j] << " "; } std::cout << std::endl; return array[i - 1]; } int main() { const int iSize = 3; int i_arr[iSize] = {23, 45, 78}; std::cout << "Int array: "; std::cout << "Last element: " << printArr<int, int>(i_arr, iSize) << std::endl; } What do I get by compiling it: Int array: 23 45 78 Last element: 78 What should I get in my opinion: Int array: Last element: 23 45 78 78 Most likely, I do not understand how the computer that compiles my code thinks. Here you can see that the result is the same as I described in my question: http://cpp.sh/2lfbcf And I also try to compile the code in Visual Studio 2019 and the result is identical
Before C++17, given an expression E1 << E2, it is unspecified whether every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2. See cppreference note 19 In your code, using a standard before C++17, it is unspecified whether the return value of printArr() is calculated (which as a side-effect, streams to std::cout) before or after std::cout << "Last element: ".
71,025,656
71,025,826
Where are return values stored and how/can they be incremented?
I've done my fair share of reading and researching but I still don't 100% get it. For this solution of " Minimum Depth of Binary Tree", the idea of having multiple returns in a recursive function is killing me. I'm not exactly sure how the value for the "minimum depth" is being incremented, and I understand it may have something to do with my misunderstanding of return statements work. Please help, thank you. int minDepth(Node *root) { if(!root) return 0; if(!root->left) return 1 + minDepth(root->right); if(!root->right) return 1 + minDepth(root->left); return 1+min(minDepth(root->left),minDepth(root->right)); }
If it helps, logically, what you have above could just as well have been written int minDepth(Node *root) { int result; if(!root) result = 0; else if(!root->left) result = 1 + minDepth(root->right); else if(!root->right) result = 1 + minDepth(root->left); else result = 1 + min(minDepth(root->left), minDepth(root->right)); return result; }
71,025,763
71,025,880
How to tell, whether a C++ proposal is accepted or not?
Let's take P1907 as an example. Is it accepted into the C++ standard? To which version? When?
Papers can be tracked here. https://github.com/cplusplus/papers/issues Entering is:issue P1907 into the search box produces: P1907 (closed) and P1907R1 (merged) Alternatively, If you use Slack, you can join the C++ slack at cpplang.slack.com and privately message any paper name to @npaperbot to get information about it.
71,025,854
71,027,185
To solve ambiguity of overloaded function without either adding typecasting or remove the overloaded functions
I made a class Dummy, which is just a wrapper of primitive type double. The purpose of the class is to test potential problems before I introduce another class that substitutes the double class. Dummy.h: class Dummy{ private: double content; public: Dummy(double _content) :content{ _content } {}; operator long int() {return (long int)content;}; } test.cpp: #include <math.h> int main(){ Dummy a = Dummy(1.1); double aa = fabs(a); } It reports: <source>:17:27: error: call of overloaded 'fabs(Dummy&)' is ambiguous 17 | std::cout << std::fabs(foo); | ~~~~~~~~~^~~~~ In file included from /usr/include/features.h:461, from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/x86_64-linux-gnu/bits/os_defines.h:39, from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/x86_64-linux-gnu/bits/c++config.h:586, from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:41, from <source>:1: /usr/include/x86_64-linux-gnu/bits/mathcalls.h:162:1: note: candidate: 'double fabs(double)' 162 | __MATHCALLX (fabs,, (_Mdouble_ __x), (__const__)); | ^~~~~~~~~~~ In file included from <source>:1: /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:241:3: note: candidate: 'constexpr float std::fabs(float)' 241 | fabs(float __x) | ^~~~ /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:245:3: note: candidate: 'constexpr long double std::fabs(long double)' 245 | fabs(long double __x) If I add a type conversion operator: operator double(){ return content; } It somehow only works under Visual Studio, not g++ 9.3.0, which is my target compiler. During the compiling with g++ 9.3.0, the following errors are reported: I have read the information here, unfortunately I can't remove the overloaded functions in this case. Neither can I add typecasting, because it doesn't make sense for my purpose. I also check here, but I am not so familiar with templates. Hence my question is: Can I eliminate the ambiguity of overloaded function within the class, without adding typecasting, or removing the overloaded functions?
The Dummy class you have shown is only convertible to long int, but fabs() does not accept long int, it accepts either float, double, or long double. Since long int is implicitly convertible to float and double, the call was ambiguous until you added the double conversion operator. If you don't want to do that, then you have to be explicit about which overload of fabs() you want to call. Either by: casting the result of the Dummy conversion: double aa = fabs(static_cast<double>(a)); assigning/casting fabs() to a function pointer of the desired signature: double (*fabs_ptr)(double) = fabs; fabs_ptr(a); using fabs_ptr = double (*)(double); static_cast<fabs_ptr>(fabs)(a); Online Demo
71,026,223
71,028,271
Do I need to fence/sync when I use GL_MAP_COHERENT_BIT in a PMB?
I've seen contradictory documentation about it. In the Khronos documentation it's a bit ambiguous whether I need to glFinish (or variants) or not. I'm currently triple-buffering my buffer to avoid this problem (as I use the PMB dynamically) but it obviously consumes a lot of memory. I know that the flag makes the data-changes automatically visible both to the GPU and CPU, but don't know if I have to sync the writes with the reads. I need to know if I really need to sync the GL_MAP_COHERENT_BIT flag or there's an implicit synchronization.
There's no implicit synchronization because the driver/GPU has no idea when you're accessing the mapped pointer. That's what persistent mapping is all about, after all. And yes, you still need synchronization. If you're trying to read something the GPU has written... you need the GPU to have written it before you can read it. And vice-versa for writing; you don't want to write to data that's being read by the GPU. So use synchronization. If you're triple-buffering, odds are good that the wait-fence call will be a quick no-op.
71,026,400
71,026,528
Conversions to arrays of unknown bound: g++ vs. clang++
Note: this is the follow-up question for this question. Sample code (t334.cpp): typedef int T0; typedef T0 T1[]; typedef T1* T2[]; T1 x1 = { 13 }; T2 x2 = { &x1 }; Invocations: $ g++ t334.cpp -std=c++11 -pedantic -Wall -Wextra -c t334.cpp:6:11: warning: conversions to arrays of unknown bound are only available with ‘-std=c++20’ or ‘-std=gnu++20’ [-Wpedantic] 6 | T2 x2 = { &x1 }; | ^~~ $ clang++ t334.cpp -std=c++11 -pedantic -Wall -Wextra -c t334.cpp:6:11: error: cannot initialize an array element of type 'T1 *' (aka 'T0 (*)[]') with an rvalue of type 'T0 (*)[1]' T2 x2 = { &x1 }; ^~~ Can someone explain, what is wrong with this C++ code? Note: the equivalent C code is valid, because int (*)[] and int (*)[1] are compatible. Meaning that in C++ they aren't?
The first definition is of an array of known bound that is deduced from the initializer. It has the same effect as: int x1[1] = {13}; That means x1 has type int[1], and &x1 has type int (*)[1]. The second definition is trying to initialize a variable of type int (*)[] from a (brace-enclosed) expression of type int (*)[1]. In other words, it requires a conversion from a pointer to array with known bound to a pointer to array with unknown bound. Just like GCC tells you, this type of conversion only became allowed starting in C++20. If you compile your code with a recent version of Clang with -std=c++20, it should compile. See https://godbolt.org/z/4zb5xx658
71,026,443
74,538,173
How to get gcov results for included C/CPP files
I'm trying to get gcov results on a file that's brought in via #include. If I compile with it as a separate object file it works fine. For example with these files: lib.h int addFive(int num); lib.c #include "lib.h" int addFive(int num) { return num + 5; } testlib.cpp #include "lib.h" int main() { return addFive(2); } If I then compile like so: g++ -c -fprofile-arcs -ftest-coverage lib.c -o lib.o g++ -c testlib.cpp -o testlib.o g++ lib.o testlib.o -lgcov -o testlib then I will get a gcda file as expected: [~]$ strings testlib | grep gcda /home/user/lib.gcda [~]$ But if I attempt this when including the .c file like below test.cpp #include "lib.c" int main() { return addFive(2); } And compile that g++ test.cpp -lgcov -o test Then I don't get the gcda as expected: [~]$ strings test | grep gcda [~]$ Is there a way to get the gcda to show up when including a C file? The same applies to including a .cpp.
If I compile test with --coverage instead of -lgcov it does generate a test.gcda. I thought at first this was not what I wanted since I'm looking for coverage in lib.c But if I run both testlib and test and then use gcov on all the files together, it combines the coverage data properly: gcov lib.gcda lib.gcno test.gcda test.gcno And this yields lib.c.gcov with code coverage from both test runs.
71,027,045
71,027,486
Optimize Union Find (Disjoint Set Union) implementation
I have implemented a Disjoint Set Union in C++ for a Kattis problem. However, my solution is inefficient, as I get TLA (Time Limit Exceeded) for the first hidden test case. Can anyone spot an inefficiency with my code? I have based my implementation on this article. In particular, I set the parent of the parent of the smaller set to the parent of the bigger set (when making an union of the sets). According to the mentioned article, this should be as efficient as using the rank: Both optimizations are equivalent in terms of time and space complexity. So in practice you can use any of them. #include <bits/stdc++.h> using namespace std; typedef vector<int> vi; class UnionFind { private: vi p; vi size; public: UnionFind(int N) { p.assign(N, 0); for (int i = 0; i != N; ++i) p[i] = i; size.assign(N, 1); } int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } void unionSet(int i, int j) { int x = findSet(i); int y = findSet(j); if (x == y) return; if (size[x] < size[y]) swap(x, y); p[y] = x; size[x] += size[y]; } }; int main() { int n; int q; cin >> n >> q; auto set = UnionFind(n); while (q--) { char ch; cin >> ch; int x; int y; cin >> x >> y; if (ch == '=') { set.unionSet(x, y); } else if (ch == '?') { if (set.isSameSet(x, y)) cout << "yes" << endl; else cout << "no" << endl; } } }
This seems to be a Kattis-specific IO problem. Adding ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); to the start of main, and changing both occurrences of endl to '\n' causes it to pass in .2 seconds. I'll also mention that including <bits/stdc++.h> is frowned upon here, but the only cause of your error was the IO. Your implementation of Union Find is correct and runs in the standard inverse Ackermann time bounds.
71,027,176
71,074,776
Inconsistencies with C++11 function signatures
I have questions regarding functions, more specific on function signatures and how to pass them. I might be a trivial or even stupid question, but I couldn't find a satisfying answer yet. Please consider this example which uses a std::unique_ptr to manage a file pointer: #include <iostream> #include <memory> void func1(FILE* f) { std::cout << "func1 called" << std::endl; fclose(f); } int main() { FILE* f = fopen("testfile.txt", "w"); if(f) { std::unique_ptr<FILE, void(*)(FILE*)> fptr(f, &func1); } return 0; } This kind of smart pointer needs a functions signature as second template argument (shared_ptr does not for some odd reason). My current understanding of interpreting the signature here is void () (FILE) is a pointer to a function returning nothing (void) and a filepointer as argument. As a result, the user has to pass the address of the desired function with the address operator. At this point, a few questions arise: 1.) Removal of the address operator works just as well, no compiler warning is thrown, code works. Shouldn't this be an error/warning? 2.) If I use a reference to a function (e.g. unique_ptr<FILE, void(&)(FILE*)>(f, func1) ) it works as expected, so is this a superior way to pass a function as it is unambiguous? 3.) Removing the middle specifier altogether (e.g. unique_ptr<FILE, void()(FILE*)>(f, func1) ) causes compiler errors, so is passing a function by value impossible in general? (if it is, then it would make sense to overload the version in 1. by implicitly converting the function to a function pointer)
Function name is the always address of function (pointer to the function). If you want to use something else you can use some wrapper, e.g. std::function: #include <iostream> #include <memory> #include <functional> class Closer { public: void operator ()(FILE *f) { std::cout << "func1 called" << std::endl; fclose(f); } }; int main() { FILE* f = fopen("testfile.txt", "w"); if(f) { std::unique_ptr<FILE, std::function<void(FILE*)>> fptr(f, Closer()); } return 0; } Lambda in that case is anonymous functional object.
71,027,437
71,027,481
C++ Struct Members not Updating in Funtion
Firstly, while not new to programming, I am very new to C++, so please bear with me. I am using the Raylib library to attempt making a particle system for a game. This consists of a struct with a few private members and public functions: struct Particle { Particle() { mPosVector = {(float)GetMouseX(), (float)GetMouseY()}; mVelVector = {(float)GetRandomValue(15, 70)/100, (float)GetRandomValue(15, 70)/100}; mSize = GetRandomValue(5, 15); } void update(double deltaTime) { mPosVector.x += mVelVector.x; mPosVector.y += mVelVector.y; } void draw() { DrawRectangleV(mPosVector, {(float)mSize, (float)mSize}, WHITE); } private: Vector2 mPosVector; Vector2 mVelVector; int mSize; }; The Vector2 type is defined by Raylib: struct Vector2 { float x; float y; }; In my main function I have an std::vector storing Particles. A particle gets added when the left mouse button is pressed. I loop through the Particles vector twice, once for updating position based on velocity and once for drawing. I was originally doing these both in one loop, but was still getting the problem that I will get onto, so tried it this way. This is the current code: std::vector<Particle> particles = {Particle()}; while (!WindowShouldClose()) { deltaTime = GetFrameTime(); if (IsMouseButtonDown(0)) { particles.push_back(Particle()); } for (Particle part : particles) { part.update(deltaTime); } BeginDrawing(); ClearBackground(BLACK); DrawFPS(10, 10); DrawText((numToString<double>(deltaTime*1000).substr(0, 5) + "ms").c_str(), 10, 40, 20, WHITE); for (Particle part : particles) { part.draw(); } EndDrawing(); So, my problem: While particles are being instantiated as expected while pressing the left mouse button and being drawn, for some reason their positions are not being updated by their velocity. I have tried printing debug information to the console, such as the velocity, and it is as expected, but for some unknown reason to me (probably just me being stupid) their positions aren't being updated. Any help would be greatly appreciated.
for (Particle part : particles) { part.update(deltaTime); } this is making a copy of each entry , you need for (Particle &part : particles) { part.update(deltaTime); } to get a reference to the object in the vector to update it in place To understand, think that the ranged for is just short hand for this for(int i = 0; i < particles.size(); i++) { // this line copies the value particle p = particles[i]; } whereas the one with & in it does for(int i = 0; i < particles.size9); i++) { // this line gets a reference to the ith entry particle &p = particles[i]; } Its nothing special to do with the ranged for loop.
71,027,888
71,027,959
C++: Wrapping C style array into unique_ptr leads to "double free or corruption"
I have a C function that returns me a C style array. I would like wrap this into more C++ style code, so I don't have to manage its lifetime manually. So, I defined my wrapper as such: template <typename T> class Wrapper { public: std::unique_ptr<T[]> data; explicit Wrapper(T data[]) : data(data) {} }; However, when using it as follows: int main(int argc, char *argv[]) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // simulate my C style function Wrapper<int> wrapped(arr); return 0; } I get double free or corruption (out) Aborted As far as I understand, the only place where arr is destroyed, should be the destructor of std::unique_ptr, which is destroyed as soon as its parent Wrapper is destroyed. What am I missing here?
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; This variable has automatic storage duration. It will be destroyed at the end of the scope where it is declared. You pass a pointer to the first element of the automatic array into the constructor. The constructor initialises the unique pointer member to point to the automatic array. In the destructor, the unique pointer is destroyed and its destructor invokes delete[] on the stored pointer. Invoking delete[] on any pointer that was not acquired through new of an array results in undefined behaviour. The pointer in this case points to an automatic array which was not acquired by new[], and therefore the behaviour of the program is undefined. As far as I understand, the only place where arr is destroyed, should be the destructor of std::unique_ptr That is not where arr may be destroyed, because arr is an automatic variable. In conclusion: (Almost) never store pointers to any variables in smart pointers. Only store pointers to dynamic objects, whose deallocation function matches the deleter of the smart pointer. Prefer to create smart pointers using std::make_unique (and related functions) when possible to avoid making this mistake in the future. I go through them and wrap them into unique_ptr, but I'm not sure how they were allocated. These two things are not compatible with one another. In order to use a smart pointer, you must know how something is allocated because otherwise you cannot know the corresponding deleter to use with the smart pointer. I have a C function C API usually have a pair of allocation and deallocation functions, or they use malloc and expect you to free. The relevant details should be in the documentation of the API.
71,027,960
71,028,145
Adding syntactic sugar to C++
Edit 2: New edit: it looks like C++20 has a new ranges library, which does what I want from the functional point of view. How would something similar be done on C++17 or earlier? Also, would the Kotlin syntactic sugar be possible? Mainly the person example: val adam = Person("Adam").apply { age = 20 // same as this.age = 20 or adam.age = 20 city = "London" } Edit 1: I don't know if my question was that clear, so I'll give an example using Rust's map. This is how a map is done in rust: let newVector = myVector.iter().map(|x|, x * 2) This is how it is done in C++ std::string s("hello"); std::vector<std::size_t> ordinals; std::transform(s.begin(), s.end(), std::back_inserter(ordinals), [](unsigned char c) -> std::size_t { return c; }); This is a lot more verbose. I'd like to add some syntactic sugar to do something like this instead: std::string s("hello"); auto ordinals = my_ns::map(s,[](unsigned char c) -> std::size_t { return c; }); The implementation of my_ns::map could be something like this (I'm sure this will not work, it's just to show how it could be done) template<typename T, U> map(T t, std::function<U> f) { std::vector<U> ordinals; std::transform(t.begin(), t.end(), std::back_inserter(ordinals), [](U c) -> f(c)); return ordinals; } In this case ordinals doesn't need to be of type std::vector<std::size_t>, it could be of a type map which has a conversion for std::vector<T>. The reason for a type map is to be able to chain functions like reduce with map. Original Question Note: this is for a personal project only, I do not intend to use it in production or when working with C++ most of the time. I have been using a lot of Kotlin lately and I'm dabbling a little with Rust and I love their higher level features. That got me wondering, can I create some syntactic sugar to emulate some of these features? Some of the stuff I'd be trying to emulate(just an example) Rust map: let newVector = myVector.iter().map(|x|, x * 2) Kotlin let val adam = Person("Adam").apply { age = 20 // same as this.age = 20 or adam.age = 20 city = "London" } val str = "Hello" str.let { println("The string's length is ${it.length}") } I do not plan on using the exact same syntax, but I'd like to know if it would be possible to do something like: int[] arr = {1, 2, 3}; auto d_arr = map(arr, [](int x){return x*2}) // maybe return a map type to be able to use .reduce, etc The first kotlin let example I wouldn't know how to do, but the second could be solved using lambdas as well. I'm thinking of using new types and create conversions to std::vector and arrays, kind of how C#'s LINQ works. Any tips on how to do this are appreciated. Ps: I know about std::transform and other functions(I'd probably use them when implementing this), but I'd like a simpler API than the ones offered (and I also think that it would be a nice personal project).
Your example can be changed to working C++ code fairly easily: template <typename T, typename Fun> auto map(T t, Fun f) { std::vector<typename T::value_type> ordinals; std::transform(t.begin(), t.end(), std::back_inserter(ordinals), f); return ordinals; } This is neither very idiomatic nor optimized for performance, but it works. (Pre-resize the vector instead of using std::back_inserter and pass t by reference for a big performance boost.) Edit: You can add reduce as follows: template <typename T, typename R, typename Fun> auto reduce(T t, R init, Fun f) { return std::transform(t.begin(), t.end(), init, f); } And then combine them: reduce(map(x, [](auto a) {...}), 0, [](int& a, auto b) {...}) The obvious caveat: This is going to be really slow. These functions are fun to learn template concepts, but in practice, ranges or old-style std::reduce/... will be much, much faster. Edit 2: If you want to use map as a member function, just make a wrapper class: template<class T> struct Wrapper { T d; template <typename Fun> auto map(Fun f) { std::vector<typename T::value_type> ordinals; std::transform(d.begin(), d.end(), std::back_inserter(ordinals), f); return wrap(ordinals); } template <typename R, typename Fun> auto reduce(R init, Fun f) { return wrap(std::transform(d.begin(), d.end(), init, f)); } }; template<class T> Wrapper<T> wrap(const T& t) { return {t}; } template<class T> Wrapper<T> wrap(T&& t) { return {t}; } Then you can do wrap(my_vec).map(...).reduce(..., ...) for loops would be faster here, because you're doing a lot of unnecessary copying: you're unnecessarily creating a new vector in map and copy data lots of times (std::back_inserter, pass-by-value).
71,028,202
71,032,447
Making a template function mirror its template argument's signature
I have a template function: template <??? func> ??? wrapper(??? args) { // ... Stuff return func(args); } It should have the same signature as the func non-type template parameter. The closest I've gotten is using auto in the template declaration and then using some form of function traits to deduce the return type, however, this method does not allow for deducing the parameters as a whole. Ideally, template <typename R, typename... Args, R(*func)(Args...)> R wrapper(Args&&... args); // ... or some other imaginary syntax would A. be allowed and B. deduce R and Args from func. func must be specified at compile time and the function may not have any additional parameters (I need to take the address of the wrapper). At this point I feel like my current solution, template <auto func, typename... Args> auto wrapper(Args&&... args) { return func(std::forward<Args>(args)...); } cannot be improved, since it appears impossible to generate "pure" variadic template arguments (getting them back after "storing" them anywhere (e.g. a tuple)). Which is sad, because it forces the Args to be provided manually. But of course I'd love to see someone prove me wrong on this!
You can create traits to extract returs type and parameters. issue would be to handle arity only from function declaration. If you can wrap in a class/functor, it would be possible: template <auto func> struct wrapper_t; template <typename Ret, typename ... Ts, Ret (*func)(Ts...)> struct wrapper_t<func> { Ret operator() (Ts... args) const { return func(std::forward<Ts>(args)...); } }; // handle ellipsis functions ala printf template <typename Ret, typename ... Ts, Ret (*func)(Ts..., ...)> struct wrapper_t<func> { template <typename ...EllipsisArgs> Ret operator() (Ts... args, EllipsisArgs&&... ellipisisArgs) const { return func(std::forward<Ts>(args)..., std::forward<EllipsisArgs>(ellipisisArgs)...); } }; template <auto func> constexpr wrapper_t<func> wrapper{}; Demo
71,029,221
71,029,283
How to call a non-static method from a function pointer?
I have a class "Person" like so: typedef void (*action)(); typedef std::unordered_map<int, action> keybindMap; // maps keycodes to functions class Person { keybindMap keybinds; void doSomething(); } I use this to call the functions at the right times: iter = keybinds.find(event.key.keysym.sym); // event.key.keysym.sym is the key code if (iter != keybinds.end()) { (*iter->second)(); // call whatever function that key is bound to. } To bind a key, I used keybinds.insert_or_assign(SDLK_a, doSomething). However, this doesn't work (because doSomething is non-static). How do I change the binding code and/or the (*iter->second)() part so that I can call something equivalent to person.doSomething?
A non-static method requires an object to call it on. An ordinary function pointer doesn't have room to hold a reference to an object. If you change your map to hold std::function instead, you can then use std::bind() or a lambda to associate an object with a method pointer, eg: using action = std::function<void()>; using keybindMap = std::unordered_map<int, action>; class Person { keybindMap keybinds; void doSomething(); }; ... Person p, otherP; //must outlive the map... p.keybinds[...] = [&otherP](){ otherP.doSomething(); } ... iter = keybinds.find(event.key.keysym.sym); if (iter != keybinds.end()) { iter->second(); } On the other hand, if all of the target methods are in the same class/object, you can use a plain method pointer instead of std::function, which will reduce some overhead, eg: class Person { using action = void (Person::*)(); using keybindMap = std::unordered_map<int, action>; keybindMap keybinds; void doSomething(); }; ... keybinds[...] = &Person::doSomething; ... iter = keybinds.find(event.key.keysym.sym); if (iter != keybinds.end()) { (this->*(iter->second))(); }
71,029,666
71,029,964
send and receive binary files properly using sockets c++
hello stackflow users, so i want to send and receive my binary file using sockets in c++ and here is how i send it from server program send(Connections[conindex], reinterpret_cast<char*>(rawData), sizeof(rawData), NULL); and here is how my client program receives it char raw[647680]; recv(Connection, raw, sizeof(raw), NULL); is there any proper way than this? i want so that i don't have to hard code the size every time. or any other alternatives etc
A rather general way to achieve this (in both C and C++) is something like this: if (FILE *fp = fopen(filename, "rb")) { size_t readBytes; char buffer[4096]; while ((readBytes = fread(buffer, 1, sizeof(buffer), fp) > 0) { if (send(Connections[conindex], buffer, readBytes, 0) != readBytes) { handleErrors(); break; } } close(Connections[conindex]); } And on the client side: if (FILE *fp = fopen(filename, "wb")) { size_t readBytes; char buffer[4096]; while ((readBytes = recv(socket, buffer, sizeof(buffer), 0) > 0) { if (fwrite(buffer, 1, readBytes, fp) != readBytes) { handleErrors(); break; } } } Alternatives to this rather FTP-esque connection style includes sending the size of the file first, so the client will know when to stop listening instead of waiting for the disconnect. Please note that this code is untested and merely meant to illustrate the concept.
71,029,777
71,029,904
Difference between a deconstructor and exit() C++
In college, when learning C++ specifically, we're always taught that we need to deallocate dynamically allocated memory or close an open file using a deconstructor. What is the difference between that and just using the operating system call exit(0)? Just wondering.
They are not comparable. Apples and oranges exit() is a C library function. Cpp Reference tells us: Causes normal program termination to occur. Several cleanup steps are performed: functions passed to atexit are called, in reverse order of registration all C streams are flushed and closed files created by tmpfile are removed A deconstructor is a C++ specific feature. It's a class member function that handles cleanup of an object when it goes out of scope. Cpp Reference tells us: A destructor is a special member function that is called when the lifetime of an object ends. The purpose of the destructor is to free the resources that the object may have acquired during its lifetime. You call exit() once and the program ends. Meanwhile destructors are executed all of the time. Because objects get created and go out of scope all the time. Just think of local variables. Or during copying of objects.
71,029,917
71,030,554
Is it possible to depend expected calls in gMock together?
Assume that I want to test following function: template<typename Pack> bool is_valid(const Pack& pack) { if (pack.a() > 0) return pack.b(); return false; }; I will write a small mocker for Pack as follows: class PackMock { public: MOCK_METHOD(int, a, (), (const)); MOCK_METHOD(bool, b, (), (const)); }; and now I try to write test this method with in test function: TEST(MyTests, IsValidTest) { PackMock p; EXPECT_CALL(p, a()) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(20)); EXPECT_CALL(p, b()) .WillOnce(Return(true)) .WillOnce(Return(false)) .WillOnce(Return(true)); EXPECT_FALSE(is_valid(p)); EXPECT_FALSE(is_valid(p)); EXPECT_TRUE(is_valid(p)); } At the first sight, this code should be OK. I have 3 expectation and my mocker returns 3 different set of values and this is what happens in real application running (data-wise). But if you run this code, you will get error that mocker expectations is not satisfied (it says that b() is expected to call 3 times while it is called twice). The reason is that when first test happens, a() returns 0, and because of if condition, b() is not called at all. So at the end, everything is messed up. Now I wonder if there is a way to for example connect these expectations together or I should always set my expectations based on how code works rather than how my data works? I personally think that the later should be correct. For example, if a() in mocker called we make sure that at we always satisfy 1 expectation in b()? or for example we chain these expectations together in a way that b() is expected only if a() > 0?
Firstly, you can use a testing::Sequence instance to keep track of mock calls in sequence. You can also directly define a InSequence for the test as in the docs. Secondly, your first EXPECT_CALL does not call the b() mock call, because a() returns 0 which then never evaluates the return pack.b(). As an example found here, I've indicated how you can use a Sequence class in your example as follows: TEST(MyTests, IsValidTest) { // Setup the mock object PackMock p; // Keep track of the sequence of events // using a sequence class testing::Sequence sequence; // # First is_valid() - a EXPECT_CALL(p, a()) .InSequence(sequence) .WillOnce(Return(0)); // # First is_valid() - b - not called // EXPECT_CALL(p, b()) // .InSequence(sequence) // .WillOnce(Return(true)); // # Second is_valid() - a EXPECT_CALL(p, a()) .InSequence(sequence) .WillOnce(Return(1)); // # Second is_valid() - b EXPECT_CALL(p, b()) .InSequence(sequence) .WillOnce(Return(false)); // # Third is_valid() - a EXPECT_CALL(p, a()) .InSequence(sequence) .WillOnce(Return(20)); // # Third is_valid() - b EXPECT_CALL(p, b()) .InSequence(sequence) .WillOnce(Return(true)); // Act - Initiate the calls and inject the // mock object as a dependency // # First call - a() returns 0, // thus returns false (but() b is not called) EXPECT_FALSE(is_valid(p)); // # Second call - a() returns 1, // thus returns false, because b returns false EXPECT_FALSE(is_valid(p)); // # Third call - a() returns 20, // thus returns true, because b returns true EXPECT_TRUE(is_valid(p)); } This will provide the following output: Running main() from /opt/compiler-explorer/libs/googletest/release-1.10.0/googletest/src/gtest_main.cc [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from MyTests [ RUN ] MyTests.IsValidTest [ OK ] MyTests.IsValidTest (0 ms) [----------] 1 test from MyTests (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test. Thus, to answer your question: Is it possible to depend expected calls in gMock together? Yes, using a testing::Sequence class with or just using testing::InSequence() Thus, if you have calls depending on each other in your test, use a sequence class instance(s) to link them.
71,029,970
71,030,131
C++ istream input fails yet consumes data. Expected to be able read bad data after failure
My understanding of iostream has always been that when an input conversion fails, the data remains in the stream to be read after clearing the error. But I have an example that does not always work that way, and I would like to know if the behavior is correct. If so, could someone point me at some good documentation of the actual rules? This small program represents the idea of using an i/o failure to read an optional repeat count and a string. #include <iostream> #include <string> int main() { int cnt; std::cout << "in: "; std::cin >> cnt; if(!std::cin) { cnt = 1; std::cin.clear(); } std::string s; std::cin >> s; std::cout << "out: " << cnt << " [" << s << "]" << std::endl; } So, here's how it runs: [me@localhost tmp]$ ./bother in: 16 boxes out: 16 [boxes] [me@localhost tmp]$ ./bother in: hatrack out: 1 [hatrack] [me@localhost tmp]$ ./bother in: some things out: 1 [some] [me@localhost tmp]$ ./bother in: 23miles out: 23 [miles] [me@localhost tmp]$ ./bother in: @(#&$(@#&$ computer out: 1 [@(#&$(@#&$] So it mostly works. When there's a number first, it is read, then the string is. When I give a non-numeric first, the read fails, the count is set to 1 and the non-numeric input is read. But this breaks: [me@localhost tmp]$ ./bother in: + smith out: 1 [smith] The + fails the integer read because it's not enough to make a number, but the + does not remain on the stream to be picked up by the string read. Likewise with -. If it reads the + or - as a zero, that would be reasonable, but then the read should succeed and cnt should show that zero. Perhaps this is correct behavior, and I've just always been wrong about what it is supposed to do. If so, what are the rules? Your advice appreciated.
Plus and minus are valid parts of an integer and so are read, when the next character is read the stream fails and that character is left in the stream but the leading sign character is not put back into the stream. See https://en.cppreference.com/w/cpp/locale/num_get/get for the full rules
71,030,029
71,030,304
I don't understand where I made a mistake
I tried this code after documenting myself : struct person { int a; char s; }; struct person test; test.a = 12; And Code::Blocks returns this following error : error: 'test' does not name a type Can someone explain this error to me? I found this sample code on the internet! I don't understand my mistake. Thanks for reading, have a nice day.
To make your code work you need to put it in a function and there should be a main function too. struct person { int a; char s; }; int main() // you need to have a main { // code needs to be in a function /*struct*/ person test; // struct is not needed test.a = 12; return 0; }
71,030,038
71,032,888
How to get template class template parameter?
I have a template class and want to know, how to get template class variable type when it is used as a template parameter of function. I tried to do the following #include <iostream> #include <type_traits> using namespace std; template <typename T> class foo { }; template <typename templateClass> void f() { if (is_same<typename templateClass::T, int>::value) cout << "int"; else if (is_same<typename templateClass::T, double>::value) cout << "double"; else cout << "Unknown type"; } int main() { f<foo<double>>(); return 0; } This code does not compile, because no type named 'T' in 'foo<double>'. Then I changed it a little bit: #include <iostream> #include <type_traits> using namespace std; template <typename T> class foo { public: using Type = T; //can't write : using T = T; }; template <typename templateClass> void f() { if (is_same<typename templateClass::Type, int>::value) cout << "int"; else if (is_same<typename templateClass::Type, double>::value) cout << "double"; else cout << "Unknown type"; } int main() { f<foo<double>>(); return 0; } Now it works fine, but I had to rename template parameter. Can I get template parameter value without renaming it with using?
You can create traits to extract that information without changing originel types. template <typename T> struct template_parameter; template <template <typename ...> class C, typename T> struct template_parameter<C<T>> { using type = T; }; template <typename T> using template_parameter_t = typename template_parameter<T>::type; and then template <typename templateClass> void f() { if constexpr (std::is_same_v<template_parameter_t<templateClass>, int>) std::cout << "int"; else if constexpr (std::is_same_v<template_parameter_t<templateClass>, double>) std::cout << "double"; else std::cout << "Unknown type"; } Demo
71,030,102
71,045,093
How to detect if left mousebutton is being held down with SDL2
I know how to use events to detect when the mouse button is pressed, however, how do detect if a mouse button is currently held down? Note I am not asking how to get it from an event. I have not tried anything apart from SDL_GetMouseState(&x, &y); however it seems to only return the X and Y position of the mouse.
SDL_GetMouseState() returns the buttons that were pressed. Example: if (SDL_GetMouseState(...) & SDL_BUTTON_LMASK) // Left button is pressed.
71,030,397
71,035,870
stable partition in c++ - why is it O(n lg n)?
I was looking at the possible implementation of stable partition in c++: https://en.cppreference.com/w/cpp/algorithm/ranges/stable_partition it’s stated this is at worst O nlgn. How is this possible? it seems like in the worst case a rotate is called at every index, resulting in an O n**2 algorithm.
As ALX23z notes, the sample implementation is not conforming with respect to running time. Here is what an O(n log n) in-place stable_partition could look like (at least from an algorithms perspective; if you want a library-grade implementation go look at the actual libraries). #include <algorithm> template <typename Iterator, typename Predicate> Iterator my_stable_partition(Iterator first, Iterator last, Predicate predicate) { auto n = std::distance(first, last); if (n <= 1) { if (n == 1 && predicate(*first)) ++first; return first; } auto middle = first; std::advance(middle, n / 2); auto a = my_stable_partition(first, middle, predicate); auto b = my_stable_partition(middle, last, predicate); return std::rotate(a, middle, b); } Here's a quick and dirty test. #include "my_stable_partition.cc" #include <assert.h> #include <stdlib.h> #include <vector> bool odd(int n) { return n % 2 == 0; } int main() { for (int i = 0; i < 1000; i++) { std::vector<int> arr(i); long long checksum = 0; for (int &x : arr) { checksum += x = random() / 31337; } auto mid = my_stable_partition(arr.begin(), arr.end(), odd); for (auto it = arr.begin(); it != mid; ++it) { assert(odd(*it)); checksum -= *it; } for (auto it = mid; it != arr.end(); ++it) { assert(!odd(*it)); checksum -= *it; } assert(checksum == 0); } }
71,030,923
71,032,922
How do I access data in "int20_t"?
I got a lot of memory pieces in 512 bits. I need to write numbers in 20 bits. For example: // a piece of 512 bits memory void *p = malloc(64); struct Coords { int20_t x, y; }; // usage Coords *pcoord = (Coords *)p; for (int i = 0; i < 512 / 40/*sizeof(Coords)*/; ++i) { pcoord[i].x = i; pcoord[i].y = 2 * i; } How to implement int20_t ? I need exactly 20 bits for an integer. The numbers must be continuous. ( [0] to [19] for the first Coords.x; [20] to [39] for the first Coords.y; ... There are 12 pairs of Coords with 480 bits and 32 bits for the pad.)
The type int20_t is only available on very specific hardware with 20 bit registers. You do not need this type to handle your data, you can either use plain int to store the coordinates or possibly use bit-fields but it does not seems necessary. The main issue is the conversion from the external representation (12 packed pairs of 20 bit values in a 512 bit block) to a more manageable in memory representation as an array of structures, and possibly the other way around. To handle this conversion, you must specify precisely how the bits are packed in the 64 byte block. Each value will be split in 3 parts, the order of these bytes and bits inside the last byte bytes must be specified. Here is an example where values are stored in big endian format with the third byte containing the low order bits of x in its high order bits and the high order bits of y in its low order bits: struct Coords { int x, y; }; void load_coords(struct Coords *a, const unsigned char *p) { for (int i = 0; i < 20; i++) { a->x = (p[0] << 12) + (p[1] << 4) + (p[2] >> 4); a->y = ((p[2] & 15) << 16) + (p[3] << 8) + p[4]; p += 5; a++; } } void store_coords(unsigned char *p, const struct Coords *a) { for (int i = 0; i < 20; i++) { p[0] = a->x >> 12; p[1] = a->x >> 4; p[2] = (a->x << 4) | ((a->y >> 16) & 15); p[3] = a->y >> 8; p[4] = a->y; p += 5; a++; } }
71,030,981
71,031,427
VSCode deal the command parameter as literal
I want to build a Rasterizer project with opencv.The below command work well in shell(some parameter is omitted, such as -static-libgcc): g++ *.cpp -g -o Rasterizer `pkg-config --libs opencv` However, when I want to do the same thing with VSCode, it fails and throw an error: g++: error: `pkg-config --libs opencv`: No such file or directory The log tells me that the executed task in VSCode is(also omit some parameters) g++ *.cpp -g -o Rasterizer '`pkg-config --libs opencv`' I think the reason is the parameter `pkg-config --libs opencv` is surrounded by a pair of quotes ' and saw as literal. How can I solve this problem? The whole error message can be seen here: > Executing task: g++ /home/cs18/GAMES101/pa1/*.cpp -fdiagnostics-color=always -g -o /home/cs18/GAMES101/pa1/build/main -static-libgcc -fexec-charset=GBK '`pkg-config --libs opencv`' < g++: error: `pkg-config --libs opencv`: No such file or directory The terminal process "/bin/bash '-c', 'g++ /home/cs18/GAMES101/pa1/*.cpp -fdiagnostics-color=always -g -o /home/cs18/GAMES101/pa1/build/main -static-libgcc -fexec-charset=GBK '`pkg-config --libs opencv`''" failed to launch (exit code: 1). My VSCode configuration file task.json: { "tasks": [ { "type": "shell", "label": "C/C++: g++ build active file", "command": "g++", "args": [ "${fileDirname}/*.cpp", "-fdiagnostics-color=always", "-g", "-o", "${fileDirname}/build/${fileBasenameNoExtension}", "-static-libgcc", "-fexec-charset=GBK", "`pkg-config --libs opencv`" ], "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "new" }, "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" }
let's try this . { "tasks": [ { "type": "shell", "label": "C/C++: g++ build active file", "command": "g++", "args": [ "${fileDirname}/*.cpp", "-fdiagnostics-color=always", "-g", "-o", "${fileDirname}/build/${fileBasenameNoExtension}", "-static-libgcc", "-fexec-charset=GBK", "${PKG_RET}" ], "options": { "env": { "PKG_RET": "${input:pkg_ret}" } }, "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "new" }, "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" }, "inputs": [ { "id": "pkg_ret", "type": "command", "command": "shellCommand.execute", "args": { "command": "pkg-config --libs opencv" } } ] refer : Using a shell command as VSCode task variable value
71,031,329
71,032,025
why does this for loop in C++ using getline() work
I compiled this nested for loop in C++. It works, however I don't understand why. Can you please explain the mechanics, and also any information on why the push_back() is allowed in addition to the increment. for (std::string line; std::getline(in, line); text->push_back(line), ++ln) // why does this work? { // do something std::istringstream iss(line); for (std::string word; iss>>word;) // why does this work? // do something }; text is a shared_ptr<vector<string>>.
The for loop for (A; B; C) { D; } is equivalent to { A; while (B) { D; C; } } and any of A, B, C, and D can be empty. If those parts are syntactically correct in the while loop, they are also correct in the corresponding for loop. So your nested loop is equivalent to { std::string line; while (std::getline(in, line)) { std::istringstream iss(line); { std::string word; while (iss>>word) { // do something } } text->push_back(line), ++ln; } } Note that the push_back line uses the comma operator for sequencing because the semicolon is the delimiter in the for-loop header.
71,031,682
71,031,744
Can only compile and run when including .cpp file
I'm doing some linked list practices in C++ and created a simple class for the single linked list. When I try to include the header-file in the main program however I get an undefined reference error. If I include the .cpp file however it works as I want it to. It's been a while since I last coded in C++ and I can't for the love of me figure out what's wrong. Some help would be deeply appreciated. I'm using Windows Termnial with git-bash interface and g++ -std=c++11. The code is included below! //The main file .cpp #include "SingleNode.h" int main() { SingleNode* tail = new SingleNode(2); SingleNode* head = new SingleNode(1, tail); head->print(); return 0; } //SingleNode.h #ifndef SINGLENODE_H #define SINGLENODE_H class SingleNode { public: int val; SingleNode* next; SingleNode(); SingleNode(int x); SingleNode(int x, SingleNode* next); void print(); }; #endif //SingleNode.cpp #include "SingleNode.h" #include <iostream> using namespace std; SingleNode::SingleNode() : val(0), next(nullptr) {} SingleNode::SingleNode(int x) : val(x), next(nullptr) {} SingleNode::SingleNode(int x, SingleNode* next) : val(x), next(next) {} void SingleNode::print() { if (this->next != nullptr) { cout<<this->val<<"->"; this->next->print(); } else { cout<<this->val<<"->"<<"null"<<endl; } } When run: $ g++ -std=c++11 LinkedList.cpp -o LinkedList.exe C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x30): undefined reference to `SingleNode::SingleNode(int)' C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x59): undefined reference to `SingleNode::SingleNode(int, SingleNode*)' C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x69): undefined reference to `SingleNode::print()' collect2.exe: error: ld returned 1 exit status If I instead #include "SingleNode.cpp" it works fine.
You include the header file, so prototypes are available, and the compiler does not complain. The linker needs to find the source associated with those functions. Using g++ -std=c++11 LinkedList.cpp -o LinkedList.exe to compile means that you're only using the main file source and not the other file that contains the linked list implementation. The solution is to also pass the SingleNode.cpp file to the compiler. Hence: g++ -std=c++11 LinkedList.cpp SingleNode.cpp -o LinkedList.exe and include the SingleNode.h file in LinkedList.cpp. The #include directive performs textual substitution, which means that when you include the .cpp file(which, in turn, includes the header file) you have one final translation unit that contains the required source of both source files. Also see: Why should I not include cpp files and instead use a header?