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,285,611
71,286,009
Working with threads in c/c++, across many different platforms
In my understanding, if you use C, then you are bound to use POSIX Threads. These are OS dependent, and if you use Linux, you have to use <pthread.h>, while if you use Windows, you have to go with <windows.h>. These things are transferable to C++ as well. However, if you use C++ and specifically a version after C++11, ...
Since C11, there is a support of threads directly in the standard C language (using threads.h). Note that mainstream compilers (Clang, GCC, ICC, MSVC) support OpenMP which can be used to parallelize computing codes using multiple threads (typically numerical codes). OpenMP is available in both C and C++ (as well as FOR...
71,285,757
71,285,881
Why isn't my brute-force string match algorithm display an output?
Here is the source code of the bfSM algorithm. The program should display the starting index of the part where a total match with the pattern is found, or -1 if there are no matches in the given text. I tried including all the libraries i've used thus far while programming but when I debug the program nothing is displa...
You never print the result, which is the reason you cannot see any result. In the main function, replace bruteForceSM(pattern, text); with cout << "Index at which pattern is found: " << bruteForceSM(pattern, text) << endl; This will print Index at which pattern is found: 15 As an additional general advice: never use...
71,286,002
71,286,186
std::ranges::remove still not suported / broken on clang trunk when using libstdc++?
Works fine on gcc trunk, but not on clang trunk, both with libstd++. Or am I missing something exceedingly obvious? Godbolt #include <algorithm> #include <iostream> #include <ostream> #include <vector> std::ostream& operator<<(std::ostream& os, const std::vector<int>& v) { for (auto&& e: v) os << e << " "; r...
This seems to be a Clang bug, affecting ranges when using libstdc++, see this issue with the underlying cause which is still open and other issues linked to it as duplicates with examples how it affects ranges with libstdc++. There seems to have been some work on it about two weeks ago. In libc++ std::ranges::remove do...
71,286,053
71,286,155
google::protobuf::io::GzipOutputStream does not write anything if the file handle is closed at the end
The following code writes to file as expected int ofd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0777); google::protobuf::io::FileOutputStream outp(ofd); google::protobuf::io::GzipOutputStream fout(&outp); MyMessage msg; ConstructMessage(&msg); CHECK(google::protobuf::util::SerializeDelimitedT...
You should close things in the opposite order of opening: int ofd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0777); google::protobuf::io::FileOutputStream outp(ofd); google::protobuf::io::GzipOutputStream fout(&outp); ... fout.Close(); outp.Close(); close(ofd); With the missing outp.Close();, some data ...
71,286,460
71,286,709
C++ implement class constructs instance of another classes depending on string it consumes
I need to implement one abstract class, three its concrete subclasses, class which goal to create one of this three classes instances and last class executor of three classes. Requirements are c++98, and not to use if/elseif/else to construct class instance, like i did in a Maker class method make Form. What mechanism ...
You could typedef a pointer to function and then use a map from string to this type (pointer to function). And then use your parameter with indexer syntax to access the correct pointer to function. Here is an example: #include <iostream> #include <map> // The class definitions with a virtual function hello() common to...
71,286,510
71,286,536
Why do we return *this in asignment operator and generally (and not &this) when we want to return a reference to the object?
I'm learning C++ and pointers and I thought I understood pointers until I saw this. On one side the asterix(*) operator is dereferecing, which means it returns the value in the address the value is pointing to, and that the ampersand (&) operator is the opposite, and returns the address of where the value is stored in ...
this is a pointer that keeps the address of the current object. So dereferencing the pointer like *this you will get the lvalue of the current object itself. And the return type of the copy assignment operator of the presented class is A&. So returning the expression *this you are returning a reference to the current...
71,286,633
71,286,756
I need to print element of a struct that is itself in a map in c++
I have in c++ an include like that: struct my_struct { time_t time; double a, b, c, d; } typedef std::map<std::string, std::vector<my_struct> Data; In my code (for debugging issue) I want to print some of the values in Data for specific key. I don't remember the syntax and keep having errors. Here the kind of synt...
Look at the following line properly: typedef std::map<std::string, std::vector<my_struct> Data; As you can see the second element of the std::map is a list of my_struct. Now here: for (const auto& [key, value] : inputData) { if (key == "mytest") { std::cout << '[' << key << "] = " << value.a << std::en...
71,286,704
71,287,103
Invalid use of incomplete type for named template argument
I have the following class template: template<typename T=class idType, typename U=class uType> class f { std::unordered_map<T::Type, float> id_; // error! } I am using the dependency injection framework boost::di and I therefore need to name my template argument to be able to bind those templates to actual ty...
They are defined after I include the file containing the example above Yeah, that's not gonna work. While templates and class definitions do have some specific leeway in that they can sometimes reference things declared/defined after them, these are very specific cases. The bodies of class member functions can refere...
71,287,571
71,287,618
Access violation when writing to location inside of 2d array
Hi im doing some assignment that has to do with reading information from a file to write to a 2d int array. When accessing the index of the array to change the data at the point, it throws an exception that says access violation. The arrays has been pre declared in the global scope. int ImportMapDataFromFile(const char...
MapData[col][row] If you go back and review how this matrix was allocated, it looks like the indexes are reversed. The first dimension is the row, the 2nd one is the column. Either that, or change the dimensions' allocations: MapData = new int* [BINARY_MAP_HEIGHT]; // allocates the rows of the map data array These l...
71,288,178
71,288,211
Unqualified name lookup does not look in local namespace after using declaration
namespace A { int overloaded_f(float some_float); enum class Enum { Value }; } namespace B { int overloaded_f(A::Enum some_enum); int f(A::Enum some_enum){ using A::overloaded_f; // using B::overloaded_f; // return B::overloaded_f(some_enum) + overloaded_f(0.0f); return...
Does the code snippet fail to compile because name lookup ends as soon as a declaration is found for the name? You're correct. The lookup of overloaded_f in the expression overloaded_f(some_enum) has two components: The unqualified component: this stops searching outward as soon as it finds a declaration, which in t...
71,288,948
71,367,355
Using VCPKG with cmake and Qt 6 for Windows ARM64
Qt 6.2 introduced Windows on Arm support (https://bugreports.qt.io/browse/QTBUG-85820). I tried to create a new cmake project set up using Qt Creator and everything works fine. Then I wanted to add some external packages to my project using vcpkg. The standard way to use vcpkg with cmake is using the CMAKE_TOOLCHAIN_FI...
I found out that VCPKG provides a way to achieve this as explained here: To use an external toolchain file with a project using vcpkg, you can set the cmake variable VCPKG_CHAINLOAD_TOOLCHAIN_FILE on the configure line: cmake ../my/project \ -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake \ -DVCPKG...
71,289,256
71,289,370
no known conversion for argument 1 from 'int' to 'gnu_cxx::normal_iterator<int*, std::vector<int>>&&'. I'm unable to find a way to get my code working
I am trying to carry out a binary search to find the index of a specific element within the vector. I tried getting the first and last element and passing them to the variable high and low. I am getting some sort of conversion error. The error is below inside the BinarySearchVector funtion. #include <iostream> #includ...
Since your binarySearchVector function is supposed to return the index of the found element (not an iterator) you should probably not use begin() and end() (that return iterators, not indices). Example: int binarySearchVector(std::vector<int>& elements, int searchval) { std::sort(elements.begin(), elements.end()); ...
71,289,454
71,289,476
GCC throws "pure virtual method called", but not when optimizations are on
I have an abstract base class, ITracer, with pure virtual method logMessage. ITracer also has a virtual destructor. I have a derived class, NullTracer, which implements logMessage. I have a class, TestClass, whose constructor optionally takes a const-ref ITracer. If no ITracer is provided, a NullTracer is instantiated....
When the TestClass constructor creates a temporary NullTracer object, the const-reference parameter tracer ensures that the object lives only for the lifetime of the constructor call. When the constructor exits, the temporary object gets destroyed. Even though the m_tracer class member is also a const-reference, it DO...
71,289,523
71,289,560
How can I alloc member value with "Get" function?
Here's a simple code. class Sub { ... public: Sub() { ... } } class Main { private: Sub* m_pSub public: Main() { // I don't want construct "Sub" here m_pSub = nullptr; } Sub* GetSub() { return m_pSub; } } ///////////////////// /...
The simplest way to make your code work is to have GetSub() return a reference, eg: class Main { private: Sub* m_pSub = nullptr; public: Main() = default; Sub*& GetSub() { return m_pSub; } }; However, this isn't very good class design. Another option is to have GetSub() create the object...
71,289,536
71,297,979
Add or modify a nullptr Vector from a partially filled flatbuffer?
This builds off of the monster schema example. If I partially fill a flatbuffer such as in the official test.cpp. Relevant lines also copied below // Create a mostly empty FlatBuffer. flatbuffers::FlatBufferBuilder nested_builder; auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0, nest...
Disclaimer: Flatbuffers doesn't generally allow mutating a vector after the buffer has been finished. However, we do have some advanced APIs in the reflection API for doing such mutations, but are generally slow and not recommended. We don't support the case of resizing a null vector. We store null within the vtable an...
71,289,600
71,289,712
C++ 20 concept to accept a random access container but reject std::list
std::vector is known to meet the requirement of a RandomAccessContainer, so using the [] operator is constant time. However, std::list only meets the weaker requirements of a Container and ReversibleContainer, and hence retrieving an element is O(N), moreover the [] operator doesn't exist. I would like to constrain a t...
You could start with a type trait to check if the type supports subscripting: template<class T> struct has_subscript { static std::false_type test(...); template<class U> static auto test(const U& t) -> decltype(t[0], std::true_type{}); static constexpr bool value = decltype(test(std::declval<T>()))::...
71,289,825
71,289,930
How to count characters in a C_String in C++?
I'm a new Computer Science student, and I have a homework question that is as follows: Write a Function that passes in a C-String and using a pointer determine the number of chars in the string. Here is my code: #include <iostream> #include <string.h> using namespace std; const int SIZE = 40; int function(const char...
First of all welcome to stackoverflow ye0123! I think you are trying to rewrite the strlen() function here. Try giving the following link a look Find the size of a string pointed by a pointer. The short answer is that you can use the strlen() function to find the length of your string. The code for your function will l...
71,289,889
71,289,926
Simplifying a code snippet - vector rotation in a circle
Given the following code pattern, wherein I am trying to state a vector direction in increments of 45 degrees over the integers int x and int y, inside of a circle positioned at the origin // x == 0 && y == 0 case is already taken cared of if(x > 1) { if(y == 0) { // horizontal right m_rotation = ...
Something like constexpr int rotation[3][3] = { {225, 180, 135}, {270, 0, 90}, {315, 0, 45}, }; if (x != 0 || y != 0) // if (!(x == 0 && y == 0)) m_rotation = rotation[1 + sign(x)][1 + sign(y)];
71,290,175
71,290,241
Combine multiple boost::asio::const_buffer into a single buffer
My program receives data in the form of std::vector<boost::asio::const_buffer> buf_vect. I need to combine the const_buffer in the vector into a single buffer which will then be converted to a std::string for further processing. First attempt: size_t total_size = 0; for (auto e : buf_vect) { total_size += e.size();...
std::vector<boost::asio::const_buffer> buf_vect That satisfies the criteria for a ConstBufferSequence [I need to combine the const_buffer in the vector into a single buffer which will then be converted to] a std::string [for further processing] Let's skip the middle man? std::string const for_further_processing(asi...
71,290,245
71,315,566
How can I set a stack panel's border color programmatically in C++ in WinUI3?
I am working on a project using WinUI 3 in C++, and I want to change the border color of a XAML control(e.g. stackpanel) according to some condition. I have tried search it online, but most of answers are in c#, and some in C++ I have tried but got no luck. For example: ("StackPanel" is defined in the xaml ) StackPanel...
From what I'm seeing the actual error (as best as i can replicate what you're doing) is Severity Code Description Project File Line Suppression State Error C2664 'void Windows::UI::Xaml::Controls::StackPanel::BorderBrush::set(Windows::UI::Xaml::Media::Brush ^)': cannot convert argument 1 from 'Windows::...
71,290,448
71,290,471
C++ Left Shift Operation Bit Manipulation
I am not able to get why it is giving negative after certain point. Also I am using long long to prevent overflow. Code #include <iostream> using namespace std; int main() { for(long long i=0;i<64;i++){ cout << 1LL*(1<<i) << " "; } return 0; } Output 1 2 4 8 16 32 64 128 256 512 1024 204...
1 << i ..in the above line, 1 is an int and i is a long long. So to fix your issue you can cast to a long long as such: #include <iostream> using namespace std; int main() { for (long long i = 0; i < 64; i++) { cout << 1LL * (static_cast<long long>(1) << i) << " "; } return 0; } This will allow...
71,290,668
71,302,645
Time Complexity Analysis of a function
What is the time complexity of this following function? I am confused between O(log n) and O(sqrt(n)). map<long long int,long long int> mp; void PrimeFactorization(long long n) { while(n%2==0) { n/=2; mp[2]++; } for(long long int i=3;i<=sqrt(n)+1;i+=2) { while(n%i==0) ...
This runs in O(sqrt(n)). Technically, it's O(sqrt(n) + log(n)log(log(n))), but that log factor isn't really that big of a deal (and you can get rid of it by using an unordered map). Think of the worst case: If n is prime, then the loop from 3 up to sqrt(n) will just spin all the way up to its limit. This isn't even muc...
71,291,961
71,291,980
Iterate through optional vector in C++
I have an optional vector like optional<std::vector<string>> vec = {"aa", "bb"}; How can I iterate through the vector? Doing the following: for (string v : vec) { cout<<v<<endl; } gives the error: error: no matching function for call to ‘begin(std::optional<std::vector<std::__cxx11::basic_string<char> > >&)’ ...
Use the dereference operator on vec. for (string v : *vec) { cout<<v<<endl; } Note that your program will exhibit undefined behavior with this if vec.has_value() == false. So... check for that first.
71,292,311
71,292,494
how to solve a violation Error using a method
I am getting such a weird violation error by using the getAt() method. I use the method in this order: OdDbBlockTablePtr w_kOdBlockTablePtr ; bool lbCreateDefaults = false; OdDb::MeasurementValue lkMeasurement = OdDb::kEnglish; OdDbDatabasePtr pDb; // Datenbank initialisieren pDb = g_Ex...
That's not weird at all. If you hover your mouse over pkTablePtr, you will almost certainly find that it is nullptr (or the debugger might report this as 0). There's not enough information in your question to say why this might be, but since you are already running under the debugger you can walk through your code and...
71,292,498
71,301,452
Vulkan hpp header bloating compile times, looking for a workaround
I used clang's ftime-trace to profile the compilation of time of my program. Turns out that about 90% of the time is spent parsing the massive vulkan.hpp header provided by the khronos group. This in turn means that if I minimize the inclusion of this header on header files and put it only on cpp files my compile times...
There are some ways to mitigate the issue on your side. vulkan_handles.hpp exists First, there are several headers now (there did not used to be, this was a huge complaint in virtually every vulkan survey). This does not completely mitigate the issues you have (the headers are still massive) but you don't have to incl...
71,292,698
71,294,890
Minimal working example Ctypes and cmakes: function not found
I'm trying to create a minimal working example to run c++ code in python, while using Cmake and Ctypes. These are my files: get_five.cpp extern "C" { int get_five(){ return 5; } } get_five.py import ctypes import os dir_path = os.path.dirname(os.path.realpath(__file__)) dll_file = os.path.join(dir_pat...
The function get_five was not exported. The following MWE works correctly: get_five.cpp extern "C" { __declspec(dllexport) int __cdecl get_five(){ return 5; } } get_five.py import ctypes import os dir_path = os.path.dirname(os.path.realpath(__file__)) dll_file = os.path.join(dir_path,'get_five.dll') ...
71,292,753
71,292,838
What's the difference between std::vector and dynamic allocated array?
I have wrote two functions to compare the time cost of std::vector and dynamic allocated array #include <iostream> #include <vector> #include <chrono> void A() { auto t1 = std::chrono::high_resolution_clock::now(); std::vector<float> data(5000000); auto t2 = std::chrono::high_resolution_clock::now(); float *p...
First, note that the std::vector<float> constructor already zeros the vector. There are many plausible system-level explanations for the behavior you observe: One very plausible is caching: When you allocate the array using new, the memory referenced by the returned pointer is not in the cache. When you create a vector...
71,293,303
71,293,723
GNU gettext ignores set locale
I'm trying to use GNU gettext in a C++ program running on MS Windows. I manage to set the locale as for instance char *locale = setlocale(LC_ALL, "French_France.1252"); I check the returned string so I know it took. Then I set the environment as textdomain("Test"); bindtextdomain("Test", "C:\\develop\\test\\executables...
As far as I can remember in Windows you also have to set the thread locale using SetThreadLocale (you will have to map to the locale ID, take a look at this webpage). Finally, take into consideration that in Windows each thread has its own locale; set it for all threads using translations.
71,293,665
71,294,882
Implementing strdup() in c++ exercise from Bjarne's Book, copying char* to another char* then print out gets nothing
I'm learning c++ using the book:Programming Principles and Practice using C++ by Bjarne Stroustrup. In Chapter 19, exercise 1 implement strdup() functions which will copy a c strings into another using only de-referencing method (not subscripting). My copying doesn't print anything I've been look for answers for days. ...
using only de-referencing method (not subscripting) So this is already wrong, because is uses the subscript operator []: // count the size int n {0}; while(q[n]) { ++n; } I just don't know how to turn the pointer back to the first char. Well, there are two basic approaches: stop damaging y...
71,294,659
71,331,228
How to get mac address
i'm working on a uwp app runing on hololens2, i want get the wifi mac address. according to this documents: Windows.Networking, i wrote this code. // part of includes at pch.h #include <winrt/Windows.ApplicationModel.Activation.h> #include <winrt/Windows.ApplicationModel.Core.h> #include <winrt/Windows.Foundation.h...
How to get mac address for hololens2. For this scenario, you could use GetAdaptersAddresses method to approach. The document has simple code that you could refer.
71,295,094
71,295,807
How can I implement a custom iNode on linux?
So every directory, file, queue or whatever in Linux creates it's own inodes that can be accessed in one way or another. How would I go about implementing my own inode type that doesn't quite fit any of the existing descriptions? A custom something that is visible in the file system but isn't a file? Do I have to exten...
So every directory, file, queue or whatever in Linux creates it's own inodes that can be accessed in one way or another. False. Directories, files etc. do not create their own inodes. They are stored with use of inodes belonging to the filesystem on which they are stored. The inodes are not even created specifical...
71,295,342
71,393,074
C++ function in DLL called through Excel / VBA generates exception when passing double argument
I'm trying to use a C / C++ static function in Excel / VBA through a DLL. I'm getting an exception when debugging in VS17, and I suspect it's an issue with the way the argument is passed (it's a double) Exception thrown at 0x00007FFA28BBA14F (kernel32.dll) in EXCEL.EXE: 0xC0000005: Access violation reading location 0x...
I have successfully ran your code exactly without any problem on my computer. My VBA script: Private Declare PtrSafe Function get_sum_cpp Lib "D:\Codes\VC\TestVBA\x64\Debug\Dll2.dll" (ByVal my_var As Double) As Double Sub testSum() Dim A As Double Dim Asum As Double A = 5 Asum = get_sum_cpp(A) ...
71,295,439
71,295,690
GCC 11.x vexing-parse + inconsistent error (redeclaration as different symbol type), is it a GCC bug?
The following code compiles with no problems from GCC 4.7.1 up to but not including GCC 11.1: constexpr int SomeValue = 0; void test () { void (SomeValue) (); } On GCC 11.x it fails with: <source>:4:23: error: 'void SomeValue()' redeclared as different kind of entity 4 | void (SomeValue) (); | ...
The difference is that your first snippet declares a function that exists globally; all your other declarations are of local entities. (Note that even if the declaration were valid, you couldn't call that function, since it can't exist.) In the last snippet, closure is not a type, so it can't be a declaration.
71,295,518
71,854,368
Change QDateEdits behaviour on select all
I am learning Qt (in C++) and I have a question regarding the QDateEdit. I want to be able to type after selecting the text in my QDateEdit. By default you cannot type if you select the whole date. I am sure there is an easy way to do that. How can I change the behaviour to start at the beginning of my QDateEdit instea...
In case anyone else has the same problem, the solution is rather simple. Currently I am using the QDateTimeEdit. You can override the "keyPressed" method, check for "ctrl+a" and use the "setSelectedSection" method with "sectionAt(0)" which allows the user to start typing at the beginning of the QDateTimeEdit.
71,295,538
71,295,789
Passing a non-static method or std::function<void(...)> as a void (*) argument
I'm trying to define a function/method (void MyClass::myDispatcher(int, int, void *) or std::function<void(int, int, void *)> myDispatcher) which would be a member of a host class. However, I also need to pass this function to through an external library which takes as argument: void (*dispatcher) (int, int, void *). I...
As stated, this is not possible since there is no way to meaningfully construct a plain function pointer from a (non static) method, a closure, or a std::function object. Roughly speaking, each of the constructs above are logically formed by two parts: some fixed code (a pointer to a fixed, statically known function), ...
71,296,091
71,298,269
Question regarding time complexity of nested for loops
Let n be a power of 2. int sum = 0; for (int i = 1; i < n; i *= 2) for (int j = 0; j < n; j++) sum += 1 Is the time complexity O(N) or O(nlogn). Thanks!
So first of all, it isn't necessary to know what kind of number is n is, since the asymptotic complexity is dependent of any arbitrary n(as long it is a positive integer). We also know that the inner loop will do n iterations, hence we can denote the inner loop the time complexity of O(n). About the outer loop. We know...
71,296,302
71,296,975
‘numeric_limits’ is not a member of ‘std’
I am trying to compile an application from source, FlyWithLua, which includes the sol2 library. I am following the instructions but when I run cmake --build ./build I get the following error: In file included from /home/jon/src/FlyWithLua/src/FloatingWindows /FLWIntegration.cpp:10: /home/jon/src/FlyWithLua/src/third_p...
/home/jon/src/FlyWithLua/src/third_party/sol2/./upstream/sol.hpp:7194:59: error: ‘numeric_limits’ is not a member of ‘std’ 7194 | std::size_t space = (std::numeric_limits<std::size_t>::max)(); This error message implies that src/third_party/sol2/./upstream/sol.hpp header uses std::numeric_limits...
71,296,412
71,296,727
C++ reading a file which contains nulls
I'm reading a file a RSA encrypted binary file which contains nulls. The file is encrypted and saved in python, then read in c++. Python treats it fine, reading and writing it just displays the nulls as ...\x94\x00\xbf... However, in my C++ it terminates it early. FILE* fpy = fopen("test.txt", "rb"); unsigned char* s...
Continuing the code: FILE* fpy = fopen("test.txt", "rb"); unsigned char* signPy = (unsigned char*)malloc(256); int const count = fread(signPy, 1, 256, fpy); fclose(fpy); // cout << signPy << endl; for (int i = 0; i < count; ++i) putchar(signPy[i]); Problem was that cout will treat signPy as null terminated char buff...
71,297,185
71,298,757
Adding xml-comments to boost::property_tree
I am using boost::property_tree::xml_parser to create an xml-file. Now I also need to add comments to the xml-file. I've done some research and found out that comments are not allowed in JSON, and thus also not supported by the boost::property_tree::json_parser... Furthermore I found out, that there is a no_comments fl...
If comments are not disabled with the mentioned flag, they get represented as nodes named <xmlcomment> (just like attributes are under nodes named <xmlattr>): Live On Coliru #include <boost/property_tree/xml_parser.hpp> #include <iostream> int main() { boost::property_tree::ptree pt; pt.put("some.node.<xmlattr...
71,297,314
71,297,446
Is uncaught exception message guaranteed
Is the following code #include <stdexcept> int main() { throw std::runtime_error("foobar"); } guaranteed to produce the following outout? terminate called after throwing an instance of 'std::runtime_error' what(): foobar fish: Job 1, './a.out' terminated by signal SIGABRT (Abort) Can I rely on this exact outp...
No it is not guaranteed, it unspecified whether there is any message. From cppreference: If an exception is thrown and not caught, including exceptions that escape the initial function of std::thread, the main function, and the constructor or destructor of any static or thread-local objects, then std::terminate is cal...
71,297,521
71,297,552
Why character need 1 byte and not 4?
Character have an ASCII code which is a number(integer). Then why it only takes 1 byte and not 4 bytes "like an int value" to store it in the memory.
ASCII is a 7 bit encoding. Most modern CPU have an 8 bit byte. On a system with 8 bit byte, a single byte is sufficient to represent a character of a 7 bit encoding. There is no need to use more bytes than one.
71,297,640
71,300,469
Do changes in GCC mangling affect ABI compatability?
Documentation for -fabi-version says this[only part here]: [...] Version 11, which first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the ...
Yes, each ABI version is incompatible, but most of the changes affect only rare cases, and hopefully certain versions like 12 are rare because they were fixed quickly. The reason such changes are made at all is usually that certain things mangle to the same name, which breaks even if only one component uses it rather ...
71,298,056
71,298,171
Undefined symbols: "BankAccount::BankAccount( ... "
i'm new to c++ and am learning from a course. I trying to write a program using classes to store bank info. This is how my class is set up. #include <iostream> using namespace std; class BankAccount { private: double balance = 0; int acountNumber = 0; string ownerName; double interestRate = 0; public...
Implement your constructors as such: BankAccount() {} BankAccount(double balance, double interestRate, int acountNumber, string ownerName) : balance(balance), interestRate(interestRate), acountNumber(acountNumber), ownerName(ownerName) {} Using an unimplemented function causes linker issues.
71,298,203
72,319,524
How to use GstReferenceTimestampMeta properly
My goal is to attach timestamps to GstBuffer which is independent of GST time. I found GstReferenceTimestampMeta, which looks exactly what I am after. However I have some issues when trying to utilize it. Maybe I have misundestood the usage of the GstMeta structure. Brief overview of pipeline: server: appsrc -> h265enc...
as far as I know, GstMeta data is intra-pipeline only. If you need an inter-pipeline solution, you need to implement it in the coded (H.264, H.265, ...) or in the RTP header. Cheers,
71,298,250
71,298,335
Passing parameter to a constructor
I created a class vector in C++ and then tried to use an vector object in a different class called abc. What I want to do is define a object in class abc of type vector Something like this: #include <iostream> using namespace std; class vector{ public: double icomponent=1; double jcomponent=1; double kcom...
You cannot do what you are trying to do in the way you've defined. Essentially, you cannot pass the variables i, j, and k to the constructor for velocity in such a manner. You need a constructor. Example: class abc { double i, j, k; vector velocity; public: abc( double i, double j, double k ) : i{i}, j{j}, ...
71,298,728
71,298,836
Metafunction as member function parameter
Currently my code has this form: template <typename T> class A { private: T data; public: void apply_process(A<T> obj, std::function<T(A<T>&)> process) { data = process(obj); } // ... }; This works with runtime lambdas; yet, while obj will be only known on runtime,process will be known at compile time. Ca...
It is not clear what you want, but by combining up the keywords you are throwing, I think you want this: template <typename T> class A { private: T data; public: template<class UnaryFunction> void apply_process(A<T> obj, UnaryFunction process) { data = process(obj); } // ... }; to be a bit more pedantic...
71,299,167
71,299,417
c++ format unordered map with fmt::join
I'm trying to create a libfmt formatter for a std::unordered_map<std::string, Foo> using fmt::join but I can't seem to get it to work: #include <fmt/core.h> #include <fmt/format.h> #include <unordered_map> struct Foo{ int a; }; using FooPair = std::pair<std::string, Foo>; using FooMap = std::unordered_map<std::stri...
Here is fixed version: https://godbolt.org/z/r6dGfzesz using FooMap = std::unordered_map<std::string, Foo>; using FooPair = FooMap::value_type; Problem is this: using FooPair = std::pair<std::string, Foo>;. Note documentation of unordered_map: std::unordered_map - cppreference.com value_type std::pair<const Key, T> ...
71,299,247
71,299,304
Inserting an element in given positions (more than one) of a vector
I am trying to add a certain value in loop to a given position of a certain vector. For example: the value is 11 and hence local_index = 11 The vector of position I have in input is neigh = {5,7} The starting vector is Col={0,1,2,3,4,5,6,7,8,9,10} I want to have as output Col={0,1,2,3,4,5,11,6,7,11,8,9,10}. This is m...
Per the vector::insert() documentation on cppreference.com: Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The pas...
71,299,545
71,299,622
How Should I Define an Array of Pointers to Functions in C++?
I'm trying to make an array of functions so I can call functions from the array with an index. I can't seem to figure out the parentheses, asterisks and brackets to create this array of functions. Here is what I have: void Game::getPawnMoves(int position, bool color, Move ** moveList) { ... } typedef void (*GetMov...
How Should I Define an Array of Pointers to Functions in C++? typedef void (*GetMoveFunction) (int, bool, Move **); This is a pointer to function. GetMoveFunction functions[] = { // ... }; This is an array of pointers to functions. You've achieved what you asked for in the title of the question. Game.cpp...
71,300,057
71,300,112
Initializing a pointer with 'this' keyword. Does it create new instance? Using it make my program thread-safe or not?
Here is a singleton design pattern. I am trying to make the given code thread safe, using thread_local. First of all, I need to know how the given instantiation of the pointer with 'this' works. File : Myclass.h class Student { public: Student(); int x; private: static Student *globalStudent; }; File...
globalStudent = this; // How this works? this is a special expression that yields a pointer to the object whose member function is being called. This assignment makes the assigned pointer point to the object whose member function is being called. Does it creates an instance? No, assigning a pointer doesn't create ...
71,300,163
71,310,291
How to create a window with CreateWindowEx but ignoring the scale settings on Windows
When I create a window with CreateWindowEx it will follow the resolution but also use the scale settings from the display settings. So, in 1920 x 1080 if I try to create the window, the size is actually 1200 something when scale is at 150%. Is there a way to get around this limitation? If I just set the size manually t...
Thanks to Remy Lebeau it was as simple as adding the following call to the main initialization of the app. Now I always get a window with the physical resolution and not a logic scaled resolution. SetProcessDPIAware();
71,300,438
71,300,481
How to initialize private variables in a different file and make it so it holds the value for other functions?
I just need to know how to have size, index, and counter keep their values when they are called in another function. Right now they are just being given random values when they are called instead of the values I'm initializing them with in the constructor. How can I fix this? The objective for this code is to make a pr...
You are defining new local variables inside of your Array constructor and shadowing the member variables of the same name -- which is why the value isn't being preserved. You only need to specify the type when defining new variables, but not when assigning to existing ones. To assign to the member variables, this shoul...
71,301,202
71,301,534
Why do I keep needing to rebuild solution in Visual Studio?
I'm new to Visual Studio, so I haven't gotten used to things yet. I've been using it for weeks with no problem, but today I've noticed that I have to click rebuild solution every time I make any changes to my code, otherwise it'll run an old version of the code. Is this a common thing? I've never had to do it until tod...
C++ has multiple stages, the compile stage to the link stage. If code changes, VS has to build (compile) and then link those changes into the app. If a library changes, then VS needs to link in the library changes. If you are having to rebuild everytime, then VS is detecting some type of change to either a C++ file or ...
71,301,568
71,301,669
Unable to trigger a duel to play out c++
Working on an assignment to have a duel play out amongst three players with varying accuracy and needs them to shoot in order. Aaron has an accuracy of 1/3, Bob has an accuracy of 1/2, and Charlie never misses. A duel should loop until one is left standing. Here is my code so far and it only ever causes the first two p...
look at the last line of shoot void shoot(bool& targetAlive, double accuracy) { double x; x = (((float)rand() / (float)(RAND_MAX)) * 1.0); if (x < accuracy) { cout << "target is hit!" << endl; targetAlive = false; } else cout << "missed!" << endl; cout << x << endl; targetAlive = true; <<<<==...
71,301,988
71,302,465
Shorten variadic parameter pack to N types
I would like to write a class that takes a size N (> 0) and a variable number of arguments (>= N). It should have a constructor that takes N arguments and a member std::tuple which has the same type: template <size_t N, typename... Args> struct Example { // A constructor taking N parameters of type Args[N], initializ...
To the extent I understand the question, it simply seems to be asking how to produce a tuple from arguments. Which, using Boost.Mp11, is a short one-liner (as always): template <size_t N, typename... Args> using Example = mp_take_c<N, std::tuple<Args...>>; Rather than Example<3, int, float, int, bool> being some type ...
71,302,065
71,302,143
Is there a way to modify another object's member directly from within one object's function?
all! This is my first post, so please be gentle. My code is meant to simulate a rudimentary version of transferring money from one bank account to another. My code is as follows: #include <cstdio> struct Account { virtual ~Account() {} virtual double get_balance() = 0; virtual double set_balance(double amo...
You've duplicated all your member variables in both types. When you attempt to modify balance directly, it's trying to modify Account::balance, but set_balance and get_balance will use UserAccount::balance since that's available in the scope where the virtual is implemented.
71,302,120
71,302,182
Why does my code ignore a large chunk of itself?
hey I've just started on a school project but can't figure out why the code just ignores a large chunk of itself. (also the code is part of a function inside of "math.h") ill paste the whole segment here so that debugging it is easier. #include <iostream> #include <chrono> #include <thread> #include <algorithm> using ...
Because of type mismatch! you defined "diff" as a char and use it as such in your switch statement. However, in your second switch statement, you remove the quotes and use it as a number. That causes a char to int conversion according to the ascii table. Look at the decimal field, the number 1 as an int corresponds to...
71,302,334
71,302,480
Convert vector<string> to char** for use in execvp
I have a vector named tokens that holds the command in tokens[0] and args as the rest of the vector. I am trying to convert the vector so I can make the call to execvp(args[0], args); Currently args[0] and args just print as memory addresses. char **args = (char**)malloc(tokens.size() * sizeof(string)); char *arg; ...
I found that the answer lies with adding the NULL terminator to the end of the vector so that execvp knows where to end pvec.data(); This is thanks to Fatih above. std::vector<char*> pvec(tokens.size()); std::transform(tokens.begin(), tokens.end(), pvec.begin(), [](auto& str) { return &str[0]; }); pvec.push...
71,302,765
71,302,894
Create struct array by a function C++
I want to create a function that creates an array of structures. What I have done is the following: struct Student { char studentNames[128]; unsigned int FN; short selectiveDisciplinesList[10]; unsigned short countOfSelectiveDisciplines; bool hasTakenExams; }; void fillInStudentInfo(Student...
You really cannot do what you are trying to do in that way: Student createStudentsArray() { ... Student studentsArray[countOfStudents]; ... return *studentsArray; } Firstly, this is using a variable length array, which strictly speaking is invalid C++. My compiler, for example, doesn't allow it. Second...
71,303,379
71,305,495
How to assign an enum for a switch case from UserInput string in C++
I'm writing this code that takes in a char userinput and uses the switch statement do execute the respective command. However because C++ switch statements can only read ints and enums, I'm not sure how to incorporate this. The user input must be a char. any ideas? I know charInput >> enumInput doesn't work but I'm not...
There's no need for an enum here. switch works with char because char is convertible to int. So if we define a char as such: char c = 'a'; ..and then switch on it: switch (c) This works because 'a' can be converted to int (ASCII value). So this can also be written as: switch (int(c)) // Same as switch (c) Example: #...
71,303,497
71,303,633
My attempt at Row-major order of array is showing correct values but indexing incorrect values
I have made a class called matrix that stores values in a 1D array, but outputs it as a 2D array. I have included print statements to show the exact values supposedly being put into the array however when I use the print function to index it, it shows incorrect value on the second row last index. not entirely sure what...
I changed your indexing logic and it seems okay. Still not getting why you use row * row + col instead of row * cols + col. Dynamic allocated the size of the matrix and layout the 2d matrix into 1d. Then you should use the length to fill the array, not (row index)^2. Live Demo #include <iostream> class Matrix { pr...
71,303,617
71,304,324
c++ testing if one file is older than a set of files
I am creating a cache for some data, but of course I want the cache to become invalid if any of the source files from which the cache is made is modified. TO that effect I made this function: bool CacheIsValid( const std::string& cache_shader_path, const std::vector<std::string>& shader_paths) { // This is ...
due to you want to find youngest_file_ts -> find most recently timestamp (greater number) of a changing file however double time_diff = difftime(youngest_file_ts, current_timestamp); if(time_diff > 0) youngest_file_ts = current_timestamp; // find greater number one after the for loop youngest_file_ts is oldest timesta...
71,303,668
71,303,962
Missing type despite forward declaration
I'm trying to create a basic factory function that returns a pointer to a forward-declared class, as follows below: #ifndef EQUATION_PLUGIN_HPP #define EQUATION_PLUGIN_HPP //! \file equation_plugin.hpp // \brief Definition of EquationPlugin #include <string> #include <shared_library.hpp> class Equation; class Plugi...
The issue is resolved. The error occurs here in a completely independent source file: ... #include <plugin_manager.hpp> #include <plugin.hpp> #include <equation_plugin.hpp> ... The plugin.hpp header, which is included before equation_plugin.hpp (where Equation is forward-declared), defines an enumerator, PluginType, w...
71,303,671
71,304,458
How to call Python from C++?
From the docs : cppyy is an automatic, run-time, Python-C++ bindings generator, for calling C++ from Python and Python from C++. (Emphasis mine) I don't see any instructions for doing the same, however, so is it possible to call Python via C++ using cppyy?
As a qualifier, since I don't know from where you obtained cppyy, the main code that was at the time the reason for typing that sentence does not exist in cppyy master, but does exist in its historic home of PyROOT. This so-called "class generator" plugin allows Cling to "see" Python classes as C++ classes, for straigh...
71,303,695
71,304,819
How to make a QTimer as Idle timer in qt using CPP
I am new to Qt programming, I want to make the timer an idle timer. The question is whether just setting the timer->start(0) will make the timer an idle timer? How can I know it's an idle timer.
I'd like to repeat the concerns of @Jeremy Friesner: On a general-purpose/multitasking OS (such as Qt usually runs under) you want to minimize your app's CPU usage so that any other programs that may be running can use those leftover CPU cycles (or in the case of a battery-powered device, so that the battery can be co...
71,303,725
71,304,078
Poco installed with vcpkg is missing ssl related header files
I use the command to install Poco. vcpkg.exe install openssl:x64-windows And openssl x64 is installed. When i use visual studio 2022, it show me that it can't found the file Poco/Net/SSLManager.h, and Other libraries related to ssl. Why is this happening? #include "Poco/StreamCopier.h" #include "Poco/URI.h" #include "...
Ok guys, i get the answer. when you install poco, just add this: vcpkg install poco[netssl]
71,304,093
71,304,357
Can I default class member functions and specify extra specifiers?
I have a problem where if I use my class as the element type in a vector it doesn't move it but rather constructs it and tries to copy assign it (I believe because the compiler sees certain functions as throwing exceptions). I don't want to redefine my own move constructor every time this happens, can I default the mov...
Yes, if functions are defaulted on their first declaration without noexcept specifier, then they will be noexcept(true) if and only if they don't contain anything potentially throwing. But if you add a noexcept specifier this will override it. Note my comments under your question though.
71,304,161
71,304,244
Why SFINAE report error in function overloading
Follwing code can't compile,I just want testing SFINAE,why it can't compile? #include <type_traits> template<typename T> class TestVoid { template<std::enable_if_t<std::is_void_v<T>> * = nullptr> void func() { std::cout << "void\n"; } template<std::enable_if_t<!std::is_void_v<T>> * = nullptr> ...
When you instantiate the class template, all of the member function declarations must be valid. In your case, one of them won't be. Instead, you can delegate func to another function template. live link template<typename T, std::enable_if_t<std::is_void_v<T>> * = nullptr> void func() { std::cout << "void\n"; } tem...
71,304,262
71,304,836
dynamic allcocation object and int c++
hello I have a doubt how does the code below works?? #include <iostream> using namespace std; int main() { int* arr = new int; arr[0] = 94; arr[1] = 4; cout << arr[0] << endl; } and why does this shows me a error what should I do #include <iostream> using namespace std; struct test { int data; }...
In your code: #include <iostream> using namespace std; int main() { int* arr = new int; arr[0] = 94; // This will work arr[1] = 4; // This will cause undefined behaviour cout << arr[0] << endl; } Int the above code, arr is a pointer to a single int, so you can access that one int using either: arr[0] ...
71,305,813
71,305,920
Is it undefined behavior to compare a character array char u[10] with a string literal "abc"
I came across this question on SO, and this answer to the question. The code is as follows: int main() { char u[10]; cout<<"Enter shape name "; cin>>u; if(u=="tri") //IS THIS UNDEFINED BEHAVIOR because the two decayed pointers both point to unrelated objects? { cout<<"everything is fine"; ...
Standard says: [expr.eq] The == (equal to) and the != (not equal to) operators group left-to-right. The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the operands... Hence, we are comparing pointers to the respective arrays...
71,306,043
71,306,334
verifyExists function is throwing a crazy amount of errrors
I'm making a wordle program for a class assignment and the basic concept is to load all 5 letter words in the English language from a text file into an array, then pick one randomly to be the correct one, and I have that part correct (probably isn't that efficient but it works for now). I need to verify the user input ...
Your code has a lot of problems in it: 1.Your includes are wrong and some of them are missing: #include <string> #include <fstream> #include <ctime> // There's no need of this. Just #include <iostream> and you should be good Here are the correct includes: #include <iostream> #include <string> #include <stream> 2.Max ...
71,306,261
71,313,745
Correct way to access functions defined in .exe from .dll
I have a VS solution with an executable and a DLL. In the executable (MAIN): __declspec(dllexport) void testExe() { printf("Hello from EXE"); } __declspec(dllimport) void DoStuff(); int main() { DoStuff(); } while in the .dll (DLL) __declspec(dllimport) void testExe(); __declspec(dllexport) void testDll() {...
Use GetModuleHandleW(NULL) to get the module handle of the executing EXE. Then use GetProcAddress to get the address of the function. Watch out for C++ name mangling and calling conventions (using __stdcall will add something like @4) changing the function name. To avoid the function name changing, use extern "C" bef...
71,306,268
71,306,446
Why is the return type of std::rand() not an unsigned int?
std::rand said, int rand(); Returns a pseudo-random integral value between ​0​ and RAND_MAX (​0​ and RAND_MAX included). Since it is guaranteed that a non-negative integer will be returned, why the return type is signed? I am not talking about if we should use it here. Is it a historical issue or some bad design?
There is much debate about unsigned. Without going too much into subjective territory, consider the following: What matters is not whether the value returned from rand() cannot be negative. What matters is that rand() returns a value of a certain type and that type determines what you can do with that value. rand() nev...
71,306,988
71,307,308
Use AllocateAndGetTcpExTableFromStack function in c#
How can I use that function in c# I need to use windows IP helper, to get specific process connections cause it wouldn't work like this [DllImport("Iphlpapi.dll", CharSet = CharSet.Ansi)] public static extern int AllocateAndGetTcpExTableFromStack(); Cause I get the err: System.EntryPointNotFoundExcepti...
According to the documentation, this function is 'no longer available'. The linked page suggests alternatives, you should use one of those. This function is no longer available for use as of Windows Vista. Instead, use the GetTcpTable or GetExtendedTcpTable function to retrieve the TCP connection table.
71,307,199
71,349,841
SFML square's off set
I am new to sfml/c++. I am trying to display a yellow square on a chess board at piece's first and last location. I succeed in that but my square isn't completely overlapped on the chess board's square. It's look kind an unnatural. here's my texture class and main function(with photo). main function: #include <SFML/Gra...
First, you don't need to load 4 texture files, since you are loading twice the same one (OLDsquare.png). You can just use setTexture() with the same sf::Texture for the two Sprites yellown and yellowo.(You can even make it only one file to load by putting all your textures in one file and telling the Sprites where to g...
71,307,295
71,307,513
Code using core issue 2118: why doesn't Clang see the function definition?
Sample code (taken from here [uses core issue 2118], slightly modified): #include <type_traits> template<int N> struct tag{}; template<typename T, int N> struct loophole_t { friend auto loophole(tag<N>) { return T{}; }; }; auto loophole(tag<0>); struct detector { template <typename T, int = sizeof(loophole_...
In your code return loophole(tag<0>{}); is not dependent on a template parameter. I am unsure at the moment whether the standard requires that the type of loophole(tag<0>{}) be deduced at the point of the template definition, which would make the program ill-formed, but even if it doesn't, this is ill-formed, no diagn...
71,307,728
71,307,765
Loop does not continue correctly
I have been programming in C++ for the past 3 years, and I have always used the continue keyword in loops with success. But right now, a simple code of mine with continue is not working properly. Here is the code that is showing the problem: int main() { int num = 2, result = 0; while (num > 1 && num < 50) ...
Loop is indeed continuing (continue works properly) correctly Initially, num = 2, so if condition fails and goes to else. So it will call continue. Then again the loop starts from the beginning with num = 2. This continues forever. In short, num value is not changing and if condition always fails.
71,307,892
71,310,222
What is the difference between non-export declarations and declarations in private module fragment?
On cppreference.com about modules it says about export: Module interface units can export declarations and definitions, which can be imported by other translation units. [ … ] All declarations and definitions exported in the module interface units of the given named module will be available in the translation unit usi...
What is the difference between putting something in the private module fragment than to just not exporting it The principle difference in terms of implementation is that non-exported definitions that are in a module interface can be imported by other pieces of code that are part of the same module (implementation uni...
71,308,047
71,309,240
Gmock: save a pointer of a passed argument or compare by address in expected call
Suppose I have a method void Mock::foo(const A& obj); and I want to check that it was called exactly with the object obj rather than its copy: A obj; EXPECT_CALL(mock, foo(obj)); mock->foo(obj); How can I check this? I found Address(m) matcher here. But I cannot find it in ::testing, i.e. it does not compile.
As mentioned in comments, ::testing::Address() matcher was introduced in GoogleTest 1.11. You can use instead ::testing::Ref() matcher, which does the same thing underneath (comparing addresses) and is available since at least GoogleTest 1.8 (see it online): #include <gmock/gmock.h> struct Data {}; struct Mock { ...
71,308,403
71,308,495
How to replace characters of a string in c++ with a recursive function?
Hello I'm a beginner in cpp programming. I was reading some examples of cpp programs and i see this question but i couldn't solve it : There's an algorithm below starting from 0 as each step that goes forward you should replace all 0's with 01 and 1's 10. The input is the number of stage and the output is the number th...
The number of recusions is given so the function will look something like this: std::string replace_recursive(const std::string& in, int n) { if (n <= 0) return in; std::string next = replace(in); return replace_recursive(next,n-1); } It has a stop condition, it executes a single step (by calling replace...
71,308,817
71,309,245
Capturing lambda and move assignable
I am confused by why a capturing lambda is not move assignable, but its manual definition (as struct with operator()) is. Consider the following simplified code: struct Environment { Environment(std::unique_ptr<int>&& p): ptr(std::move(p)) {} std::unique_ptr<int> ptr; }; class LambdaCPPInsights { public: i...
A lambda with a capture has a deleted copy assignment operator, which also implies that it has no implicit move assignment operator. See [expr.prim.lambda.closure]/13. Your LambdaCPPInsights is not correctly reproducing the closure type. It should explicitly default the copy and move constructors, and explicitly delete...
71,308,999
71,309,211
Iomanip setprecision() Method Isn't Working as It Should Only on the First Line, Why?
So I'm writing a program to count the execution time of a function using clock and I used iomanip to change the output to decimal with 9 zeros. This is the code that I am using: #include <time.h> #include <iomanip> using namespace std; void linearFunction(int input) { for(int i = 0; i < input; i++) { } }...
Look at the following line properly: cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9); See? You are setting the precision after printing out time_taken. So for the first time, you don't see the result of setprecision(). But for the second time and onwards, as...
71,309,239
71,309,644
solve clang-12 overloaded-virtual warning
The code below gives a clang-12 warning: warning: 'foo::TIFFFormat::encodePixels' hides overloaded virtual function [-Woverloaded-virtual] What can I do to solve the problem described by this warning ? namespace foo { struct bar { int k; }; class IImageFormat { public: virtual ~IImageFormat() = default; ...
Declaring one of the two overloads in the derived class, but not the other, will cause name lookup from the derived class to find only the one declared in the derived class. So with your code you will not be able to call e.g. tf.encodePixels(foo::bar{}). If you don't want to repeat all overloads in the derived class, y...
71,309,247
71,310,482
conditional execution path on static class trait
I have problems finding an adequate solution in the attempt to implement an new API alternative to an existing API, which I still want to support for backwards-compatibility; let this be my old API: typedef int[3] Node; template <class T> struct convert{ static std::pair<bool, T> decode(Node node); } //and a call ...
I don't know a way to solve this problem with a single type-traits that receive the name of the method (decode or decode_new_api) as argument. But, if you accept different tests for different methods, a possible solution is a couple of declared (no need to define) functions to test "declare" template <typename> std::fa...
71,309,305
71,309,623
does std::vector::insert allocate spare capacity?
Code like std::vector<int> a; for(size_t i = 0; i < n; ++i) a.push_back(0); is guaranteed to run in linear time in n. This is achieved by allocating some additional spare capacity when reallocating (typically increasing the total capacity by a constant factor). But what about std::vector::insert(pos, x)? I.e. is i...
The actual language is [vector.overview] A vector is a sequence container that supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time and more specifically [vector.modifiers 1] Complexity: If reallocation happens, linear in the number of elements of...
71,309,925
71,310,893
When I perform placement new on trivial object, Is it guaranteed to preserve the object/value representation?
struct A { int x; } A t{}; t.x = 5; new (&t) A; // is it always safe to assume that t.x is 5? assert(t.x == 5); As far as I know, when a trivial object of class type is created, the compiler can omit the call of explicit or implicit default constructor because no initialization is required. (is that right?) The...
Well, let's ask some compilers for their opinion. Reading an indeterminate value is UB, which means that if it occurs inside a constant expression, it must be diagnosed. We can't directly use placement new in a constant expression, but we can use std::construct_at (which has a typed interface). I also modified the clas...
71,310,054
71,310,216
How to declare the template argument for an overloaded function
I have a fairly big project that, regarding this question, I can summarize with this structure: void do_something() { //... } template<typename F> void use_funct(F funct) { // ... funct(); } int main() { // ... use_funct(do_something); } All is working ok until someone (me) decides to reformat a ...
You can wrap the function in a lambda, or pass a function pointer after casting it to the type of the overload you want to call or explicitly specify the template parameter: use_funct([](){ do_something (); }); use_funct(static_cast<void(*)()>(do_something)); use_funct<void()>(do_something); Wrapping it in a lambda ha...
71,310,201
71,310,605
MacOS: VSCode C/C++ intellisense fails to deduce types
MacOS Catalina 10.15.7, VSCode 1.64.2 (Universal) :I had the intellisense working for my project without problems, but then for whatever reason it has stopped working in some cases: whenever I assign something to an 'auto variable', for example: auto val = (float)foo; I'd get intellisense error: int val: explicit type ...
The issue seems to be that intellisense is using older c++ version for determining the syntax. The way to fix this is to set to some newer version like c++17 Go to settings in your VSCode and search for Cpp Standard and from the dropdown select c++17 or any newer version that you use. In case you follow JSON style sett...
71,310,261
71,313,929
ASIO C++ coroutine cancellation
I am spawning a coroutine as shown below. asio::co_spawn(executor, my_coro(), asio::detached); How am I supposed to cancel it? As far as I know, per handler cancellation can be achieved simply by binding a handler with asio::bind_cancellation_slot. This does not work in my specific example (irrespective of using the a...
To cancel a coroutine in asio use the new awaitable_operator '||'. The awaitable operator '||' allows to co_await for more than one coroutine until one of the coroutines is finished. For example: #include "boost/asio/experimental/awaitable_operators.hpp" #include <boost/asio.hpp> #include <boost/asio/deadline_timer.hpp...
71,310,599
71,310,822
Convert a string array with special characters to an int array. Inputs are from a file
My problems here is to take all the integers in a file, and store to an int array (of course without |), and then do something with it (here I just need help to print out the array). The data from the file is said to be a 10x10 matrix. My code output is another 10x10 with trash values, as I tried using std::stringstrea...
Two issues: You try to read 10x20 when there is only 10x10 in the file. Further your code assumes that there is a | between all adjacent numbers, but thats not the case. There is no | between the last number in a line and the first in the next line. Change the size accordingly and read full lines before you split them ...
71,310,805
71,311,108
Compiling a function with templates fails in variadic template function
I have come across a compiler error involving variadic templates. The following code is a strongly simplified version which reproduces the error in my original code: #include <iostream> #include <sstream> #include <string> #include <vector> typedef std::vector<std::string> stringvec; // dummy function: return string ...
You can add an overload of vecDummy that handles the std::vector case and 'dumb down' the more general one to (say) just return an empty string: // dummy function: return string version of first vectorelement (catch-all) template<typename T> std::string vecDummy(const std::string, const T) { return ""; } // dummy ...
71,310,981
71,312,908
Add an additional control to a QFileDialog
I am using the Native file dialog, so there is no layout() but want to add an additional control to the dialog. The builtin Notepad application has a perfect example when they allow the user to select the desired encoding (see below, to the left of the "Save" button). Is it possible to add an additional control in Qt5 ...
TL;DR: Completely custom components are not available with native dialogs, filters can be controlled using QFileDialog::setNameFilters. Qt's implementation of the native windows file dialog uses ABI::Windows::Storage::Pickers. You can check the implementation out here. Depending on the type of action you perform, the ...
71,311,512
71,311,850
Execute a bat file with parent process privilege in qt
I have a directory in the current working path of my executable which is called Store. In this directory, there is a bat file which is called init.bat. I have written the following code to run this file, but it seems CreateProcessW doesn't run the bat file. How should I fix this code? I didn't receive any error, the pr...
In Qt, you would use the QProcess-API (see QProcess::start()). Using CreateProcess is not the Qt way to do this. In the linked documentation, you will find a hint on executing commands via cmd on Windows and hints for other OS.
71,311,765
71,324,900
QUdpSocket broadcast not working to more than one client
I have an application that uses QUdpSocket to broadcast a heartbeat message: mpsckUDP = new QUdpSocket(this); mpsckUDP->bind(QHostAddress::Broadcast, clsMainWnd::mscuint16Port); QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdh())); mscuint16Port is: const quint16 clsMainWnd::mscuint16Port(8081);...
Main application: mpsckUDP = new QUdpSocket(this); //Connection only required if you are going to receive data back on UDP QObject::connect(mpsckUDP, SIGNAL(readyRead()), this, SLOT(onUDPdataRdy())); Broadcast logic: qint64 int64Written(mpsckUDP->writeDatagram(carybytData, QHostAddress::Broadcast, clsMainWnd::mscuint1...
71,311,939
71,312,140
Forward declared variable not accessible in cpp file
Considering the example below: header.h extern int somevariable; void somefunction(); source.cpp #include "header.h" somevariable = 0; // this declaration has no storage class or type specifier void somefunction(){ somevariable = 0; // works fine } I couldn't find the answer to the following questions: Wh...
extern int somevariable; means definition of somevariable is located somewhere else. It is not forward declaration. Forward declaration is used in context of classes and structs. somevariable = 0; is invalid since this is assignment and you can't run arbitrary code in global scope. It should be: int somevariable = ...
71,312,797
71,312,939
C++ template argument limited to classes (not basic types)
Is it possible specify a template argument, that would never match to a basic type, such as an int? I'm heavily fighting ambiguities. So for example: template<class T> void Function(const T& x) { SetString(x.GetString()); }; That would work only if there's a method GetString in T, but if the compiler sees this functio...
Method 1 You can use std::enable_if as shown below: C++11 //this function template will not be used with fundamental types template<class T> typename std::enable_if<!std::is_fundamental<T>::value>::type Function(const T& x) { SetString(x.GetString()); }; Demo C++17 template<class T> typename std::enable_if...
71,313,002
71,313,525
Printf display only one word
I want to display more than one word using printf, Do I should change first parameter in pritnf? #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { int value; printf("How many:"); scanf("%d", &value); char* arr1 = new char[value]; scanf("%s[^\n]", arr1); printf("%s", arr1); ...
As already pointed out in the comments section, the following line is wrong: scanf("%s[^\n]", arr1); The %s and %[^\n] are distinct conversion format specifiers. You seem to be attempting to use a hybrid of both. If you want to read a whole line of input, you should use the second one. However, even if you fix this li...
71,313,052
71,315,846
Function Pointers, In STM32 and how do i understand these Type Handles?
I'm getting a very confusing error as I may be making a small mistake with the phrasing or the type handles or it could be a more complicated problem Basically I want to create this funciton Buf_IO(HAL_StatusTypeDef IO) that can take one of two inputs either HAL_SPI_Transmit or HAL_SPI_Recieve these are both defined as...
In C++, you should use the using directive to define the function signature. using is similar to typedef in C, but makes things much more readable. using IO = HAL_StatusTypeDef(SPI_HandleTypeDef*, uint8_t*, uint16_t, uint32_t); Note, that IO is now the alias of the function signature itself, not a pointer to the funct...
71,313,184
71,314,167
I don't understand how cin.ignore() works. When I run this piece of code, my program breaks down
There is an array of classes. I want to input an amount of players and then by using a for-loop, input player's names. The problem is that I don't understand how to avoid the program crashing, using cin.ignore(). void main() { int numberOfPlayers; cout << "Input amount of players:"; getline(cin, numberOfPla...
You have not allocated the individual players This Player** arrOfPlayers = new Player*[numberOfPlayers]; only allocates an array of pointers to players You also need to create those players for (int i = 0; i < numberOfPlayers; ++i) arrOfPlayers[i] = new Player;
71,313,729
71,313,808
Structure with an array, is memory contiguous?
if I have struct S { int a; float* b; int c; }; Aside from any padding. a, b (the variable where a pointer is kept), and c will be contiguous. The element that b is pointing to, may be somewhere else in memory if I have struct S { int a; float b[10]; int c; }; a, every element of b, and c will...
Yes, a, (the elements of) b, and c will be contiguous, if we ignore possible padding between a and b, or b and c. Of course there's no padding between the elements of b.