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
67,901,973
67,902,070
Use the " character in a string
Hello I would like to use the character "in a string variable like this: std::string hello = """; Is it possible to do such a thing or am I talking nonsense? Thanks in advance!
You can either use the escaped character like std::string hello( "\"" ); or std::string hello = "\""; or use a constructor that accepts a character literal like std::string hello( 1, '"' ); Or you can use even a raw string literal like std::string hello( R"(")" ); or std::string hello = R"(")";
67,902,458
67,903,656
Write a program to elaborate the concept of function overloading using pointers as a function arguments?
I know what overloaded functions are but I don’t know how to elaborate it using pointers. If someone can give me a basic program to elaborate function overloading using pointer as a function argument.
As the comments stated, it's not entirely clear where your problem is. It would be nice if you included an example for what you want to understand better, anyway, here's an example: #include <iostream> void foo(int x) { std::cout << x << std::endl; } void foo(int* x) { std::cout << (*x + 1) << std::endl; } int...
67,902,499
67,902,569
Link libraries to linux biinary file in c++
I'm compiling a c++ program using g++ and i am using two libraries called libsdl2-dev and libsdl2-image-dev I installed both these libraries in my ubuntu machine with the commands apt install libsdl2-dev libsdl2-image-dev and when I compile the program everything works fine. Then I copied these libraries from /usr/lib...
That's because the dynamic linker loading runtime dependencies looks for them in some specified locations, which are "by default" your system library directories (where those libraries got installed by apt). The other user should ideally install those libraries too (which could be done "automatically" if you build a .d...
67,903,306
67,903,447
use of cin and getline are causing errors
In the following code, I have made two classes, the second class is inherited from the first one. However when I call the getdata function. it skips input, I have tried using cin.ingnore() and also cin>>ws, but I am still getting the same errors. It runs properly till " Enter the Last name" but after that, it just prin...
You cannot just slap ignore() randomly and expect things to work. By default, ignore() will remove 1 character. If there is no character there, it will set eof() bit and your stream cannot read anything more until you clear() eof flag from it. Only use ignore() when there is a leftover end of line (like after formatted...
67,903,437
67,904,083
Per-object singleton
(I tried searching, but you just get a flood of plain singleton explanations.) A "normal" singleton guarantees that only one object of a given type exists in the entire program. For example, like this: template <class T> T& getSingleton() { static T instance; return instance; } I am looking for a way to have no mo...
The standard library provides std::type_index which can be used to effectively associated a unique value to every type. This type is designed to be usable as a key for associative containers. A std::unordered_map<std::type_index, std::any> can be used to contain a collection of any types. And the since knowing the orig...
67,903,874
67,903,931
How should I fix the configure.yaml file?
I am trying to install hpctoolkit using spack. In order to do that, I executed : git clone https://github.com/spack/spack.git cd spack/share/spack source setup-env.sh spack fetch -D hpctoolkit spack install hpctoolkit In order to see the available compilers, I need to look at the content of compilers.yaml. Here is i...
Try changing lcompilers to compilers. It's just a typo error.
67,904,226
67,904,334
issues with getline() and input stream
Code #include<iostream> int main() { char s[20]; char ch; std::cin.getline(s,10); std::cout<<"x"<<s<<"x"<<"\n"; std::cin>>ch; std::cout<<"x"<<ch<<"x"; std::cin>>ch; std::cout<<"x"<<ch<<"x"; std::cin>>ch; std::cout<<"x"<<ch<<"x"; } Output-1 bonaparte // I e...
In Output-2, std::cin.getline(s,10); fails (because it can't read a complete line). It then sets the stream in a failed state and all subsequent extractions will also fail (unless you clear() the stream). if(not std::cin.getline(s, 10)) { // an empty string is considered ok if(std::cin.eof()) { std::cout <<...
67,904,736
67,904,949
Initialising a vector of structs containing function pointers gives "no viable overloaded '=' "
I am trying to write a chip CPU emulator and implementing its instruction table as a vector of structs where each struct contains a value and a function pointer to a particular operation. My compiler (clang++) however gives me the error: no operator "=" matches these operands -- operand types are: std::__1::vector<A::...
The structure definition should look like struct someStruct{ int a = 0; void (A::*fptr)(void) = nullptr; }; because you are trying to use member functions of the class A as initializers. A::A(){ func_table = {{1,&A::func1},{2,&A::func2}}; } That is you have to declare pointers to class mem...
67,904,738
67,904,771
Is it undefined behaviour to read a different member than was written in a Union?
union test{ char a; // 1 byte int b; // 4 bytes }; int main(){ test t; t.a = 5; return t.b; } This link says: https://en.cppreference.com/w/cpp/language/union It's undefined behavior to read from the member of the union that wasn't most recently written. According to this, does my sample code above have...
Yes the behaviour is undefined in C++. When you write a value to a member of union, think of that member becoming the active member. The behaviour of reading any member of a union that is not the active member is undefined. in C++, a union is often coupled with another variable that serves as a means of identifying the...
67,904,839
67,904,911
Trouble getting suggestions in vs code
I am learning c++ code and using vs code as IDE. It was going good but now I am not getting suggestion when I write my code. I am using C/C++ extension by intellisense. I tried reinstalling it, resetting its settings but nothing worked. Please help. This is the only suggestion it shows when I type #include.
You need to save(cmd+s / ctrl+s) the file in order for intellisense to work.
67,904,943
67,905,239
Cant work with characters like á à ã ă â é è ê
My code is supposed to clear any character that isn't a-z or A-Z. For other characters, for instance á à ã ă â é è ê if I can make it work, I'll make them change from á to a and è to e etc. #include <iostream> #include <string> using namespace std; int main() { int counter=0; string* word = new string[1]; ...
You can use wcout and wstring to deal with Unicode character in C++ within Windows: #include <iostream> #include <string> #include <io.h> #include <fcntl.h> using namespace std; int main() { _setmode(_fileno(stdout), _O_U16TEXT); //set the mode of the output file handle to take only UTF-16 data int counter=0; ...
67,905,067
67,905,216
copy_if with map whose value is also a std::pair
I have an input map inMap whose type is map<double, pair<int, double>>. I am trying to filter this map by means of copy_if like this: map<double, pair<int, double>> outMap; copy_if(inMap.begin(), inMap.end(), outMap.begin(), [](pair<double, pair<int, double>> item) {return (true) ;} // I have simplified the predicate ...
The iterators of a std::map are not suitable for use with copy_if, as that algorithm is simply going to attempt to assign the entire value. However, the iterator of a std::map has a value type of std::pair<const K, V>, which means it is not copy assignable. However, you can use std::inserter to accomplish what you wan...
67,905,422
67,905,954
How to compile and use libraries with MinGW?
I am currently trying to use some libraries (specifically libPNG if it helps) for a project, and would like to know how to compile/use/include it using MinGW. I have not tried anything yet as I am very clueless about this. edit: I would appreciate if you explain to me as if I were a child, since I am new to this entire...
One of the simplest ways of obtaining the binaries for open source libraries compatible with mingw is to switch to use msys2 to provide mingw and pull compiled packages using the package manager pacman that msys2 uses. The installation of msys2 can be done from here: https://www.msys2.org/ There is quite an extensive l...
67,905,633
67,906,341
How to install Qt with multimedia on Windows
I'd installed QT for Windows but when I try to use QT += multimedia in the .pro file it showed me that this module was unknown. I checked Qt online installer for additional modules but there was no such a component there. How can I get Qt with multimedia on Windows?
If you're using Qt 6, Qt multimedia will be re-provided in Qt 6.2 which hasn't been released yet. You can find the whole list of modules which will be added to Qt 6.2 here: https://www.qt.io/blog/add-on-support-in-qt-6.0-and-beyond For Qt 6.2 we are planning to provide the following additional libraries: Qt Bluetooth...
67,905,841
67,906,065
Does assigning return value from a lambda cause a copy?
I have used this pattern before to do module-specific initialization, e.g. at the top of a .cpp file: static bool isInitialized = []() { ...//do stuff return true; }(); But what about something like: static MyObject something = []() { MyObject ret(...); ret.x(...) return ret; }(); Is it definitive...
Case one should not be a copy in C++17. You are returning a prvalue, so no temporary is created and instead isInitialized is directly constructed. In C++14 this is only an optional optimization. Case two is using a named variable so you would have to rely on NRVO, which is not guaranteed in any version of C++, to do ...
67,906,096
67,906,509
C++20 chrono parse problem in VS2019 (latest)
I have a function that works under C++14 using the date.h library but I'm converting my program to use C++20 and it's no longer working. What am I doing wrong, please? My C++14/date.h code is as follows: #include <date/date.h> // latest, installed via vcpkg #include <chrono> auto StringToUnix(const std::string& source...
There's a bug in the spec that is in the process of being fixed. And VS2019 faithfully reproduced the spec. Wrap your format string in string{}, or give it a trailing s literal to turn it into a string, and this will work around the bug. in >> parse("%Y-%m-%d %H:%M:%S"s, tp);
67,906,479
67,906,583
What does memory 32bit Alignement constraint mean for AVX?
The documentation of _mm256_load_ps states that the memory must be 32bit-aligned in order to load the values into the registers. So I found that post that explained how an address is 32bit aligned. #include <immintrin.h> #include <vector> int main() { std::vector<float> A(height * width, 0); std::cout << "&A =...
You missread this - it says 32 BYTE aligned, not BIT. So you have to do 32-byte alignment instead of 4-byte alignment. To align any stack variable you can use alignas(32) T var;, where T can be any type for example std::array<float, 8>. To align std::vector's memory or any other heap-based structure alignas(...) is not...
67,906,546
67,906,801
Linker cannot find local shared library
I'm trying a very simple exmaple to create a shared library and link to it. The shared library is as follows: #ifndef ARDUGRAB_H_ #define ARDUGRAB_H_ #include <iostream> using namespace std; namespace ArduGrabLibrary{ class ArduGrab{ public: ArduGrab(); virtual void initCamera(); ...
This is becuase you are using the -l flag. When you use this flag (Rather than specify a library specifically) it assumes a certain naming convention. -lX The linker assumes the file name is libX.so (or libX.a) So the commands you want are: > g++ -fPIC -shared -o libardugrab.so ardugrab.cpp > # ^^^...
67,906,679
67,907,135
Difference b/w std::vector<int> V(N) and std::vector<int> V[N]?
Are these 2 statements std::vector<int> V(N) and std::vector<int> V[N] equivalent?? Also what do they mean?
std::vector<int> V(N) creates an std::vector<int> of size N. std::vector<int> V[N] creates an array of size N containing std::vector<int>. You can see this from this piece of code : #include <vector> #include <iostream> #include <typeinfo> const int N = 100; int main() { std::vector<int> test(N); std::cout << ...
67,906,729
67,906,840
How to use second overload of std::optional<T>::emplace
In the std::optional::emplace docs there is an overload that accepts std::initializer_list: template< class U, class... Args > T& emplace( std::initializer_list<U> ilist, Args&&... args ); provided that std::is_constructible<T, std::initializer_list&, Args&&...>::value is true I thought that it might be used to empl...
but shouldn't first emplace overload T& emplace( Args&&... args ); be enough for that? It isn't because a braced-init-list, i.e. {1, 2, 3} has no type. Because it has no type, there is nothing to compiler can do to deduce what Args should be. We need to have an overload that explicitly takes a std::initializer_list...
67,906,815
67,913,781
Apply Blur effect to a ID3D11Texture2D
I have this code: ID3D11Texture2D* Buffer; SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBuffer); to get a screenshot of my game, I want to blur it for my game GUI, I have no idea how to do it unfortunately
This DirectX Tool Kit tutorial covers writing HLSL to do blur/bloom. You may find it useful: https://github.com/microsoft/DirectXTK/wiki/Writing-custom-shaders
67,907,498
67,908,058
How to create a Makefile that finds files across multiple directories and puts the object files into a different directory?
I'm a beginner in Makefiles and what I want to do is pretty complicated and if someone can help me then please consider to also explain me how things work so I can learn and understand. Of course I made my research and I wasn't able to find something that will help. So we have the following project: src | File1.cpp |...
You can pass variable to your makefile using the syntax: $ make SOMEVAR=SOMEVALUE This can be used to pass the folder you want to build: $ make SRC=src1 # or src, src2, ... The makefile can be something like this (you only mentioned obj file, so I only added that): SRC_FILES=$(wildcard $(SRC)/*.cpp) OBJ_FILES=$(pa...
67,907,684
67,911,808
is this some kind of casting function? if so, why is it __thiscall?
I am reverse-engineering a program, and found a member method that looks like this: int __thiscall sub_40A490(void *this) { return *(_DWORD *)this; } IDA generated this code, the original assembly looks like this: sub_ proc near mov eax, [ecx] retn sub_ endp What is...
Probably is the solution: from comments "It looks to me like sub_40A490 is a member function of some class which returns a _DWORD member, which is the first member of the class." – François Andrieux
67,907,777
67,908,880
Trait for non qualified or pointer/reference types
I'm implementing a check to see if a type is stripped of any qualifications: template <class T> struct is_plain : std::integral_constant< bool, std::is_same_v<T, std::decay_t<T>> // * >; Is the logic in std::is_same_v<T, std::decay_t<T>>, i.e. check if a type is stripped of anything that decay would remove,av...
This is a bit verbose, but it should cover every case there is. With template<typename T> constexpr auto is_plain_v = !(std::is_function_v<T> || std::is_pointer_v<T> || std::is_lvalue_reference_v<T> || std::is_rvalue_reference_v<T> || std::is_array_v<T> || ...
67,907,927
68,033,666
Generate a source file that may or may not be updated
I have a CMakeLists.txt in which I want to generate several source files (namely, versiondata.cpp and version.rc.inc, included by res.rc) that depends on the general environment (current git HEAD, gcc -v output, CMakeCache.txt itself, and so on). If it depended just on some files, I would generate it using an add_custo...
In CMake there are two types of dependencies: Target-level dependency, between targets. A target can be build only after unconditional building of all targets it depends on. File-level dependency, between files. If some file is older than one of its dependencies, the file will be regenerated using corresponded COMMAN...
67,908,211
67,908,307
How does std::declval return a value?
I wanted to try writing a template wrapper that checks whether a class has a member function. and for this it was necessary to use std::declval template<typename T> struct has_member<T, void_t<decltype(std::declval<T>().push_back())>>:std::true_type{}; As I saw, the implementation of declval should be like this: templ...
declval has no return statement because the function has no implementation. If you ever tried to call declval, you would get a compile error. declval exists to be used in what C++ calls an "unevaluated context". This is in a place where an expression will be parsed, the types used worked out, but the expression will ne...
67,908,591
67,936,794
How to convert boost::asio::awaitable to std::future?
I have a function that returns boost::asio::awaitable. What is the idiomatic way to convert this awaitable to std::future?
Before we get into the answer, be warned: You should not, under any circumstance, get() or wait() a future to a boost::asio::awaitable from the same thread as the executor that is running the coroutine. That being said. That third parameter to co_spawn(), the one almost every example blindly sets to the magic detached ...
67,909,125
67,909,724
I am stuck with this struct in C++
I am currently learning "struct" in C++ and stuck at this: #include "iostream" #define SIZE 100 struct date{ int day; int month; int year; }; typedef struct{ char *name; struct date date_of_birth; int score; } person; void entry(person *roster){ person temp; std::cout << "Input name: " << '\n'; get...
The problem is that gets(temp.name) does not allocate memory for the string for you, it expects temp.name to already point to allocated storage. However, temp.name was never initialized, at best your program will crash trying to read the name, at worst it will seem to work but will overwrite memory that will cause prob...
67,909,709
67,927,683
Direct write to D3D texture from kernel
I am playing around with NVDEC H.264 decoder from NVIDIA CUDA samples, one thing I've found out is once frame is decoded, it's converted from NV12 to BGRA buffer which is allocated on CUDA's side, then this buffer is copied to D3D BGRA texture. I find this not very efficient in terms of memory usage, and want to conver...
Ok, for anyone who struggling on question "How to write D3D11 texture from CUDA kernel", here is how: Create D3D texture with D3D11_BIND_UNORDERED_ACCESS. Then, register resource: //ID3D11Texture2D *textureResource from D3D texture CUgraphicsResource cuTexResource; ck(cuGraphicsD3D11RegisterResource(&cuTexResource, tex...
67,909,738
67,911,369
Change the Code Using Pointers to Achieve Many-to-Many Relationship
I have the following code in Movie.hpp #ifndef MOVIE_H #define MOVIE_H class Movie { private: std::string title; public: std::string getTitle() const {return this->title;} // const added void setTitle(std::string newTitle){this->title = newTitle;} }; #endif In Actor.hpp #ifndef ACTOR_H #define ACT...
If the Movie object needs to be shared between Actors, another way to do this is to use std::vector<std::shared_ptr<Movie>> instead of std::vector<Movie> or std::vector<Movie*>. The reason why std::vector<Movie> would be difficult is basically what you've discovered. The Movie object is separate from another Movie obj...
67,910,068
67,912,213
hide template function from header file
I have the following use case. Messages.h template <typename Message> Message deserialize(std::string const &buf); template <> RequestHeader deserialize(std::string const &buf); template <typename Message> std::string serialize(Message const &msg); #include "Messages.inl" Messages.inl template <typename Message> Me...
Before C++20 you generally have only two options: Either you "hide" the helper functions by moving them to a namespace such details or helper. This way one will not see it immediately but can still access them (Try it here!): namespace details { template <typename Message> Message deserialize(std::string const &bu...
67,910,071
67,910,124
Instantiating a pointer and passing it to two Queues to be consumed by two Threads?
I have some code where a thread callback effectively generates some data and writes it to a queue to be consumed by another thread looking something like this auto data_ptr = std::make_shared<DataFrame>(); data_queue_.write(std::move(data_ptr)); I know it was written this way as to avoid copies when reading and writin...
Does that mean that the object only gets deleted when it gets pulled out of both of the threads reading from this queue and then only the data_ptr memory allocated gets deleted? No it doesn't. The first use of std::move will 'rob' data_ptr and the second is, effectively, UB. Don't be afraid to copy a std::shared_ptr...
67,910,093
67,913,628
Variadic templated container passing reference to contained items
I'm trying to create a variadic templated container that will contain items that have a reference back to the container. Unfortunately I can't quite figure out how to declare the container. It's a bit of a chicken and egg problem. The Items are templated on the Container, but the Container is also templated on the It...
if you confirm all of Items has CollectionA itself as the template argument, why not pass the template? template <template<typename>class... ItemTempls> class Collection{ public: Collection() : items(*this) {} std::tuple<ItemTempls<Collection>...> items; void doSomething() {} }; int main( int, char** ){ ...
67,910,210
67,910,367
C++ - sending Curl requests gives the response in the console without printing it
Here is my code: CURL *curl; CURLcode res; curl = curl_easy_init(); std::string json_message = "{\r\n \"email\":\"test@abv.bg\",\r\n \"password\":\"asdasdasd\"\r\n}"; if(curl) { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(curl, CURLOPT_URL, "https://www.examle.com/myUrl"); ...
By default, curl writes the received data to stdout. You can change that by using curl_easy_setopt() to specify a custom CURLOPT_WRITEFUNCTION callback, giving it a string* pointer via CURLOPT_WRITEDATA. For example: static size_t writeToString(void *data, size_t size, size_t nmemb, void *userp) { size_t realsize...
67,910,727
67,911,609
implicit default value for class member variable?
I'm doing C++ tests for my certification exam and I came across this exercise that i don't understand: (the question is what is the output of the following program) #include <iostream> using namespace std; class A { public : float v; float set(float v) { A::v += 1.0; A::v = v+1.0; return v; } ...
Like you mentioned, the first line of set used A::v, which was never initialized before. However, that itself doesn't produce an error, it is undefined behavior. What it means is the compiler may initialize it for you, or it might just pickup a random number it sees on the memory, or whatever they are pleased to. The C...
67,910,798
67,911,029
C specifier for printing type pair<size_t, bool>
So I am working on a project which uses C++. I made a multimap and an iterator of the following type- std::multimap < size_t, std::pair<size_t, bool> > position_seqsmapper; std::multimap < size_t, std::pair<size_t, bool> > :: iterator position_seqsmap_iterator; Now the issue is I need to use printf (cannot use cout be...
When dereferenced, your iterator yields a pair, whose second member is another pair. printf() doesn't know how to print a pair, so you have to pass each first and second member individually to printf(). But, for that 2nd pair, you are trying to use 2 format strings in a single printf() call, which simply will not work...
67,910,936
67,910,960
'cout': is not a member of 'std'
I've looked at a lot of solutions for this problem but none have worked Main: #include "player.cpp" #include "player.h" #include <iostream> #include <SDL.h> using namespace std; int main() { player p; SDL_Init(SDL_INIT_EVERYTHING); for (;;) { p.move() } } player.h: #pragma once #ifnde...
The player.h file does not have a #include <iostream> in it. You have two choices: Make every header file able to stand on its own. Ensure that you document and meet the pre-requisites for every header file you include. You have done neither of these things.
67,911,443
67,912,275
How to Change the Code After inserting Object in Vectors
In Movie.hpp #ifndef MOVIE_H #define MOVIE_H class Movie { private: std::string title; public: std::string getTitle() const {return this->title;} void setTitle(std::string newTitle){this->title = newTitle;} }; #endif In Actor.hpp #ifndef ACTOR_H #define ACTOR_H #include "Person.hpp" #include "M...
I'll employ some database theory here. Each movie will have a unique ID and a title: class Movie { unsigned int m_id; std::string m_title; public: Movie(unsigned int id, const std::string& title) : m_id(id), m_title(title) { ; } std::string get_title() { return m_title; } void set_tit...
67,911,613
67,912,011
C++20 ranges reverse view problem in VS2019 (latest)
I'm trying to read a vector in the reverse order using a ranges::subrange view but I'm confused about how it should work. I'm aware of ranges::reverse but I'm trying to avoid using this method as a personal preference and learning experience. My non-working example code is here: #include <algorithm> #include <ranges> #...
Given that you want 4,3,2, you're looking for: v | views::drop(1) | views::reverse That is, drop the first element (the 1), and then reverse the remainder. If you really want to avoid the range adapters, you could do: subrange(v.rbegin(), v.rend() - 1) to accomplish the same thing. All subrange does is combine two i...
67,912,185
67,912,306
Deleting node in a double linked list is not working
This is a basic function that takes an iterator position and deletes the node in this position but it gives me a runtime error. what am i doing wrong? iterate erase(iterate position) { iterate i; Node<T>* temp = head; if (head == NULL) { cout << "empty list" << endl; } else if (position.poi...
Your function is lacking adequate return statements. There are multiple flows that can cause the function to exit, but only one of them has a return statement. So the return value will largely be indeterminate, causing undefined behavior for any caller that tries to use the return value. In any case, your while loop i...
67,912,346
67,925,471
Is there a faster argmin/argmax implementation in OpenACC?
Is there a faster alternative for computing the argmin in OpenACC, than splitting the work in a minimum-reduction loop and another loop to actually find the index of the minimum? This looks very wasteful: float minVal = std::numeric_limits<float>::max(); #pragma acc parallel loop reduction(min: minVal) for(...
We've gotten requests for minloc/maxloc but it's difficult and would most likely not be performant, so not something that's been added. The method you're using is the recommended solution for this.
67,912,839
67,912,980
How do you specify a threads dependency in cmake for distributing a header-only library in a cross-platform way?
I was contributing to a nice little c++ header-only library and I was fixing up the cmake to make the library properly installable and findable/usable by other projects. The library itself does make use of various parts of the stl including those that you are required to link manually. Specifically it makes use of std:...
CMake comes with the Threads package for that very purpose: find_package(Threads REQUIRED) target_link_libraries(header-only-project INTERFACE Threads::Threads)
67,912,880
68,010,805
Share single copy of structure/data defined in shared library to different objects defined in multiple shared libraries
Language: C++/C Android Makefile System: https://developer.android.com/ndk/guides/android_mk I have an application which open a shared library foo.so and within foo.so we open three other shared libraries bar1.so, bar2.so and bar3.so in three different threads (pthread_create) but in same application/process. pid is sa...
class __attribute__ ((visibility ("default")) SharedObject Defining the class as above solved the issue. It seems like without this, symbol is not exported and not available for dynamic linker.
67,913,640
67,913,711
'Circumference' was not declared in this scope
I am taking an introductory course in C++ ver. 14 and I keep running into this error. Code is using header file and I'm not sure how to effectively transfer user numerical inputs from the .cpp file to the .h file and vice versa. Here is my code for the .cpp file: #include<iostream> //ignore this part the stack ov...
You should look toward the following implementation. Your header file should look somewhat like these: #include <cmath> class Circle { double RadiusVal; double CircleArea; double Circumference; double CircleDiam; public: // Constructor // Both, the dafault constructor // and the one that ta...
67,913,691
67,914,463
initialize an array of std::byte with integer type
I have a typedef std::array<std::byte, 4> CatType; And I want to initialize a constant of this type. I can do const CatType mycat = {std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}}; Which works, but I'd like for readability something like const CatType mycat = 0x001020ff Which fails with error co...
You can define CatType as a wrapper class instead of a typedef, and define a converting constructor from int: #include <array> #include <cstddef> class CatType { private: std::array<std::byte, 4> m_arr; public: CatType(int value) : m_arr { std::byte((value >> 24) & ...
67,913,986
67,914,109
My C++ program crashed whenever I try to read the string
Here my code: #include<iostream> #include<string.h> #define SIZE 100 struct person{ std::string name; int age; }; void entry(struct person *info){ std::getline(std::cin, info->name); std::cin >> info->age; } int main(int argc, char const *argv[]) { struct person roster[SIZE]; int n; // number of people i...
Please don't mind the prints to user I've introduced here. The execution flow is just so much more clear with them. So, you should look toward the following: #include<iostream> #include<string.h> #define SIZE 100 struct person{ std::string name; int age; }; void entry(struct person *info){ std::cout << "E...
67,914,311
67,914,368
How do I use _malloca instead of _alloca in Win32 C++ project?
I'm updating an old C++ DLL project. For one of the exported functions there's BSTR __stdcall j2cs( const long lJulian, int bDMY, BSTR sDelim ) { USES_CONVERSION; int iDay, iMonth; long lYear; char chDate[20]; char chInt[10]; char * cDelim = W2A( sDelim ); The W2A macro is defined as #define W2...
W2A can't be changed to using malloc. You have to add free in all places where W2A used. The ideal alternative is std::vector in place of _alloca. Update the macro USES_CONVERSION, so it contains std::vector<WCHAR> _buffer; and update the macro W2A: #define USES_CONVERSION int _convert = 0; (_convert); std::vector<WCHA...
67,914,377
67,914,570
Confusion about a notation of a union type in a structure
This msdn page shows how INPUT is defined. typedef struct tagINPUT { DWORD type; union { MOUSEINPUT mi; KEYBDINPUT ki; HARDWAREINPUT hi; } DUMMYUNIONNAME; } INPUT, *PINPUT, *LPINPUT; Case 1 #include <windows.h> int main() { INPUT input = { 0 }; input.DUMMYUNIONNAME.ki.wScan = 0x12; } Case...
You're missing part of the equation. For compilers that support anonymous unions, DUMMYUNIONNAME is an empty macro: #define DUMMYUNIONNAME typedef struct tagINPUT { DWORD type; union { MOUSEINPUT mi; KEYBDINPUT ki; HARDWAREINPUT hi; } DUMMYUNIONNAME; } INPUT, *PINPUT, *LPINPUT; An anonymous un...
67,914,479
67,914,824
C++ OpenCV about scale and taking the value
I wanna do some processings with an image. I used the resize function to do scaling (normalization). std::string image_path = "test.png"; Mat image = imread(image_path, IMREAD_COLOR); auto input_size = cv::Size(224, 224); Mat resized; cv::resize(image,resized,input_size,0,0,INTER_LINEAR); cv::Mat Scaleimg; resized.con...
You are using the wrong data type for accessing a 3-Channel Float pixel. The correct data type is cv::Vec3f, which is a vector of 3 float elements. This code snippet shows the modifications you need to perform: // Scale Image: cv::Mat Scaleimg; resized.convertTo(Scaleimg, CV_32F, 1.0 / 255.0, 0); // Loop thru image: f...
67,914,605
67,943,984
How can I optimize the following code? (it's in arduino)
I need to perform a function that sets the color depending on the path, that is, to have a single function instead of calling bring up void red, void green, void blue. I understand that I must pass the route and the value of each color as parameters (String route, int color) but I don't know how to do it. #include<...
If I understand your question correctly you can do it by passing the color variable you want to set as a call by reference parameter, like so: void setRGB(String route, int &colorValue) { if (Firebase.getInt(firebaseData,route)) { if (firebaseData.dataType() == "int") { int val = firebaseData.intData(); ...
67,914,738
67,930,812
How to initialize INPUT in winapi in general?
These two are definitions of INPUT and KEYBDINPUT. typedef struct tagINPUT { DWORD type; union { MOUSEINPUT mi; KEYBDINPUT ki; HARDWAREINPUT hi; } DUMMYUNIONNAME; } INPUT, *PINPUT, *LPINPUT; typedef struct tagKEYBDINPUT { WORD wVk; WORD wScan; DWORD dwFlags; DWORD time...
The problem is not 0. The problem is that you need to initialize a Controllable, Knowable value. You can even use memset(inputs, 1,sizeof(inputs)); which I tested.
67,914,917
67,914,984
Type holder in std C++
Is there in std C++ library anything like this?: template <typename T> struct TypeHolder { using type = T; }; i.e. special structure that is only used to pass a type around and store it. The idea is that I want to pass it inside functions by value, like: Try it online! void f(auto th) { typename decltype(th)::type val...
From C++20, you can use std::type_identity which is exactly the type you want. f(std::type_identity<int>()); g(std::type_identity<int>()); demo
67,915,691
67,916,176
Split wchar_t on size
I want split a wchar_t string on size: e.g. wchar_t* t= L"Abcdefghijk" and I want to split on size 4 then the chunks I should get are: {"Abcd", "efgh", "ijk"} I wrote the following code for doing this, however it has bugs: int maxSize=10; while ((lqs > maxSize) && (it < lqs)) { wchar_t *strng = (wc...
Here's a version with a single allocation: #include <cstddef> // for size_t #include <cstdio> // for printf #include <cwchar> // for wmemcpy, wcslen int main() { auto const str = L"Abcdefghijk"; auto const sz = std::wcslen(str); auto const split_count = sz / 4 + (sz % 4 != 0); // round up division using...
67,915,799
67,915,849
reinterpret_cast<std::string*> cause segmentation fault on gcc but works on clang
both gcc and clang version is 11, here is the sample code #include <string> #include <cstddef> void store_rvalue_string(std::byte* buffer, std::string&& value) { *reinterpret_cast<std::string*>(buffer) = std::move(value); } int main() { auto buffer = new std::byte[1024]; std::string str = "hello"; s...
This is a strict aliasing violation, and thus UB. A less formal answer is that you're calling std::basic_string::operator= on a piece of memory for which the string constructor was never called in the first place. My guess is that on Clang the memory happened to be filled with zeroes, and that a string filled with zero...
67,916,281
67,916,548
Limits of templated sub-class specialization in C++
Suppose we have code: Try it online! template <int Size> struct A { template <typename T, typename Enable = void> struct B; template <> struct B<bool, std::enable_if_t<Size >= 1>> {}; template <> struct B<short, std::enable_if_t<Size >= 2>> {}; }; template <int Size> struct D { template <typename T> st...
Why A doesn't work You can notice the difference between A and F, std::enable_if is using Size for checking, but it's the template parameter of class template A, but not template parameter of the inner template B itself. If you add one as F does, then it'll work. E.g. template <int Size> struct A { template <int ...
67,916,514
67,916,712
Does multi dimension array matter when passing it to a function?
So i have a function and a MD array int arrayMD[2][2] = { 0,3,6,8 }; void display(int *ptr) { cout << *(ptr + 1); } display(*arrayMD, 2, 2); // Invoke When I pass the it to the function it will point to a 1-D Array so the *ptr would point to {0,3} (CMIIW) When I call a function / invoke I pass a dereferenced ...
Let's put it this way first: void display(int (*ptr)[2]) { // Takes a pointer to an array of 2 ints std::cout << **(ptr); // Display [0][0] std::cout << *(*(ptr)+1); // Display [0][1] std::cout << **(ptr+1); // Display [1][0] std::cout << *(*(ptr+1)+1); // Display [1][1] } int main() { int arrayMD[...
67,916,544
67,916,896
Put elements at Even position after elements at Odd position in a Linked List
The question is asking us to put elements at odd positions before elements at even position in a linked list. Test Cases: {1, 2, 3, 4, 5, 6} --> {1, 3, 5, 2, 4, 6} {1, 2, 3, 4, 5, 6, 7} --> {1, 3, 5, 7, 2, 4, 6} My Code: #include <bits/stdc++.h> using namespace std; class node { public: int data; node *next;...
Before you go into loop in OddEven, odd is 1 and even is 2. while (odd->next != NULL && even->next != NULL) { odd->next = even->next; odd = odd->next; even->next = odd->next; even = even->next; } After first loop, odd is 3 and even is 4. Next is odd is 5 and even is 6, then ...
67,916,714
67,949,260
How does the return statement work in recursion?
#include<iostream> using namespace std; int binarySearch(int a[], int size, int x, int low, int high){ if(low > high) return -1; int mid = (low + high)/2; if(a[mid] == x){ return mid; } if(a[mid] < x){ return binarySearch(a, size, x, mid+1, high); } else{ return b...
Well, when you are specifying the return type of a function, the function indeed expected to return some value when the control-flow left out from the function. so a function, int function() is expected to return a value of type integer, that's the standard. Now, coming to your program, you have divided the array into ...
67,916,905
67,917,086
How to properly apply decltype together with SFINAE?
I wrote a template wrapper that should find out if the class owns the function. template<typename...> using void_t = void; template <typename ,typename = void> struct has_member:std::false_type{}; template<typename T> struct has_member<T, void_t<decltype(std::declval<T>().push_back())>>:std::true_type{}; But I can't...
I use a vector there and expected that it will pass The problem is in std::declval<T>().push_back(), there's no push_back taking nothing for std::vector. You need to pass argument to push_back, e.g. template<typename T> struct has_member<T, void_t<decltype(std::declval<T>().push_back(std::declval<typename T::value_ty...
67,917,132
67,918,218
Confused about two types of sub problems in dynamic programming
At first i apologize for my bad english. Recently i am facing some confusing thing about two types of dynamic programming. In "longest common subsequence" problem if the char is not equal then we take the maximum between two sub problems . On the other hand " Edit Distance " problem , if the characters is not equal the...
The number of choices is different because the nature of the two problems is different. For the Levenshtein distance (which is the edit distance that you are referring to), the three choices correspond to the three possible operations. When computing lev[i][j], corresponding to the substrings a[1..i] and b[1..j], and i...
67,917,336
67,939,173
Running valgrind on NVIDIA Jetson gives no leak source information
tl;dr valgrind not showing reachable memory leak source details C++ application was built using cmake with following extra options: set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0") set(CMAKE_C_FLAGS_DEBUG "-ggdb3 -O0") which were passed as seen from make VERBOSE=1 command. Output from running /usr/bin/valgrind --num-callers=50...
In case of problems with valgrind, it is always recommended to try with a recent version, either the last release or the git version. Note that it is quite easy to recompile valgrind from sources, at it has very few dependencies. In case of specific problems with stack traces, it is always useful to compare the stack t...
67,917,749
67,918,314
Accessing the value of the last iteration from inside the loop
I know this might be just an if statement that i don't know where to place but i am having difficulties understanding how to proceed. #include <time.h> #include <iostream> #include <sstream> using namespace std; int main() { float a; float sum; float tA = 5050 ; int b [5] = {5, 10, 15, 30, 100}; do...
You can only compute divident after the end of the loop, but you want to use it starting with the first iteration: that is not possible using one single loop. You should use two loops, first one to compute sum and divident, and second one to display the values: float sum = 0; ... double arr[5]; for (int i = 0; i < 5; i...
67,917,821
67,917,847
Invalid binary expression operands for template argument for special string case
Here is what I wanted to achive. I need a function that takes lhs and rhs where lhs is always of type std::string and return the string {rhs} + {lhs}. In theory rhs can be any type, but the library will only take std::string and all types supported by std::to_string(input). So my idea was to use std::is_same<T1, T2>::...
The problem is that base + rhs; must be valid even std::is_same<T, std::string>::value is false; i.e. both statement-false and statement-true need to be valid no matter whether the condition is true or false. You need the help of Constexpr If (since C++17). The statement-true or statement-false would be discarded accor...
67,918,033
67,920,457
How can I make the C++ compiler support template for STL?
I am trying to install hpctoolkit using Spack. In order to do that, I executed : git clone https://github.com/spack/spack.git cd spack/share/spack source setup-env.sh spack fetch -D hpctoolkit spack install hpctoolkit I can't execute the last command because I get the following error: Error: ProcessError: Command ex...
In order to fix this error, you should precise the path to g++. In my case, here is the updated content of my compilers.yaml file: compilers: - compiler: spec: gcc@7.5.0 paths: cc: /usr/bin/gcc-7 cxx: null f77: /usr/bin/gfortran-7 fc: /usr/bin/gfortran-7 f...
67,918,037
67,918,335
Something like std::integral_constant but with auto template argument in std C++20 library?
Starting from C++20 one can use auto template argument to implement integral constant: Try it online! template <auto Value> struct integral_constant2 : std::integral_constant<decltype(Value), Value> {}; which can be used instead of more verbose variant std::integral_constant that has two template arguments. Sure i...
No, I am not aware of such replacement. I believe it would be difficult to defend such proposal, given how easy it is to write your own. On the other hand the only reason might be that nobody proposed it yet. Mainly as a curiosity, and expanding on a comment, you can take this one step further via: #include <type_trai...
67,918,149
67,927,319
What is the best practice of passing reference counted C++ objects to Lua?
I want to have my reference counted C++ object also managed in Lua callbacks: when it is held by a Lua variable, increase its refcount; and when the Lua variable is destroyed, release one refcount. It seems the releasing side can be automatically performed by __gc meta-method, but how to implement the increasing side? ...
I assume you have implemented two Lua functions in C: inc_ref_count(obj) and dec_ref_count(obj) local MT = {__gc = dec_ref_count} local setmetatable = setmetatable local T = setmetatable({}, {__mode="k"}) function register_object(obj) if not T[obj] then T[obj] = setmetatable({}, MT) inc_ref_count(obj) ...
67,918,226
67,919,029
Why does Qt use raw pointers?
I have gone back to Qt/C++ programming recently after coding a lot with plain C++. When browsing StackOverflow, I often catch up on posts like "Why use pointers?" where in most cases the gist of the answers is "if you can avoid it, don't use them". When coding in C++, I now mostly try using stack variables which are pa...
Qt since versions 4.x was designed around imitating Java's framework ideology in C++ environment, using C++98 means. Instead of RAII approach of interaction it establishes "owner" - "slave" relation, in framework's term that's "parent" and "child". More of, Qt uses concept of PIMLP -private implementation. QObjects y...
67,918,400
67,919,402
C++ Outlook Object Model get shared calendar folder
I want to user GetCalendarExporter() on contact folder of shared calendar. I have written code which I feel will give only default calendar folder(i.e. Owner's calendar folder). I want Shared(Delegated) Calendar folder object/pointer. Any idea how to do that? As of now my code is like: CComPtr<Olk::_NameSpace> spNameS...
You need to use the NameSpace.GetSharedDefaultFolder method which returns a Folder object that represents the specified default folder for the specified user. This method is used in a delegation scenario, where one user has delegated access to another user for one or more of their default folders (for example, their sh...
67,918,597
67,918,988
How to access private Constructor from within inner class? C++14
I am trying to apply the builder pattern to an object, but the private constructor is not visible from the inner class. #include <iostream> #include <memory> class Outer{ private: Outer(void){ std::cout << "Constructed!" << std::endl; } public: class Builder{ public: std::unique_ptr<Outer> build(vo...
This doesn't work because the real builder is std::make_unique, and it is neither a friend nor a member. Making it a friend is not really possible, because you don't know what internal function it delegates to, and it would defeat the purpose of a private constructor anyway. You can just use bare new instead of std::ma...
67,920,398
67,920,481
What does "dp[0][i2] = dp[0][i2 - 1] && s2[i2 - 1] == s3[i2 - 1];" this mean?
Can anyone help me in getting my this doubt clear: bool isInterleave(string s1, string s2, string s3) { int n1 = (int)s1.size(), n2 = (int)s2.size(), n3 = (int)s3.size(); if(n1 + n2 != n3) return false; vector<vector<bool>> dp(n1 + 1, vector<bool>(n2 + 1, false)); dp[0][0] = tr...
It is a concise form of testing two conditions and assigning the logical result. dp[0][i2] = dp[0][i2 - 1] && s2[i2 - 1] == s3[i2 - 1] dp[0][i2] = ((dp[0][i2 - 1] != false) && (s2[i2 - 1] == s3[i2 - 1]))) ? true : false; if ((dp[0][i2 - 1] != false) && (s2[i2 - 1] == s3[i2 - 1]))) { dp[0][i2] = true; } else { dp[...
67,920,476
67,921,296
How to parallelize this array correct way using OpenMP?
After I try to parallelize the code with openmp, the elements in the array are wrong, as for the order of the elements is not very important. Or is it more convenient to use c++ std vector instead of array to parallelize, could you suggest a easy way? #include <stdio.h> #include <math.h> int main() { int n = 100; ...
As an alternative to using a critical section, this solution uses atomics and could therefore be faster. The following code might freeze your computer due to memory consumption. Be careful! #include <cstdio> #include <cmath> #include <vector> int main() { int const n = 100; // without a better (smaller) upper...
67,920,784
67,922,644
Can libusb be build using GNU GCC compiler?
I am trying to start using libusb for communication via COM port ( EDIT: for my Rs232 device), on windows 10 x64 only. My IDE is Code:blocks. I have a couple of questions: I downloaded libusb from their website (latest windows binaries) But I noticed there is a libusb-win32 ''version'' of it in sourceforge. It says "...
"I am trying to start using libusb for communication via COM port ( EDIT: for my Rs232 device), on windows 10 x64 only" If you have a device that when you plug it into your PC via a USB port, it instantiates a COM port, then that device does have a UART. The device must also have driver that upon connecting to the PC...
67,921,673
67,921,986
Pass vector reference to window process
I'm passing a struct that contains a vector reference to a window process using: SetWindowLongPtr(hWnd, 0, (LONG_PTR)&windowExtraData); In the function that creates the window. windowExtraData will contain the mentioned reference. Within the window process function I get the passed data with: auto* windowExtraData = ...
The vector's growth is internal, and its address doesn't change because of it. Therefore, you can do whatever you'd like with it inside. Note that if windowExtraData is destroyed the pointer won't be valid anymore.
67,922,271
67,922,342
Create C-style array form parameter pack
How can I create an array from the parameter pack? template<typename T, typename... Tpack> void covert(Tpack ...pack){ T *arr = new T[???]; //TODO: how to get Tpack size? // TODO: how to fill array? }
You might do: template<typename T, typename... Tpack> void covert(Tpack ...pack){ T *arr = new T[sizeof...(Tpack)]{pack...}; // ... delete[] arr; } Demo but your function is strange as-is. std::tuple might be more appropriate, or change input parameter to std::initializer_list<T> or std::array<T, N>.
67,922,360
67,922,675
how to use c++ to upload file to ftp server in centos?
I know there are some question about this, but i found them based on windows. So is there any good and simple method can upload in centos(linux)? it would be great if nothing need to install(better no package)
maybe you can try to use libcurl, there is an example from curl repos: https://github.com/curl/curl/blob/master/docs/examples/ftpupload.c
67,922,783
67,923,495
Combining Eigen's .transpose() and other operations
I was reading libigl's documentation, when I opened their MATLAB to libigl+Eigen conversion table. There (17th row, or the first red colored row), it stands: Do not attempt to combine .transpose() in expression like this: C = A + B.transpose(); Instead, they do: SparseMatrixType BT = B.transpose(); SparseMatrixType C...
According to Eigen docs, the only limitation on transpose() is m = m.transpose(); Therefore MatrixType res = A + B.transpose(); is legal
67,923,011
67,923,108
Are std::optional members stored contiguously?
I suppose I'm a bit confused as to how exactly optional values are stored. When constructing a class or struct that contains std::optional<T> members, will these members be stored contiguously in memory or does optional allocate dynamically? For example, would the below struct be one contiguous block of memory? struct ...
optional is required to not use dynamic allocation. If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() a...
67,923,474
67,923,677
Closing an app not sending WM_QUIT message?
Having such a simple Win32 app: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR pCmdLine, int nCmdShow) { ... HWND hwnd = CreateWindowEx(0, CLASS_NAME, L"Learn to Program Windows", WS_POPUP | WS_BORDER, 0, 0, 190, 110, nHwnd, NULL, hInstance, NULL); if (hwnd != NULL) { ShowWindow(hwnd, nCm...
Reading documentation at https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-quit: The WM_QUIT message is not associated with a window and therefore will never be received through a window's window procedure. It is retrieved only by the GetMessage or PeekMessage functions. Do not post the WM_QUIT message using t...
67,923,491
67,923,534
reverse a string recursively
string rev(string s,int n,int st) { if(st==n||st>n) { return s; } swap(s[st],s[n]); rev(s,n-1,st+1); return s; } st is 0 n is lenght-1 and s is string. I am trying to print the reverse of the string but I am not getting the answer. like the sentence is "Geeks" the the output is "seekG" actually my string is g...
Do not return the original string from the argument with two swapped chars. Return the final result. Replace rev(s,n-1,st+1); return s; with return rev(s,n-1,st+1); if(st==n||st>n) better is if(st >= n)
67,923,687
67,923,834
when I try and use std::filesystem in vs 2019 I get an error
I am using Microsoft Visual Studio 2019, and whenever I type std::filesystem there's a red bar under "filesystem", with the messages namespace "std" has no member "filesystem" and name followed by '::' must be a class or namespace name when I don't have "::" in front of it and when I do respectively. I have include...
The filesystem library was added in C++17 and VS2019 starts in C++14 mode by default. Open Project\<project name> Properties Select Configuration Properties\General To the right, there is a field named C++ Standard, select one of these: ISO C++17 Standard (/std:c++17) Preview - Features from the latest C++ working dr...
67,924,107
67,924,359
Detect if Windows device is locked while running as Local System account
Is is usually possible to check if a desktop is locked by using the SHQueryUserNotificationState API, but when running as LocalSystem, the state is not correctly detected. Is anyone aware of any workarounds or alternative APIs that could be used to detect if the device is locked?
SHQueryUserNotificationState() queries the state of the desktop session of the calling user. But multiple users can be logged in at a time. So you will have to query the specific user session you are interested in. You can use WTEnumerateSessions() to see which user sessions are running, and then use WTSQuerySessionI...
67,924,325
67,924,438
How will std::spanstream usually be used in C++?
<spanstream> will debut in C++23 (see cppreference). According to the proposal, they are string-streams with std::span based buffers. My questions are: Does std::spanstream have somewhat equivalent uses of the old std::strstream (or strstream deprecated in C++ 98)? What will be the benefits of using them after the fu...
They are intended to be a near drop-in replacement for strstream (except with proper bounds checking). As such, they will have the exact same use cases. When you have an existing buffer that you want to stream into/outof. The ability to move a std::string into stringstreams added in C++20 eliminated the use case when t...
67,924,612
67,924,668
What does MAX_MODULE_NAME32 do?
Hey so I've been reading a book recently and i saw this line of code: TCHAR procName[MAX_MODULE_NAME32] = TEXT("sauerbraten.exe"); and I'm curious what MAX_MODULE_NAME32 actually does.(I've tried reading documentation but I wasn't able to find any info on what it does.)
This statement declares an array of type TCHAR of length MAX_MODULE_NAME32. TCHAR procName[MAX_MODULE_NAME32] basically the maximum number of allowable characters in the module name. It is implementation defined but in this search result I see it is 255 in that particular case, though it may be platform and compiler-s...
67,924,821
67,925,069
Making a local struct instance accessible to another function (C++)
So I have a struct which holds variables for entities within a game (hit points, x and y coordinates, etc) and I have the struct declared globally. However, I have the instances created in a "setup" function and want their variables to be modified in a separate "logic" function. But obviously, since the instances are l...
There are a few different ways you can solve this: move dummy into global scope: struct entity { int hp, atk, x, y; }; entity dummy; void Setup() { dummy.hp = 10; dummy.atk = 2; dummy.x = 5; dummy.y = 5; } void Logic() { if (dummy is attacked) dummy.hp -= 4; } int main() { Setup...
67,924,924
68,033,904
Can't handle exceptions when invoking C# function from unmanaged C++ code
The idea of issue is following: I'm passing C# function pointer to C++ compiled library then from C++ invoke passed function. I want to catch C#/C++ exceptions from code, which lays before C++ function invoke. The idea of issue is following: I'm passing C# function pointer to C++ compiled library then from C++ invoke p...
It works that way on Windows because the Windows stack frames support the exception mechanism through non-managed frames. It does not work that way on Linux because the Linux stack frames do not support the exception mechanism through non-managed frames. – Eljay
67,925,395
67,925,813
How to create a class constructor which accepts parameters in curly braces in C++?
I'm trying to implement a Matrix class which has a vector of vectors as its member. class Matrix{ public: Matrix(); Matrix(/*what goes here?*/) : /*here*/ { /*and here?*/ } std::vector<std::vector<float>> contents; } According to the instructions in my assignment, it should be possible to i...
class Matrix { std::vector<std::vector<float>> contents; public: Matrix(); Matrix(const decltype(contents) & _contents) : contents(_contents) {} };
67,925,486
68,304,579
How do I conditionally specify OpenGL ES version in a Qt application with shared OpenGL contexts?
The hellogles3 sample constructs the QGuiApplication before testing for desktop OpenGL. If you don't do this then QOpenGLContext::openGLModuleType() crashes. int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QSurfaceFormat fmt; fmt.setDepthBufferSize(24); // Request OpenGL 3.3 core o...
It appears to be safe to instantiate a temporary QGuiApplication for the check. For example: int main(int argc, char *argv[]) { { QGuiApplication tempapp(argc, argv); QSurfaceFormat fmt; fmt.setDepthBufferSize(24); // Request OpenGL 3.3 core or OpenGL ES 3.0. if (QOpenGLCon...
67,925,722
67,926,408
Raise compile-time error if a string has whitespace
I have a base class that is intended to be inherited by other users of the code I'm writing, and one of the abstract functions returns a name for the object. Due to the nature of the project that name cannot contain whitespace. class MyBaseClass { public: // Return a name for this object. This should not includ...
I think this is possible in C++20. Here is my attempt: #include <string_view> #include <algorithm> #include <stdexcept> constexpr bool is_whitespace(char c) { // Include your whitespaces here. The example contains the characters // documented by https://en.cppreference.com/w/cpp/string/wide/iswspace conste...
67,926,057
67,926,108
c++ Inheritance (no base constructor) without initializer lists (lower than c++ 11)?
I am implementing the Decorator design pattern in c++ and I ran into this problem (code taken from https://www.studytonight.com/cpp/initializer-list-in-cpp.php): #include<iostream> using namespace std; class Base_ { public: // parameterized constructor Base_(int x) { cout << "Base Class Constru...
You're getting confused on the terminology. There is an initializer list, which looks like { for, bar, baz, ... }, there is a std::initializer_list type that can wrap an initilizer list, and then there is the class member initialization list, which is used to initialize the members in the class. That last one is what ...
67,926,577
67,926,716
Calling a function template before and after a more constrained version is defined gives weird results
My coworkers showed me following example today: Run on gcc.godbolt.org #include <concepts> #include <iostream> template <typename T> void foo(T) { std::cout << "1\n"; } template <typename T> void bar(T value) { foo(value); } void foo(std::same_as<int> auto) { std::cout << "2\n"; } Here, bar(42); and foo...
Cool. Every compiler is wrong. Within bar, the call to foo(value) only has the unconstrained foo<T> visible in scope. So when we call foo(value), the only possible candidates are (1) that one (2) whatever argument-dependent lookup finds. Since T=int in our example, and int has no associated namespaces, (2) is an empty ...
67,927,315
67,975,697
how to detect non-ascii characters in C++ Windows?
I'm simply trying detect non-ascii characters in my C++ program on Windows. Using something like isascii() or : bool is_printable_ascii = (ch & ~0x7f) == 0 && (isprint() || isspace()) ; does not work because non-ascii characters are getting mapped to ascii characters before or while getchar(...
Okay, I have solved this. I was not aware of translation modes. _setmode(_fileno(stdin), _O_WTEXT); Was the solution. The link below essentially explains that there are translation modes and I think phase 5 (character-set mapping) explains what happened. https://en.cppreference.com/w/cpp/language/translation_phases
67,927,353
67,998,018
TBB: Can't use an array type?
I have some code that uses TBB: tbb::concurrent_vector<float[3]> vnors2; vnors2.resize(NUM_VERTS); tbb::concurrent_vector<float[3]> lnors_weighted2; lnors_weighted2.resize(NUM_LOOPS); and I get an error compiling this (Windows, Visual Studio 2019): non-scalar type 'T' cannot be used in a pseudo-destructor expression ...
Yes, @Yksisarvinen you are correct. The issue is indeed not related to TBB. @easythrees You can find more about the syntax of array in https://en.cppreference.com/w/cpp/container/array
67,927,585
67,927,639
traversing memory owned by a unique_ptr gives segfault
In order not to have to remember to delete, we are using unique_ptr to manage the memory. We were under the impression that we can write and read in the memory, just that deletion is up to the smart pointer. However, the following code crashes on i=7220 with a segfault. What is wrong? #include <memory> using namespace ...
unique_ptr<uint64_t> mem = make_unique<uint64_t>(n); This allocates one uint64_t dynamically with the value n. You want: unique_ptr<uint64_t[]> mem = make_unique<uint64_t[]>(n); This specialization allocates an array of uint64_t with n elements, and has an operator[] overload which makes the below possible: for (int ...
67,927,710
67,928,928
I am trying to find the factors of factorial of a number
I am trying to solve the SPOJ problem DIVFACT where we need to find the factorial of a number. Though I used the correct formulae and at the same time I also checked the special case of 0 and 1,still I am getting wrong answer and it's really difficult for me to figure out what's wrong with my code. Can someone please h...
The problem states that the answer should be in MOD 10^9+7 but you have mistakenly defined MOD as 10^8+7.
67,927,753
68,533,998
How I can create const char* []
I have code: int ParseCommandLine( int argc, const char* argv[]) { string inFilePath = ""; string outFilePath = ""; for( int i = 1; i < argc; ++i ) { if( string( argv[i] ) == "-i" || string( argv[i] ) == "--input") { // Check for "-i @args" form of reqest. if( a...
Just change char to const char
67,927,813
67,928,160
Add class containing a circular buffer to Vector
I am trying to create a vector filled with class objects, and the class objects contain circular buffers as one of their members. I am running into this error: In file included from .pio/libdeps/teensy40/Vector/src/Vector.h:95:0, from src/main.cpp:2: .pio/libdeps/teensy40/Vector/src/Vector/VectorDefini...
Looking at the code of the circular buffer: CircularBuffer(const CircularBuffer&) = delete; CircularBuffer(CircularBuffer&&) = delete; CircularBuffer& operator=(const CircularBuffer&) = delete; CircularBuffer& operator=(CircularBuffer&&) = delete; This means that the circular buffer, once allocated, ca...
67,927,916
67,930,856
Template parameter pack peel args in pairs
I want to create a function for an ESP2866 microcontroller that saves an arbitrary number of configurations to a config file on the filesystem. I found a way to do it and I was wondering if it could be any better. // Saves the configuration values to the file system template <typename... Args> void SaveConfig(const cha...
If you really want to use templates instead of containers, you can try the following: template<typename ...Args, std::size_t ...I> void SetDataImpl(JsonDocument& doc, std::tuple<Args...> tup, std::index_sequence<I...>) { int dummy[] = { (doc[std::get<2*I>(tup)] = std::get<2*I+1>(tup), 0)... }; } template<typen...
67,928,129
67,928,304
How to instantiate, by the standard, a class template containing nested subclass templates
There is a template declaration template<class C> struct Data { template<typename T> struct Item1 { void Test() { } }; }; Using MSVC v19.28 with the compile option /std:c++latest, I tried to instantiate the template as follows: template<class C> struct Data { template<typename T> struct Ite...
There's a few things going wrong here: template <class C> struct MyData : Data<C> { MyData::Item1<int> item10; }; MyData is an incomplete type here, so we can't use it just yet in that way. However, since Item1 is inherited from Data<C>, we should be able to just refer to it directly: Data<C>::Item1<int> item10; Bu...
67,928,429
68,136,145
ICU: How to filter the charset detection to the available converters?
I'm working on character set detection using ICU, via another library that includes it, but it does not have converters for all character sets it can detect. For example, there is a converter for ISO-8859-1, but not for ISO-8859-2. I've tried a couple of things, such as using ucnv_getAvailableName, but it returns names...
(unless I made a mistake) I made a mistake. ucsdet_setDetectableCharset sets the status to failure for charsets that it can not detect (logical). I did not reset the failure status, expecting the functions to set the correct status (i.e. success in case of success); however, this is not how ICU works and I forgot abo...
67,928,583
67,929,202
Reference to an array of unknown bound (C++)
I have a templated class used for modelling views on objects, like std::shared_ptr and std::weak_ptr but without any owning semantics. The class internally holds a pointer to the viewed object and a functor which is called on class destruction (It is useful for reference counting the viewed object, or for thread-safe l...
The problem I am facing comes from the fact that a pointer to an array of unknown bound is, by my understanding, illegal C++. You're mistaken. Pointer to an array of unknown bound is not illegal in C++. I am in fact invoking undefined behaviour. (Or, possibly, some non-standard compiler extension?) Neither (as long...