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,948,568
71,948,740
Convert void pointer to a dynamic type
I am trying to convert a void pointer to a dynamic type. For example, I passed double variable to test1 function which I expected the sum function will work. But I got C2664 cannot convert argument error on sum(*reinterpret_cast<myType*>(tmp)). If I using this, it will work. double c= *reinterpret_cast<double*>(tmp); sum(c); How do I fix this? void sum(double a) { cout << "sum:" << a+10 << endl; } void test1(void* tmp) { typedef decltype(tmp) myType; sum(*reinterpret_cast<myType*>(tmp)); } int main() { double a = 87.7; test1(&a); return 0; }
First of all, dynamic type is really only meaningful when you're using inheritance. For example, if you have code like this: class Base {}; class Derived : public Base {}; int main() { Base *b = new Derived; } In this case, b has a static type of Base *, but a dynamic type of Derived * (because it was declared as a pointer to a Base, but is actually pointing at an instance of Derived). So, if you want to recover an actual dynamic type, you'll need to start by defining some base class, and some derived class(es), and convert between them. When/if you do that, you usually want to use dynamic_cast rather than reinterpret_cast to do the job (it'll automatically check the actual type, so the cast will fail if you try to cast to a type that it's not really pointing at). But in most cases, you want to define some sort of virtual function in the base class, and override it as needed in the derived classes, so you don't need to use dynamic_cast at all. Also note that dynamic_cast only works on classes that contain at least one virtual function (but if you're using public inheritance without any virtual functions, you're probably doing something wrong). Alternatively, you can create basically a discriminated union. You'll need to store something to record what actual type is stored, and you'll use that to cast back to the correct when needed. enum type { FLOAT, DOUBLE }; struct value { type t; void *value; }; float f = 1.2f double d = 3.2; value v { FLOAT, &f }; value y { DOUBLE, &d }; void do_call(value v) { if (v.type == FLOAT) { use_float(*reinterpret_cast<float *>(v.value)); else if (v.type == DOUBLE) use_double(*reinterpret_cast<double *>(v.value)); } The compiler, however, won't store anything in a void * to keep track of what type of object it's really pointing at. If you want to cast back from void * to float or double as applicable, you're going to have to store something to keep track of which type that actually was. Rather than the latter, you might also want to look into using std::variant, which handles storing the type tag automatically, and can help automate most of the type dispatching as well (e.g., with std::visit). At least as typically used, this will act more like an actual tagged union though, so it stores the actual values, rather than pointers to values that are stored elsewhere.
71,949,173
71,949,353
How to print out debug info to terminal when running c++ with CMake?
I am reading a C++ project and want to print out the #ifdef _DEBUG message when running the program at a Linux terminal. For example: #ifdef _DEBUG cout << s1 << endl; #endif Currently, it doesn't print out the debug info above, but only prints out logger info as below: logger_(MY_MODULE_LOG_ERROR, "config is null "); The project is made through cmake. It has a top level CMakeLists.txt file, in addition to each CZMakeLists.txt under src/ and its subdirectories. The content of the top-level CMakelists.txt is below: cmake_minimum_required (VERSION 3.12) project (TAGS_NEW ) set(CMAKE_VERBOSE_MAKEFILE true) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC -w") # gdb debug : -g add_compile_options( -Wall -Wextra -Wstrict-aliasing -Wno-unused-parameter -Wno-missing-field-initializers -Wchar-subscripts -Wpointer-arith -Wformat -Wformat-security -Werror=format-security -fstack-protector-all -fPIE -fpie -fPIC -fpic -pipe -fdata-sections -ffunction-sections ) option(DEBUG_OUTPUT "option for debug out" OFF) if (DEBUG_OUTPUT) add_definitions(-D_DEBUG) endif() # option(DEBUG_GDB "option for gdb debug" OFF) # if (DEBUG_GDB) # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -ggdb") # endif() # set(CMAKE_BUILD_TYPE "Debug") option(CMAKE_BUILD_TYPE "option for gdb debug" DEBUG) set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb") set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall") option(COMPILE_DLL "option for generate dynamic library" OFF) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${TAGS_NEW_SOURCE_DIR}/output) add_definitions(-D_Python_CALL -D_ChaiScriptON) include_directories(${TAGS_NEW_SOURCE_DIR}/third-party/include ${TAGS_MINING_NEW_SOURCE_DIR}/include ) # $(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") find_package( PythonLibs 2.7 REQUIRED ) include_directories( ${PYTHON_INCLUDE_DIRS} ) link_directories(${TAGS_NEW_SOURCE_DIR}/third-party/lib) add_subdirectory (src) execute_process(COMMAND sh genGlobal.sh ${TAGS_NEW_SOURCE_DIR} WORKING_DIRECTORY ${TAGS_NEW_SOURCE_DIR}) I tried to change the OFF to ON in the line below, but it doesn't help: option(DEBUG_OUTPUT "option for debug out" OFF) I am new to CMake. How to print out all the debug info?
Options are meant to be provided from outside not to be modified in the CMake file. In fact you can't change an option with the option command once it is set in the cache (after the first CMake run). So run your cmake like this: cmake -DDEBUG_OUTPUT=ON .. and you will get your macro defined.
71,949,970
71,977,538
C++ generate new EC_KEY using OpenSSL 1.1.1n
I'm very new to this OpenSSL stuff and trying to learn my way through it. I want to generate an ec key but its keep failing to generate. I'm currently using OpenSSL 1.1.1n and here's a snippet based on understaning of EC_Key through documentation and from other people's example online: EC_KEY* key = EC_KEY_new_by_curve_name(NID_secp521r1); if (!key) { ERROR } EC_GROUP* ecgroup = EC_GROUP_new_by_curve_name(NID_secp521r1); if (ecgroup) { printf("ECGROUP IS NOT NULL!\n"); if (EC_KEY_set_group(key, ecgroup) != 1) { ERROR } } if (EC_KEY_generate_key(key) != 1) //<-- fails at this function { ERROR } Maybe this piece of code is from an older version of OpenSSL but I don't see that function being mentioned in a change log. Any help would be really appreciated! Thanks in advance! Edit: Thanks for Jakob's answer I was able to get some more information about the failure by using ERR_get_error() function. The error I see now is error:2406C06E:random number generator:RAND_DRBG_instantiate:error retrieving entropy
Answering myself in case someone is having this same issue. I was able to get around this problem by building OpenSSl with no-shared flag. I'm not sure how that is affecting the lib in getting an entropy but that's the parameter that made the EC_KEY_generate_key() work. Here's my working configuration command: perl Configure no-shared VC-WIN32
71,950,689
71,950,894
Why is the built-in array subscript can be an lvalue?
Indicate in cppreference that the expression representing the subscript must be a prvalue of unscoped enumeration or integral type. So why can a for loop that traverses a built-in array, which beginners have learned, be compiled. such as: int a[10] = {0}; // as we know ,i is a lvalue for(int i = 0; i < 10; i++) { std::cout << a[i] << std:endl; }
Indicate in cppreference that the expression representing the subscript must be a prvalue of unscoped enumeration or integral type. // as we know ,i is a lvalue So why can a for loop that traverses a built-in array, which beginners have learned, be compiled. A glvalue expression may be implicitly converted to prvalue with lvalue-to-rvalue conversion.
71,951,159
71,952,159
How do I find the line number and line item number in a text file?
I need to find the line number and position number in the line with the specified character in the text file. I did this, but found the last symbol. I have a task to find the fourth point "." from the end of the text file, how is this possible? Text file: One One Two .... Three .. Three Now I get the following result: Line: 2 Pos: 6 What I have tried: Check out my code (I'm looking for the first dot from the end of the file): #include <fstream> #include <iostream> #include <string> using namespace std; int main() { ifstream fin("t.txt"); string line; int lines = 0; int characters = 0; int found_line = 0; size_t found_pos = string::npos; while (true) { if (!getline(fin, line)) break; auto pos = line.find_last_of('.'); if (pos != string::npos) { found_line = lines; found_pos = (characters + pos); } ++lines; characters += line.length(); } if (found_pos != string::npos) { found_line = (lines - 0 - found_line); // line no, counting backwards from the bottom of the file found_pos = (characters - 0 - found_pos); // pos of the 'first' dot, counting backwards from the end of the file cout << "line " << found_line << "\n"; cout << "pos " << found_pos << "\n" + 1; } return 0; }
In my comment, I sketched the following possible algorithm to solve OPs issue: What you could do: While reading the file you can count the line numbers. Scan the line for one (or multiple) .s. The results can be stored in an array of 4 entries. (You have to manage an index for this.) For each found ., you store the line and inc. the index modulo 4 (e.g. i = (i + 1) % 4;. When you reached the end of file, the (i + 1) % 4 will contain the line for the 4th . from end. Of course, you also have to count that you found at least 4 .s (to handle edge cases). Just for fun, I made an MCVE on coliru: #include <array> #include <fstream> #include <iostream> #include <string> // (a kind of) ring buffer template <typename V, int N> struct RingT { std::array<V, N> values; int i = 0; int n = 0; void push(const V& value) { values[i++] = value; if (i >= N) i = 0; if (n < N) ++n; } int size() const { return n; } const V& operator[](int j) const { return values[((i - 1 + j) % n + n) % n]; } }; // text coordinates struct Coord { int line, col; }; int main() { const int N = 4; // the number of occurrences (from end) to count const char C = '.'; // the character to count occurrences for // use (a kind of) ring buffer to store text coordinates RingT<Coord, N> coords; // scan file for occurrences of character C #if 0 // OP std::ifstream fIn("t.txt"); #else // for online check std::ifstream fIn("main.cpp"); #endif // 0 int line = 1; for (std::string buffer; std::getline(fIn, buffer); ++line) { for (size_t col = 0;; ++col) { col = buffer.find(C, col); if (col < buffer.size()) coords.push({ line, (int)col }); else break; } } // output result if (coords.size() < N) { std::cerr << "ERROR! File didn't contain " << N << " occurrences of '" << C << "'.\n"; } else { const Coord& coord = coords[1]; // equivalent to coords[N - 1] -> it's a ring std::cout << "The " << N << "th occurrence of '" << C << "' from end" << " was in line " << coord.line << ", col. " << coord.col << '\n'; } } Output: The 4th occurrence of '.' from end was in line 52, col. 85 To simplify things on coliru, I used the source code main.cpp instead of t.txt. The online viewer of coliru displays line numbers. Hence, it's quite easy to check that the 4th occurrence of . from end is in fact in line 52. Line 52 is this one: std::cerr << "ERROR! File didn't contain " << N << " occurrences of '" << C << "'.\n"; (I must admit that I didn't check the column but 85 looks reasonable.—There is a . near the end of line.) The complete code is actually quite simple and straight-forward. The most convoluted thing is probably the RingT::operator[]: const V& operator[](int j) const { return values[((i - 1 + j) % n + n) % n]; } Thus, I'd like to dissect and explain it a bit: There is given the index j as argument which should be looked up. The index is relative to the last entry which was done: i - 1 + j. The index is used modulo n to wrap around inside the buffer: (i - 1 + j) % n. If i - 1 + j was a negative value then (i - 1 + j) % n becomes a negativ value as well. To fix this, n is added and then again modulo n: ((i - 1 + j) % n + n) % n. This grants that the resulting index for array access will always be in the range [0, n). (Admittedly, possible integer overflow issues are ignored.)
71,951,408
71,955,157
iOS biometrics, how to create LAContext instance from C++?
I'm trying to implement biometric authentication on iOS from a C++ codebase. Here is one example. In order to achieve this, I need to use the LAContext obj-c APIs. However, when I try to initialize the class from C++ I get a pointer/reference error: // Cannot initialize a variable of type 'LAContext *__strong' with an rvalue of type 'LAContext' LAContext* authContext = LAContext(); Is there any way to achieve this? Or is this struct available from Obj-c only? Edit 1: My file is in Obj-C++, so in theory I should be able to mix C++ and Obj-C code, however when I try to write a Obj-C function to alloc the LAContext object I get a missing symbols error: -(bool)biometricsAvailable { LAContext *myContext = [[LAContext alloc] init]; NSError *authError = nil; return true; } On the compilation step this error is thrown: Undefined symbol: _OBJC_CLASS_$_LAContext XCode itself does not show any error while editing the file, only happens when I try to build/compile the app.
As it turns out, the problem was not with mixing C++ and Obj-C code, but rather with my library being linked via cocoapods and the LocalAuthentication framework being missing. I needed to add: s.frameworks = "LocalAuthentication" to the podspec and creating a LAContext instance works just fine.
71,952,109
72,110,574
How do I translate this simple OpenACC code to SYCL?
I have this code: #pragma acc kernels #pragma acc loop seq for(i=0; i<bands; i++) { mean=0; #pragma acc loop seq for(j=0; j<N; j++) mean+=(image[(i*N)+j]); mean/=N; meanSpect[i]=mean; #pragma acc loop for(j=0; j<N; j++) image[(i*N)+j]=image[(i*N)+j]-mean; } As you can see, the first loop is told to be executed in sequence / single thread mode, the first loop inside too, but the last one can be parallelized so I do that. My question is, how do I translate this to SYCL? Do I put everything inside one q.submit() and then inside create a parallel_for() only for the parallel region? Would that be possible (and correct)? Second question, the above code continues as follows: #pragma acc parallel loop collapse(2) for(j=0; j<bands; j++) for(i=0; i<bands; i++) Corr[(i*bands)+j] = Cov[(i*bands)+j]+(meanSpect[i] * meanSpect[j]); How do I indicate the collapse() tag in SYCL? Does it exist or do I have to program it in other way? Thank you very much in advance.
In case anyone sees this, here's the correct answer: First code: for(i=0; i<bands; i++) { mean=0; for(j=0; j<N; j++) mean+=(image[(i*N)+j]); mean/=N; meanSpect[i]=mean; q.submit([&](auto &h) { h.parallel_for(range(N), [=](auto j) { image[(i*N)+j]=image[(i*N)+j]-mean; }); }).wait(); } Second code: q.submit([&](auto &h) { h.parallel_for(range<2>(bands_sycl,bands_sycl), [=](auto index) { int i = index[1]; int j = index[0]; Corr[(i*bands)+j] = Cov[(i*bands)+j]+(meanSpect[i] * meanSpect[j]); }); }).wait();
71,952,784
71,964,329
Using constexpr and string_view in module
Modern C++ offers constexpr and std::string_view as a convenient alternative to string literals. However, I am unable to link to a "constexpr std::string_view" within a module. By contrast, I am able to use string_view (not constexpr) within the module as well as a "constexpr std::string_view" outside of the module. Furthermore, the problem does not occur for other uses of constexpr within the module, such as for integers. Below is the minimal code to recreate the error: module interface unit (my_string.cpp): export module my_string; import <string_view>; export namespace my_string { struct MyString { static std::string_view string_at_runtime; static constexpr std::string_view string_at_compilation{"Hello World at compilation (inside module)"}; static constexpr int number_at_compilation{1}; }; } module implementation unit (my_string_impl.cpp): module; module my_string; namespace my_string { std::string_view MyString::string_at_runtime = "Hello World at runtime"; } hello_world.cpp: import <iostream>; import <string_view>; import my_string; static constexpr std::string_view hello_world{"Hello World at compilation (outside module)"}; int main(){ std::cout << hello_world << std::endl; std::cout << my_string::MyString::string_at_runtime << std::endl; std::cout << my_string::MyString::number_at_compilation << std::endl; std::cout << my_string::MyString::string_at_compilation << std::endl; //<-- ERROR is here } Compilation and attempt to link (using gcc 11.2.0 running on Linux): g++ -c -fmodules-ts -std=c++20 -xc++-system-header iostream string_view g++ -c my_string.cpp -fmodules-ts -std=c++20 g++ -c my_string_impl.cpp -fmodules-ts -std=c++20 g++ -c hello_world.cpp -fmodules-ts -std=c++20 g++ -o main my_string.o my_string_impl.o hello_world.o -fmodules-ts -std=c++20 Only the last instruction (linking) results in an error: g++ -o main my_string.o my_string_impl.o hello_world.o -fmodules-ts -std=c++20 /usr/bin/ld: hello_world.o: in function `main': hello_world.cpp:(.text+0x97): undefined reference to `my_string::MyString::string_at_compilation' collect2: error: ld returned 1 exit status In addition to searching the answers to related questions (e.g. constexpr in modules and constexpr and namespaces) I have reread the GCC Wiki. I have not yet tried this code with other compilers (e.g. clang, msvc). Is this error a failure in my code or a not-yet-implemented feature in gcc?
I have found a work around solution: adding a getter method. In the module interface unit (my_string.cpp) add: static std::string_view GetStringAtCompilation(); In the module implementation unit (my_string_impl.cpp) add: std::string_view MyString::GetStringAtCompilation(){ return string_at_compilation; } And now the following line in the "main" function (see hello_world.cpp in question) compiles, links and executes without error: std::cout << my_string::MyString::GetStringAtCompilation() << std::endl; I believe that the reasons that the original attempt did not work without a getter method is given in this answer about constexpr and string_view in headers
71,953,007
71,977,776
C++ How to read/split EPRT command?
I am currently writing a C++ FTP server and I was wondering what would be the best way to read the EPRT command from the client. << DEBUG INFO. >>: the message from the CLIENT reads: 'EPRT |2|::1|58059|\r\n' ^ ^ ^ Ip Version | | | | Ipv6 Address- | Port Number- I tried using the sscanf function in multiple ways but I don't think I'm doing it right. // method one int ipVersion; char* portNum; char* v6_addr; int scanned_items = sscanf(receive_buffer, "EPRT |%d|%s|%s|", &ipVersion, &v6_addr, &portNum); // method two int ipVersion; char* portNum; char v6_addr[3]; int scanned_items = sscanf(receive_buffer, "EPRT |%d|%s:%s:%s|%s|", &ipVersion, &v6_addr[0], &v6_addr[1], &v6_addr[2], &portNum); Should I be storing the IP address and port number differently. Any ideas? Thanks.
int ipVersion; char ipv6_str[64], rest[47], port[12]; int scanned_items = sscanf(receive_buffer, "EPRT |%d|%s", &ipVersion, rest); char *first = strchr(rest, '|'); *first = 0; scanned_items = sscanf(rest, "%s", ipv6_str); char *portT = first + 1; char *second = strchr(portT, '|'); *second = 0; scanned_items = sscanf(portT, "%s", port); If anyone was interested
71,953,477
71,954,829
Error: This compiler appears to be too old to be supported by Eigen
I am trying to compile a project that includes the eigen library and I get this error: In file included from /home/--/--/--/Eigen/Core:19, from /home/--/--/--/Eigen/Geometry:11, from /usr/include/rl-0.7.0/rl/math/Transform.h:34, from /home/--/--/--/example.cpp:2: /home/--/--/--/Eigen/src/Core/util/Macros.h:674:2: error: #error This compiler appears to be too old to be supported by Eigen 674 | #error This compiler appears to be too old to be supported by Eigen | ^~~~~ I am using: Ubuntu 20.04 Cmake 3.16.3 VSCode Compiler GCC 10.3.1 Eigen 3.4.90 The problem seems to be related to these lines in Macros.h file: // The macros EIGEN_HAS_CXX?? defines a rough estimate of available c++ features // but in practice we should not rely on them but rather on the availability of // individual features as defined later. // This is why there is no EIGEN_HAS_CXX17. #if EIGEN_MAX_CPP_VER<14 || EIGEN_COMP_CXXVER<14 || (EIGEN_COMP_MSVC && EIGEN_COMP_MSVC < 1900) || \ (EIGEN_COMP_ICC && EIGEN_COMP_ICC < 1500) || (EIGEN_COMP_NVCC && EIGEN_COMP_NVCC < 80000) || \ (EIGEN_COMP_CLANG && ((EIGEN_COMP_CLANG<309) || (defined(__apple_build_version__) && (__apple_build_version__ < 9000000)))) || \ (EIGEN_COMP_GNUC_STRICT && EIGEN_COMP_GNUC<51) #error This compiler appears to be too old to be supported by Eigen #endif Do you know how to fix this error?
As @Lala5th suggested, by changing the C++ standard the problem is solved. I have modified the CMakeLists.txt: From: set(CMAKE_CXX_STANDARD 11) To: set(CMAKE_CXX_STANDARD 17) (It also works with 14)
71,954,053
71,954,517
What does the vertical pipe | mean in the context of c++20 and ranges
There are usages of | which look more like function pipe-lining or chaining rather than a bitwise or, seen in combination with the c++20 ranges. Things like: #include <views> #include <vector> template<typename T> std::vector<T> square_vector(const std::vector<T> &some_vector) { auto result = some_vector | std::views::transform([](T x){ return x*x; }; return {result.begin(), result.end()}; } where clearly the | operator is not a bitwise or. Since when does it work, and on what sort of functions/objects? Are these like regular views? What are some caveats?
This sort of function chaining has been introduced with C++20 ranges, with the biggest feature allowing lazy evaluation of operation on views (more precisely, viewable ranges). This means the operation transforming the view will only act on it as it is iterated. This semantic allows for the pipeline syntax sugar, putting in a readable way what will happen when the result is iterated. The functions this is used with are based on range adaptors, which take a view (and possibly additional arguments after it) and transform it as they are iterated (essentially returning another view). The pipeline syntax is reserved for a special sub group of these called range adaptor closures, which only take a single view with no additional parameters. These can be either adaptors with no additional arguments, adaptors with the excess arguments bound, or the result of some library functions such as the std::views::transform in the OP. Since cpp23 you can also define these yourself). Once we have some of these, the syntax: some_viewable_range | std::views::some_adaptor_closure | some_other_adaptor_closure is equivalent to some_other_adaptor_closure(std::views::some_adaptor_closure(some_viewable_range)) which will evaluate the pipeline as the returned view is iterated. Similarly, some_vector | std::views::transform([](T x){ return x*x; }); is the same as std::views::transform([](T x){ return x*x; })(some_vector); // The first call returns the adaptor std::views::transform(some_vector, [](T x){ return x*x; }) with the second argument bound. but more readable. Like any view you can iterate them directly. Since this is lazy bad things can happen such as: template<typename T> auto square_vector(const std::vector<T> &some_vector) { return some_vector | std::views::transform([](T x){ return x*x; }); } int main () { for(auto val : square_vector(std::vector<int>{1, 2 ,3, 4, 5})) std::cout << val << '\n'; } by the time you get to print your val, the original vector does not exist, so the input to the chain is gone, and it goes down hill from there. To delve further into the world of ranges and adaptors you can check https://en.cppreference.com/w/cpp/ranges, and the original library these were based on, https://ericniebler.github.io/range-v3/.
71,954,469
71,962,324
Is safe boost::multi_array_ref returned by a function?
I'm trying to use boost::multi_array_ref to use a block of contiguous data in my code. But I worry about if I use the code like below, the 1d C array won't be confirmed to save: #include <iostream> #include "boost/multi_array.hpp" boost::multi_array_ptr<double, 2> test(int N,int c,int d) { double *data = new double[N]; boost::multi_array_ref<double, 2> a(data, boost::extents[c][d]); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { a[i][j] = 10 * i + j; } } return a; } int main() { boost::multi_array_ptr<double, 2> a = test(100000000,10000,10000); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { std::cout << a[i][j] << std::endl; } } } The result is right and I want to use std::unique_ptr to replace the C style array, but the Visual Studio told me: no instance of constructor "boost::multi_array_ref<T, NumDims>::multi_array_ref [with T=double, NumDims=2Ui64]" matches the argument list I don't know which kind of parameter boost::multi_array_ref need. Why the std::unique_ptr can't be use as parameter but C style array can? Can I use C style array without worry? Is safe boost::multi_array_ref returned by a function? I'm sure that it will cause memory leak,but how to solve it?
double *data = new double[N]; That's a raw pointer and no-one owns the allocation. You're correct that it leads to memory leaks. However, since you want to include ownership, why use multi_array_ref? Live On Compiler Explorer #include <algorithm> #include <numeric> #include "boost/multi_array.hpp" auto test(int c, int d) { boost::multi_array<double, 2> a(boost::extents[c][d]); std::iota(a.data(), a.data()+a.num_elements(), 0); return a; } #include <fmt/ranges.h> int main() { boost::multi_array<double, 2> a = test(4, 5); fmt::print("{}\n", a); fmt::print("{}\n", test(3, 6)); fmt::print("{}\n", test(6, 2)); } Prints: [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]] [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17]] [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]] And has no memory leaks. If you need the multi-array-ref: You might hack your way around with owning smart pointers: using ARef = boost::multi_array_ref<double, 2>; using ARefPtr = boost::shared_ptr<ARef>; Now you can allocate the data like you did before - but without the leak: auto test(int c, int d) { auto data = boost::shared_ptr<double[]>(new double[c*d]); See this post for details and compatibility with std::shared_ptr And Use the aliasing constructor to share ownership of data while changing the apparent element type to ARef: auto a = ARefPtr(data, new ARef(data.get(), boost::extents[c][d])); std::iota(a->data(), a->data() + a->num_elements(), 0); return a; } #include <fmt/ranges.h> int main() { ARefPtr a = test(4, 5); fmt::print("{}\n", *a); fmt::print("{}\n", *test(3, 6)); fmt::print("{}\n", *test(6, 2)); } Of course, now you're dealing with smart pointers, so you need more de-references. See it Live: [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]] [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17]] [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]
71,954,780
71,959,655
How to check a type has constexpr constructor
I want my class use another implementation for types don't have constexpr constructor. like this: template <typename A> class foo { public: // if A has constexpr constructor constexpr foo() :_flag(true) { _data._a = A(); } // else constexpr foo() : _flag(false) { _data.x = 0; } ~foo(){} bool _flag; union _data_t { _data_t() {} // nothing, because it's just an example ~_data_t() {} A _a; int x; }_data; }; To achieve what the title says, I try this: template<typename _t, _t = _t()> constexpr bool f() { return true; } template<typename _t> constexpr bool f() { return false; } It works well for types haven't constexpr constructor. But for other types it causes a compile error with ambiguous overloads. so how can I check?
I suppose you can use SFINAE together with the power of the comma operator Following your idea, you can rewrite your f() functions as follows template <typename T, int = (T{}, 0)> constexpr bool f (int) { return true; } template <typename> constexpr bool f (long) { return false; } Observe the trick: int = (T{}, 0) for the second template argument This way f() is enabled (power of the comma operator) only if T{} can be constexpr constructed (because (T{}, 0) is the argument for a template parameter), otherwise SFINAE wipe away the first version of f(). And observe that the fist version of f() receive an unused int where the second one receive a long. This way the first version is preferred, when available, calling f() with an int; the second one is selected, as better than nothing solution, when the first one is unavailable (when the first template argument isn't constexpr default constructible). Now you can construct two template constructors for foo that you can alternatively enable/disable according the fact the template parameter T (defaulted to A) is or isn't constexpr constructible template <typename T = A, std::enable_if_t<f<T>(0), std::nullptr_t> = nullptr> constexpr foo() { std::cout << "constexpr" << std::endl; } template <typename T = A, std::enable_if_t<not f<T>(0), std::nullptr_t> = nullptr> constexpr foo() { std::cout << "not constexpr" << std::endl; } The following is a full compiling example (C++14 or newer, but you can modify it for C++11): #include <iostream> #include <type_traits> template <typename T, int = (T{}, 0)> constexpr bool f (int) { return true; } template <typename> constexpr bool f (long) { return false; } template <typename A> struct foo { template <typename T = A, std::enable_if_t<f<T>(0), std::nullptr_t> = nullptr> constexpr foo() { std::cout << "constexpr" << std::endl; } template <typename T = A, std::enable_if_t<not f<T>(0), std::nullptr_t> = nullptr> constexpr foo() { std::cout << "not constexpr" << std::endl; } }; struct X1 { constexpr X1 () {} }; struct X2 { X2 () {} }; int main() { foo<X1> f1; // print "constexpr" foo<X2> f2; // print "not constexpr" }
71,955,172
71,955,422
C++ std::for_each printing repeats of indexes
Greetings so I'm making a program for my CS1 class, and in this program, for some odd reason it'll randomly repeatedly print some values. For example, I tried 2 students for the printReportCard function and it printed the first one twice and the second one once. Then I tried 3 students, and it printed each one twice in total printing 6 report cards. I have no idea why it's doing this, I've even tried printing vector size and it prints the correct number but for some reason iterates more than once over some report cards. I then checked the text file before it formats it and it had the proper amount of reports but only during that std::for_each is where it goes wrong oddly enough. code: void printReportCard(int numStudents) { fstream reportCards; reportCards.open("reportCard.txt"); string current_card = "2022 First Semester Report Card\n\n"; string name, currentClass, currentGrade; for (int student = 1; student <= numStudents; student++) { getline(reportCards, name); current_card += "Student Name: " + name + "\n"; current_card += "----------------------------------------------\nCourse:\t\t\tGrade:\n----------------------------------------------\n"; for (int i = 0; i < 7; i++) { reportCards >> currentClass >> currentGrade; current_card += currentClass + getTabs(currentClass) + currentGrade + "\n"; } string gpa, honorRoll; reportCards >> gpa >> honorRoll; if (honorRoll == "!") { honorRoll = "You are not on the Honor Roll."; } else { honorRoll = "You are on the " + honorRoll + " Honor Roll."; } current_card += "\nSemester GPA: " + gpa; current_card += "\n\nHonor Roll: " + honorRoll + "\n\n"; reportCardsVector.push_back(current_card); system("CLS"); } reportCards.close(); system("PAUSE"); system("CLS"); reportCards.open("reportCard.txt", ios::trunc | ios::out); for_each(reportCardsVector.begin(), reportCardsVector.end(), [ & ](const string VALUE) { reportCards << VALUE << "\n"; cout << VALUE << endl; }); reportCards.close(); } text file before format: Student One classOne f classTwo f classThree f classFour f classFive f classSix f classSeven f 0 ! Student Two classOne a classTwo a classThree a classFour a classFive a classSix a classSeven a High
"You need to reset current_card at the beginning of each loop iteration, otherwise it just keeps getting longer and longer. The most obvious way would be to move string current_card = "2022 First Semester Report Card\n\n"; inside the loop at the beginning. You should read Why does std::getline() skip input after a formatted extraction? as well for when you run into that." - Retired Ninja Thank you, Retired! This worked, and also thanks for the heads up I fixed that by adding reportCards >> std::ws inside the call to std::getline.
71,955,796
71,956,426
Is increment stackable? I.e x++++; or (x++)++;
When me and my friend were preparing for exam, my friend said that x+++; is the same as x+=3; It is not true but is x++++; same as x+=1; or is (x++)++;? Could I generalize it? I.e. x++++++++++++++; or ((((((x++)++)++)++)++)++)++; is equivalent to x+=7; Maybe it's completely wrong and it is true for ++++++x; or ++(++(++x)); equivalent to x+=3; Also it should generalize to --x; and x--;
The behavior of your program can be understood using the following rules from the standard. From lex.pptoken#3.3: Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-name is only formed within a #include directive. And from lex.pptoken#5: [ Example: The program fragment x+++++y is parsed as x ++ ++ + y, which, if x and y have integral types, violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression.  — end example ] is x++++; same as x+=1; Using the statement quoted above, x++++ will be parsed as x++ ++. But note that from increment/decrement operator's documentation: The operand expr of a built-in postfix increment or decrement operator must be a modifiable (non-const) lvalue of non-boolean (since C++17) arithmetic type or pointer to completely-defined object type. The result is prvalue copy of the original value of the operand. That means the result of x++ will a prvalue. Thus the next postfix increment ++ cannot be applied on that prvalue since it requires an lvalue. Hence, x++++ will not compile. Similarly, you can use the above quoted statements to understand the behavior of other examples in your snippet.
71,956,169
71,960,041
Performance problems using QVector<QPair<QPair<QString, QString>, QString>>
I am having serious performance issues using a QVector<QPair<QPair<QString, QString>, QString>> instance. Let's say I have a class EmojiList which does nothing but to hold this vector which is being filled with about 4000 emojis and their respective shortname and category: emojilist.h #include <QVector> class EmojiList { public: static const QVector<QPair<QPair<QString, QString>, QString>>& list() { static EmojiList list; return list.emojiList; } private: QVector<QPair<QPair<QString, QString>, QString>> emojiList { { { "‍‍‍", ":woman_woman_girl_girl:" }, "People & Body" }, { { "‍‍‍", ":woman_woman_girl_boy:" }, "People & Body" }, { { "‍‍‍", ":woman_woman_boy_boy:" }, "People & Body" }, { { "‍‍‍", ":man_woman_girl_girl:" }, "People & Body" }, { { "‍‍‍", ":man_woman_girl_boy:" }, "People & Body" }, // ... ~ 4000 entries to come }; It's being referenced (not copied) two times in other classes and queried directly on construction in a QAbstractListModel subclass: emojilistmodel.h #include "emojilist.h" class EmojiListModel : public QAbstractTableModel { Q_OBJECT // ... private: const QVector<QPair<QPair<QString, QString>, QString>>& _emojiMap { EmojiList::list() }; When compiling my application including emojilist.h, compiling takes about 1:20min, without emojilist.h, it takes 3.8 seconds. Also, starting the application takes heavily longer than when leaving out emojilist.h: startup time without emojilist.h included is 4 seconds, startup time including emojilist.h is 3:40min. How can I optimize my code for performance and speed here? Should I use a different class than QVector or should I maybe switch to a QMap or a different type of container? Maybe also using a Singleton in this case wouldn't be that much of a good idea? Thanks a lot in advance.
I managed to reduce the compile time to 3 seconds by outsourcing the emoji list parsing into the .cpp file: emojilist.h #include <QVector> class EmojiList { public: struct EmojiData { EmojiData(const QString& _code, const QString& _shortname, const QString& _category) : code(_code), shortname(_shortname), category(_category) {} QString code; QString shortname; QString category; }; static const QVector<EmojiData>& list(); private: QVector<EmojiData> emojiList; void parseFromFile(); }; emojilist.cpp #include "emojilist.h" #include <QFile> #include <QTextStream> const QVector<EmojiList::EmojiData>& EmojiList::list() { static EmojiList list; if (list.emojiList.isEmpty()) { list.parseFromFile(); } return list.emojiList; } void EmojiList::parseFromFile() { QFile emojiResource { ":/media/new_emoji.list" }; if (emojiResource.open(QIODevice::ReadOnly)) { QTextStream in { &emojiResource }; while (!in.atEnd()) { QStringList line { in.readLine().split(',') }; emojiList.append({ line.at(0), line.at(1), line.at(2) }); } } emojiResource.close(); } It is then being retrieved in my list model: emojilistmodel.cpp QVariant EmojiListModel::data(const QModelIndex &index, int role) const { if (_emojiMap.isEmpty() || !index.isValid() || index.row() > _emojiMap.size()) { return QVariant(); } switch (role) { case EmojiName: return _emojiMap.at(index.row()).shortname; case Emoji: return _emojiMap.at(index.row()).code; case EmojiCategory: { return _emojiMap.at(index.row()).category; } default: return QVariant(); } } It works quite well, however startup still takes incredibly long (5+ minutes). Anyways, this seems to be a QML-related problem so I'll have to create an extra issue for that. Thanks a lot everyone for helping so far.
71,956,803
71,957,395
normalize image with opencv in c++?
I have a TfLite model that takes a standardized float32 image as an input, the pixel range should convert from the [0~255] to [-1~1] I wrote a demo function but it didn't work. I couldn't set the color value back to the image; How can I set the color back to the "des" image? and Is there a better way to do that? this is my demo code #include <cstdint> #include <vector> #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/dnn.hpp> void standardize(cv::Mat &src, cv::Mat &des) { cv::Vec3b src_color,des_color; for(int i = 0; i < src.rows; i++) { for(int j = 0; j < src.cols; j++) { src_color = src.at<cv::Vec3b>(cv::Point(j,i)); des_color = des.at<cv::Vec3b>(cv::Point(j,i)); des_color[0] = ((int) src_color[0] -127.5 ) / 127.5 ; des_color[1] = ((int) src_color[1] -127.5 ) / 127.5 ; des_color[2] = ((int) src_color[2] -127.5 ) / 127.5 ; des.at<cv::Vec3b>(cv::Point(j,i)) = des_color ; std::cout << (int) src_color[0] << std::endl; std::cout << ((int) src_color[0] -127.5 ) / 127.5 << std::endl; std::cout << (int) des.at<cv::Vec3b>(cv::Point(j,i))[0] << std::endl; } } } int main(int argc, char *argv[]) { cv::Mat src, des; // src ---> CV_8UC3 src = cv::imread("/test.jpg"); // copy to take the same size src.copyTo(des); // des ----> CV_32FC3 src.convertTo(des, CV_32FC3); standardize(src,des); return 0; }
please do not write for loops. instead: src.convertTo(dst, CV_32F); dst -= 127; dst /= 255; // EDIT
71,956,811
71,956,898
How to get the result of Windows_x64 message without truncation in Qt5?
In Qt5, the function for processing native Windows messages is: bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result) and the documentation says, that the third parameter means LRESULT on Windows. In Qt6, the parameter was changed to qintptr: bool QWidget::nativeEvent(const QByteArray &eventType, void *message, qintptr *result) Now you can properly pass 64-bit LRESULT using 64-bit qintptr. But what should be done on Windows x64 with 32-bit long in Qt5? I have a custom MessageHandler which returns various 8-byte pointers using its LRESULT, so the call *result = SendMessage(...) from nativeEvent stores the truncated result.
what should be done on Windows x64?" Don't use Qt5. Well, you can use Qt5 for most of your program, but you can't use Qt for processing this particular message. What you can do is subclass the window (see WinAPI function SetWindowSubclass) and write your own window procedure which processes only that single message, while allowing all the rest to process through the Qt window procedure as usual. Here is an official Microsoft tutorial on subclassing: https://learn.microsoft.com/en-us/windows/win32/controls/subclassing-overview#subclassing-controls-using-comctl32dll-version-6 While it talks about subclassing a child window (control), the same technique works fine for top-level windows.
71,956,916
71,956,983
What does (1) mean when declaring a vector?
What does the ...(1) do? std::vector<std::vector<cv::Point>> tight_contour(1);
tight_contour is a std::vector object containing elements of type std::vector<cv::Point>. The (1) is constructing tight_contour to hold 1 initial default-constructed element.
71,957,099
71,957,295
c++: how to remove surrogate unicode values from string?
how do you remove surrogate values from a std::string in c++? looking for regular expression like this: string pattern = u8"[\uD800-\uDFFF]"; regex regx(pattern); name = regex_replace(name, regx, "_"); how do you do it in a c++ multiplatform project (e.g. cmake).
First off, you can't store UTF-16 surrogates in a std::string (char-based), you would need std::u16string (char16_t-based), or std::wstring (wchar_t-based) on Windows only. Javascript strings are UTF-16 strings. For those string types, you can use either: std::remove_if() + std::basic_string::erase(): #include <string> #include <algorithm> std::u16string str; // or std::wstring on Windows ... str.erase( std::remove_if(str.begin(), str.end(), [](char16_t ch){ return (ch >= 0xd800) && (ch <= 0xdfff); } ), str.end() ); std::erase_if() (C++20 and later only): #include <string> std::u16string str; // or std::wstring on Windows ... std::erase_if(str, [](char16_t ch){ return (ch >= 0xd800) && (ch <= 0xdfff); } ); UPDATE: You edited your question to change its semantics. Originally, you asked how to remove surrogates, now you are asking how to replace them instead. You can use std::replace_if() for that task, eg: #include <string> #include <algorithm> std::u16string str; // or std::wstring on Windows ... std::replace_if(str.begin(), str.end(), [](char16_t ch){ return (ch >= 0xd800) && (ch <= 0xdfff); }, u'_' ); Or, if you really want a regex-based approach, you can use std::regex_replace(), eg: #include <string> #include <regex> std::wstring str; // std::basic_regex does not support char16_t strings! ... std::wstring newstr = std::regex_replace( str, std::wregex(L"[\\uD800-\\uDFFF]"), L"_" );
71,957,465
71,957,541
Errors when statically linking libsndfile with vcpkg and running sf_open
So here's a bit of example code: #include<sndfile.h> int main() { SNDFILE* sndfile; SF_INFO sfinfo; sndfile = sf_open("", SFM_READ, &sfinfo); std::cout << "Hello, World!"; } So basically I'm statically linking it from vcpkg, and I followed all the steps like using :x64-windows-static at the end, changing the visual studio settings and configuration file, and more, but for some reason I get these errors specifically when I compile statically and when using sf_open. Errors: 3 unresolved externals unresolved external symbol __imp_PathCombineW referenced in function INT123_compat_catpath unresolved external symbol __imp_PathIsRelativeW referenced in function wpath_need_elongation unresolved external symbol __imp_PathIsUNCW referenced in function wlongpath Note: Yes I do realize that libsndfile is licensed under LGPL, so I plan to include the object files since that apparently allows me to statically link it.
These are functions from the windows api. Just Google them and the msdn help page will tell you which windows library you need to link. For example PathCombineW has this help page: https://learn.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathcombinew in the Requirements section it tells you that you need to link to Shlwapi.lib
71,958,041
71,959,195
Format string based on word match
I ran out of ideas. I need to format this text creating a paragraph for each instance of the word 'Group'. Notice Group1, Group2: ('uniqueName', 'Group', True ), ('Value', 'float', 0, 5, 1 ), ('Value', 'int', 1 ), ('Value', 'bool', true), ('uniqueName', 'Group', True ), ('Value', 'bool', true), .... I need to separate this is in two paragraphs: ('uniqueName', 'Group', True ), ('Value', 'float', 0, 5, 1 ), ('Value', 'int', 1 ), ('Value', 'bool', true), ('uniqueName', 'Group', True ), ('Value', 'bool', true), Each group represents the parameters below it, so Group1 have value1 - value3. The groups and values share the same pattern so is being difficult. I'm using QT with QString.
Thanks to Aconcagua's comment I found a solution. Just had to check for each Group match and add a new line before copying the line to the file. Then check for everything that was not a group and add it to the file after adding the group: If(Group) { // add a blank line // Copy the group to the file } if(!Group) { // Copy the line to the file }
71,958,323
71,961,194
How bad it is to lock a mutex in an infinite loop or an update function
std::queue<double> some_q; std::mutex mu_q; /* an update function may be an event observer */ void UpdateFunc() { /* some other processing */ std::lock_guard lock{ mu_q }; while (!some_q.empty()) { const auto& val = some_q.front(); /* update different states according to val */ some_q.pop(); } /* some other processing */ } /* some other thread might add some values after processing some other inputs */ void AddVal(...) { std::lock_guard lock{ mu_q }; some_q.push(...); } For this case is it okay to handle the queue this way? Or would it be better if I try to use a lock-free queue like the boost one?
How bad it is to lock a mutex in an infinite loop or an update function It's pretty bad. Infinite loops actually make your program have undefined behavior unless it does one of the following: terminate make a call to a library I/O function perform an access through a volatile glvalue perform a synchronization operation or an atomic operation Acquiring the mutex lock before entering the loop and just holding it does not count as performing a synchronization operation (in the loop). Also, when holding the mutex, noone can add information to the queue, so while processing the information you extract, all threads wanting to add to the queue will have to wait - and no other worker threads wanting to share the load can extract from the queue either. It's usually better to extract one task from the queue, release the lock and then work with what you got. The common way is to use a condition_variable that lets other threads acquire the lock and then notify other threads waiting with the same condition_variable. The CPU will be pretty close to idle while waiting and wake up to do the work when needed. Using your program as a base, it could look like this: #include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <queue> #include <thread> std::queue<double> some_q; std::mutex mu_q; std::condition_variable cv_q; // the condition variable bool stop_q = false; // something to signal the worker thread to quit /* an update function may be an event observer */ void UpdateFunc() { while(true) { double val; { std::unique_lock lock{mu_q}; // cv_q.wait lets others acquire the lock to work with the queue // while it waits to be notified. while (not stop_q && some_q.empty()) cv_q.wait(lock); if(stop_q) break; // time to quit val = std::move(some_q.front()); some_q.pop(); } // lock released so others can use the queue // do time consuming work with "val" here std::cout << "got " << val << '\n'; } } /* some other thread might add some values after processing some other inputs */ void AddVal(double val) { std::lock_guard lock{mu_q}; some_q.push(val); cv_q.notify_one(); // notify someone that there's a new value to work with } void StopQ() { // a function to set the queue in shutdown mode std::lock_guard lock{mu_q}; stop_q = true; cv_q.notify_all(); // notify all that it's time to stop } int main() { auto th = std::thread(UpdateFunc); // simulate some events coming with some time apart std::this_thread::sleep_for(std::chrono::seconds(1)); AddVal(1.2); std::this_thread::sleep_for(std::chrono::seconds(1)); AddVal(3.4); std::this_thread::sleep_for(std::chrono::seconds(1)); AddVal(5.6); std::this_thread::sleep_for(std::chrono::seconds(1)); StopQ(); th.join(); } If you really want to process everything that is currently in the queue, then extract everything first and then release the lock, then work with what you extracted. Extracting everything from the queue is done quickly by just swapping in another std::queue. Example: #include <atomic> std::atomic<bool> stop_q{}; // needs to be atomic in this version void UpdateFunc() { while(not stop_q) { std::queue<double> work; // this will be used to swap with some_q { std::unique_lock lock{mu_q}; // cv_q.wait lets others acquire the lock to work with the queue // while it waits to be notified. while (not stop_q && some_q.empty()) cv_q.wait(lock); std::swap(work, some_q); // extract everything from the queue at once } // lock released so others can use the queue // do time consuming work here while(not stop_q && not work.empty()) { auto val = std::move(work.front()); work.pop(); std::cout << "got " << val << '\n'; } } }
71,958,824
71,960,646
QFileSystemModel doesn't emit fileRenamed signal
I am trying to watch the changes in a directory using QFileSystemModel. Whenever I rename a file in the root path, only the directoryLoaded() signal is emitted. I want the fileRenamed() signal to be emitted so that I know which file is renamed to a new name. Here is my code: model = new QFileSystemModel; model->setRootPath("C:/test/"); QObject::connect(model, SIGNAL(fileRenamed(const QString&, const QString&, const QString&)), this, SLOT(updateRename())); QObject::connect(model, SIGNAL(directoryLoaded(const QString&)), this, SLOT(loadDir()));
I am afraid you expect too much from this QFileSystemModel class. It does not and cannot catch if the renaming operation happens outside of the model. I looked up all uses of fileRenamed() signal and it seems that the only place where it is emitted is here: https://code.woboq.org/qt5/qtbase/src/widgets/dialogs/qfilesystemmodel.cpp.html#933 And if you go a few lines above, you can see that this is triggered when the renaming happens inside this function https://code.woboq.org/qt5/qtbase/src/widgets/dialogs/qfilesystemmodel.cpp.html#873 In other words, if you use QFileSystemModel::setData() to set a name to an item, it will rename the item and emit the signal. And it is the only way to have the signal emitted. And this is logical, if renaming happens outside of your program, then there is no certain way to find out that a certain file was renamed. Your application only observes that some file disappeared and another file with a different name emerged. Of course, you can check whether the timestamp and size of the file is the same, whether they are also in the same parent folder, maybe also check the file content... and only if these things match and the only difference is in the file names, then you can conclude that the file was renamed. But this is something you must program yourself. QFileSystemModel will not do it for you because it does not know your specific intentions.
71,959,452
71,959,817
std::filesystem::path::u8string might not return valid UTF-8?
Consider this code, running on a Linux system (Compiler Explorer link): #include <filesystem> #include <cstdio> int main() { try { const char8_t bad_path[] = {0xf0, u8'a', 0}; // invalid utf-8, 0xf0 expects continuation bytes std::filesystem::path p(bad_path); for (auto c : p.u8string()) { printf("%X ", static_cast<uint8_t>(c)); } } catch (const std::exception& e) { printf("error: %s\n", e.what()); } } It deliberately constructs a std::filesystem::path object using a string with incorrect UTF-8 encoding (0xf0 starts a 4-byte character, but 'a' is not a continuation byte; more info here). When u8string is called, no exception is thrown; I find this surprising as the documentation at cppreference states: The result encoding in the case of u8string() is always UTF-8. Checking the implementation of LLVM's libcxx, I see that indeed, there's no validation performed - the string held internally by std::filesystem::path is just copied into a u8string and returned: _LIBCPP_INLINE_VISIBILITY _VSTD::u8string u8string() const { return _VSTD::u8string(__pn_.begin(), __pn_.end()); } The GCC implementation (libstdc++) exhibits the same behavior. Of course this is a contrived example, as I deliberately construct a path from an invalid string to keep things simple. But to my knowledge, the Linux kernel/filesystems do not enforce that file paths are valid UTF-8 strings, so I could encounter a path like that "in the wild" while e.g. iterating a directory. Am I right to conclude that std::filesystem::path::u8string actually does not guarantee that a valid UTF-8 string will be returned, despite what the documentation says? If so, what is the motivation behind this design?
The current C++ standard states in fs.path.type.cvt: char8_­t: The encoding is UTF-8. The method of conversion is unspecified. and also If the encoding being converted to has no representation for source characters, the resulting converted characters, if any, are unspecified. So, in a nutshell, anything involving the actual interpretation of the bytes making up the path is unspecified, meaning that implementations are free to handle invalid data as they see fit. So yes, std::filesystem::path::u8string() does not really guarantee that a valid UTF-8 string is returned. Regarding the motivation: The standard says nothing about it. But one might have an idea by looking at boost::filesystem, which the standard is based on. The documentation states: When a class path function argument type matches the operating system's API argument type for paths, no conversion is performed rather than conversion to a specified encoding such as one of the Unicode encodings. This avoids unintended consequences, etc. I guess you are using a posix system, in which case the underlying operating system API is most likely using UTF-8 or binary filenames. Hence, inputs are kept as is so to not stumble into any conversion issues. On the other hand, Windows is using UTF-16 and hence needs to convert the string already when constructing a path, resulting in an exception when the input is an invalid UTF-8 encoding (godbolt).
71,960,298
71,960,358
c++ calling int twice
I was writing a code, and accidentally put int before a variable twice, and noticed something different in the end product. int main () { int number = 123456789; int step = 0; while (number>0) { cout << number%10 << endl; number = number/10; step = step+1; cout << "step ; " << step << endl; } return 0; } The output was: 9 step ; 1 8 step ; 2 7 step ; 3 6 ... However, when I called it this way: int main () { int number = 123456789; int step = 0; while (number>0) { cout << number%10 << endl; number = number/10; int step = step+1; cout << "step ; " << step << endl; } return 0; } The output suddenly changed to: 9 step ; 11006125 8 step ; 11006126 7 step ; 11006127 6 Can someone please explain the difference, so that I will be mindful next time?
C++ is block scoped. When you redeclare step inside the while loop (by using int step instead of just step), you "shadow" the step from outside that scope; while the outer step (with value 0) still exists, it cannot be read directly from the inner scope (a pointer/reference to the outer step with a different name could read/write the data, you just can't read the outer step directly through that name). The outer step is invisible, so int step = step + 1; translates as "please assign to the local step the value of whatever is already stored in the local step (which, not existing until that moment, has no defined value yet) after adding 1". Since the step it reads from is garbage, this is undefined behavior, and in practice, it gets garbage (whatever junk happened to be left on the stack in that position from before you entered the while). The second and subsequent creations of the inner step are still undefined behavior, but in this case (and in most cases where loop unrolling isn't involved) the compiler chose to reuse the same storage for them as the prior use of inner step (that expired when that iteration of the loop ended). Thus, as a coincidence of the new inner step reading from the same memory location as the expired inner step, it increments normally from then on, based on the original garbage value as a base. But again, to be clear, all of this is undefined behavior. Be thankful you didn't get nasal demons, and only use the first form in the future. I'll note, if you enable all warnings, any compiler worth its salt should detect this error (the entire error exists in the scope of a single line); sadly, it appears at least GCC is not worth its salt, because the only thing it detects, even with -Wall -Wextra -Werror -pedantic is that you didn't use the outer step variable. If you used it, or deleted the declaration of the outer step, it compiles with no warnings, so I guess you're stuck just remembering not to initialize a variable in terms of its own value.
71,960,411
71,960,514
Why can I "captureless-capture" an int variable, but not a non-capturing lambda?
The following function is valid (as of C++20): void foo() { constexpr const int b { 123 }; constexpr const auto l1 = [](int a) { return b * a; }; (void) l1; } even though l1 does not capture anything, supposedly, it is still allowed to "captureless-capture" the value of b, as it is a const (it doesn't even have to be constexpr; but see @StoryTeller's comment). But if I try to capture something more complex in a new lambda: void foo() { constexpr const int b { 123 }; constexpr const auto l1 = [](int a) { return b * a; }; (void) [](int c) { return l1(c) * c; }; } This fails to compile. Why? The compiler should have no trouble calling l1 from within the lambda; so why is b ok for captureless-capture, and l1 isn't? See this on GodBolt.
This has to do with odr-use. First, from [basic.def.odr]/10: A local entity is odr-usable in a scope if: either the local entity is not *this, or an enclosing class or non-lambda function parameter scope exists and, if the innermost such scope is a function parameter scope, it corresponds to a non-static member function, and for each intervening scope ([basic.scope.scope]) between the point at which the entity is introduced and the scope (where *this is considered to be introduced within the innermost enclosing class or non-lambda function definition scope), either: the intervening scope is a block scope, or the intervening scope is the function parameter scope of a lambda-expression that has a simple-capture naming the entity or has a capture-default, and the block scope of the lambda-expression is also an intervening scope. If a local entity is odr-used in a scope in which it is not odr-usable, the program is ill-formed. So in this example, a is odr-usable but b is not: void foo() { constexpr const int b { 123 }; constexpr const auto l1 = [](int a) { return b * a; }; (void) l1; } And in this example, similarly, the a and c are odr-usable, but neither b or nor l1 are. void foo() { constexpr const int b { 123 }; constexpr const auto l1 = [](int a) { return b * a; }; (void) [](int c) { return l1(c) * c; }; } But the rule isn't just "not odr-usable", it's also "odr-used". Which one(s) of these are odr-used? That's [basic.def.odr]/5: A variable is named by an expression if the expression is an id-expression that denotes it. A variable x whose name appears as a potentially-evaluated expression E is odr-used by E unless x is a reference that is usable in constant expressions ([expr.const]), or x is a variable of non-reference type that is usable in constant expressions and has no mutable subobjects, and E is an element of the set of potential results of an expression of non-volatile-qualified non-class type to which the lvalue-to-rvalue conversion ([conv.lval]) is applied, or x is a variable of non-reference type, and E is an element of the set of potential results of a discarded-value expression ([expr.context]) to which the lvalue-to-rvalue conversion is not applied. For the b * a case, b is "a variable of non-reference type that is usable in constant expressions" and what we're doing with it is applying "the lvalue-to-rvalue conversion". That's the second bullet exception to the rule, so b is not odr-used, so we don't have the odr-used but not odr-usable problem. For the l1(c) case, l1 is also "a variable of non-reference type that is usable in constant expressions"... but we're not doing an lvalue-to-rvalue conversion on it. We're invoking the call operator. So we don't hit the exception, so we are odr-using l1... but it's not odr-usable, which makes this ill-formed. The solution here is to either capture l1 (making it odr-usable) or make it static or global (making the rule irrelevant since l1 wouldn't be a local entity anymore).
71,961,061
71,967,349
DElem<T,N> derives from BElem<T> and DContainer<DElem<T,N>> derives from BContainer<BElem<T>> How to code it?
The question is easy to explain in code. I have coded several template classes that they derive from a unique template class: template<typename T,unsigned N> struct DElem : public BElem<T> {}; My problem arises when I have to code a container of these anterior derived types from a container of the base class: template<typename T, unsigned N> struct DContainer<DElem<T,N>> : public BContainer<BElem<T>> {}; In my concrete case, Container could be std::tuple or std::array. My first approximation is: template<typename T, T B, std::size_t N> struct DContainer : public std::array<BElem<T>,N> { // This container is to hold **DElem<T,B>** // // This class has to do a cast for every // // **DElem<T,B>** (that is what the DContainer holds) // // to **BElem\<T\>** // // *If this task is easy I don't found the way* }; Someone has an idea to do these tasks more easy or some other design more appropiate?
You are out of luck. A container of DElem<T, N> is not substitutable for a container of BElem<T>. If it could, the following nonsense would be allowed. DContainer<T, 10> d10Container; BContainer<T> & bContainer = d10Container; DElem<T, 20> d20; bContainer.push_back(d20); // pushed a d20 into a container of d10 What you can have is a view of BElem<T> template<typename T> class BView { class iterator { using value_type = BElem<T>; using reference = BElem<T> &; using pointer = BElem<T> *; using difference_type = std::ptrdiff_t; using iterator_category = std::forward_iterator_tag; // or whatever reference operator*(); pointer operator->(); // etc... }; virtual iterator begin() = 0; virtual iterator end() = 0; // no insert / push_back / whatever }; You probably want to hide (or delete) the assignment operator of BElem<T>, because polymorphic assignment is also fairly nonsensical. Now you have a shared base class for all your DContainer<T, N>s which doesn't permit nonsense. Alternatively, if you don't need runtime polymorphism, you can just define a concept for BContainer. Using the pre-concept Container requirements as a base: template<container C, typename T> concept BContainer = std::derived_from<typename C::value_type, BElem<T>>;
71,961,417
71,974,275
How can I achieve native-level optimizations when cross-compiling with Clang?
When cross-compiling using clang and the -target option, targeting the same architecture and hardware as the native system, I've noticed that clang seems to generate worse optimizations than the native-built counter-part for cases where the <sys> in the triple is none. Consider this simple code example: int square(int num) { return num * num; } When optimized at -O3 with -target x86_64-linux-elf, the native x86_64 target code generation yields: square(int): mov eax, edi imul eax, edi ret The code generated with -target x86_64-none-elf yields: square(int): push rbp mov rbp, rsp mov eax, edi imul eax, edi pop rbp ret Live Example Despite having the same hardware and optimization flags, clearly something is missing an optimization. The problem goes away if none is replaced with linux in the target triple, despite no system-specific features being used. At first glance it may look like it simply isn't optimizing at all, but different code segments show that it is performing some optimizations, just not all. For example, loop-unrolling is still occurring. Although the above examples are simply with x86_64, in practice, this issue is generating code-bloat for an armv7-based constrained embedded system, and I've noticed several missed optimizations in certain circumstances such as: Not removing unnecessary setup/cleanup instructions (same as in x86_64) Not coalescing certain sequential inlined increments into a single add instruction (at -Os, when inlining vector-like push_back calls. This optimizes when built natively from an arm-based system running armv7.) Not coalescing adjacent small integer values into a single mov (such as merging a 32-bit int with a bool in an optional implementation. This optimizes when built natively from an arm-based system running armv7.) etc I would like to know what I can do, if anything, to achieve the same optimizations when cross-compiling as compiling natively? Are there any relevant flags that can help tweak tuning that are somehow implied with the <sys> in the triple? If possible, I'd love some insight as to why the cross-compilation target appears to fail to optimize certain things simply because the system is different, despite having the same architecture and abi. My understanding is that LLVM's optimizer operates on the IR, which should generate effectively the same optimizations so long as nothing is reliant on the target system itself.
TL;DR: for the x86 targets, frame-pointers are enabled by default when the OS is unknown. You can manually disable them using -fomit-frame-pointer. For ARM platforms, you certainly need to provide more information so that the backend can deduce the target ABI. Use -emit-llvm so to check which part of Clang/LLVM generate an inefficient code. The Application Binary Interface (ABI) can change from one target to another. There is no standard ABI in C. The chosen one is dependent of several parameters including the architecture, its version, the vendor, the OS, the environment, etc. The use of the -target parameter help the compiler to select a ABI. The thing is x86_64-none-elf is not complete enough so the backend can actually generate a fast code. In fact, I think this is actually not a valid target since there is a warning from Clang in this case and the same warning appear with wrong random targets. Surprisingly, the compiler still succeed to generate a generic binary with the provided information. Targets like x86_64-windows and x86_64-linux works as well as x86_64-unknown-windows-cygnus (for Cygwin in Windows). You can get the list of the Clang supported platforms, OS, environment, etc. in the code. One particular aspect of the ABI is the calling conventions. They are different between operating systems. For example, x86-64 Linux platforms uses the calling convention from the System V AMD64 ABI while recent x86-64 Windows platforms uses the vectorcall calling convention based on the older Microsoft x64 one. The situation is more complex for old x86 architectures. For more information about this please read this and this. In your case, without information about the OS, the compiler might select its own generic ABI resulting in the old push/pop instruction being used. That being said, the compiler assumes that edi contains the argument passed to the function meaning that the chosen ABI is the System V AMD64 (or a derived version). The environment can play an important role in stack optimizations like the access of the stack from outside the function (eg. the callee functions). My initial guess was that the assembly backend disabled some optimizations due to the lack of information regarding the specified target, but this is not the case for x86-64 ELFs as the same backend is selected. Note that target is parsed by architecture-specific backend (see here for example). In fact, the issue comes from Clang emitting an IR code with frame-pointer flag set to all. You can check the IR code with the flag -emit-llvm. You can solve this problem using -fomit-frame-pointer. On ARM, the problem can be different and come from the assembly backend. You should certainly specify the target OS or at least more information like the sub-architecture type (mainly for ARM), the vendor and the environment. Overall, note that it is reasonable to think that a more generic targets produces a less efficient code due to the lack of information. If you want more information about this, please fill an issue on the Clang or LLVM bug tracker so to track the reason why this happens or/and let developers fix this. Related posts/links: clang: how to list supported target architectures? https://clang.llvm.org/docs/CrossCompilation.html
71,961,678
71,961,757
How to change the position of a window scrollbar?
How to change the position of the Vertical Scrollbar of a window? I'm referring to the position in xy, for example set it in the middle of the window instead of the edges.
You cannot reposition a scrollbar that is built-in to a window. You will have to disable the native scrollbar (remove the window's WS_HSCROLL/WS_VSCROLL style) and then create a separate ScrollBar control as a child of the window. Then you can position that child wherever you want, using the x/y parameters of CreateWindow/Ex() or SetWindowPos().
71,961,793
71,961,856
Odd behavior from character array
I am trying to write a helper program for Wordle which will display all of the letters which have not been eliminated and the letters which have been confirmed. I've broken the program into functions, and I'm having an issue with the confirmed_letters() function. I have this array declared in the global scope: char* word[NUM_LETTERS]; and it's initialized like this: for (int i = 0; i < NUM_LETTERS; i++) word[i] = new char(char(42)); Here's the function: void confirmed_letters() { int num_let = 0; // the # of confirmed letters int temp_num; // holds the position of the confirmed letter char temp_letter; std::cout << "\n\nHow many letters have you confirmed?\n" << "Enter only the letters whose positions are known. "; std::cin >> num_let; std::cin.ignore(1000, '\n'); if (num_let == 0) return; std::cout << "Enter the integer position of the confirmed letter, " << "followed by the letter. Press the enter (return) key between each entry.\n"; for (int i = 0; i < num_let; i++) { //temp_num = -1; // I don't think this is needed std::cin >> temp_num; std::cin.ignore(1000, '\n'); if (temp_num > 5 || temp_num < 1) { std::cout << "Invalid letter position. Enter an integer between 1 and 5.\n"; i--; goto end; } std::cin >> temp_letter; std::cin.ignore(1000, '\n'); word[temp_num - 1] = &temp_letter; end: display_word(); } return; } display_word() is just a function to display the word. Here's the output I got: How many letters have you confirmed? Enter only the letters whose positions are known. 3 Enter the integer position of the confirmed letter, followed by the letter. Press the enter (return) key between each entry. 1 o o * * * * 2 i i i * * * 3 e e e e * * So, for some reason, each additional letter is modifying the previous letters. I don't understand what is going on here. Each time the value of one of the elements of word[] is modified, it should only modify one element, but it's modifying all of them. Thoughts?
word[temp_num - 1] = &temp_letter; stores the address of a local variable that will be reused on the next loop iteration and hold whatever new value the user inputs. The old value will be lost, so it'll look like all of the used slots store the same letter. Because they do. Worse, the variable goes out of scope at the end of the function and will no longer be valid. This is dangerous as the pointer lives on and might even give what looks to be correct results. Solution: Don't store pointers to letters in word. Store the letters themselves. char word[NUM_LETTERS]; Initialize like this: for (int i = 0; i < NUM_LETTERS; i++) word[i] = '*'; // use the character not the code. It's easier to understand the intent of // * than the number 42 and not all systems will use 42 for *. and store word[temp_num - 1] = temp_letter;
71,962,198
71,962,230
I would like to know how this code can be rewritten as an IF statement?
mcPlayerTurn = (mcPlayerTurn == 'W') ? 'B' : 'W'; I am making a game of two players and after one player another player's turn comes.
Per Conditional operator on cppreference.com: The conditional operator expressions have the form E1 ? E2 : E3 The first operand of the conditional operator is evaluated and contextually converted to bool. After both the value evaluation and all side effects of the first operand are completed, if the result was true, the second operand is evaluated. If the result was false, the third operand is evaluated. So, the statement mcPlayerTurn = (mcPlayerTurn == 'W') ? 'B' : 'W'; means: If mcPlayerTurn is equal to 'W', assign 'B' to mcPlayerTurn Otherwise, assign 'W' to mcPlayerTurn. That would look like the following as an if statement: if (mcPlayerTurn == 'W') mcPlayerTurn = 'B'; else mcPlayerTurn = 'W';
71,962,514
71,962,558
Why the destructor of a struct in vector are called every time I iterate over them?
I'm trying to implement a HashMap in LeetCode 706. Design HashMap with C++, it's a simple HashMap with add, remove, get operations: struct Slot { int key; int val; void setValue(int v) { cout << "-set " << v << "fo SV"<<endl; val = v; } ~Slot() { cout << "dtor Slot " << key << endl; } }; #define BUCKET_SIZE 769 class MyHashMap { private: vector<vector<Slot>> buckets; //const int BUCKET_SIZE; public: MyHashMap() :buckets(BUCKET_SIZE, vector<Slot>()) { } void put(int key, int value) { auto bucket = buckets[key % BUCKET_SIZE]; cout << "Add: use bucket " << (key % BUCKET_SIZE) << endl; for (auto iter = bucket.begin(); iter != bucket.end(); iter++) { if (iter->key == key) { cout << "Add: update key " << key << " with value " << value << endl; *iter = Slot{key, value}; return; } } cout << "Add: push key " << key << " to back with value " << value << endl; buckets[key % 769].push_back(Slot{key, value}); } int get(int key) { auto bucket = buckets[key % BUCKET_SIZE]; for (auto iter = bucket.begin(); iter != bucket.end(); iter++) { if (iter->key == key) { return iter->val; } } return -1; } void remove(int key) { auto bucket = buckets[key % BUCKET_SIZE]; for (auto iter = bucket.begin(); iter != bucket.end(); iter++) { if (iter->key == key) { cout << "Remove: remove " << key << endl; bucket.erase(iter); return; } } } }; ["MyHashMap","put","put","get","get","put","get","remove","get"] [[],[1,10],[2,2],[1],[3],[2,1],[2],[2],[2]] When I tried to use the HashMap as below: MyHashMap* obj = new MyHashMap(); obj->put(1, 10); obj->put(2, 2); obj->get(1); obj->get(3); obj->put(2, 1); obj->get(2); obj->remove(key); obj->get(2); The output shows that the destructor of every element in the vector are called: Add: use bucket 1 Add: push key 1 to back with value 10 dtor Slot 1 Add: use bucket 2 Add: push key 2 to back with value 2 dtor Slot 2 dtor Slot 1 Add: use bucket 2 Add: update key 2 with value 1 dtor Slot 2 dtor Slot 2 dtor Slot 2 Remove: remove 2 dtor Slot 2 dtor Slot 2 dtor Slot 1 dtor Slot 2 Is there anything I have missed?
Your put(), get() and remove() methods all making the same mistake. On this statement: auto bucket = buckets[key % BUCKET_SIZE]; bucket is a copy of the vector located at index key % BUCKET_SIZE, and thus it makes its own copy of all of the Slot objects. You are then looping through, and accessing/modifying, that copied vector, not the original vector. When the method exits, all of those copies get destroyed. That is what you are seeing in your output. To avoid the copies, you need to change the above statement to this instead: auto &bucket = buckets[key % BUCKET_SIZE]; bucket will now be a reference to the original vector, not a copy.
71,962,608
71,962,643
Do invalid statements provide valid results
I made this code and it should be invalid #include<iostream> using namespace std; int main() { int a,b; a=3,014; //invalid b=(3,014); //invalid cout<<a<<endl<<b; } Output: 3 12 However both the invalid statements give valid results. But the result should be 3014. It is changed. Why does this happen?
There's nothing "invalid" about either of those. a = 3,014; This parenthesizes as (a = 3) , 014; So a gets assigned the value 3, and then 014 (a number) gets evaluated and discarded. Hence, a = 3. b = (3 , 014); Here, we've explicitly put in parentheses. So the right-hand side is an application of the comma operator. The 3 gets evaluated then discarded. The 014 is an octal number, and 14 in base 8 is equal to 12 in base 10, so b = 12.
71,962,952
71,963,361
Can we take the value of iterator which was returned from lower_bound as vector index?
I'm new to vector in C++ and trying to get how it works. First, I have a vector array: vector<int>container; Then I want to get the position of a given number in a vector array. vector<int>::iterator position; position = lower_bound(container.begin(), container.end(), temp); After that, I want to get the value at that position that was returned from lower_bound by container[position] But I get the error that No viable overloaded operator[] for type 'vector' When I change it into *(position+1), it works fine. So what is the different between those two?
Welcome to stackoverflow :) First of all, we should understand what an iterator is. According to the hackingcpp objects that point to a location may point to a readable memory address / object .. There are a lot of containers in C++ STL, such as vector, list, map and others. A iterator is an abstraction of pointer, which allows you to access elements stored in container, use algorithm(such as sort, find, lower_bound) provided by STL no matter what kind of container we have. Therefore, the return type of std::lower_bound is an iterator as you know vector<int>::iterator, You couldn't access an element by calling container[position], there is no such function vector[iterator] provided by vector. When I change it into *(position+1) *itreator means return the value of where an iterator points out. By the way, it's dangerous to do something like this *(position+1). Since perhaps the given value tmp is in vector, perhaps it's not, so you should check whether the given value tmp is in vector by calling iterator != vector.end().
71,963,029
71,970,071
Emscripten: Can't using emscripten::val in pthread
I'm working on project to attach video from c++. I have success create video element from c++. video = emscripten::val::global("document").call<emscripten::val>("createElement", emscripten::val("video")); video.set("src", emscripten::val("http://jplayer.org/video/webm/Big_Buck_Bunny_Trailer.webm")); video.set("crossOrigin", emscripten::val("Anonymous")); video.set("autoplay", emscripten::val(true)); video.call<void>("load"); But the problem came up is I have to wait until video buffer load enough to play. My solution is using pthread to create thread wait until video buffer load enough and do stuff with the video. pthread_create(&threadVideo, NULL, attachVideo, NULL); And inside attachVideo function void *attachVideo(void *arg) { pthread_detach(pthread_self()); cout << "ready to run" << endl; cout << "readyState: " << video["readyState"].as<int>() << endl; pthread_exit(NULL); } And when I run it cameout error: Cannot read properties of undefined (reading 'value')" Can someone help me with this ?
This is because emscripten::val is represents an object in JS and the JS state is all thread local. Another way of putting it: Each thread gets is own JS environment, so emscripten::val cannot be shared between threads.
71,963,142
71,965,951
The parameters of the Main function in C++
When I try to compile this code, an error appears : #include<iostream> using namespace std; int main() { char* p = "Hello"; return 0; } error C2440: 'initializing': cannot convert from 'const char [6]' to 'char *' This error is fixed when I add the word const in the declaration of p. This code compiles and runs: #include<iostream> using namespace std; int main() { const char* p = "Hello"; return 0; } So my question is : How is the main() function able to take char *argv[] (as a parameter) and not const char *argv[] (as a parameter)? int main (int argc, char *argv[])
Let's see what is happening in your example on case by case basis: Case 1 Here we consider the statement: char* p = "Hello"; On the right hand side of the above statement, we've the string literal "Hello" which is of type const char[6]. There are two ways to understand why the above statement didn't work. In some contexts, const char[6] decays to a const char* due to type decay. This basically means that on the right hand side we will have a const char* while on the left hand side we have a char*. Note also that this means that on the right hand side we've a low-level const but on the left hand side we don't have any low-level const. So, the given statement won't work. For the statement to work we've to make sure that the left hand side should've either same or greater low-level const qualifier than the right hand side. A few example would illustrate the point: int arr1[] = {1,2,3}; int* ptr1 = arr1; //this works because arr1 decays to int* and both sides have no low level const const int arr2[] = {1,2,3}; int* ptr2 = arr2; //won't work, right hand side will have a low level const(as arr2 decays to const char*) while the left hand side will not have a low level const const int* ptr3 = arr2; //this works, both side will have a low level const The second way(which is basically equivalent to the 1st) to understand this is that since "Hello" is of type const char[6], so if we are allowed to write char* p = "Hello"; then that would mean that we're allowed to change the elements of the array. But note that the type const char[6] means that the char elements inside the array are immutable(or non-changable). Thus, allowing char* p = "Hello"; would allow changing const marked data, which should not happen(since the data was not supposed to change as it was marked const). So to prevent this from happening we have to use const char* p = "Hello"; so that the pointer p is not allowed to change the const marked data. Case 2 Here we consider the declaration: int main (int argc, char *argv[]) In the above declaration, the type of the second parameter named argv is actually a char**. That is, argv is a pointer to a pointer to a char. This is because a char* [] decays to a char** due to type decay. For example, the below given declarations are equivalent: int main (int argc, char *argv[]); //first declaration int main (int argc, char **argv); //RE-DECLARATION. Equivalent to the above declaration In other words, argv is a pointer that points to the first element of an array with elements of type char*. Moreover, each elements argv[i] of the array(with elements of type char*) itself point to a character which is the start of a null terminated character string. That is, each element argv[i] points to the first element of an array with elements of type char(and not const char). Thus, there is no need for const char*. A diagram is given for illustration purposes:
71,963,214
71,966,692
C++ reordering Singly Linked List
Hi I'm trying to write a code for singly linked list that reorders the nodes so that: L1->L2->L3->...->Ln to L1->Ln->L2->Ln-1->L3->Ln-2... So I tried to do this by finding the node at the end of the list and setting that node as the next of current node and then finishing the loop by setting the current node as the next next of current node. #include <cstdlib> #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; ListNode* newNode(int x){ ListNode* temp = new ListNode; temp->val = x; temp->next = NULL; return temp; } void printlist(ListNode* head) { while (head != NULL) { cout << head->val << " "; if (head->next) cout << "-> "; head = head->next; } cout << endl; } void reorderList(ListNode* head){ ListNode *curr = head; ListNode *temp=head; ListNode *last=NULL; while(curr->next != NULL){ while(temp->next != NULL){ temp=temp->next; last=temp; } curr->next=last; last->next=curr->next->next; curr=curr->next->next; temp=curr->next; } } int main(int argc, char** argv) { ListNode* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); printlist(head); // Print original list reorderList(head); // Modify the list printlist(head); // Print modified list return 0; } So far, after displaying the original list, the program stops by saying that the run failed. I'm having some problem understanding the singly linked list and I don't know what I'm doing wrong.
I have modified your code to show a correct answer: #include <iostream> struct ListNode { int val; ListNode* next; ListNode(): val( 0 ), next( nullptr ) {} ListNode( int x ): val( x ), next( nullptr ) {} ListNode( int x, ListNode* next ): val( x ), next( next ) {} }; void printlist( ListNode* head ) { while( head != nullptr ) { std::cout << head->val << " "; if( head->next ) std::cout << "-> "; head = head->next; } std::cout << std::endl; } void reorderList( ListNode* head ) { ListNode* pf = head; ListNode* pt = nullptr; ListNode* tmp = nullptr; while( true ) { // find n-1 node tmp = pf; while( tmp && tmp->next && tmp->next->next ) tmp = tmp->next; // check to see n-1 node is not equal to the first node if( tmp == pf ) break; // reorder pt = tmp; tmp = pf->next; pf->next = pt->next; pt->next->next = tmp; pf = tmp; pt->next = nullptr; } } int main( int argc, char** argv ) { ListNode* head = new ListNode( 1 ); head->next = new ListNode( 2 ); head->next->next = new ListNode( 3 ); head->next->next->next = new ListNode( 4 ); head->next->next->next->next = new ListNode( 5 ); head->next->next->next->next->next = new ListNode( 6 ); printlist( head ); // Print original list reorderList( head ); // Modify the list printlist( head ); // Print modified list return 0; } and the result is like below: 1 -> 2 -> 3 -> 4 -> 5 -> 6 1 -> 6 -> 2 -> 5 -> 3 -> 4
71,963,600
71,997,121
Migrate a "zmq_send" command to Python
I have a c function that publish data to a c++ subscriber, now I want to migrate this c function to Python: void setup_msg_publish() { int r; zmqcontext = zmq_ctx_new(); datasocket = zmq_socket(zmqcontext, ZMQ_PUB); r = zmq_bind(datasocket, "tcp://*:44000"); if (r == -1) { printf(zmq_strerror(errno)); } } void publishdata(int x, int y) { if (datasocket == 0) { setup_msg_publish(); } zmq_data zd; zd.msgType = int 0; zd.x = x; zd.y = y; size_t len = sizeof(zd); int res = zmq_send(datasocket, &zd, len, NULL); assert(res == len); } I've tried to implement this in Python: import zmq import pickle from collections import namedtuple Data = namedtuple("Data", "msgType x y") def send_zmq(): data = Data("0", "1", "2") msg = pickle.dumps(data) context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:44000") socket.send(msg) For debug purposes I can recive the data with Python like this: import zmq import pickle context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://127.0.0.1:44000") while True: message = socket.recv() data = pickle.loads(message) print(data) But I don't receive anything in my c++ code (it just prints no data): #include "View.h" #include <iostream> #include <thread> #include <chrono> View::View() : viewSubscriber(zmqcontext, ZMQ_SUB) { unsigned _int16 msgType = 0; viewSubscriber.connect("tcp://127.0.0.1:44000"); //viewSubscriber.setsockopt(ZMQ_SUBSCRIBE, &msgType, sizeof(msgType)); viewSubscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0); std::cout << msgType; } void View::run() { using namespace std; bool received_view_data = false; bool checkForMore = true; zmq_view data; while (checkForMore) { zmq::message_t msg; //cout << &msg; if (viewSubscriber.recv(&msg, ZMQ_NOBLOCK)) { received_view_data = true; memcpy(&data, msg.data(), sizeof(data)); cout << &data.x; } else { std::this_thread::sleep_for(std::chrono::milliseconds(500)); cout << "no data \n"; } } } int main(){ View *app = new View(); app -> run(); return 0; } Any ideas what to fix so I receive the data in the namedTuple on the c++ side? Could it be that the c++ "needs to know more" about the type of each attribute of the namedTuple (if that is the case how do I specify whether the data is a double or int etc?)?
The solution was found after testing to go from C++ -> Python thank you J_H for the idea. Instead of using a namedtuple a packed struct was used. import zmq import struct def send_zmq(): struct_format = 'Idd' msg_type = 0 x = 1.0 y = 1.0 msg = struct.pack(struct_format, msg_type, x, y) context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:44000") socket.send(msg)
71,963,867
71,964,521
matplotlib-cpp connecting first and last point in the data set
I was able to link matplotlib-cpp to visual studio. When I set the data and plot it everything works fine except first point and last point gets connected. I know that the first point and last point is not the same. My code #include <iostream> #include <vector> #include <cstdio> #include "matplotlibcpp.h" namespace plt = matplotlibcpp; int main() { FILE *fp1; fp1 = fopen("data1.tmp", "r"); int num = 139; std::vector<double> xval(num + 1), yval(num + 1); i = 0; while (i < num) { fscanf(fp1, "%lf \t %lf\n", &xval[i], &yval[i]); i++; } fclose(fp1); plt::figure_size(1200, 780); plt::plot(xval,y1val,"r--"); plt::show(); } My list of data 0.000000 0.000000 0.005000 0.005000 0.010000 0.010000 0.015000 0.014999 0.020000 0.019999 0.025000 0.024997 0.030000 0.029996 0.035000 0.034993 0.040000 0.039989 0.045000 0.044985 0.050000 0.049979 0.055000 0.054972 0.060000 0.059964 0.065000 0.064954 0.070000 0.069943 0.075000 0.074930 0.080000 0.079915 0.085000 0.084898 0.090000 0.089879 0.095000 0.094857 0.100000 0.099833 0.105000 0.104807 0.110000 0.109778 0.115000 0.114747 0.120000 0.119712 0.125000 0.124675 0.130000 0.129634 0.135000 0.134590 0.140000 0.139543 0.145000 0.144492 0.150000 0.149438 0.155000 0.154380 0.160000 0.159318 0.165000 0.164252 0.170000 0.169182 0.175000 0.174108 0.180000 0.179030 0.185000 0.183947 0.190000 0.188859 0.195000 0.193767 0.200000 0.198669 0.205000 0.203567 0.210000 0.208460 0.215000 0.213347 0.220000 0.218230 0.225000 0.223106 0.230000 0.227978 0.235000 0.232843 0.240000 0.237703 0.245000 0.242556 0.250000 0.247404 0.255000 0.252245 0.260000 0.257081 0.265000 0.261909 0.270000 0.266731 0.275000 0.271547 0.280000 0.276356 0.285000 0.281157 0.290000 0.285952 0.295000 0.290740 0.300000 0.295520 0.305000 0.300293 0.310000 0.305059 0.315000 0.309816 0.320000 0.314567 0.325000 0.319309 0.330000 0.324043 0.335000 0.328769 0.340000 0.333487 0.345000 0.338197 0.350000 0.342898 0.355000 0.347590 0.360000 0.352274 0.365000 0.356949 0.370000 0.361615 0.375000 0.366273 0.380000 0.370920 0.385000 0.375559 0.390000 0.380188 0.395000 0.384808 0.400000 0.389418 0.405000 0.394019 0.410000 0.398609 0.415000 0.403190 0.420000 0.407760 0.425000 0.412321 0.430000 0.416871 0.435000 0.421410 0.440000 0.425939 0.445000 0.430458 0.450000 0.434966 0.455000 0.439462 0.460000 0.443948 0.465000 0.448423 0.470000 0.452886 0.475000 0.457338 0.480000 0.461779 0.485000 0.466208 0.490000 0.470626 0.495000 0.475032 0.500000 0.479426 0.505000 0.483807 0.510000 0.488177 0.515000 0.492535 0.520000 0.496880 0.525000 0.501213 0.530000 0.505533 0.535000 0.509841 0.540000 0.514136 0.545000 0.518418 0.550000 0.522687 0.555000 0.526943 0.560000 0.531186 0.565000 0.535416 0.570000 0.539632 0.575000 0.543835 0.580000 0.548024 0.585000 0.552199 0.590000 0.556361 0.595000 0.560509 0.600000 0.564642 0.605000 0.568762 0.610000 0.572867 0.615000 0.576959 0.620000 0.581035 0.625000 0.585097 0.630000 0.589145 0.635000 0.593178 0.640000 0.597195 0.645000 0.601198 0.650000 0.605186 0.655000 0.609159 0.660000 0.613117 0.665000 0.617059 0.670000 0.620986 0.675000 0.624897 0.680000 0.628793 0.685000 0.632673 0.690000 0.636537 0.695000 0.640385 0.700000 0.644218 and here is the result How do I remove that annoying line?
These two lines: int num = 139; std::vector<double> xval(num + 1), yval(num + 1); create vectors xval and yval of 140 double elements initialized to 0. You only load 139 points from your dataset and the first point in the dataset is (0,0); so your first (0-th) and last (139-th) points are indeed equal. You may try: int num = 139; std::vector<double> xval(num), yval(num);
71,964,315
71,964,358
Unexpected iterator behavior as a member variable
I'm having trouble with iterators: class Foo { private: std::istream_iterator<char> it_; public: Foo(std::string filepath) { std::ifstream file(filepath); it_ = std::istream_iterator<char>(file); } char Next() { char c = *it_; it_++; return c; } bool HasNext() { return it_ != std::istream_iterator<char>(); } }; int main() { Foo foo("../input.txt"); while (foo.HasNext()) { std::cout << foo.Next(); } std::cout << std::endl; return EXIT_SUCCESS; } The file input.txt is just Hello, world!. But when I run this, it only prints H. It seems to have something to do with storing the iterator as a member variable?
Here: Foo(std::string filepath) { std::ifstream file(filepath); it_ = std::istream_iterator<char>(file); } You store an iterator to file. Once this constructor returns files destructor is called and all iterators to the ifstream become invalid. It is similar to using a pointer to a no longer existing object. You need a ifstream to read from, the iterator just refers to contents that can be extracted from the file, but if the file is gone you cannot extract from it. Store the ifstream as member too. You can read the first character, because already on construction of the std::istream_iterator the first character is extracted from the file.
71,964,541
71,965,024
Mutex does not work as I expect. What is my mistake?
I was trying to figure out the data race theme, and I made this code. Here we work with the shared element wnd. I thought that by putting lock in the while loop, I would prohibit the th1 thread from working with wnd, but this did not happen and I see an unobstructed output of the th1 thread. #include <iostream> #include <thread> #include <mutex> #include <chrono> int main() { bool wnd = true; std::mutex mutex; std::unique_lock<std::mutex> lock(mutex, std::defer_lock); std::thread th1([&]() { int i = 0; while (true) { ++i; if (wnd) std::cout << i << " WND TRUE" << std::endl; else std::cout << i << " WND FALSE" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }); while (true) { lock.lock(); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); if (wnd) wnd = false; else wnd = true; lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } th1.join(); return 0; } To tell the truth, I was hoping to see that the th1 thread stops printing for 2+-seconds at a time when the main thread is inside the lock section.
You are not using the mutex and specially std::unique_lock properly. #include <iostream> #include <thread> #include <mutex> #include <chrono> int main() { bool wnd = true; std::mutex mutex; std::thread th1{[&]() { for (int i = 0; i<10000; ++i) { std::unique_lock<std::mutex> lock(mutex); std::cout << i << "\tWND\t " << std::boolalpha << wnd << std::endl; }; }}; for (int i = 0; i<30; ++i) { std::unique_lock<std::mutex> lock(mutex); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); wnd = !wnd; }; th1.join(); } std::unique_lock uses its constructor operand as a resource whose acquisition is lock and release is unlock. It is designed to use RAII as a means of guaranteeing correct lock/unlock sequences on mutexes. a defered lock only means the mutex is not locked at the begining of lifespan of the std::unique_lock and it is not the usual use case. You can manually lock/unlock the mutex, but that generally leads to less maintainable, more error-prone code. Keep in mind that if the threads involved are not racing over the ownership of the mutex, neither waits for the other; in your original prorgram, the worker thread did not touch the mutex. But in the program above, both threads are competing to lock the mutex; winner gets a chance to continue what he wants, and the loser has to wait until the mutex is unlocked - so that he can take its ownership.
71,965,085
71,966,177
Why does capturing stateless lambdas sometimes results in increased size?
Given a chain of lambdas where each one captures the previous one by value: auto l1 = [](int a, int b) { std::cout << a << ' ' << b << '\n'; }; auto l2 = [=](int a, int b) { std::cout << a << '-' << b << '\n'; l1(a, b); }; auto l3 = [=](int a, int b) { std::cout << a << '#' << b << '\n'; l2(a, b); }; auto l4 = [=](int a, int b) { std::cout << a << '%' << b << '\n'; l3(a, b); }; std::cout << sizeof(l4); We can observe, that the resulting sizeof of l4 is equal to 1. That makes sense to me. We are capturing lambdas by value and each of those objects has to have sizeof equal to 1, but since they are stateless, an optimization similar to [[no_unique_address]] one applies (especially since they all have unique types). However, when I try to create a generic builder for chaining comparators, this optimization no longer takes place: template <typename Comparator> auto comparing_by(Comparator&& comparator) { return comparator; } template <typename Comparator, typename... Comparators> auto comparing_by(Comparator&& comparator, Comparators&&... remaining_comparators) { return [=](auto left, auto right) { auto const less = comparator(left, right); auto const greater = comparator(right, left); if (!less && !greater) { return comparing_by(remaining_comparators...)(left, right); } return less; }; } struct triple { int x, y, z; }; auto main() -> int { auto by_x = [](triple left, triple right) { return left.x < right.x; }; auto by_y = [](triple left, triple right) { return left.y < right.y; }; auto by_z = [](triple left, triple right) { return left.z < right.z; }; auto comparator = comparing_by(by_x, by_z, by_y); std::cout << sizeof(comparator); } Note 1: I am aware of the fact that comparing_by is inefficient and sometimes calls the comparator in a redundant fashion. Why in the above case the resulting sizeof of comparator is equal to 3 and not to 1? It is still stateless, after all. Where am I wrong? Or is it just a missed optimization in all of the big three compilers? Note 2: This is purely an academic question. I am not trying to solve any particular problem.
What's happening in the first example is not what you think it is. Let's say l1 has type L1, l2 L2 , etc. These are the members of those types: struct L1 { // empty; }; sizeof(L1) == 1 struct L2 { L1 l1; }; sizeof(L2) == sizeof(L1) // 1 struct L3 { L2 l2; }; sizeof(L3) == sizeof(L2) // 1 struct L4 { L3 l3; }; sizeof(L4) == sizeof(L3) // 1 And in your next example, you capture all the lambdas by value, so the closure type has three non-overlapping members, so the size will be at least 3. [[no_unique_address]] can't be generically applied to the data members of a closure type (consider a empty class that puts its address in a global map). The compiler could use empty base optimisation for a "well behaved type" (a trivilly-copyable empty type maybe?), so this might be a missed optimisation. The standard says this about what can be done ([expr.prim.lambda.closure]p2): The closure type is not an aggregate type. An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing: the size and/or alignment of the closure type, whether the closure type is trivially copyable ([class.prop]), or whether the closure type is a standard-layout class ([class.prop]). So the change in size is OK, but it would have to be done so that is_empty_v<lambda_that_captures_stateless_lambda> is not true (since that's an observable behaviour) To "manually" apply this optimisation, you can, instead of calling the lambda comparator(left, right), default construct something of the type of the closure type and call that (decltype(comparator){}(left, right)). I've implemented that here: https://godbolt.org/z/73M1Gd3o5
71,965,838
71,966,231
no suitable user-defined conversion, but the convertion is specified
I am coding a vector class with iterators for a school exercice. I am getting the following error and I don't know how to go about it: 'no suitable user-defined conversion from "vectorIterator" to "vectorIterator<const int>" exists' This is the code I am trying to execute: vector<int> v; v.push_back(1); v.push_back(2); vector<int>::const_iterator it = v.begin(); This is part of the code in my class vector: template <typename T, typename Alloc = std::allocator<T> > class vector { .. public: typedef vectorIterator<value_type> iterator; typedef vectorIterator<const value_type> const_iterator; .. iterator begin() { return iterator(m_data); } // if commented the above code works const_iterator begin() const { return const_iterator(m_data); } .. } If I comment the first form of begin() the code compiles and runs ok, so it seems that it obscures the const form. I would expect the compiler to know to use the const form of begin(), but it does not. What am I missing? Thanks a lot
Since vectorIterator is a template class, which means that vectorIterator<int> and vectorIterator<const int> are two different types, they can not be converted to each other. You need to add a conversion constructor for vectorIterator<const int> that accepts vectorIterator<int>, using template should be enough (some constraints on U are omitted here for simplicity): template<typename T> struct vectorIterator { // ... template<typename U> vectorIterator(vectorIterator<U>); }; Demo
71,966,191
71,966,366
Is it valid to use const char*[] as the type of second parameter of main
I am learning C++ and learnt that the following given declarations are equivalent: int main (int argc, char *argv[]); //first declaration int main (int argc, char **argv); //RE-DECLARATION. Equivalent to the above declaration My question is that if i change the declaration to say: //note the added const int main (int argc,const char *argv[]); //IS THIS VALID? Is the above declaration where i have added a const valid? That is, does the C++ standard allow this modified declaration with the added const.
Adding const changes the type of the function. It is not declaration of the same function. Whether that is valid for main in particular, depends on language implementation: [basic.start.main] An implementation shall not predefine the main function. Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined. An implementation shall allow both a function of () returning int and a function of (int, pointer to pointer to char) returning int as the type of main ([dcl.fct]). It may in theory be valid in some implementation, but it will not be portable to all systems.
71,967,571
72,028,202
SDL driver fails when starting debug session on remote linux
On Win10, I have a visual studio c++ project for linux that uses the SDL2 driver. The target machine is a VirtualBox - Ubuntu 18.04. I configured Visual studio to compile remotely on the target system, which works fine. Running the output file from console on the remote machine shows that SDL uses the XServer: SDL_GetCurrentVideoDriver: x11 When I start debugging from visual studio (starts GNU debugger gdb on remote side): SDL_Init error: No available video device SDL_GetCurrentVideoDriver: null starting gdb from remote anyway works as expected: gdb ./myProgram (gdb) run But this doesn't let me debug in visual studio, which i'm looking forward to. Any idea ?
In Project Settings: Configuration Properties -> Debugging -> Pre-Launch Command -> export DISPLAY=:0
71,967,878
71,967,894
Slicing string character correctly in C++
I'd like to count number 1 in my input, for example,111 (1+1+1) must return 3and 101must return 2 (1+1) To achieve this,I developed sample code as follows. #include <iostream> using namespace std; int main(){ string S; cout<<"input number"; cin>>S; cout<<"S[0]:"<<S[0]<<endl; cout<<"S[1]:"<<S[1]<<endl; cout<<"S[2]:"<<S[2]<<endl; int T = (int) (S[0]+S[1]+S[2]); cout<<"T:"<<T<<endl; return 0; } But when I execute this code I input 111 for example and my expected return is 3 but it returned 147. [ec2-user@ip-10-0-1-187 atcoder]$ ./a.out input number 111 S[0]:1 S[1]:1 S[2]:1 T:147 What is the wrong point of that ? I am totally novice, so that if someone has opinion,please let me know. Thanks
It's because S[0] is a char. You are adding the character values of these digits, rather than the numerical value. In ASCII, numerical digits start at value 48. In other words, each of your 3 values are exactly 48 too big. So instead of doing 1+1+1, you're doing 49+49+49. The simplest way to convert from character value to digit is to subtract 48, which is the value of 0. e.g, S[0] - '0'.
71,967,949
71,969,771
How can we change behaviour of c++ method depending on initialization parameter?
In python I can write something like class C: def __init__(self, mode): if mode == 0: self.f = self.f0 elif mode == 1: self.f = self.f2 (...) else: raise KeyError def f0(self, a1, a2): <do stuff> def f1(self, a1, a2): <do other stuff> (...) As an alternative to writing a parent class with subclasses C1, C2, ... that overwrite f. The short question is: Can i do something similar in C++ without summoning Cthulhu? Before anyone asks "why": This is useful, for example if I have another class D, that uses C, because it allows the parameter mode to simply be passed on to C rather than writing separate cases everywhere an instance of C is initialised. I want to avoid a switch or if-tree that is evaluated every time f is called, because f is a small function that is called very many times in an already expensive calculation.
Thanks to @AlanBirtles and @Yksisarvinen ! The working solution I ended up with was stuff.h: class C{ C(int mode); const int mode; double f(int i, int j, int k); using FunctionType = double(C::*)(int, int, int); double f0(int i, int j, int k); double f1(int i, int j, int k); FunctionType f_p; }; stuff.cpp: C::C(int mode) : mode{mode} { switch (mode){ case 0: f_p = &C::f0; break; case 1: f_p = &C::f1; break; default: throw "Non-valid mode!"; } } double C::f(int i, int j, int k) {std::invoke(f_p, this, i, j, k);} double C::f0(int i, int j, int k){ <do stuff> } double C::f1(int i, int j, int k){ <do other stuff>} As suggested by @mch, using a template class would probably have been just as simple. However (not specified in the question) I needed this to work with a python-wrapper using pybind11, so the above solution allowed me to avoid any trouble related to wrapping a template class.
71,968,902
71,968,958
Forwarding reference and argument deduction
I'm trying to understand perfect forwarding a bit deeply and faced a question I can't figure out myself. Suppose this code: void fun(int& i) { std::cout << "int&" << std::endl; } void fun(int&& i) { std::cout << "int&&" << std::endl; } template <typename T> void wrapper(T&& i) { fun(i); } int main() { wrapper(4); } It prints int&. To fix this one should use std::forward. That's clear. What is unclear is why it is so. What the code above unwraps into is: void fun(int & i) { std::operator<<(std::cout, "int&").operator<<(std::endl); } void fun(int && i) { std::operator<<(std::cout, "int&&").operator<<(std::endl); } template <typename T> void wrapper(T&& i) { fun(i); } /* First instantiated from: insights.cpp:21 */ #ifdef INSIGHTS_USE_TEMPLATE template<> void wrapper<int>(int && i) { fun(i); } #endif int main() { wrapper(4); return 0; } So i should have rvalue type of int&&. The question is: why do I need std::forward here since compiler already knows that i is int&& not int& but still calls fun(it&)?
Types and value categories are different things. Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category. i, the name of the variable, is an lvalue expression, even the variable's type is rvalue-reference. The following expressions are lvalue expressions: the name of a variable, ... Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression; ... That's why we should use std::forward to preserve the original value category of a forwarding reference argument.
71,968,955
71,969,908
Publisher/Subscriber on the same node C++ ROS
I aim to create a Subscriber and a Publisher in the same node! I want to access a part of the message available on a topic of a rosbag. The message of the thread is as follows: Type: radar_msgs/RadarDetectionArray std_msgs/Header header uint32 seq time stamp string frame_id radar_msgs/RadarDetection[] detections uint16 detection_id geometry_msgs/Point position float64 x float64 y float64 z geometry_msgs/Vector3 velocity float64 x float64 y float64 z float64 amplitude I am looking to access position "x" only, and publish it afterward. #include "ros/ros.h" #include "std_msgs/String.h" #include "radar_msgs/RadarDetection.h" #include "radar_msgs/RadarDetectionArray.h" #include "geometry_msgs/Point.h" //radar_msgs::RadarDetectionArray pub_data; double pub_data; void srr2Callback(const radar_msgs::RadarDetection msg) { pub_data = msg.position.x; } int main(int argc, char **argv) { ros::init(argc, argv, "talker"); ros::NodeHandle n; ros::Publisher chatter_pub = n.advertise<radar_msgs::RadarDetection>("srr2_detections", 1000); ros::Subscriber sub = n.subscribe("/rear_srr/rear_right_srr/as_tx/detections", 1000, srr2Callback); ros::Rate loop_rate(10); int count = 0; while (ros::ok()) { chatter_pub.publish(pub_data); ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; } I also share the error I got! error: request for member ‘__getMD5Sum’ in ‘m’, which is of non-class type ‘const double’ return m.__getMD5Sum().c_str(); error: request for member ‘__getDataType’ in ‘m’, which is of non-class type ‘const double’ return m.__getDataType().c_str();
Here: chatter_pub.publish(pub_data); You are publishing a double in a topic that expect radar_msgs::RadarDetection. The error is telling you that it cannot call __getMD5Sum on a double, which is obviously accurate. If you intend to publish a double you MUST create a publisher specific for that type: ros::Publisher chatter_pub = n.advertise<std_msgs::Float64>("srr2_detections", 1000); But even with this change you should not publish the double directly, you must do something like this: std_msgs::Float64 msg; msg.data = pub_data; chatter_pub.publish(msg); You can also do that with radar_msgs::RadarDetection if you do not want to change the publisher's type: radar_msgs::RadarDetection msg; msg.x = pub_data; chatter_pub.publish(msg);
71,969,019
71,970,139
OMP parallel for is not dividing iterations
I am trying to do distributed search using omp.h. I am creating 4 threads. Thread with id 0 does not perform the search instead it overseas which thread has found the number in array. Below is my code: int arr[15]; //This array is randomly populated int process=0,i=0,size=15; bool found=false; #pragma omp parallel num_threads(4) { int thread_id = omp_get_thread_num(); #pragma omp cancellation point parallel if(thread_id==0){ while(found==false){ continue; } if(found==true){ cout<<"Number found by thread: "<<process<<endl; #pragma omp cancel parallel } } else{ #pragma omp parallel for schedule(static,5) for(i=0;i<size;i++){ if(arr[i]==number){ //number is a int variable and its value is taken from user found = true; process = thread_id; } cout<<i<<endl; } } } The problem i am having is that each thread is executing for loop from i=0 till i=14. According to my understanding omp divides the iteration of the loops but this is not happening here. Can anyone tell me why and its possible solution?
Your problem is that you have a parallel inside a parallel. That means that each thread from the first parallel region makes a new team. That is called nested parallelism and it is allowed, but by default it's turned off. So each thread creates a team of 1 thread, which then executes its part of the for loop, which is the whole loop. So your omp parallel for should be omp for. But now there is another problem: your loop is going to be distributed over all threads, except that thread zero never gets to the loop. So you get deadlock. .... and the actual solution to your problem is a lot more complicated. It involves creating two tasks, one that spins on the shared variable, and one that does the parallel search. #pragma omp parallel { # pragma omp single { int p = omp_get_num_threads(); int found = 0; # pragma omp taskgroup { /* * Task 1 listens to the shared variable */ # pragma omp task shared(found) { while (!found) { if (omp_get_thread_num()<0) printf("spin\n"); continue; } printf("found!\n"); # pragma omp cancel taskgroup } // end 1st task /* * Task 2 does something in parallel, * sets `found' to true if found */ # pragma omp task shared(found) { # pragma omp parallel num_threads(p-1) # pragma omp for for (int i=0; i<p; i++) // silly test if (omp_get_thread_num()==2) { printf("two!\n"); found = 1; } } // end 2nd task } // end taskgroup } } (Do you note the printf that is never executed? I needed that to prevent the compiler from "optimizing away" the empty while loop.) Bonus solution: #pragma omp parallel num_threads(4) { if(omp_get_thread_num()==0){ spin_on_found; } if(omp_get_thread_num()!=0){ #pragma omp for nowait schedule(dynamic) for ( loop ) stuff The combination of dynamic and nowait can somehow deal with the missing thread.
71,969,045
71,969,117
passing 2 arrays of different sizes using templates in C++
I have the following code template <size_t size_x, size_t size_y> void product(int (&arr)[size_x][size_y],int (&arr1)[size_x][size_y]) { for (int i=0;i<size_x;i++) for (int j=0;j<size_y;j++) { cout << "The size of a1[][] is" << arr[i][j] << endl; } for (int i=0;i<size_x;i++) for (int j=0;j<size_y;j++) { cout << "The size of a1[][] is" << arr1[i][j] << endl; } } int main() { int A[2][2] = { { 1, 2 }, { 3, 4 }}; int B[2][2] = { { 0, 5}, { 6, 7 } }; product(A,B); return 0; } I am trying to pass arrays to a function. However this program works fine if the arrays are of equal dimension. I want to pass arrays with different dimensions. How can I pass an array of 22 and 32 array to a function?
How can I pass an array of 22 and 32 array to a function? This can be done simply by providing extra template parameters template <size_t size_x1, size_t size_y1, size_t size_x2, size_t size_y2> void product(int (&arr)[size_x1][size_y1],int (&arr1)[size_x2][size_y2]); Demo
71,969,281
71,972,102
__declspec(dllexport) and __declspec(dllimport) in C++
I often see __declspec(dllexport) / __declspec(dllimport) instructions on Windows, and __attribute__((visibility("default"))) on Linux with functions, but I don't know why. Could you explain to me, why do I need to use theses instructions for shared libraries?
The Windows-exclusive __declspec(dllexport) is used when you need to call a function from a Dll (by exporting it) , that can be accessed from an application. Example This is a dll called "fun.dll" : // Dll.h : #include <windows.h> extern "C" { __declspec(dllexport) int fun(int a); // Function "fun" is the function that will be exported } // Dll.cpp : #include "Dll.h" int fun(int a){ return a + 1; } You can now access the "fun" from "fun.dll" from any application : #include <windows.h> typedef int (fun)(int a); // Defining function pointer type int call_fun(int a){ int result = 0; HMODULE fundll = LoadLibrary("fun.dll"); // Calling into the dll if(fundll){ fun* call_fun = (fun*) GetProcAddress(fundll, "fun"); // Getting exported function if(call_fun){ result = call_fun(a); // Calling the exported fun with function pointer } } return result; }
71,969,411
71,999,093
Python bytestream to image
I'm trying to achieve the same thing as this question, but with color image : How to I transfer an image(opencv Matrix/numpy array) from c++ publisher to python sender via ZeroMQ? Here is my input image This is what my code display C++ side : cv::Mat frame = cv::imread("/home/victor/Images/Zoom.png"); int height = frame.rows; //480 int width = frame.cols; // 640 zmq_send(static_cast<void *>(pubSocket), frame.data, (height*width*3*sizeof(uint8_t)), ZMQ_NOBLOCK); Python side : try: image_bytes = self._subsocketVideo.recv(flags=zmq.NOBLOCK) width = 480 height = 640 try: temp = numpy.frombuffer(image_bytes, dtype=numpy.uint8) self.currentFrame = temp.reshape(height, width, 3) except Exception as e : print("Failed to create frame :") print(e) except zmq.Again as e: raise e Python code displaying the image : this part works, I tried with static images instead of what I got on network def videoCB(self): try: self._socket.subVideoReceive() print("Creating QImg") qimg = QImage(self._socket.currentFrame.data, 480, 640, 3*480, QImage.Format_RGB888) print("Creating pixmap") pixmap = QtGui.QPixmap.fromImage(qimg) print("Setting pixmap") self.imageHolder.setPixmap(pixmap) self.imageHolder.show() except Exception as e: print(e) pass I feel like I have 2 or 3 issues : Why is my output image wider than high? I tried to inverse height and width in reshape, without any result There seems to be a RGB mixup somewhere Overall, I feel like data is there but I don't put it correctly together. The reshape function looks like it does nothing, I have the same output without it. Thoughts?
Managed to make it work : changed python side into image2 = Image.frombytes('RGB', (height,width), image_bytes) self.currentFrame = ImageQt(image2) and displaying with qimg = QImage(self._socket.currentFrame) pixmap = QtGui.QPixmap.fromImage(qimg) self.imageHolder.setPixmap(pixmap) self.imageHolder.show()
71,969,416
72,039,026
C++ member variables are not initialized when using a debug version static library
Environment: Windows10, cpp17, visual studio 2019, debug version static library Recently I tried to use Cesium-Native to read 3DTiles files in my project, but there was a confusing problem that some member variables are not initialized correctly. As following codes show, Tileset() use initializer list to initialize its member variables, but some of them like_loadsInProgress,_previousFrameNumber are initialized to random value which shoule have been 0. However some of them are initialize correctly like _url, _options, and it works well in Release Library and the same code in its original project. What a strange bug! Tileset::Tileset( const TilesetExternals& externals, const std::string& url, const TilesetOptions& options) : _externals(externals), _asyncSystem(externals.asyncSystem), _userCredit( (options.credit && externals.pCreditSystem) ? std::optional<Credit>(externals.pCreditSystem->createCredit( options.credit.value(), options.showCreditsOnScreen)) : std::nullopt), _url(url), _isRefreshingIonToken(false), _options(options), _pRootTile(), _previousFrameNumber(0), _loadsInProgress(0), _subtreeLoadsInProgress(0), _overlays(*this), _tileDataBytes(0), _supportsRasterOverlays(false), _gltfUpAxis(CesiumGeometry::Axis::Y), _distancesStack(), _nextDistancesVector(0) { if (!url.empty()) { CESIUM_TRACE_USE_TRACK_SET(this->_loadingSlots); this->notifyTileStartLoading(nullptr); LoadTilesetDotJson::start(*this, url).thenInMainThread([this]() { this->notifyTileDoneLoading(nullptr); }); } } Through debugging, I found that _loadsInProgress was 0 at first, and it changes when a vector construct function is called. Maybe it's because generation of debug static lib? Any suggestions will be appreciated!
The problem solved by carefully checking all setting in running correctly original project and my project. And try to clean Visual Studio Cache and rebuild project and lib may be helpful for the problem. At first I used the different library version for inlucde and lib files, then I found that, I change the same version library include files to my project. But due to VS cache and the same file name(I guess), the change failed to apply to my project actually.
71,969,651
71,970,331
Why does a defaulted default constructor depend on whether it is declared inside or outside of class?
In the following example, struct A does not have default constructor. So both struct B and struct C inherited from it cannot get compiler-generated default constructor: struct A { A(int) {} }; struct B : A { B() = default; //#1 }; struct C : A { C(); }; C::C() = default; //#2 #1. In struct B, defaulted default constructor is declared inside the class, and all compilers accept it, with only Clang showing a warning saying that explicitly defaulted default constructor is implicitly deleted [-Wdefaulted-function-deleted] #2. But defaulted default constructor declared outside of struct C generates a compiler error. Demo: https://gcc.godbolt.org/z/3EGc4rTqE Why does it matter where the constructor is defaulted: inside or outside the class?
Note that if you actually try and instantiate B then you'll also get the error that B::B() is deleted: https://gcc.godbolt.org/z/jdKzv7zvd The reason for the difference is probably that when you declare the C constructor, the users of C (assuming the definition is in another translation unit) have no way of knowing that the constructor is in fact deleted. At best this would lead to some confusing linker error, at worst it'd just crash at runtime. In the case of B all users of B will immediately be able to tell that the default constructor is deleted so it does no harm (even if it makes no sense as warned by clang) to declare it as defaulted.
71,969,830
71,970,563
arrange line in txt file in ASCII order using array and display them
#include <stdio.h> #include <string.h> #include <fstream> #include <iostream> using namespace std; int main() { ifstream infile; // ifstream is reading file infile.open("read.txt"); // read.txt is the file we need to read std::cout << infile; string str; if (infile.is_open()) { while (getline(infile, str)) { char str[2000], ch; int i, j, len; len = strlen(str); for (i = 0; i < len; i++) { for (j = 0; j < (len - 1); j++) { if (str[j] > str[j + 1]) { ch = str[j]; str[j] = str[j + 1]; str[j + 1] = ch; } } } } cout << "\nProcessed data:" << str; } return 0; } My txt file: Today is a fine day. It’s sunny. Let us go out now! My result should be: .Taaaddefiinosyy ’.Innsstuy !Legnooosttuuw Spaces is consider here as well. I'm new to C++. I need some pros help. Thank you very much!
Your code does not work, because: The line std::cout << infile; is wrong. If you want to print the result of istream::operator bool() in order to determine whether the file was successfully opened, then you should write std::cout << infile.operator bool(); or std::cout << static_cast<bool>(infile); instead. However, it would probably be better to simply write std::cout << infile.fail(); or std::cout << !infile.fail();. The function std::strlen requires as a parameter a pointer to a valid string. Maybe you intended to write str.length()? In that case, you should delete the declaration char str[2000], because it shadows the declaration string str;. You should print the sorted result immediately after sorting it, before it gets overwritten by the next line. Currently you are only printing the content str a single time at the end of your program, so you are only printing the last line. After performing the fixes mentioned above, your code should look like this: #include <stdio.h> #include <string.h> #include <fstream> #include <iostream> using namespace std; int main() { ifstream infile; // ifstream is reading file infile.open("read.txt"); // read.txt is the file we need to read std::cout << infile.fail(); string str; if (infile.is_open()) { while (getline(infile, str)) { char ch; int i, j, len; len = str.length(); for (i = 0; i < len; i++) { for (j = 0; j < (len - 1); j++) { if (str[j] > str[j + 1]) { ch = str[j]; str[j] = str[j + 1]; str[j + 1] = ch; } } } cout << "\nProcessed data:" << str; } } return 0; } For the input Today is a fine day. It's sunny. Let us go out now! this program has the following output: 0 Processed data: .Taaaddefiinosyy Processed data: '.Innsstuy Processed data: !Legnooosttuuw Note that the input posted in your question contains a forward tick ’ instead of an apostrophe '. This could cause trouble. For example, when I tested your program, this forward tick was encoded into a multi-byte UTF-8 character, because it is not representable in 7-bit US-ASCII. This caused your sorting algorithm to fail, because it only supports single-byte characters. I was only able to fix this bug by replacing the forward tick with an apostrophe in the input.
71,970,051
71,970,369
Why is std::variant required to become valueless_by_exception in move assignment?
I have seen the following notes on cppreference regarding to the valueless_by_exception method: A variant may become valueless in the following situations: (guaranteed) an exception is thrown during the move initialization of the contained value during move assignment (optionally) an exception is thrown during the copy initialization of the contained value during copy assignment So, the code like this std::variant<MyClass> var = {...}; var = myClassObj; is not required to make var.valueless_by_exception() equal to true (and, presumably, would leave var in its previous state), but this code std::variant<MyClass> var = {...}; var = std::move(myClassObj); is guaranteed to make var.valueless_by_exception() equal to true if an exception happens. What is the actual reason for such a difference in specifications between copy and move assignment?
Note that Cppreference is talking about a different situation. When it says copy/move assignment, it's talking about copy/move assignment from a variant, not from a T. Assignment from T is dealt with in the next statement: (optionally) an exception is thrown when initializing the contained value during a type-changing assignment The reason failed move assignment from a variant will always leave the target variant valueless is that there's no other option. The issue at hand here is something specific to assignment. When you are assigning one variant to the other, there are two possibilities. Either the two variants hold the same Ti type, or they don't. If they share the same Ti, then a copy/move assignment between their stored types can happen directly. When that happens, variant provides the exception guarantee of the assignment operation for the Ti being used. At no point does the variant itself become valueless; it always holds a live Ti which is in whatever state the failed copy/move assignment operator left it in. However, if the two variants differ on Ti, then the destination variant must destroy its current object and create a new object of the source type Ti via copy/move construction (not assignment). If variant were to provide a strong exception guarantee, that would mean that if this copy/move construction fails, then the variant should still hold the object type and value it had before the assignment operator. But you'll notice that this object was destroyed before the creation of the new object. This is because variant stores a union of all of its Ts, and thus they all share memory. You can't attempt to create a Ti in the variant without first destroying whatever was there. And once its destroyed, it's gone and cannot be recovered. So now we have a variant that doesn't hold the original type, and we failed to create a Ti within it. So... what does it hold? Nothing. The reason why going valueless from a copy is optional is that, if a type throws on copy construction but not on move construction (as many throwing-copy types provide), it is possible to implement the copy operation with a two object solution. You do the copy-initialization to a stack temporary before destroying the internal variant object. If that succeeds, you can destroy the internal object and move-construct from your stack object. The committee didn't want to require this implementation, but it didn't want to forbid it either.
71,970,390
71,970,724
Are there difference between fn(); and fn<T>(); in template class member function of C++
template <class T> class Stack { public: Stack(); }; template <class T> class Stack { public: Stack<T>(); } By the way, what's the meaning of <T>?
From injected-class name in class template's documentation: Otherwise, it is treated as a type-name, and is equivalent to the template-name followed by the template-parameters of the class template enclosed in <>. This means that both the given snippets in your example are equivalent(Source). In the 1st snippet, the declaration Stack(); for the default ctor is actually the same as writing: Stack<T>(); //this is the same as writing `Stack();` what's the meaning of ? Stack<T> denotes an instantiated class-type for some given T. For example, when T=int then Stack<int> is a separate instantiated class-type. Similarly, when say T=double then Stack<double> is another distinct instantiated class-type. When instantiating a template(class or function) we generally(not always as sometimes it can be deduced) have to provide additional information like type information for template type parameters etc. And the way to provide this additional information is by giving/putting it in between the angle brackets. For example, template <class T> class Stack { public: Stack(); //this is the same as Stack<T>(); due to injected class name in class template }; template<typename T> Stack<T>::Stack() { } int main() { Stack<int> obj; //here we've provided the additional information "int" in between the angle brackets } The above code will generate a class type Stack<int> that will look something like: template<> class Stack<int> { public: Stack<int>() { } };
71,970,435
71,970,740
How do I use the __cpp_lib_* feature test macros?
I wanted to use the feature test macros to check if std::filesystem was available, but __cpp_lib_filesystem isn't defined even when I know std::filesystem is present. For example, the following test program: #include <iostream> int main () { std::cout << "__cpp_lib_filesystem: " #ifdef __cpp_lib_filesystem << __cpp_lib_filesystem #else << "not defined" #endif << std::endl; std::cout << "__has_include(filesystem): " #ifndef __has_include << "don't have __has_include" #elif __has_include(<filesystem>) << "yes" #else << "no" #endif << std::endl; } // also, this compiles: #include <filesystem> std::filesystem::path test; Outputs this with gcc 8.1 (my actual target compiler) and gcc 11.2, with --std=c++17: __cpp_lib_filesystem: not defined __has_include(filesystem): yes Here it is on Compiler Explorer. I also tried including <version>, but, with GCC 8.1, it's not present: <source>:2:10: fatal error: version: No such file or directory #include <version> ^~~~~~~~~ compilation terminated. Additionally, the note here says: Library feature-test macros - defined in the header <version> (C++20) Which, unless I'm misinterpreting, means the library feature test macros aren't in <version> until C++20, which doesn't apply to C++17 (although I'm not really clear if it means the header is the C++20 feature, or if the macros are the C++20 feature). Now, in this particular case, I know I can test for it by doing: #if defined(__has_include) && __has_include(<filesystem>) // ... #else // ... #endif That'll work here because filesystem was officially added in C++17 and __has_include has been around since C++17 (or maybe earlier, I dunno) as well -- i.e. there shouldn't be a situation where __has_include isn't available but std::filesystem is. So that's fine. However, my question is about __cpp_lib_filesystem: Why isn't it defined in the above test? What did I miss / how do I use it?
There are two ways to use the __cpp_lib_XXX macros: Actually include the corresponding header: https://godbolt.org/z/xo68acnrz And the given library also need to support such feature with the given C++ version e.g., __cpp_lib_constexpr_vector will not be defined under C++17 even if <vector> was included. Uses C++20, and include the <version> header.
71,970,568
71,970,721
Why can't ranges be used if in a function?
I'm trying to get a range like python like below: #include <iostream> #include <ranges> auto Range(double start, double end, double step) { if (start <= end) { auto step_fun = [=](auto x) { return x * step + start; }; auto end_pred = [=](auto x) { return x <= end; }; auto range = std::views::iota(0) | std::views::transform(step_fun) | std::views::take_while(end_pred); return range; } else { auto step_fun = [=](auto x) { return -x * step + start; }; auto end_pred = [=](auto x) { return x >= end; }; auto range = std::views::iota(0) | std::views::transform(step_fun) | std::views::take_while(end_pred); return range; } } int main() { auto range = Range(108, 100, 1); for (auto i : range) std::cout << i << ' '; return 0; } But the Visual Studio told me: Error C3487 'std::ranges::take_while_view<std::ranges::transform_view<std::ranges::iota_view<_Ty,std::unreachable_sentinel_t>,Range::<lambda_3>>,Range::<lambda_4>>': all return expressions must deduce to the same type: previously it was 'std::ranges::take_while_view<std::ranges::transform_view<std::ranges::iota_view<_Ty,std::unreachable_sentinel_t>,Range::<lambda_1>>,Range::<lambda_2>>' and Message No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called test But only start>endorstart<end,it can work,like: auto Range(double start, double end, double step) { auto step_fun = [=](auto x) { return x * step + start; }; auto end_pred = [=](auto x) { return x <= end; }; auto range = std::views::iota(0) | std::views::transform(step_fun) | std::views::take_while(end_pred); return range; } How can I fix it?
A function must have one return type, auto doesn't change that. Your two returns have different, incompatible types, because each lambda expression has a unique type. The error message rather buried it: blah blah Range::<lambda_3>,Range::<lambda_4> vs blah blah Range::<lambda_1>,Range::<lambda_2> You can do some arithmetic to reduce it to one return auto Range(double start, double end, double step) { if (start > end) { step *= -1; } int count = (end - start) / step; auto step_fun = [=](auto x) { return x * step + start; }; return std::views::iota(0, count) | std::views::transform(step_fun); } Caveat: this function is still problematic if step is negative, you might instead want to throw if end is not reachable from start.
71,970,806
71,970,807
Is there an equivalent of torch.distributions.Normal in LibTorch, the C++ API for PyTorch?
I am implementing a policy gradient algorithm with stochastic policies and since "ancillary" non-PyTorch operations are slow in Python, I want to implement the algorithm in C++. Is there a way to implement a normal distribution in the PyTorch C++ API?
The Python implementation actually calls the C++ back-end in the at:: namespace (CPU, CUDA, where I found this). Until the PyTorch team and/or contributors implement a front-end in LibTorch, you can work around it with something like this (I only implemented rsample() and log_prob() because it's what I need for this use case): constexpr double lz = log(sqrt(2 * M_PI)); class Normal { torch::Tensor mean, stddev, var, log_std; public: Normal(const torch::Tensor &mean, const torch::Tensor &std) : mean(mean), stddev(std), var(std * std), log_std(std.log()) {} torch::Tensor rsample() { auto device = torch::cuda::is_available() ? torch::kCUDA : torch::kCPU; auto eps = torch::randn(1).to(device); return this->mean + eps * this->stddev; } torch::Tensor log_prob(const torch::Tensor &value) { // log [exp(-(x-mu)^2/(2 sigma^2)) / (sqrt(2 pi) * sigma)] = // = log [exp(-(x-mu)^2/(2 sigma^2))] - log [sqrt(2 pi) * sigma] = // = -(x - mu)^2 / (2 sigma^2) - log(sigma) - log(sqrt(2 pi)) return -(value - this->mean)*(value - this->mean) / (2 * this->var) - this->log_std - lz; } };
71,971,092
71,971,236
Infer type of non-type template argument
I'm not great at template metaprogramming, so apologies if this is a dumb question. I have a type like template<int n> struct S { typedef decltype(n) type_of_n; // ... }; and I'd like to write functions that look something like template< typename T, typename T::type_of_n n, typename = std::enable_if_t<std::is_same<T, S<n>>::value>> void f(const T &) { /* ... */ } with the idea being that if the type of the non-type template argument to S changes at some point in the future (say to std::size_t or int64_t or something) then calling code will just continue working. But I'm not sure how to get the compiler to infer both T and n in tandem here. The only things I've come up with are basically hacks: Do something like typedef int type_of_S_n outside of S. Write something like S<0>::type_of_n instead of actually inferring the type Is what I'm trying to do possible? If not, is there a "cleaner" way to do it than the hacks above?
If you are looking to only accepts S and want to also deduce the value of n, then you can since c++17 use auto to deduce the type of a non-type template parameter. template<auto n> void f(const S<n> &) { /* ... */ } You can also make it more generic and accept any type with a single non-type parameter by using a template template parameter. template<template <auto> typename T, auto n> void f(const T<n> &) { /* ... */ }
71,971,104
71,971,792
How can I install the filesystem C++ library with minGW?
For a new project i need use filesystem library but when I try to include it, my compilation fail cause it can't find the library. I'm compiling on Windows with gcc installed via minGW and his version should be 6.3. I know for sure that from gcc 8+ this library should be included in the standard one. I' ve also tried to find it in experimental but it can't do it. Is there any way to solve this problem? Like installing a newer version of gcc or including this library in any other way? Sorry but I'm not used to this type of thing.
The C++ filesystem library was introduced in C++17, but your compiler might be configured to use an earlier version of the language by default. Try using the -std=c++17 option.
71,971,138
71,971,302
Call derived class appropriately
I have a class order and two derived classes: single_order and repeated_order. struct order{ string desc; }; struct single_order : public order{ datetime dt; }; struct repeated_order : public order{ datetime dt1; datetime dt2; }; I have a list<order*> ll that can contain single_order and repeated_order and two methods: bool is_expired(single_order &el){ if(today>el.dt){ //do something } } bool is_expired(repeated_order &el){ if(today>el.dt1){ //do something } if(today>el.dt2){ //do something else } } I would like to iterate over ll and call the most appropriate method in each case. (the parameter of the two functions may also be other than a reference) How to do that?
You knew to tag polymorphism, but you seem to be struggling with the concept. Here's some code: #include <iostream> #include <memory> #include <vector> class Base { public: Base() = default; virtual ~Base() = default; virtual void do_foo() = 0; }; class Bar : public Base { public: Bar() = default; void do_foo() override { std::cout << "From Bar\n"; } }; class Baz : public Base { public: Baz() = default; void do_foo() override { std::cout << "From BAZ\n"; } }; int main() { std::vector<std::unique_ptr<Base>> v; v.emplace_back(new Bar()); v.emplace_back(new Baz()); for (const auto& i : v) { i->do_foo(); } } You can see that in Base, there is a pure virtual function, virtual do_foo() = 0; This means a couple things. Base is a pure virtual class and you cannot declare Base objects, only pointers or references to Base. In order to have a concrete class, or one that you can create objects of, you need to override those pure virtual functions. You have a function that you want to be able to call on both derived types. This is a perfect example of how polymorphism can make your life easier. You can see that each derived class overrides the pure virtual function and does its own thing, and I am then able to store both derived types in the vector in my main() function, and call the appropriate function on each object. Output: ❯ ./a.out From Bar From BAZ
71,971,345
71,972,541
SQLite: Reading a blob from a table that has no rowid
I'm using the C SQLite library. I need to obtain the value of a blob from a row. The row is in a table that does not have any row id. This causes sqlite3_blob_open to return an error - that rowid is not present in the table. Software like DB Browser for SQLite is able to query the value of these blobs, so there must be a way to do it.
The answer is to use sqlite3_step() in conjunction with sqlite3_column_blob()
71,971,528
71,971,921
Pass a pointer to a file buffer to a class, expecting to read from file inside a class
I want to learn how to search in the file by passing the pointer of the stream to a class. I can successfully get the first character from the file using std::fstream and std::filebuf* char symbol; std::fstream by_fstream; by_fstream.open("First_test_input.txt"); std::filebuf* input_buffer = by_fstream.rdbuf(); symbol = input_buffer -> sbumpc(); std::cout << "\nSymbol that get from a file by rdbuf(): " << symbol; Output: Symbol that get from a file by rdbuf(): M But I'm not sure how can I send any pointer to my original stream of the file from main to a class. Ideally, it would be great to do something like this: #include <iostream> #include <fstream> class from_file { public: char c; from_file () { std::cout << "\nCharacter that get from file by to class variable" <<" then printed: " << c; }; from_file (char *pointer){ c = pointer -> sbumpc(); }; ~from_file (); }; int main(){ std::fstream by_fstream; by_fstream.open("First_test_input.txt"); std::filebuf* input_buffer = by_fstream.rdbuf(); from_file send(&input_buffer); from_file show; return 0; } Looking for advice on where I can find documentation about similar headers to do a such task.
You are going about this all wrong. First off, you should pass around (a reference to) the stream itself, not its internal buffer. Use std::istream methods like read() or get() or operator>> to read from the stream, let it handle it own buffer for you. Secondly, you are trying to make a 2nd completely separate object "magically" know what a previous object is holding. That is not going to work out the way you want, either. Try something more like this instead: #include <iostream> #include <fstream> class from_stream { public: char c; from_stream (std::istream &in){ c = in.get(); // or: in.get(c); // or: in.read(&c, 1); // or: in >> c; }; void show() const { std::cout << "\nCharacter that get from file by to class variable" <<" then printed: " << c; } }; int main(){ std::ifstream by_ifstream; by_ifstream.open("First_test_input.txt"); from_stream send(by_ifstream); send.show(); return 0; }
71,971,636
71,979,639
How to create QT Login Page bedore Mainwindow?
My Qt windows application is ready, but when the application opens, I want the login dialog to be opened, how can I do this? I'm new to Qt and C++. It would be great if it was descriptive.
You have many ways to achieve that... QDialog is a nice way. Here is a short sample using QInputDialog. One solution could be to add this code in your main.cpp file, and to load the mainwindow only if the credentials are ok. #include "gmainwindow.h" #include <QApplication> #include <QInputDialog> int main(int argc, char *argv[]) { QApplication a(argc, argv); GMainWindow w; QString login = QInputDialog::getText(NULL, "Login","Name ?",QLineEdit::Normal); if (login == "USER") { w.show(); } else { //display an error message return a.quit(); } return a.exec(); } Of course you may want to put an encrypted password and other things, but the idea will be more or less the same.
71,971,649
71,971,723
Template virtual method for each type
If I have a template as such: template <typename ... TYPES> class Visitor { public: //virtual void visit(...) {} }; Is there a way I can have C++ generate virtual methods "for each" type in the list? For example, conceptually, I would like class A; class B; class C; class MyVisitor : public Visitor<A,B,C>; To have the following virtual methods virtual void visit(const A&) {} virtual void visit(const B&) {} virtual void visit(const C&) {}
You could add a base class template for Visitor and for each type in TYPES that defines a visit function for the type provided and then you would inherit from those base classes. That would look like template <typename T> class VisitorBase { public: virtual void visit(const T&) { /* some code */ } }; template <typename ... TYPES> class Visitor : public VisitorBase<TYPES>... { public: using VisitorBase<TYPES>::visit...; // import all visit functions into here };
71,972,000
71,981,884
Is having a declaration Stack<T>(); for the default ctor valid inside a class template
I saw this answer to a question on SO related to the declaration for a default constructor of a class template that said that the following code is not valid C++ due to CWG1435: template <class T> class Stack { public: Stack<T>(); //IS THIS VALID? }; While another answer said that the above example is valid C++. There are 2 sources for the claim that the above example is valid: Injected class names: Otherwise, it is treated as a type-name, and is equivalent to the template-name followed by the template-parameters of the class template enclosed in <> In a CppCon conference Dan Saks basically showed a very similar example. So as we can see the two linked answers make opposite claims and i don't know which one is correct. So my question is which of the two answers is correct. That is, is the declaration Stack<T>(); valid C++ or not. PS: I am asking my question for Modern C++ meaning from C++11 & onwards.
The shown snippet is valid for Pre-C++20 but not valid from C++20 & onwards as explained below. Pre-C++20 From class.ctor#1.2: 1 -- Constructors do not have names. In a declaration of a constructor, the declarator is a function declarator of the form: ptr-declarator ( parameter-declaration-clause ) noexcept-specifieropt attribute-specifier-seqopt where the ptr-declarator consists solely of an id-expression, an optional attribute-specifier-seq, and optional surrounding parentheses, and the id-expression has one of the following forms: 1.2 -- in a member-declaration that belongs to the member-specification of a class template but is not a friend declaration, the id-expression is a class-name that names the current instantiation of the immediately-enclosing class template; or (end quote) This means that in C++17, we are allowed to use Stack<T>(); as the constructor declaration. C++20 From class.ctor#1.1: 1 -- A constructor is introduced by a declaration whose declarator is a function declarator ([dcl.fct]) of the form: ptr-declarator ( parameter-declaration-clause ) noexcept-specifieropt attribute-specifier-seqopt where the ptr-declarator consists solely of an id-expression, an optional attribute-specifier-seq, and optional surrounding parentheses, and the id-expression has one of the following forms: 1.1 -- in a member-declaration that belongs to the member-specification of a class or class template but is not a friend declaration ([class.friend]), the id-expression is the injected-class-name ([class.pre]) of the immediately-enclosing entity or So as we can see, the injected class name(which is Stack and not Stack<T> in your example) is needed for declaring the ctor of a class template. This means that your given code is not valid for C++20. The same is also mentioned at diff.cpp17.class#2: Affected subclauses: [class.ctor] and [class.dtor] Change: A simple-template-id is no longer valid as the declarator-id of a constructor or destructor. Rationale: Remove potentially error-prone option for redundancy. Effect on original feature: Valid C++ 2017 code may fail to compile in this revision of C++. For example: template<class T> struct A { A<T>(); // error: simple-template-id not allowed for constructor A(int); // OK, injected-class-name used ~A<T>(); // error: simple-template-id not allowed for destructor };
71,972,269
72,001,860
How to append to CXXFLAGS in Makefile without editing Makefile?
I'm writing a build script for a Qt application. The script first calls qmake on the .pro file and then runs make CXXFLAGS=-DSWVERSION=xxxx. The problem with this is that it overwrites the CXXFLAGS already defined in the Makefile. Currently, the only method I know to solve this problem is to edit the Makefile and change this: CXXFLAGS = <flags> To this: CXXFLAGS += <flags> I was hoping there would be a simpler solution. Is there any way I can simply append to CXXFLAGS from the command line WITHOUT rewriting the Makefile? Alternatively, my real problem is defining SWVERSION at build-time (because it is dependent on the build timestamp). Do you know of a better way to define this at runtime instead of passing it to CXXFLAGS?
For anyone reading this in the future, the solution I found was to call qmake <project file> DEFINES+="SWVERSION=xxxx". Hope someone finds this helpful.
71,972,492
71,972,833
C++ placement new to create global objects with defined construction order - Is this usage correct?
I am using the Arduino framework. To avoid issues with dynamic memory (heap-underflow as well as stack-overflow), Arduino works widely with global objects. I think that is good practice and I want to continue working with this pattern. At the same time, I want to use dependency injection for those global objects, i.e. some objects need other objects injected in their constructor. But there is no defined order in constructing global objects in c++. To overcome that, I figured I could use the placement new operator and construct the objects into memory of global objects. I constructed a template with the sole purpose of reserving memory for any type T which I want to create in global memory space. To reserve the actual memory space, I have a member buffer_ which I declared as an array of long to make sure the memory is perfectly aligned for any objects. But this causes warnings about alignment issues. Using an array of char on the other hand works perfectly without warning. But I think it is much less likely to be correctly aligned for any T. The question: Why is an array of chars apparently correctly aligned but an array of long is not? The following code shows the reservation template and the second snipped shows how to use it: #include <memory> template<class T> class ObjectMemory { //long buffer_[(sizeof(T) + sizeof(long)-1)/sizeof(long)];//make sure it is aligned for long (=biggest size) //=> but this line creates warnings regarding alignments: // warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] // T& operator *() { return reinterpret_cast<T&>(*buffer_); } // ^~~~~~ char buffer_[sizeof(T)]; //this line compiles without warning but looks to me less aligned than an array of longs. public: ObjectMemory() = default; ObjectMemory( const ObjectMemory &c ) = delete; ObjectMemory& operator=( const ObjectMemory &c ) = delete; T& operator *() { return reinterpret_cast<T&>(*buffer_); } T* operator ->() { return reinterpret_cast<T*>( buffer_); } operator T&() { return reinterpret_cast<T&>(*buffer_); } void destroyObject(){(reinterpret_cast<T*>(buffer_))->~T();} }; template<class T> void * operator new(size_t cbsize, ObjectMemory<T>& objectMemory) { if(cbsize > sizeof(T)) { while(true){} //alternatively return nullptr; (will cause warnings) } return &objectMemory; } And here is the usage of the template and the placement new operator: //global objects ObjectMemory<Driver_Spi> spi; ObjectMemory<Driver_DigitalPin> ACS_BoardAdcSpiCs; ObjectMemory<Driver_InternalRtc> rtc; ObjectMemory<Driver_BoardAdc> boardAdc; ObjectMemory<Dcf77Decoder> dcf77Decoder; // The setup() function runs once each time the micro-controller starts void setup() { //... // now call the constructors in correct order: new (spi) Driver_Spi(); new (ACS_BoardAdcSpiCs) Driver_DigitalPin(PIN_5);//CSA new (rtc) Driver_InternalRtc(); new (boardAdc) Driver_BoardAdc(spi, ACS_BoardAdcSpiCs); new (dcf77Decoder) Dcf77Decoder(rtc, PIN_0); //DCF77_INPUT (with interrupt) //... boardAdc->init(); } void loop() { //... }
The warning that you're seeing isn't related to alignment, but instead type punning. Type punning is referring to the same memory location with two differently typed pointers (long* and T*). From the c++ language reference there are only a few special types where the compiler can't issue a warning (char is one of those special types): Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true: AliasedType and DynamicType are similar. AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType. AliasedType is std::byte, (since C++17) char, or unsigned char: this permits examination of the object representation of any object as an array of bytes. This explains why the compiler warns when the buffer is typed as a long[] and doesn't warn when using a char[]. To properly align the char[] to T's alignment you should make use of the alignas() specifier. This will cause the compiler to align your char[] as though it were a T. For example your ObjectMemory class could be modified as follows: template<class T> class ObjectMemory { alignas(T) char buffer_[(sizeof(T)]; public: ObjectMemory() = default; ObjectMemory( const ObjectMemory &c ) = delete; ObjectMemory& operator=( const ObjectMemory &c ) = delete; T& operator *() { return reinterpret_cast<T&>(*buffer_); } T* operator ->() { return reinterpret_cast<T*>( buffer_); } operator T&() { return reinterpret_cast<T&>(*buffer_); } void destroyObject(){(reinterpret_cast<T*>(buffer_))->~T();} };
71,973,148
71,973,478
Why do I get the right output but it also displays the if else output for program 2 and 3
This is a program for admission and there are certain conditions for each program //The front cout<<"Welcome to admission system"<<"\n"; cout<<"---------------------------"<<"\n"; cout<<"Admission open for year 2022"<<"\n"; cout<<"Press 1 for BSc Electrical Engineering Department"<<"\n"; cout<<"Press 2 for BSc Mechanical Engineering Department"<<"\n"; cout<<"Press 3 for MSc Mechanical Engineering Department"<<"\n"; //Personal details cout<<"Your personal details"<<"\n"; cout<<"---------------------"<<"\n"; cout<<"Enter your Civil ID:"; cin>>civil_no; cout<<"Enter your Name: "; cin>>name; cout<<"Enter Age: "<<"\n"; cin>>age; cout<<"Enter contact Number: "; cin>>phone; cout<<"Enter program applying for: "; cin>>pg; //pg here is meant as the department the user want to choose //Education details cout<<"Education Details"<<"\n"; cout<<"-----------------"<<"\n"; cout<<"Enter Applicant highest qualification passing years:"; //cin>>year_of_passing; cout<<"Enter Qualification Passing Year:"; //cin>>qualification; cout<<"Enter Obtained marks (%):"; //cin>>marks; //Program 1 if (pg==1 && marks>=60 && qualification==12) { cout<<"You are fully eligible for this program1"<<"\n"; } else if(pg==1 || marks<60 || qualification!=12){ cout<<"you are not eligible 1"<<"\n"; } //Program 2 if (pg==2 && marks>=65 && qualification==12) { cout<<"You are fully eligible for this program 2"<<"\n"; } else if(pg==2 || marks<65 || qualification!=12){ cout<<"you are not eligible 2"<<"\n"; } //Program 3 if (pg==3 && marks>=70 && qualification==14) { cout<<"You are fully eligible 3"<<"\n"; } else if(pg==3 || marks<70 || qualification!=14){ cout<<"you are not eligible 3"<<"\n"; }
The set of if else statements is incorrect. For example if you entered a value of the qualification not equal to 12 then all three else statements will be executed because the condition qualification!=12 evaluates to true in all three else statements. You need to write either //Program 1 if (pg==1 && marks>=60 && qualification==12) { cout<<"You are fully eligible for this program1"<<"\n"; } else if(pg==1 && ( marks<60 || qualification!=12 )){ cout<<"you are not eligible 1"<<"\n"; } //Program 2 if (pg==2 && marks>=65 && qualification==12) { cout<<"You are fully eligible for this program 2"<<"\n"; } else if( pg==2 && ( marks<65 || qualification!=12 )){ cout<<"you are not eligible 2"<<"\n"; } //Program 3 if (pg==3 && marks>=70 && qualification==14) { cout<<"You are fully eligible 3"<<"\n"; } else if( pg==3 && ( marks<70 || qualification!=14 ) ){ cout<<"you are not eligible 3"<<"\n"; } or for example //Program 1 if ( pg==1 ) { if ( marks>=60 && qualification==12) { cout<<"You are fully eligible for this program1"<<"\n"; } else { cout<<"you are not eligible 1"<<"\n"; } } //Program 2 if (pg==2 ) { if ( marks>=65 && qualification==12) { cout<<"You are fully eligible for this program 2"<<"\n"; } else { cout<<"you are not eligible 2"<<"\n"; } } //Program 3 if ( pg==3 ) { if ( marks>=70 && qualification==14) { cout<<"You are fully eligible 3"<<"\n"; } else { cout<<"you are not eligible 3"<<"\n"; } }
71,973,876
71,973,938
How to get a subset of map from another map based on a list of keys? C++
I have an old map sample: map<string, int> map_ = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5} and a list of keys: vector<string> list_ = {"B", "D", "E"} I want to get a new map from the old one based on the key list: map<string, int> mapNew_ = {"B": 2, "D": 4, "E": 5} Is there any smart way to do this?
You can do this with a simple ranged based for loop. That would look like map<string, int> mapNew_; for (const auto& e : list_) mapNew_[e] = map_[e]; If list_ could contain elements that are not in the map, then you would need to add a check for that like map<string, int> mapNew_; for (const auto& e : list_) if (auto it = map.find(e); it != map.end()) mapNew_[e] = it->second; // no map_[e] here since it already points to the needed value
71,974,052
71,974,175
C++ creating an array pointing to different arrays
The inputs to this program are as follows: 2 2 3 1 5 4 5 1 2 8 9 3 0 1 1 3 I would like n to be an array that points to other integer arrays. So, n should essentially be {{1, 5, 4}, {1, 2, 8, 9, 3}}. If I wanted to access the 0th array and the 1st index, the value should return 5, and if I were to access the 1st array and the 3rd index, the value should be 9. However, the values that this code returns are 32764 and 32764. #include <cstdio> #include <iostream> using namespace std; int main() { int n_l; // integer variable that will hold the length of array n int q_l; // integer variable that will hold the length of the number of queries cin >> n_l >> q_l; // assigns values to the variables n_l and q_l int *n[n_l]; // creates an array that will contain pointers for (int i = 0; i < n_l; i++){ // loops through the length of array n int amount; // declares the variable amount cin >> amount; // assigns a value to the variable amount int k[amount]; // creates one of the arrays that will be added to n for (int x= 0; x < amount; x++){ // loops through the length of k and assigns a value to each index cin >> k[x]; } n[i] = k; // adds the array k to the position in array n } for (int i = 0; i < q_l; i++){ int arraynum; int index; cin >> arraynum >> index; cout << n[arraynum][index] << endl; } }
cin >> n_l >> q_l; // assigns values to the variables n_l and q_l int *n[n_l]; This isn't allowed in C++. The size of an array variable must be compile time constant. You can create dynamic arrays. Most convenient way is to use std::vector class template from the standard library. The issue with your pointers is that the automatic arrays that you create in the loop are automatically destroyed at the end of the loop statement and the pointers in the array are all dangling (i.e. invalid) pointers to destroyed arrays. When you later indirect through the invalid pointers, the behaviour of the program is undefined. You want multiple arrays. What's a good way to create multiple objects? Array is a good way to create multiple objects. So, in order to create multiple arrays, you can create an array of arrays. Or, since you want dynamic sizes, you can create a vector of vectors. Here is an example of how to create a vector of vectors: std::vector<std::vector<int>> n(n_l); for(auto& vec : n) { int amount; std::cin >> amount; vec.resize(amount); for(auto& i : vec) { cin >> i; } } You could create a vector of pointers to the arrays within the vectors in the vector of vectors, but that would be pointless. You don't need the pointers.
71,974,122
71,974,379
How to write a type trait that checks if tuple types are compatible with function arguments
I am trying to write a type trait that checks whether the types stored in a tuple are compatible with the arguments of a given callable. Currently, I have 'almost working' code, shown below. However, static assert fails in the last statement with a callable that expects reference parameters (e.g. [](int&, std::string&){}), I don't really understand why it's failing. And how does one write a trait that is inclusive for this type as well? #include <type_traits> #include <tuple> #include <string> template<typename, typename> struct is_callable_with_tuple: std::false_type {}; template<typename Func, template<typename...> class Tuple, typename... Args> struct is_callable_with_tuple<Func, Tuple<Args...>>: std::is_invocable<Func, Args...> {}; template<typename Func, typename Args> constexpr bool is_callable_with_tuple_v = is_callable_with_tuple<Func, Args>::value; int main() { static_assert(is_callable_with_tuple_v<decltype([](int, std::string){}), std::tuple<int, std::string>>); // OK static_assert(is_callable_with_tuple_v<decltype([](const int&, const std::string&){}), std::tuple<int, std::string>>); // OK static_assert(is_callable_with_tuple_v<decltype([](int&, std::string&){}), std::tuple<int, std::string>>); // Fails }
You may want to modify your trait slightly: template<typename Func, template<typename...> class Tuple, typename... Args> struct is_callable_with_tuple<Func, Tuple<Args...>>: std::is_invocable<Func, Args&...> {}; // <--- note & Or not, depending on how exactly you plan to use it. If your tuple is always an lvalue, it is probably OK. If not, then you may want to specialise it for an lvalue-reference tuple type: template<typename Func, template<typename...> class Tuple, typename... Args> struct is_callable_with_tuple<Func, Tuple<Args...>&>: // <--- note & here std::is_invocable<Func, Args&...> {}; // <--- and also here template<typename Func, template<typename...> class Tuple, typename... Args> struct is_callable_with_tuple<Func, Tuple<Args...>>: // <--- note NO & here std::is_invocable<Func, Args...> {}; // <--- and also here and use it like this: is_callable_with_tuple<decltype(myfunc), decltype((mytuple))> // note double parentheses
71,974,453
71,974,485
Visual Studio Express 2017 Output not displaying for stroke text function
I've been trying to run this program in visual studio express 2017. Using opengl. I found the rendering code and stroke code in a pdf and was trying it out but first it showed many errors, once taken care of I compiled the program. Although the run was without any errors the output screen remains blank. #include "stdafx.h" #include <windows.h> #include <gl/GL.h> #include <glut.h> #include <gl/GLU.h> void myInit(void) { glClearColor(1.0, 1.0, 1.0, 0.0); glColor3f(0.0f, 0.0f, 0.0f); glMatrixMode(GL_PROJECTION); glLineWidth(6.0); glLoadIdentity(); gluOrtho2D(0.0, 700, 0.0, 700); } void drawStrokeText(const char *string, int x, int y, int z) { const char *c; glPushMatrix(); glTranslatef(x, y + 8, z); glScalef(0.09f, -0.08f, z); for (c = string; *c != '\0'; c++) { glutStrokeCharacter(GLUT_STROKE_ROMAN, *c); } glPopMatrix(); } void render() { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glColor3ub(255, 50, 255); drawStrokeText("Hello", 300, 400, 0); glutSwapBuffers(); } void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT); render(); glFlush(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(700, 700); glutInitWindowPosition(100, 150); glutCreateWindow("My First Program"); glutDisplayFunc(myDisplay); myInit(); glutMainLoop(); }
Matrix mode is switched to GL_PROJECTION in myInit but never switched back. Therefore the glLoadIdentity() instruction in render will override the projection matrix. You have to switch the matrix mode to GL_MODELVIEW before glLoadIdentity(): void render() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); // <-- glLoadIdentity(); glColor3ub(255, 50, 255); drawStrokeText("Hello", 300, 400, 0); glutSwapBuffers(); }
71,974,618
71,976,462
Why are copy-capturing lambdas not default DefaultConstructible in c++20
C++20 introduces DefaultConstructible lambdas. However, cppreference.com states that this is only for stateless lambdas: If no captures are specified, the closure type has a defaulted default constructor. Otherwise, it has no default constructor (this includes the case when there is a capture-default, even if it does not actually capture anything). Why does this not extend to lambdas that capture things that are DefaultConstructible? For instance, why can [p{std::make_unique<int>(0)}](){ return p.get(); } not be DefaultConstructible, where the captured p would be nullptr? Edit: For those asking why we would want this, the behavior only seems natural because one is forced to write something like this when calling standard algorithms that require functors to be default-constructible: struct S{ S() = default; int* operator()() const { return p.get(); } std::unique_ptr<int> p; }; So, we can pass in S{std::make_unique<int>(0)}, which does the same thing. It seems like it would be much better to be able to write [p{std::make_unique<int>(0)}](){ return p.get(); } versus creating a struct that does the same thing.
There are two reasons not to do it: conceptual and safety. Despite the desires of some C++ programmers, lambdas are not meant to be a short syntax for a struct with an overloaded operator(). That is what C++ lambdas are made of, but that's not what lambdas are. Conceptually, a C++ lambda is supposed to be a C++ approximation of a lambda function. The capture functionality is not meant to be a way to write members of a struct; it's supposed to mimic the proper lexical scoping capabilities of lambdas. That's why they exist. Creating such a lambda (initially, not by copy/move of an existing one) outside of the lexical scope that it was defined within is conceptually vacuous. It doesn't make sense to write a thing bound to a lexical scope, then create it outside of the scope it was built for. That's also why you cannot access those members outside of the lambda. Because, even though they could be public members, they exist to implement proper lexical scoping. They're implementation details. To construct a "lambda" that "captures variables" without actually capturing anything only makes sense from a meta-programming perspective. That is, it only makes sense when focusing on what lambdas happen to be made of, rather than what they are. A lambda is implemented as a C++ struct with captures as members, and the capture expressions don't even technically have to name local variables, so those members could theoretically be value initialized. If you are unconvinced by the conceptual argument, let's talk safety. What you want to do is declare that any lambda shall be default constructible if all of its captures are non-reference captures and are of default constructible types. This invites disaster. Why? Because the writer of many such lambdas didn't ask for that. If a lambda captures a unique_ptr<T> by moving from a variable that points to an object, it is 100% valid (under the current rules) for the code inside that lambda to assume that the captured value points to an object. Default construction, while syntactically valid, is semantically nonsense in this case. With a proper named type, a user can easily control if it is default constructible or not. And therefore, if it doesn't make sense to default construct a particular type, they can forbid it. With lambdas, there is no such syntax; you have to impose an answer on everyone. And the safest answer for capturing lambdas, the one that is guaranteed to never break code, is "no." By contrast, default construction of captureless lambdas can never be incorrect. Such functions are "pure" (with respect to the contents of the functor, since the functor has no contents). This also matches with the above conceptual argument: a captureless lambda has no proper lexical scope and therefore spawning it anywhere, even outside of its original scope, is fine. If you want the behavior of a named struct... just make a named struct. You don't even need to default the default constructor; you'll get one by default (if you declare no other constructors).
71,974,667
71,975,399
Efficient Perpetual Numlock Keystate Check
I bought a really nice keyboard (logitech G915) that for whatever inane reason doesn't have a numlock indicator. Thus, I'm using Logitech's lighting SDK to make the functionality myself using the key's rgb backlight. I have an extremely simple console proof of concept that works: while (true) { if (GetKeyState(VK_NUMLOCK) & 0x1) LogiLedSetLightingForKeyWithKeyName(LogiLed::KeyName::NUM_LOCK, 0, 100, 100); else LogiLedSetLightingForKeyWithKeyName(LogiLed::KeyName::NUM_LOCK, 0, 0, 0); } But I don't think it's good to eat up cpu cycles with a perpetual while loop for such a tiny feature. Should I just have it sleep for time (length suggested?) or is there a way to sleep until the system gets a numlock state change or am I simply going about this wrong? Additionally, I haven't looked into it yet, but I want to make this a background process or a tray application (doesn't matter, just hidden away) so I guess answers should have that limitation in mind if it is one. Thanks!
At app startup, use GetAsyncKeyState() instead of GetKeyState() to get the key's current state and update the light accordingly. Then, use SetWindowsHookEx() to install a global WH_KEYBOARD_LL hook to detect whenever the key is pressed afterwards. On each callback event, use the state information provided by the hook, or start an asynchronous task to get the current key state immediately after your hook callback exits (as GetAsyncKeyState() has not been updated yet when the callback is called), and then update the light accordingly. Alternatively, use the Raw Input API to monitor the keyboard and receive WM_INPUT window messages on each key press. And then get the key's current state and update the light accordingly.
71,975,120
71,977,930
Generic set insert function int
I have a little problem with the next task. The insert function should also work for the int type but unfortunately it doesn't work. What might be the problem? Some example for the insert function call: Set<int, 4> s0; s0.insert(2); This is an four-elemet array and the firs element is 2. template <class T, size_t n = 10> class Set{ private: T adat[n]; public: size_t size (){return n;} bool isElement (T num){ for (size_t i = 0; i < n; i++) { if (adat[i] == num) return true; } return false; } void insert (T data){ if (!isElement(data)){ size_t i = 0; while((adat[i] != 0)||(i != n)) i++; if (i != n) { adat[i] = data; } else throw("The array is full!"); } } };
This is a maybe somehow subtle out of bounds bug. Cool. In this while loop while((adat[i] != 0)||(i != n)) i++; you will go out of bounds, because the last element is "(n-1)" and not "n". And you will always go out of bounds, because of the "or" in the condition. The loop will always run at least until "i==n", because of the right part of the "or". And then, after being out of bounds, the accessed value "adat[i]" will be indetermined, and most likely not null. So, you safeguard "i!=n" will never be touched. This also because of boolean shortcut evaluation. if "(adat[i] != 0)" is already true, then the next term in the "or" has no meaning and will also be not evaluated. And then the endless loop will run forever . . . You must also initialize your "adat" array, to be sure that it contains default values. Do this with: T adat[n]{};. Finally, to fix your while loop, please write: while ((adat[i] != 0) && (i < n)) {
71,975,555
71,990,268
C++ Event Dispatcher - callback casting problem
I'm venturing into creating an EventDispatcher using C++ 17 in Visual Studio 2022. Basically I store a string (id) to identify the event and a callback (lambda, function or method of a class) in a vector through the RegisterEvent() method. Then I need to call the DispatchEvent() method passing the event as a parameter. This event receives the event id as a parameter. Internally the DispatchEvent() method loops to find the event with the corresponding id and executes the previously stored callback passing the event to the callback. When using the generic Event event, everything works perfectly. (Just comment out all the content inside the doCustomEvents() method; PROBLEM When creating an event derived from the generic event, in this example CustomEvent it fails to perform the casting and issues the following error: Error C2440 : <function-style-cast>': cannot convert from 'initializer list' to 'EventProps' : LINE 41 HERE -> m_EventProps.push_back(EventProps(id, callback)); I've been studying a lot about casting, but nothing I've seen so far has been able to help me solve this problem. Could someone please help me? Thank you very much! Follow the code below: #include <iostream> #include <string> #include <vector> #include <functional> #define DEBUG(x) std::cout << x << std::endl; #define BIND(fn) [this](auto...args) -> decltype(auto) { return this->fn(args...); } class Event { public: std::string Id; Event(std::string id) : Id(id) { } std::string ToString() { return "Event(id=" + Id +")"; } }; class CustomEvent : public Event { public: std::string Message; CustomEvent(std::string id, std::string message) : Event(id), Message(message) { } std::string ToString() { return "CustomEvent(id=" + Id + ", message=" + Message + ")"; } }; struct EventProps { public: std::string Id; std::function<void(Event)> Callback; EventProps(std::string id, std::function<void(Event)> callback) : Id(id), Callback(callback) { } }; class EventDispatcher { private: std::vector<EventProps> m_EventProps; public: template<typename T> void RegisterEvent(std::string id, std::function<void(T)> callback) { m_EventProps.push_back(EventProps(id, callback)); } void DispatchEvent(Event event) { for (int i = 0; i < m_EventProps.size(); i++) { EventProps props = m_EventProps[i]; if(props.Id == event.Id) props.Callback(event); } } }; void globalCallback(Event e) { DEBUG("[Global] " + e.ToString()); } void customGlobalCallback(CustomEvent ce) { DEBUG("[Global] " + ce.ToString()); } class Application { public: EventDispatcher dispatcher; Application() { doEvents(); doCustomEvents(); // Nothing works here } void doEvents() { dispatcher.RegisterEvent<Event>("event_0", [](Event e) { DEBUG("[Lambda] " + e.ToString()); }); dispatcher.RegisterEvent<Event>("event_1", globalCallback); dispatcher.RegisterEvent<Event>("event_2", BIND(Application::OnEvent)); dispatcher.DispatchEvent(Event("event_0")); dispatcher.DispatchEvent(Event("event_1")); dispatcher.DispatchEvent(Event("event_2")); } void doCustomEvents() { dispatcher.RegisterEvent<CustomEvent>("custom_0", [](CustomEvent e) { DEBUG("[Lambda] " + e.ToString()); }); dispatcher.RegisterEvent<CustomEvent>("custom_1", customGlobalCallback); dispatcher.RegisterEvent<CustomEvent>("custom_2", BIND(Application::OnCustomEvent)); dispatcher.DispatchEvent(CustomEvent("custom_0", "Hi custom 0")); dispatcher.DispatchEvent(CustomEvent("custom_1", "Hi custom 1")); dispatcher.DispatchEvent(CustomEvent("custom_2", "Hi custom 2")); } void OnEvent(Event e) { DEBUG("[Application::OnEvent] " + e.ToString()); } void OnCustomEvent(CustomEvent ce) { DEBUG("[Application::CustomEvent] " + ce.ToString()); } }; int main() { Application app; }
This question is probably on the edge of what people would normally close, but MSVC is making your life harder by giving a really useless error message here. (You might want to try upgrading your compiler; recent MSVC on godbolt.org give much more helpful messages.) The problem is with dispatcher.RegisterEvent<CustomEvent>("custom_0", [](CustomEvent e) { DEBUG("[Lambda] " + e.ToString()); }); and the following lines. dispatcher.RegisterEvent<CustomEvent> takes a second argument of type std::function<void(CustomEvent)> and then proceeds to use it to try to construct an EventProps. However what the constructor of EventProps wants is a std::function<void(Event)>. There is no way for the compiler to convert a function that only accepts CustomEvents into a function that accepts all Events. You need to either template EventProps itself, or adapt RegisterEvent to convert a function taking events of type T into a function taking all Events.
71,975,610
71,975,649
Vector of vector with unknown size input in c++
I need to input elements of vector of vector. Size of vectors is not known. Row input ends with * character, as well as vector input. EXAMPLE 2 5 1 3 4 * 9 8 9 * 3 3 2 3 * 4 5 2 1 1 3 2 * * Code: #include <iostream> #include <vector> int main() { std::vector < std::vector < int >> a; int x; int i = 0, j = 0; for (;;) { while (std::cin >> x) { a[i][j] = x; j++; } if (!std::cin >> x) break; i++; } return 0; } This allows me to enter only the first row, and after that the program stops. Could you help me to modify this to allow input of other rows?
There are two problems with your code: you are indexing into each vector without adding any values to it first, which is undefined behavior. a[i][j] = x; does not make the vectors grow in size. Use vector::push_back() instead. You are not handling the input of * correctly. x is an int, so when std::cin >> x fails to read a non-integer value, like *, cin is put into an error state and all further reading fails until you clear() the error and ignore() the failed data from the input buffer. Since your input is line-based, consider using std::getline() to read each line at a time. You can use a std::istringstream to read integers from each line, eg: #include <iostream> #include <sstream> #include <string> #include <vector> #include <iomanip> int main() { std::vector<std::vector<int>> a; std::string line; while (std::getline(std::cin, line)) { std::istringstream iss(line); iss >> std::ws; if (iss.peek() == '*') break; std::vector<int> v; int x; while (iss >> x) { v.push_back(x); } a.push_back(v); } for(auto &v : a) { for(int num : v) { std::cout << num << ' '; } std::cout << std::endl; } return 0; }
71,975,668
71,975,690
How to append a string at the end of string?
#include <iostream> #include <string> #include <cstdlib> using namespace std; class String { private: char* s; int size; public: String() { s = NULL; size = 0; } String(const char* str) { size = strlen(str); s = new char[size]; for (int i = 0; i < size; i++) s[i] = str[i]; } String(const String& obj) { size = obj.size; s = new char[size]; for (int i = 0; i < size; i++) s[i] = obj[i]; } String(int x) { size = x; s = new char[size]; } char& operator[](int i) { return *(s + i); } const char operator[](int i) const { return *(s + i); } String& operator+(const char& str) // append a char at the end of string { int newsize = size + 1; String newstr(size); for (int i = 0; i < size; i++) { newstr.s[i] = s[i]; } newstr.s[size] = str; delete[]s; s = newstr.s; size = newsize; return *this; } String& operator+(char*& str) // append a string at the end of string { int newsize = size + strlen(str); String newstr(newsize); for (int i = 0; i < size; i++) { newstr.s[i] = s[i]; } for (unsigned i = 0; i < strlen(str); i++) { newstr.s[size + i] = str[i]; } delete[]s; s = newstr.s; size = newsize; return *this; } operator int() const { int m; m = size; return m; } }; int main() { String s1("abcd"); String s2; s2 = s1 + 'e'; cout << s2[3]; cout << s2[4]; char* c = (char*)"asdfgh"; s2 = s1 + c; cout << s2[3]; cout << s2[4]; cout << s2[8]; } My code runs perfectly until the statement char* c = (char*)"asdfgh". After this statement, I am not getting actual output. s2[3] after the statement char* c = (char*)"asdfgh" is supposed to give 'd' in the output, and similarly s2[4] is supposed to give 'a' in the output, and s2[8] is supposed to give 'g' in the output. But, the problem is, when I run this program, I am not getting these actual values. Kindly look into this and tell me where I need to make changes.
Both of your operator+ implementations are wrong. You are modifying the String object that is being added to, and then returning a reference to that object. You need to instead return a new String object that is the concatenation of the added-to and added-from String objects, without modifying the added-to String at all. What you have implemented would be more appropriate for an operator+= instead. See What are the basic rules and idioms for operator overloading? for more details. That said, there are some other problems with your code, as well. For instance, you are missing a destructor and a copy assignment operator, per the Rule of 3/5/0. You could also consider adding a move constructor and move assignment operator, as well. Try something more like this: #include <iostream> #include <cstring> #include <utility> using namespace std; class String { private: char* s; size_t size; public: String() { s = nullptr; size = 0; } String(const char* str) { size = strlen(str); s = new char[size+1]; for (int i = 0; i < size; ++i) s[i] = str[i]; s[size] = '\0'; } String(const String& str) { size = str.size; s = new char[size+1]; for (int i = 0; i < size; ++i) s[i] = str[i]; s[size] = '\0'; } String(String&& str) { size = str.size; str.size = 0; s = str.s; str.s = nullptr; } String(size_t x) { size = x; s = new char[size+1]; s[size] = '\0'; } ~String() { delete[] s; } void swap(String& other) { std::swap(s, other.s); std::swap(size, other.size); } String& operator=(char ch) { String newstr(1); newstr[0] = ch; newstr.swap(*this); return *this; } String& operator=(const char* str) { String(str).swap(*this); return *this; } String& operator=(const String& str) { if (this != &str) String(str).swap(*this); return *this; } String& operator=(String&& str) { String(std::move(str)).swap(*this); return *this; } char& operator[](size_t i) { return s[i]; } const char operator[](size_t i) const { return s[i]; } String operator+(char ch) { /* String newstr(*this); newstr += ch; return newstr; */ String newstr(size + 1); for (int i = 0; i < size; ++i) { newstr[i] = s[i]; } newstr[size] = ch; return newstr; } String operator+(const char* str) { /* String newstr(*this); newstr += str; return newstr; */ size_t slen = strlen(str); String newstr(size + slen); for (size_t i = 0; i < size; ++i) { newstr[i] = s[i]; } for (size_t i = 0; i < slen; ++i) { newstr[size + i] = str[i]; } return newstr; } String& operator+=(char ch) { String newstr(size + 1); for (size_t i = 0; i < size; ++i) { newstr[i] = s[i]; } newstr[size] = ch; newstr.swap(*this); return *this; } String& operator+=(const char* str) { size_t slen = strlen(str); if (slen > 0) { String newstr(size + slen); for (size_t i = 0; i < size; ++i) { newstr[i] = s[i]; } for (size_t i = 0; i < slen; ++i) { newstr[size + i] = str[i]; } newstr.swap(*this); } return *this; } size_t getSize() const { return size; } }; int main() { String s1("abcd"); String s2; s2 = s1 + 'e'; cout << s2[3]; cout << s2[4]; s2 = s1 + "asdfgh"; cout << s2[3]; cout << s2[4]; cout << s2[8]; }
71,975,790
71,975,896
Why can an 8-bit string literal contain multibyte characters while a vector of char cannot?
I am trying to figure out why can an 8-bit char data type contain all these weird characters since they are not part of the first 256 characters table. #include <iostream> int main() { char chars[] = " 必 西 ♠ ♬ ♭ ♮ ♯"; std::cout << "sizeof(char): " << sizeof(char) << " byte" << std::endl; std::cout << chars << std::endl; return 0; }
An 8-bit char can only hold 256 values max. But Unicode has hundreds of thousands of characters. They obviously can't fit into a single char. So, they have to be encoded in such a way that they can fit into multiple chars. Your editor/compiler is likely storing your example string in UTF-8 encoding. Non-ASCII characters in UTF-8 take up more than 1 char. In your example, in UTF-8, sizeof(chars) would be 55+1=56 chars in size (+1 for the null terminator), even though you see only 29 "characters" (if you count the spaces), where: = 0x20 (18x) = 0xF0 0x9F 0x98 0x8E = 0xF0 0x9F 0xA5 0xB8 = 0xF0 0x9F 0xA4 0xA9 = 0xF0 0x9F 0xA5 0xB3 必 = 0xE5 0xBF 0x85 西 = 0xE8 0xA5 0xBF ♠ = 0xE2 0x99 0xA0 ♬ = 0xE2 0x99 0xAC ♭ = 0xE2 0x99 0xAD ♮ = 0xE2 0x99 0xAE ♯ = 0xE2 0x99 0xAF
71,975,930
71,977,358
Limit compilation flags usage to certain files only
I'm trying to introduce -Werror flag to rather big legacy project. As expected, it breaks the compilation completely. Therefore I've decided to introduce it gradually, and for the new code first of all. My original approach was to compile new features as separate static targets and link them to the project, which works kind of good both in terms of project structure and readability. The problem which persist are pre-existing tangled includes. Basically, even after fixing all warnings in new code I'm left with chain of includes introducing new warnings. Is there any way to limit warning flags usage to given source files strictly? I do understand that include means basically copy/pasting headers into cpps, so it does not seem possible with just cmake settings. Then pragmas, perhaps?
I don't know about any compiler flags that allow you to apply flags to only some of the files included, so cmake cannot do better for you. Therefore pragmas are the way to go. Basically what you effectively want in your cpp files is something like this: #pragma GCC diagnostic push #pragma GCC diagnostic error "-Wall" #include "updated_lib/header1.hpp" #include "updated_lib/header2.hpp" ... #pragma GCC diagnostic pop #include "non_updated_lib/header1.hpp" #include "non_updated_lib/header2.hpp" Note that this would require this logic to be repeated in multiple translation units which you may want to avoid, if you're updating the headers gradually over time. As an alternative you could duplicate the header file subdirectories, and make the non-updated versions available via one path and updated headers via another, e.g. for a header foo/bar/baz.hpp either make the header available via path old/foo/bar/baz.hpp or new/foo/bar/baz.hpp and create a new header available via foo/bar/baz.hpp that looks like this: #if __has_include("new/foo/bar/baz.hpp") # pragma GCC diagnostic push # pragma GCC diagnostic error "-Wall" # include "new/foo/bar/baz.hpp" # pragma GCC diagnostic pop #else # pragma GCC diagnostic push # pragma GCC diagnostic warning "-Wall" # include "old/foo/bar/baz.hpp" # pragma GCC diagnostic pop #endif Note that you'll probably need to write these kind of headers for you. You could even generate the actual includes via cmake during the generation of the project which which would shorten the headers to 3 pragmas plus one include; this would have the additional benefit of working with compiler versions not supporting __has_include. function(my_generate_include OUT_LIST DESTINATION_DIR FIRST_HEADER) set(GENERATED_HEADERS ${${OUT_LIST}}) foreach(HEADER IN ITEMS ${FIRST_HEADER} ${ARGN}) if (HEADER MATCHES "^old/(.*)$") configure_file(old_include.hpp.in "${DESTINATION_DIR}/${CMAKE_MATCH_1}") list(APPEND GENERATED_HEADERS "${DESTINATION_DIR}/${CMAKE_MATCH_1}") elseif (HEADER MATCHES "^new/(.*)$") configure_file(new_include.hpp.in "${DESTINATION_DIR}/${CMAKE_MATCH_1}") list(APPEND GENERATED_HEADERS "${DESTINATION_DIR}/${CMAKE_MATCH_1}") else() message(FATAL_ERROR "Header '${HEADER}' doesn't start with 'new/' or 'old/'") endif() endforeach() set(${OUT_LIST} ${GENERATED_HEADERS} PARENT_SCOPE) endfunction() ... set(HEADERS) my_generate_include(HEADERS ${CMAKE_CURRENT_BINARY_DIR}/generated_includes old/a/b/c.hpp new/d/e/f.hpp )
71,976,361
71,982,814
How to get a generalized Swap-function?
Using the example for std::swap on cppreference I tried the following SWAP-template: #include <algorithm> #include <iostream> namespace Ns { class A { int id{}; friend void swap(A& lhs, A& rhs) { std::cout << "swap(" << lhs << ", " << rhs << ")\n"; std::swap(lhs.id, rhs.id); } friend std::ostream& operator<< (std::ostream& os, A const& a) { return os << "A::id=" << a.id; } public: A(int i) : id{i} { } A(A const&) = delete; A& operator = (A const&) = delete; }; } template<typename T> void SWAP(T &l, T &r) { try { std::swap(l, r); } catch(...) { swap(l, r); } } int main() { std::cout << "\n======================\n"; int a = 5, b = 3; std::cout << "before: " << a << ' ' << b << '\n'; std::swap(a,b); std::cout << "after: " << a << ' ' << b << '\n'; std::cout << "\n=========\n"; Ns::A p{6}, q{9}; std::cout << "before: " << p << ' ' << q << '\n'; // std::swap(p, q); // error, type requirements are not satisfied swap(p, q); // OK, ADL finds the appropriate friend `swap` std::cout << "after: " << p << ' ' << q << '\n'; std::cout << "\n======================\n"; std::cout << "before: " << a << ' ' << b << '\n'; SWAP(a,b); std::cout << "after: " << a << ' ' << b << '\n'; std::cout << "\n=========\n"; std::cout << "before: " << p << ' ' << q << '\n'; SWAP(p, q); std::cout << "after: " << p << ' ' << q << '\n'; } to handle the 'friend' swap-function in the namespace; to have just a single SWAP function to call that will handle all cases. The compiler-error: swap was not declared in this scope Why does calling swap() for the namespace work in main but not in the template? and is there a way to have a generalized 'SWAP'-function to handle all such cases? (edit) Thanks to @rici the following change to the template works: template<typename T> void SWAP(T &l, T &r) { using namespace std; swap(l, r); } I would still appreciate an ELI5 for the first part of my question: what/how/why does this work ...
There are 2 problems. Please first read the definition of 'std::swap' here. You will read the requirements for the type. You are using exceptions in your swap function. Remove that. From the description, you can see that your type must be Type requirements T must meet the requirements of MoveAssignable and MoveConstructible. T2 must meet the requirements of Swappable. You defined (deleted) a constructor and assign operator. With that the compiler will not create the standard constructors/assign operators for you. Please read about the rule of 5. Your class is no longer MoveAssignable and MoveConstructible. Simply remove the deleted operator and constructor. Like the below. Then it will compile. #include <algorithm> #include <iostream> namespace Ns { class A { int id{}; friend void swap(A& lhs, A& rhs) { std::cout << "swap(" << lhs << ", " << rhs << ")\n"; std::swap(lhs.id, rhs.id); } friend std::ostream& operator<< (std::ostream& os, A const& a) { return os << "A::id=" << a.id; } public: A(int i) : id{ i } { } //A(A const&) = delete; //A& operator = (A const&) = delete; }; } template<typename T> void SWAP(T& l, T& r) { std::swap(l, r); } int main() { std::cout << "\n======================\n"; int a = 5, b = 3; std::cout << "before: " << a << ' ' << b << '\n'; std::swap(a, b); std::cout << "after: " << a << ' ' << b << '\n'; std::cout << "\n=========\n"; Ns::A p{ 6 }, q{ 9 }; std::cout << "before: " << p << ' ' << q << '\n'; // std::swap(p, q); // error, type requirements are not satisfied swap(p, q); // OK, ADL finds the appropriate friend `swap` std::cout << "after: " << p << ' ' << q << '\n'; std::cout << "\n======================\n"; std::cout << "before: " << a << ' ' << b << '\n'; SWAP(a, b); std::cout << "after: " << a << ' ' << b << '\n'; std::cout << "\n=========\n"; std::cout << "before: " << p << ' ' << q << '\n'; SWAP(p, q); std::cout << "after: " << p << ' ' << q << '\n'; }
71,976,458
71,977,034
The .ccp and .h / header files output error 'this declaration has no storage class or type specifier' with implementation of SendInput function
So my problem is I keep getting error "this declaration has no storage class or type specifier" "the size of an array must be greater than zero" " expected a ';' " I don't know what's wrong. I tried to look online and find no specific solution to my problem other than generic solutions like defining the class for the terms in my .h file but I don't even know where to begin defining 'ZeroMemory' or something like that. You can see in my code, in my Source.cpp, I have commented out the code and did a paste crossover into my .h file. The error presented above appears and it seems it won't compile but its fine compiling if I leave them in my Source.cpp file instead. How do I go about solving this? I'm at my wits end here. BTW I want them on a separate file which is a .h file. Source.cpp file #include <windows.h> #include <iostream> #include <conio.h> #include "Input Buttons.h" int main() { //INPUT blocks[6], grabs[4]; /*ZeroMemory(blocks, sizeof(blocks));*/ /*ZeroMemory(grabs, sizeof(grabs));*/ //virutal key list website //learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes //Setting up key/mouse input environment //a //blocks[0].type = INPUT_KEYBOARD; //blocks[0].ki.wVk = 0x41; //keyboard button 'a' //blocks[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //press down //blocks[1].type = INPUT_KEYBOARD; //blocks[1].ki.wVk = 0x41; //blocks[1].ki.dwFlags = KEYEVENTF_KEYUP; //let go //d //blocks[2].type = INPUT_KEYBOARD; //blocks[2].ki.wVk = 0x44; //keyboard button 'd' //blocks[2].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //blocks[3].type = INPUT_KEYBOARD; //blocks[3].ki.wVk = 0x44; //blocks[3].ki.dwFlags = KEYEVENTF_KEYUP; //s //blocks[4].type = INPUT_KEYBOARD; //blocks[4].ki.wVk = 0x53; //keyboard button 's' //blocks[4].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //blocks[5].type = INPUT_KEYBOARD; //blocks[5].ki.wVk = 0x53; //blocks[5].ki.dwFlags = KEYEVENTF_KEYUP; //i //grabs[0].type = INPUT_KEYBOARD; //grabs[0].ki.wVk = 0x49; //keyboard button 'i' //grabs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //grabs[1].type = INPUT_KEYBOARD; //grabs[1].ki.wVk = 0x49; //grabs[1].ki.dwFlags = KEYEVENTF_KEYUP; //k //grabs[2].type = INPUT_KEYBOARD; //grabs[2].ki.wVk = 0x4B; //keyboard button 'k' //grabs[2].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //grabs[3].type = INPUT_KEYBOARD; //grabs[3].ki.wVk = 0x4B; //grabs[3].ki.dwFlags = KEYEVENTF_KEYUP; } Input Buttons.h #pragma once using namespace std; INPUT blocks[6], grabs[4]; ZeroMemory(blocks, sizeof(blocks)); ZeroMemory(grabs, sizeof(grabs)); //a blocks[0].type = INPUT_KEYBOARD; blocks[0].ki.wVk = 0x41; //keyboard button 'a' blocks[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY; //press down blocks[1].type = INPUT_KEYBOARD; blocks[1].ki.wVk = 0x41; blocks[1].ki.dwFlags = KEYEVENTF_KEYUP; //let go Error in image form from my perspective
As it currently is, your header file has "freestanding" execution code. This is not possible in C++ - C++ is not a scripting language where you can execute code in arbitrary files. Every executable code needs to be in a function. So you better declare a function prototype in your Buttons.h with the necessary data types. Then you create a function in Buttons.cpp where you define the function with the code you want to execute and compile and link it. You can then include Buttons.h and call the function from main() Buttons.h #include <conio.h> void do_stuff(); Buttons.cpp void do_stuff() { INPUT blocks[6]; INPUT grabs[4]; //... rest of your code// } Source.cpp #include "Buttons.h" // makes do_stuff() visible in Source.cpp int main() { do_stuff(); }
71,976,481
71,976,570
why list doesn't work similar like array in c++
Why my code is not printing the value 2 in l[0]? #include <bits/stdc++.h> using namespace std; list<int> l; int main() { l.push_back(2); cout<<l[0]; return 0; }
In C++, List containers are implemented as doubly-linked lists. They excel in performance when inserting and moving elements around, but they must be traversed. They lack direct access to the elements by their position. What you probably would rather have is a vector. Vectors allow for direct access: vector<int> l; int main() { l.push_back(2); cout << l[0]; return 0; }
71,976,700
71,976,728
Counting elements in an array greater than next element C++
Why is it giving wrong count In this question we have to find out how many elements are greater than the next element of an array #include using namespace std; int main() { //number of testcases int t; cin>>t; while(t--){ //taking number of elements in an array int n,count; cin>>n; //taking array int a[n]; count=0; for(int i=1;i<=n;i++){ cin>>a[n]; } //checking array for(int j=1;j<=n-1;j++){ if(a[j]>a[j+1]) { count++; } } cout<<count<<endl; } return 0; } Input 5 1 2 3 4 1 Expected Output 1 Output through above code 2
There are several problems with your code: Problem 1 You're going out of bounds of the array a which leads to undefined behavior, when you wrote cin >> a[n]; //undefined behavior Note that indexing of arrays starts from 0 instead of 1 in C++. Problem 2 In standard C++, the size of an array must be a compile-time constant. This mean the following is incorrect in your code: int n; cin>>n; int a[n]; //NOT STANDARD C++ BECAUSE n IS NOT A CONSTANT EXPRESSION Better would be to use std::vector instead of built in array. int n = 0; std::cin >> n; std::vector<int> a(n); //this creates a vector of size n //take input from user for(int& element: a) { std::cin >> element; } int count = 0; for(int i = 0; i< n - 1; ++i) { if(a[i] > a[i+1]) { ++count; } }
71,976,747
71,976,893
data structures access by index
-Vectors Linked Lists Maps Stack It is little confusing, when it says access, I did not quite understand what it meant. Started thinking about data structures , I know that arrays are indexed. Also know that vector can be accessed by index, but access by index? I think that got me confused
From memory, in c++: std::vector, std::string, std::array, std::deque, std::bitset, std::valarray, std::span (Not a container) So the answer is "Vectors"-ish.
71,976,905
71,976,948
Vector only contains one element
I'm making a Text Adventure in C++ as an attempt to learn the language. The player interacts using commands like look or travel north. So far I've got code that converts the text to lowercase and then splits it into a Vector. This works fine for one word commands, but when I go to implement longer commands I find that the length always = 1 and accessing over that returns in an error. Here's my code: //Input function. void Input() { const char delim = ' '; //Processing std::cin >> input; std::transform(input.begin(), input.end(), input.begin(), [](unsigned char c) { return std::tolower(c); }); std::vector<std::string> out; split(input, ' ', out); //Commands if (out[0] == "exit") exit(0); else if (out[0] == "help") Help(); else if (out[0] == "look") Look(); else if (out[0] == "travel" || out[0] == "go") { //This code will never run. if (int(out.size()) == 2) { Travel(out[1]); } } } //Split function void split(std::string const& str, const char delim, std::vector<std::string>& out) { std::stringstream ss(str); std::string s; while (std::getline(ss, s, delim)) { out.push_back(s); } } Any help would be vastly appreciated! Thanks, Logan.
Fun fact, when you do this: std::cin >> input; It reads characters up until the next whitespace character, and puts those into the string. That means input will only contain the first word you entered. Want to get the whole line? Well, clearly, you already know how to do that, just call std::getline: std::getline(std::cin, input);
71,977,106
71,977,125
seekp not seeking to proper location?
I have the following code: file.open(fileName, ios::in | ios::out | ios::binary); // many lines later file.seekp(fooAddr, ios::beg); printf("foo_addr: %d\n", foo_addr); file.write((char*)fooStruct, sizeof(FooStruct)); I know that fooAddr is 128 due to the printf. Yet, for some reason, when I open the target file in my hex editor, the first byte is written at location 80. Is this possible? Or is there some bug I am overlooking in my program? I guess, for context, all my file operations are wrapped in a macro that checks if file.goodbit is not 0 (truthy), and if so -- the program immediately exits after printing an error.
Your hex editor is displaying file offsets in hexadecimal format, not in decimal. Decimal 128 is hex 0x80.
71,977,651
71,977,844
attempting to specialize template function with non-type argument in C++
I have a templated function, which takes an array reference as a parameter: template<typename T, int arrSize> void foo(T (&pArr)[arrSize]) { cout << "base template function" << endl; } I want to specialize this function for C-strings: template<const char *, int arrSize> void foo(const char * (&pArr)[arrSize]) { cout << "specialized template function" << endl; } I try to instantiate the base and the specialization: int main(int argc, const char **argv) { float nums[] = {0.3, 0.2, 0.11}; const char *words[] = {"word1", "word2"}; foo(nums); foo(words); } But I only seem to get the base instantiation: ./foo base template function base template function I have compiled this on a Mac using clang++ with -std=c++17.
The problem is that the 2nd overloaded function template that you've provided has a non-type template parameter of type const char* that cannot be deduced from the function parameter. So to call this overloaded version we have to explicitly provide the template argument corresponding to this non-type parameter. To solve this just remove the first non-type template parameter as shown below: template<typename T, int arrSize> void foo(T (&pArr)[arrSize]) { std::cout << "base template function" << std::endl; } //overload for C-strings template< int arrSize> void foo(const char (&pArr)[arrSize]) { std::cout << "single C-string overloaded version" << std::endl; } //overload for array of pointers to C-strings template<std::size_t arrSize> void foo(const char*(&pArr)[arrSize]) { std::cout<<" array of pointers to C-string version"<<std::endl; } int main(int argc, const char **argv) { float nums[] = {0.3, 0.2, 0.11}; const char words[] = {"word1"}; const char* wordPtrs[] = {"word1", "word2"}; foo(nums); //calls base foo(words);//calls single C-string version foo(wordPtrs);//calls array of pointers to C-string version } Demo Also note that function templates cannot be partially specialized but they can be fully specialized or they can be overloaded.
71,977,913
71,977,953
Why does std::sort work when the comparison function uses greater-than (>), but not greater-than-or-equal (>=)?
On WIN32, Visual Studio 2022. When I define a vector<int> containing one hundred 0s and sort it with the code below, an exception "invalid comparator" throws. vector<int> v(100, 0); sort(v.begin(), v.end(), [](const int& a, const int& b) { return a >= b; }); However, if I use return a > b, it will execute well. Why is that?
This is just how it is required to work. You need strict weak ordering. For the rationale, I believe that the sufficient explanation is that this enables you to determine whether those elements are equal (useful for e.g. std::sets). <= or >= can't do that. <= or >= can also do that, but it seems like it was just decided to use < instead of any other relation. With this decision in mind, standard library facilities are implemented and they heavily rely on it.
71,977,976
71,978,241
Inlined requires-expression for SFINAE, and using as constexpr bool
TL;DR: My question is that requires {...} can be used as a constexpr bool expression by the standard? I haven't found anything about that in the standard, but it simplifies a lot and results a much cleaner code. For example in SFINAE instead of enable_if, or some ugly typename = decltype(declval<>()...), or something else, it is a simple clean requires-expression. This is my example: #include <type_traits> struct foo { typedef int type; }; struct bar { ~bar() = delete; }; /** * get_type trait, if T::type is valid, get_type<T>::type * equal to T::type, else void */ // T::type is valid template<typename T, bool = requires{typename T::type;}> struct get_type : std::type_identity<typename T::type> {}; // T::type is invalid template<typename T> struct get_type<T, false> : std::type_identity<void> {}; /// Template alias, this is buggy on GCC 11.1 -> internal compiler error template<typename T> using get_type_t = typename get_type<T>::type; // Tests static_assert(std::is_same_v<get_type_t<foo>, int>); static_assert(std::is_same_v<get_type_t<bar>, void>); /** * Destructible trait * * In libstdc++-v3 this is the implementation for the testing * * struct __do_is_destructible_impl * { * template <typename _Tp, typename = decltype(declval<_Tp &>().~_Tp())> * static true_type __test(int); * * template <typename> * static false_type __test(...); * }; */ // This is the same: template<typename T> struct my_destructible_impl : std::bool_constant< requires(T t) { t.~T(); } > {}; // Tests static_assert(my_destructible_impl<foo>::value); static_assert(!my_destructible_impl<bar>::value); I found that it will evaluate to true or false if I'm correct: The substitution of template arguments into a requires-expression used in a declaration of a templated entity may result in the formation of invalid types or expressions in its requirements, or the violation of semantic constraints of those requirements. In such cases, the requires-expression evaluates to false and does not cause the program to be ill-formed. The substitution and semantic constraint checking proceeds in lexical order and stops when a condition that determines the result of the requires-expression is encountered. If substitution (if any) and semantic constraint checking succeed, the requires-expression evaluates to true. So I would like to ask if requires {...} can be safely used as a constexpr bool expression as in my example, or not? Because based on cppreference.com I'm not 100% sure, but I feel like it is and it compiles with clang and GCC. However in the standard I haven't found anything about that (or maybe I just can't use ctrl+f properly...). And I haven't found anything where someone use the requires-expression like this...
requires {...} is a requires-expression and according to expr.prim.req/p2 it is a prvalue: A requires-expression is a prvalue of type bool whose value is described below. Expressions appearing within a requirement-body are unevaluated operands. So yes, you can use it in a constexpr bool context.
71,978,335
71,978,837
class template's constructor declaration doesn't compile for C++20 but compiles for C++17
I am learning about templates in C++. In particular, i saw here that we can have the following declaration for the constructor: template<typename T> struct Rational { Rational<T>(); }; But the above snippet fails to compile in C++2a and compiles successfully for C++17. Is this a compiler bug or there is a reason why it doesn't compile for C++2a and C++2b. If there is a reason then what is it. I want to know which clauses(if any) from the standard allow/prevent the following examples to compile. Since i have tested the above example with C++17 and C++20 so i am looking for citation from only these two standard versions.
It is not a bug. It is the consequence of a change in the standard. Affected subclauses: [class.ctor] and [class.dtor] Change: A simple-template-id is no longer valid as the declarator-id of a constructor or destructor. Rationale: Remove potentially error-prone option for redundancy. Effect on original feature: Valid C++ 2017 code may fail to compile in this revision of C++. For example: template<class T> struct A { A<T>(); // error: simple-template-id not allowed for constructor A(int); // OK, injected-class-name used ~A<T>(); // error: simple-template-id not allowed for destructor }; There is however a bug report, that was initially closed and then reopen with the intention of improving the diagnostics message.
71,978,346
71,978,403
Clion compile with -O3
I'm writing a c++ program using CLion and I need to specify -O3 flag on the compiler, using set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" -O3) on the CMakeList file does not work. Is there a way to do it?
Use either add_compile_options(-O3) to add it globally or target_compile_options(YourTarget -O3) to add it locally to a specific target. You could also do it by using CMAKE_CXX_FLAGS but that is a pretty old way of doing things in CMakeLists files, that's how it would look like: set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3") or set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -O3).
71,978,743
71,978,915
How to DLLImport function with array return type in c#?
Here it is: static uint8_t* Compress(const uint8_t* input, uint32_t inputSize, uint32_t* outputSize, int compressionLevel); I've tried : [DllImport("Mini7z.dll")] public static extern byte[] Compress(byte[] input, uint inputSize, out uint outputSize, int compressionLevel); and this [DllImport("Mini7z.dll")] public static extern byte[] Compress(byte[] input, uint inputSize, uint* outputSize, int compressionLevel); but nothing seems to work
You need to tell the marshaller the size of the array he needs to generate upon return from the function. Therefore you need to specify an attribute on the return value. Try this: [DllImport("Mini7z.dll")] [return:MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 2)] public static extern byte[] Compress(byte[] input, uint inputSize, [In, Out] ref uint outputSize, int compressionLevel); Note that this leaks the buffer. You need to call another method to free it. Eventually, you need to use an IntPtr as return type and do the marshalling manually to be able to return the memory correctly. Since the managed type byte[] cannot be converted back to the original pointer that was returned, you should do something like this: [DllImport("Mini7z.dll")] public static extern IntPtr Compress(byte[] input, uint inputSize, [In, Out] ref uint outputSize, int compressionLevel); [DllImport("Mini7z.dll")] public static extern FreeMemory(IntPtr memory); // or however the method is named // Then, use like this: IntPtr data = Compress(input, inputSize, ref dataSize, 9); byte[] managedData = new byte[dataSize]; Marshal.Copy(data, managedData, 0, dataSize); FreeMemory(data);
71,979,212
71,979,239
error: a function-definition is not allowed here before ‘{’ token
I've been trying to solve the error. How do I solve it? I've tried putting the functions outside the main function but its still not working. int mutexlock = 1, full = 0, emp = 20, x = 0, buffer[100]; void producer(); void consumer(); int randomgenerator(); int main() { void producer() { int d = randomgenerator(); buffer[x] = d; cout << "\n" << d; x++; } void consumer() { x--; cout << "\n" << buffer[x] << endl cout << "sum" << buffer[x] << (buffer[x] + buffer[x]); } int randomgenerator() { int num = rand() % 6 + 1; return (num); } } Error: error: a function-definition is not allowed here before ‘{’ token {
You should put all functions out of the main function. Besides, please put the code you want to run after program starts in the main function. Example: int main() { producer(); consumer(); }
71,979,351
71,979,383
Why does p3 need a default constructor in this example?
Let's say I have C++ code like this: //main.cpp #include "p3.h" #include "tri3.h" int main() { p3 point1(0.0f, 0.0f, 0.0f); p3 point2(1.0f, 0.0f, 0.0f); p3 point3(2.0f, 0.0f, 0.0f); tri3 triangle(point1, point2, point3); } //p3.h #pragma once class p3 { public: float _x; float _y; float _z; p3(float x, float y, float z) { _x = x; _y = y; _z = z; } }; //tri3.h #pragma once #include "p3.h" class tri3 { public: p3 _p1; p3 _p2; p3 _p3; tri3(p3 p1, p3 p2, p3 p3) { _p1 = p1; _p2 = p2; _p3 = p3; } }; The compilation fails with the following error in Visual Studio 2022: error C2512: 'p3': no appropriate default constructor available When I edit "p3.h" like this, the compilation is succesfull with no errors: //p3.h #pragma once class p3 { public: float _x; float _y; float _z; p3(float x, float y, float z) { _x = x; _y = y; _z = z; } p3() = default; // <-- Adding this makes the program compile just fine }; In the Microsoft documentation about error C2512, there is an example of an object being created with no arguments and because it has no default constructor, this error occurs. However, in this example, I create my objects by passing all necessary arguments. Why do I still need a default constructor?
tri3(p3 p1, p3 p2, p3 p3) The constructor fails to initialize its class's _p1, _p2, and _p3 members, therefore they must have a default constructor. _p1 = p1; _p2 = p2; _p3 = p3; This is not construction. This is assigning to existing objects. They are already constructed. To properly construct class members you must use member initialization in the constructor declaration itself. tri3(p3 p1, p3 p2, p3 p3) : _p1{p1}, _p2{p2}, _p3{p3} { } There are a number of important rules that you must follow, when it comes to properly using member initialization, see your C++ textbook for more information.