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
64,493,692
64,503,390
"cc1plus: error: bad value (‘tigerlake’) for ‘-march=’ switch" compilation error
cc1plus: error: bad value (‘tigerlake’) for ‘-march=’ switch cc1plus: note: valid arguments to ‘-march=’ switch are: nocona core2 nehalem corei7 westmere sandybridge corei7-avx ivybridge core-avx-i haswell core-avx2 broadwell skylake skylake-avx512 cannonlake icelake-client icelake-server cascadelake bonnell atom silv...
Solved installing g++-10 and gcc-10 using: sudo apt install g++-10 sudo apt install gcc-10 then running make with: make CC=gcc-10 CPP=g++-10 CXX=g++-10 LD=g++-10 Thanks to Retired Ninja and MadScientist.
64,493,754
64,493,841
Is const function thread safe
Is reading a non-mutable variable from a const function thread-safe? for example, I have a class 'DataStore' and enum SOME_ENUM class DataStore { enum SOME_ENUM enum_val; std::mutex mutex; public: void SetSomeEnum(SOME_ENUM val); SOME_ENUM GetSomeEnumVal() const; } void DataStore::SetSomeEnum(SOME_ENUM va...
The code you posted is not thread-safe. The rule is, if there is any chance that one thread might write to a variable while a second thread is concurrently accessing that same variable (i.e. either writing to it or reading it), then your program invokes undefined behavior (due to a race condition) and is not guarantee...
64,493,844
64,494,401
How to check type being assigned to result of call operator?
I'm trying to make a simple matrix class Relevant parts of "mymat.h" #ifndef _MYMAT_H_GUARD_ #define _MYMAT_H_GUARD_ #include <iostream> constexpr auto MYMAT_ERR_UNEXPECTED_TYPE = "Error, unexpected type!"; constexpr auto MYMAT_ERR_CODE_UNEXPECTED_TYPE = 0; constexpr auto MYMAT_ERR_OUT_OF_BOUND = "Error, out of bound...
To achieve what you want: m(2, 2) = 500.0; // do custom checks for conversions from // right hand side to left hand side returning a T& from operator() is not going to work, because you have no control over implicit conversions to T. In this case, you can't prevent the conversion from double to int. I...
64,494,392
64,494,433
How to get the value from a table within a table with Lua?
I'm writing a material system for a game engine that I'm working where a Lua script is basically used as a config file for the material. I'm storing values in a table, but for vector values (vec2, vec3, etc.) I am embedding a table inside the main table to hold the multiple values, like so: material = { color = {0....
The first index should be 1 and not 0. lua_rawgeti(L, -1, 1);
64,495,276
64,496,347
Code snippet doesnot compile under C++17, namespace issue?
#include <iostream> #include <vector> namespace Cactus { namespace Json { class Value { public: Value(){} }; } typedef std::vector< int > vectorInt; inline Cactus::Json::Value& operator << (Cactus::Json::Value& os, const vectorInt& v) { ...
Those operator overloads must be in the scope where your f function is. When you function f is in Cactus namespace, those operator overloads are in scope. But when it is under namespace App , those go out of scope. So either put those operator overloads in global namespace, or put operator overloads in same namespace a...
64,495,369
64,496,836
uWebSockets http serves too slow
I've cloned uWebSockets, wrote the following file. #include <App.h> #include <iostream> int main() { uWS::App() .get("/*", [](auto *res, auto *req) { res->end("Hello world!"); }) .listen(3000, [](auto *token) { if (token) { std...
I was using apache benchmark tool(ab) and it was slow, not the program. Used bomberdier and got this result Bombarding http://127.0.0.1:3000/ with 1000000 request(s) using 5000 connection(s) 1000000 / 1000000 [=============================================================================================================...
64,495,469
64,496,235
How to know the available size of the shared memory that is used by `shm_open` in C++?
I am working on IPC for my C++ program with the boost library and I find that boost::shared_memory_object will not throw any error if I request a memory size that is larger than its capacity. This issue has been asked at least twice on stack overflow: Why I can create a shared memory bigger than the size mounted on /de...
If you want a non-portable solution that's limited to glibc, you can cheat and look at the sources of glibc. shm_open: https://code.woboq.org/userspace/glibc/sysdeps/posix/shm_open.c.html#shm_open calls this function to get the base path: https://code.woboq.org/userspace/glibc/sysdeps/posix/shm-directory.c.html It's ki...
64,495,472
64,496,998
how to get uint256_t upper and lower part in nodejs/javascript,
i have equivalent c++ but not sure how to implement this in javascript/nodejs. c++: template <unsigned int BITS> enum { WIDTH = BITS / 32 }; uint32_t pn[WIDTH]; uint256 seed = "00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595d"; uint64_t Get64(int n = 0) const { return ...
How to do it with javascript "native" BigInt const get64 = (value, n=0) => (value >> BigInt(64*n)) & 0xffffffffffffffffn; const toNumber = value => +value.toString(); var hash = 0x00000800ab9d2c5409a9b4dea2aa6f8471cecc41b35706e6d6155098e5f3595dn; var first = toNumber(get64(hash, 0) % 6n + 1n); var second = toNumber(...
64,495,509
64,495,797
Is there any workaround for MSVC producing `Internal compiler error` for this code?
For some reason the below code gives me fatal error C1001: Internal compiler error. with MSVC 19.27, but not with Clang. Any idea how to write it so that the static_assert can be done also on MSVC? template <typename T, int N, typename K, int M> constexpr int countIdentifersNotInArray(const T(&identifiers)[N], const K(...
As the comment has pointed out, this is an MSVC bug and you should definitely report to Microsoft. By removing multiple lines until it stops crashing the compiler, I believe the cause is the range-for loops. So, since they're arrays with known size, you can workaround with the classic indexed loops: template <typename ...
64,496,385
64,659,835
How solve problem with installing web3 for python in windows?
I'm trying install web3 for python3.7.5 on windows 10. But I get this error every time . I don't know what should I do, because I have already installed "Microsoft Visual C++ 14.0" and Build Tools. I tried also installing in vitrual enviroment, but it ended with same error. Thanks for your advice. Building wheel for...
Problem is solved. Cytoolz supports Python 2.7+ and Python 3.4+. I had Python 3.8.5, so now I'm running on Python 3.2 and Web3 is installed
64,496,633
64,656,025
GetWindowTextA unable to get the text of ComboBox MFC C++
I'm using GetWindowTextA to get the text of ComboBox but it will be an empty string "" even the hwnd is correct. No problem when using GetWindowTextA to get the text from other class, but it won't work for the class ComboBox. Is it something related to this that need other function to get text from ComboBox? Thanks. E...
Adding TCHAR szBuf[100]; and using SendMessage will be done. #include<windows.h> #include<iostream> using namespace std; int main() { POINT pt; Sleep(3000); GetCursorPos(&pt); HWND hWnd = WindowFromPoint(pt); char class_name[100]; char title[100]; TCHAR szBuf...
64,496,685
64,496,889
Sorting objects vector with lambda, not sorting in the end
I'm trying to write a sort function for vectors using lambda, and I've seen this suggested at so many places, but I've always had problems doing this. std::sort(eventvec.begin(), eventvec.end(), [](const event& lhs, const event& rhs) { return lhs.getim < rhs.getim;}); I had multiple errors while writing it and the...
You are sorting your events by the address of event::getim, which is the same for every event. I think you mean to call a member function of event, which needs to be callable from a const event double event::getut() const { return unift; } std::sort(eventvec.begin(), eventvec.end(), [](const event& lhs, const event& r...
64,496,874
64,497,126
Why uses implicit_cast<size_t>(int) instead of static_cast<size_t>(int)?
I have read some code in muduo, an open source network library, and I found that the author use implicit_cat<size_t>(int) rather than static_cast<size_t>(int) in many place. The definition of implicit_cast is as follows: // Use implicit_cast as a safe version of static_cast or const_cast // for upcasting in the type h...
But why use implicit_cast<size_t>(int) instead of static_cast<size_t>(int)? For the same reason as in the class case. In general, the reason is also the same as why C style casts are discouraged: Prefer using the cast which allows minimal set of casts that contains the cast that you want so that you don't accidentall...
64,497,084
64,497,281
Deleting the whole Linked List
I'm not able to understand how just by deleting a particular node current every time we are actually deleting the whole list from the memory. Here they created current and put its value as the link list but no change was done on the actual link list. Only line that made sense to me was head_ref = NULL; Here is the cod...
For each node in the list, you: Save the current iteration pointer value Advance the iteration pointer to the next list node. Delete the node acquired in (1) This is repeated until the iteration node lands on NULL, which means the end of the list. Frankly, this is easier to understand if you don't leave a dangling po...
64,497,320
64,498,068
C++20 'familiar template' lambdas: specifying an explicit argument in function pointer conversion
Assuming I have the following code in C++20, using the explicit template argument lambda functionality introduced in P0428: auto f = []<auto val>(int a) { printf("%d", val + a); }; and I need a function pointer conversion for the lambda f to void(*)(int) with an explicitly specialized value (I need an explicit C ABI l...
You can leverage the fact that a non-capturing lambda is default-constructible in c++20. #include <iostream> #include <tuple> template <typename F> struct args_tuple_maker; template <auto P, typename F, typename... Args> auto make_function_pointer(F, std::tuple<Args...>) { return +[](Args... args){ F{}.template o...
64,497,651
64,497,938
Can't link header files to my main.cpp in VScode (macOS) (clang error)
I am trying to link a header file which has a class defined in it and a .cpp file that has the actual functions of that class to my main cpp file but I'm getting this error: c++ DataMembers.cpp -o DataMembers Undefined symbols for architecture x86_64: "Cat::eat()", referenced from: _main in DataMembers-053507.o "...
When compiling make sure that you reference all the cpp source files so it can generate the according object files. It seems like you forgot to reference cat.cpp. The compiler sees that you have a header file included, assuming the implementation of this class will be in another cpp file. Because you forgot to referenc...
64,497,870
64,497,978
Why does the bubble sort program show the garbage value when using "break" in for loop?
This code will take the elements of the array from the user and then sort it. The user input limit is 20. I have an issue with a specific line which is if (a[i]==0)break; if I use break here the result shows garbage values. Otherwise, it works fine but I want the user to be able to run the program with 20 or fewer numb...
The array has size 20. The user sets values until 0 is entered. That means that the other elements are uninitialized. These are the garbage values. You can fix it by saving the number of entered elements. //Sorting with user input array elements void print(float a[], int n) { for (int i = 0; i < n; i++) { c...
64,498,181
64,498,251
Is it valid to correct for std::vector iterator invalidation in the following way?
Using C++11 or higher, suppose we store an iterator pointing to an element in a vector: std::vector<int> v{1, 2, 3, 4, 5}; auto it = v.begin() + 2; // it points to 3 Now, erasing an element before or including the pointed-to element will invalidate it. I am assuming erasing an element does not cause memory reallocati...
No. From cppreference Invalidates iterators and references at or after the point of the erase, including the end() iterator. v.erase(v.begin()); has invalidated all iterators. Using it has undefined behaviour. There is no way to "correct for" iterator invalidation. Once an iterator object is invalid, the only thing y...
64,498,275
64,499,881
QPushButton not clickable in second Layout
Someone already asked a similar question, but that person was working with PyQt5 and the Designer, so I couldn't find an answer since I'm coding "from scratch" and in C++. I'm a beginner with Qt and I'm trying to add two QPushButtons to a window in a specific layout. At first, I tried to just add them to the window to ...
Taken from QLayout::addItem() documentation: The function addItem() is not usually called in application code. To add a widget to a layout, use the addWidget() function; to add a child layout, use the addLayout() function provided by the relevant QLayout subclass. So, replacing addItem() by addLayout() will solve you...
64,498,385
64,498,648
Accessing private struct of a class using auto
I discovered that next weird code compiles and runs (on VS 2019): #include <iostream> class Test { private: struct Priv { int a; }; public: static Priv WeirdFunc() {return {42};}; }; int main() { auto val = Test::WeirdFunc(); std::cout << val.a; } Output is 42, no proble...
The result of Test::WeirdFunc() is a Priv. This is also the auto-deducted type of val. The auto keyword removes the necessity to name the type of val to be Priv and therefore, the compiler does not complain. As a result, val is of (unmentioned) type Priv and has a public member a, that can be accessed freely. So the an...
64,498,563
64,498,913
How to call function member with different argument several times?
My class has function that follows simple pattern, yet I don't know if there is a way to avoid code duplication so it will be much shorter. Here is simplified example: class Data { public: void compute() { if (procedure1) { runAlpha(param1); runAlpha(param2); ...
Firstly, you found that you cannot simply pass a non-static member function as a parameter. However you can pass a reference to the member function. This must be in a specific form, as specified by the standard. Some example code #include <cstdio> class Data { public: void runAlpha(int i) { printf("a%d", i); }; ...
64,498,601
64,499,620
Warp Image by Diagonal Sine Wave
I'm trying to warp colour image using sin function in OpenCV and I was successful in doing so. However, how can I make a 'diagonal' warping using sine wave? My code is this: Mat result = src.clone(); for (int i = 0; i < src.rows; i++) { // to y for (int j = 0; j < src.cols; j++) { // to x for (i...
I think it should look like this: void deform() { float alpha = 45 * CV_PI / 180.0; // wave direction float ox = cos(alpha); float oy = sin(alpha); cv::Mat src = cv::imread("F:/ImagesForTest/lena.jpg"); for (int i = 0; i < src.rows; i+=8) { cv::line(src, cv::Point(i, 0), cv::P...
64,498,992
64,506,708
Best way to create a setter function in C++
I want to write a template function that receives parameter by move or by copy. The most efficient way that I use is: void setA(A a) { m_a = std::move(a); } Here, when we use is A a; setA(a); // <<---- one copy ctor & one move ctor setA(std::move(a)); // <<---- two move ctors I recently found out that ...
The two setter versions setA(A&& a) and setA(const A& a) can be combined into a single one using a forwarding reference (a.k.a. perfect forwarding): template<typename A> void setA(A&& a) { m_a = std::forward<A>(a); } The compiler will then synthesize either the rvalue- or lvalue-reference version as needed dependin...
64,499,215
64,503,044
Segfault coredump occurs when I use CPPUNIT_ASSERT
I recently updated to fedora 30. When running a test now, my code will coredump on the CPPUNIT_ASSERT in the destrctor of the Message, gcc version: gcc (GCC) 9.3.1 20200408 (Red Hat 9.3.1-2) Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warr...
Upgrading to cppunit 1.15 from the fc32 repo fixed the issue for me.
64,499,220
64,499,260
GL/glew.h: No such file or directory in glew.c
When I try to compile my program I get this error C:\...\CLionProjects\Radix\vendors\glew-2.1.0\src\glew.c:34:10: fatal error: GL/glew.h: No such file or directory #include <GL/glew.h> ^~~~~~~~~~~ The error is in the library code, what am I doing wrong here? My project structure looks like this: Radix |- Ra...
Adding your include directory to the source files for GLEW_210 does nothing. Add it as a PUBLIC include directory instead, so the compilation of glew.c also has access to glew headers: target_include_directories(GLEW_210 PUBLIC glew-2.1.0/include) This also propagates the include directory to any targets that link wit...
64,499,913
64,500,537
Is there a way to store a variable during a while loop?
I am using a do-while loop that will ask the user to input positive numbers. The program will terminate when I enter a zero (0) number. Then it will compute the sum of all numbers I have entered and display it. #include <iostream> using namespace std; int main () { int end = 0; int num1; do ...
its a simple program. you can add code for exception in it #include <iostream> using namespace std; int main() { int n=0; int sum=0; do { cin>>n; sum+=n; }while(n); // this loop will break when n=0 cout<<sum; }
64,500,034
64,500,188
Split a vector into an array of vectors
I want to split one vector of bytes into an array with equal vector of bytes for example if I have std::vector<uint8_t> vec{11,22,33,44,55,66,77,88}; std::array<std::vector<uint8_t>, N> arr; // N is the number of subvectors from the vector vec if N == 4 the content of arr will be 4 vectors each vector contains 2 eleme...
Since it's a hard-error if N does not divide evenly into vec.size(), this is actually pretty simple to solve. The basic logic would be: Check that the input can be split correctly (throw on failure) Create N vectors in an array as a result Reserve space for vec.size() / N for each vector in that array (optional) Store...
64,500,142
64,501,230
Why does `auto` not adopt the constexpr'ness of its initializing expression?
Why doesn't defining a variable with auto keyword carry the constexpr'ness of the expression used to initialize it? As an example, consider the following code: #include <string_view> constexpr std::string_view f() { return "hello"; } static constexpr std::string_view g() { constexpr auto x = f(); // (*) retu...
auto is intended to enable type deduction, not a replacement for "everything useful you would have typed here". constexpr is not a part of an expression's type, and is thus ignored by auto (as opposed to const and volatile, which are part of an expression's type, and are deduced). But if we remove the constexpr on l...
64,500,269
64,500,326
Converting one std::optional to another std::optional
I have a method that returns an optional struct, like this: auto getBook(const std::string &title) const -> std::optional<Book>; I want to call this method in another method that returns the optional author. Problem is that the implementation should always check whether the optional returned by getBook is filled in be...
You can generalize this pattern by creating a map function, that takes an optional o and a function f, and returns the result of f(*o) if o.has_value() == true: template <typename O, typename F> auto map(O&& o, F&& f) -> std::optional<decltype(f(*std::forward<O>(o)))> { if (!o.has_value()) { return {st...
64,500,681
64,501,301
how do I fix this errror? ; error: a function-definition is not allowed here before '{ ' token
This program makes use of a 2D array to count stock inside a furniture shop. This code works fine on a online C++ compiler but not on codeblocks. I dont understand why #include <iostream> using namespace std; int main() { int i=0, j=0; int Stock_Items=3; int NR_materials=3...
After adding #include<iostream> at the top and changing int Stock_Items=3; int NR_materials=3; to const int Stock_Items=3; const int NR_materials=3; to get rid of that "variable-sized object may not be initialized" error, your code worked fine in Visual Studio Code on my Mac. Alex
64,501,021
64,501,189
Beside concepts are there any other void_t replacements in C++20?
Assuming I do not want to write a concept (or my compiler does not support them) and there is no matching type trait is there C++20 non void_t way to check if I can construct A with arguments B and C? Note: this is a toy example, real question is is void_t still the best way beside concepts to check if something compil...
You can use the detected idiom, which is an abstraction over void_t. This is pretty much the closest you can get from concepts without them: template <typename Default, typename AlwaysVoid, template<typename...> typename Op, typename... Args> struct detector { using value_t = std::false_type; using type = Defau...
64,501,099
64,501,259
Writing to unaligned storage
I have some values that I want to write into a raw byte array, in exactly defined locations, to send them off over the network. //These are computed somewhere else in the program (and converted to little-endian regardless of platform): using float32_t = float; static_assert(sizeof(float32_t) == 4); uint32_t someInteger...
Use std::memcpy, as in std::memcpy(data + 5, &someFloat, sizeof someFloat);. It is defined by the rules of the C++ standard, unlike using reinterpret_cast in the way shown in the question, and a good compiler will optimize it to simple load and store instructions if appropriate. Note that the sizes of the objects being...
64,501,793
65,005,071
Cannot access filesystem in CMake UPW Project
I built an application that uses OpenXR with DirectX to display a simple scene in VR. As I'm tasked with implementing this in an already existing project, it's built using CMake, which works perfectly fine with Visual Studio 2019. The application can run without any issues on the Windows MR Portal, as well as on the Oc...
So as a quick follow-up, if anyone runs into the same issue: The problem here was a bug in the OpenXR loader that was introduced in version 1.0.10 of OpenXR. Updating to OpenXR 1.0.11 solved the issue of the loader not being able to access the MixedRealityRuntime.json file.
64,502,209
64,503,377
Count sum of a subset of an array without bruteforcing it
I'll start by explaining step by step what I have to do. First I make an array containing N prime numbers that I create like this: bool isPrime(int n) { if(n <= 1) return false; for(int i = 2; i * i <= n; i++) if(n % i == 0) return false; return true; } int p[n + d], j = 0; for(int i = 0; j < n + d...
To optimize this you have to invest your mathematical knowledge. You should start from calculating prime using Sieve of Eratosthenes or some better algorithm. Then note that all your q but first must be odd. All primes except 2 are odd and all their multiplication is odd too. As a result only first item in q is even. W...
64,502,773
64,503,085
Filling vector with a single char*, pointing to the base of a char* array in C
Assuming that I have a char* of the base of a char*[]. I know that every char* in the array is null-terminated, and the last entry is NULL. char* args[] = {"foo", "bar", NULL}; If I cast this to a char*, I should get the start address of "foo". char* p = (char*)args; Now, I would like to fill a vector of char*, only ...
I think filling the vector with char* p is possible using things like reinterpret_cast, but it will be tricky, dangerous, and not guaranteed. I won't recommend this. Instead of this, to fill the vector with non-null elements of args, I think you should use a pointer to point at the elements of the array char** p and us...
64,502,856
64,503,310
Issue with Intel compilation on macOS 10.15 Catalina : catastrophic error: cannot open source file "stdlib.h"
I try desperatly to compile with c++ intel compiler (icpc) a simple code that I was used to compile on my previous macBook 10.14. Now, since Headers don't exist anymore with 10.15 Catalina, the compiler has difficulties to find stdlib.h. Here the output I get : icpc -std=c++11 -O3 -xHost -fp-model strict -prec-div -pre...
Run the command in the Terminal sudo xcode-select --reset And then check if proper developer tools are selected instead of the command line tools xcode-select -p
64,502,926
64,504,066
How to add standard routine to every function in array of function pointers?
I'm creating an application in C++ for an embedded system. Therefore I'm tied to some C libraries, and do not have the freedom to use a lot of std functionality. I have a callback signature: typedef int (*callback_fn)(int a, int b); A list with pointers to the registered callbacks: callback_fn my_callback_functions[10...
Let's start naive, then add sophistication. The simplest way to add your routine would be to edit the callback function. That is, if one of your callbacks is fun1(), you could add the line myTimer.reset(); to the beginning of the function body. Except... maybe not every call to this function is supposed to reset the ti...
64,503,440
64,503,682
Why does enabling undefined behaviour sanitization interfere with optimizations?
Consider the following code: #include <string_view> constexpr std::string_view f() { return "hello"; } static constexpr std::string_view g() { auto x = f(); return x.substr(1, 3); } int foo() { return g().length(); } If I compile it with GCC 10.2, and flags --std=c++17 -O1, I get: foo(): mov eax...
Sanitizers add necessary instrumentation to detect violations at run-time. That instrumentation may prevent the function from being computed at compile-time as an optimization by introducing some opaque calls/side-effects that wouldn't be present there otherwise. The inconsistent behavior you see is because g().length(...
64,503,564
64,503,850
what can I get sum that string tokens converted int in C++?
I need to sum 100, 200, 300 in a.txt a.txt 2323|A|5|0|2|100 2424|B|6|1|3|200 2525|C|7|2|4|300 so I opened this file, and read line by line using getline(), and tokenized. main.cpp for (std::string each; std::getline(split, each, split_char); tokens.push_back(each)) { for (int i = 0; i < tokens.size(); i++) { ...
You are modifying the tokens vector while you are looping through it. Don't do that. You are affecting its size(), which accounts for why you are able to go out of bounds. You say that you need to sum only the last token of each line. But that is not what your code is trying to do. There is no need for an inner for...
64,503,643
64,511,800
Xcode Sanitizer How to Enable
Using Xcode 12, Apple Clang Address Sanitizer, I enable... Enable C++ Container Overflow Checks (for both Debug and Release). I wish Enable C++ Container Overflow Checks to give me run-time warnings, eg. by translating each [] into an .at(). I run a code similar to the below (which comes at the end of a bunch of previo...
This is the way to do it: https://developer.apple.com/documentation/xcode/diagnosing_memory_thread_and_crash_issues_early To enable this tool, select Address Sanitizer from the Diagnostics section of the appropriate scheme. Also, other sanitizer checks may be enabled from that menu. I have verified that this works, it...
64,503,937
64,504,424
Recursive virtual call not working as it should?
I have this code: #include <iostream> #include <string> using namespace std; struct Flower { virtual string str() = 0; }; struct Rose : Flower { string str() override { return "A rose"; } }; struct RedFlower : Flower { Flower& flower; RedFlower(Flower& flower) : flower{ flower } {} string str() o...
the problem here is, that the compiler automatically generates a copy- constructor with the following signature: RedFlower(RedFlower const &) That constructor is being called instead of your custom one. One solution is to add an explicit cast to Flower &: Rose rose; RedFlower red_rose{ rose }; RedFlower red_red_rose{ ...
64,504,266
64,504,397
Change recursion to something less expensive
im trying to find the shortest path from the vertex to another. To be more precise I have a directed graph and by going always "forward" in it i will always end up in the end. Something like structure of neural network. I decided to find the shortest way with recursion which worked perfectly fine with smaller numbers. ...
You can implement the Dijkstra's algorithm iteratively. Here's a snippet of code which implements Dijkstra's algorithm iteratively #include <queue> #include <unordered_map> #include <vector> using IntPair = std::pair<int,int>; std::priority_queue<IntPair, std::vector<IntPair>, std::greater<IntPair>> pq; std::unordered...
64,504,452
64,506,861
Interrupt sleep by signal
I want to write an C++ programm which should wait for a linux signal (millisecond resolution), but I am not able to find a possibility to achieve this. The following test code should terminate after 500ms, but it doesn't. #include <iostream> #include <csignal> #include <unistd.h> #include <chrono> #include <future> us...
With the idea of ti7 and user4581301 I finally found a solution. Using the idea of an mutex in the signal_handler but restricted to the set of allowed system calls, I use a semaphore. sem_t *sem_g = nullptr; extern "C" void handler(int s) { if (sem_g) sem_post(sem_g); } int main() { sem_t sem = {}; ...
64,504,534
64,505,014
How do I pass a temporary object as a non-const reference into a member function?
We are creating a class designed to send information out from the current module (the specifics are not relevant to this question). An object of this type is created and populated with a portion of the data that needs to be sent, and then passed into a (different class) member function. That function provides the objec...
As mentioned in the comments, you could simply change your doSomething function to accept an rvalue reference to the passed XferInfo object (using the double &&): void doSomething(const string& somethingParam, XferInfo&& xferInfo) { // complete data for xfer xferInfo.setCalleeInfo(somethingParam...
64,504,910
64,505,076
Is it possible to iterate through pair of values using for loop in c++?
Is something like this is possible or there is any way to assign the pair values separately in for loop? vector<pair<int, int>> arr; // Input some values here in arr for(auto &[x,y]: arr){ cout<<x<<" "<<y; }
Your code is actually valid code in C++17 or later, as @MikeCAT said. You're using what's called a structured binding. It can unpack values from arrays or simple class types, in this case from pairs.
64,505,230
64,505,343
C++ Convert stringstream into ifstream?
I am working with two pieces of code, The first class uses an AAssetManager (Android NDK object) to read an "asset" and save it's contents to a single string. It then turns the string into a stringstream and parses it. The second class parses type ifstream, which must be associated with a file. Is there some way I can ...
You can turn the ifstream into an istream. An ifstream is simply a more specific form of an istream. A stringstream inherits from an istream, so you can just pass the stringstream directly. If this is not available to you, then you would store the string to a file, then reopen the file with an ifstream, and pass that i...
64,505,297
64,505,492
Create template pack from set of traits
Is it possible (and if so, how) to generate a template pack from a indexed set of type traits so they can be used to instantiate a variant or a tuple? #include <variant> template<int n> struct IntToType; template<> struct IntToType<0> { using type = int; static constexpr char const* name = "int"; // Other co...
You could do: #include <variant> template<int n> struct IntToType; template<> struct IntToType<0> { using type = int; static constexpr char const* name = "int"; // Other compile-time metadata }; template<> struct IntToType<1> { using type = double; static constexpr char const* name = "double"; // O...
64,505,490
64,515,946
C++ ELF object file symbol table has function listed twice
I've got a source file that defines a move constructor for a very large class. I compile it with g++ 4.9.2, on a linux system. When I dump the symbol table of the resulting ELF object file, I see 2 listings for the move constructor. Both listings have the same address, the same size, the same type, and the linker links...
TL;DR: If you want to understand what's going on don't use objdump to examine ELF files, use readelf instead (see below) don't demangle names with c++filt -- different symbols can produce the same demangled name (i.e. it's not a one-to-one transformation). Details: cat foo.cc struct Foo { Foo(Foo&& f); void *p; ...
64,505,914
64,505,968
Inner while loop iteration with outer loop
I have a simple nested while loop situation but I'm not sure how to increment numGuesses inside the second loop to escape the first loop once it is no longer less than 5. while(numGuesses<5){ while(!correct){ cout << "\nGuess the number the computer randomply picked between 1 - 100: "; numGuesses++;...
You should just use one while loop! After all, the thing you're looping over is prompting for a guess. There's no need for a second layer of looping inside that. Think about when you want to stop asking for a guess -- when the guesses get to 5 or when they get it correct. So when do you want to keep asking for a guess?...
64,506,541
64,506,642
Type-checking in template function returning given type
In a function like the following: template <typename T> T foo () { std::string str("foo"); if (typeid(T) == typeid(int)) return (T)(1); // Cast to T is required in order to make sure the function returns T else if (typeid(T) == typeid(std::string)) return (T)str; // .. } It will get a compile error because th...
In C++17 and later, you can use if constexpr with std::is_same_v: template <typename T> T foo () { if constexpr (std::is_same_v<T, int>) return 1; else if constexpr (std::is_same_v<T, std::string>) return "foo"; // .. } This allows the compiler to optimize the ifs at compile-time and eliminate any unused...
64,507,009
64,507,010
aws-cpp-sdk fails during Windows build due to install(EXPORT "foo-targets" ...) includes target "foo" more than once in the export set
Asking so I can answer this myself, lost a day to it and want to save other folks the trouble. Setup: Windows (seen on both Windows 10 and Server 2019) Visual Studio (seen on both Visual Studio 2017 and Visual Studio 2019) cmake 3.19.0-rc1 (latest download as of this post) Following instructions at https://docs.aws.am...
Completely non-obvious, but the issue appears to be with "cmake 3.19.0-rc1". Changing to cmake 3.18.4 bypassed the issue. I can't tell if this is a cmake issue or an sdk issue, or I'd be posting on somebody's github instead of stackoverflow.
64,507,098
64,507,402
HidD_SetOutputReport not resolved
I'm trying to interface with a device I found that uses the hid protocol. I'm using signal11's hidapi, and c++, however I'm writing to the device using hidsdi.h, specifically HidD_SetOutputReport, however, this results in "LNK2019: unresolved external symbol HidD_SetOutputReport referenced in function main" Here is my ...
You must link your program with Hid.lib. Go to project settings / linker and add it to all targets.
64,507,502
64,508,341
How to change raw pointer to unique_ptr in container of pointers wrapped by boost::variant
Live code example I am trying to hold a variant of pointers to templated versions of a base class in a vector. The boost::variant of pointers happens to be contained in a struct. It works fine if these pointers are raw pointers, but things start going wrong when I change them to unique_ptr. struct Sayer { struct Cat...
Two things: First, you have to move g in the Category Constructor, since a variant is non-copyable if any of its members is non-copyable. Second, while every conversion in the chain AgeGetter* to Getter<int>* to std::unique_ptr<Getter<int>> to Category is implicit, C++ only does a limited number of implicit conversions...
64,507,886
64,507,963
Is it undefined behavior to compare function pointers reinterpret_cast to void(*)()?
For example, can I make a std::set<void(*)()> and use reinterpret_cast to put arbitrary function pointers into it? I obviously wouldn’t be able to call them, but if I wanted to remember what functions I’ve seen, would seen.count(reinterpret_cast<void(*)()>(fn)) be defined behavior? For now I’m assuming the functions I ...
This is fine. According to [expr.reinterpret.cast], A function pointer can be explicitly converted to a function pointer of a different type. It also says that converting a function pointer to a different function pointer type and back will yield the original pointer type.
64,507,892
64,507,936
C++ order of operation during multiplication
I'm writing a simple program in C++ and I noticed that when I switch the order while multiplying some numbers i get 2 different outputs and can't figure out why it's happening. void multiplier() { double r, v1, v2; cout << "Enter the value of r" << endl; cin >> r; v1 = 4/3*M_PI*r*r*r; cout << v1 << endl; v2...
What's happening here is the difference between integer division and floating-point divison. Multiplication and division are interpreted left to right. In the first case, the 4/3 is read first. When you write 4/3, the compiler interprets that as an integer division, which would return 1. However, in the second case, th...
64,508,119
64,508,696
printing array from unified memory on cuda device doesn`t work
I try to create some hashes on a cuda device and printing them on the host. But at the printf on the host i am getting a read error at position 0x000000000100002F The relevant lines look like this: int main() { const int block_size = 2; const int num_blocks = 256; const int N = block_size * num_blocks; unsigned char**...
The memory allocation you are using to hold the hashes is incorrect. To have an array of pointers to the memory for each hash, you would require memory allocated both for the array of pointers, and for the hashes themselves, so something like: unsigned char** hashes; unsigned char* buff; cudaMallocManaged(&hashes, N *...
64,508,290
64,511,197
How to set TextBlock properties programmatically using C++/WinRT + WinUI 3
I've been hiding under the MFC rock for many years so I can stick to standard C++ but still write Windows Desktop apps. With C++/WinRT and WinUI 3.0, it appears that I may finally have an opportunity to modernize my code. The problem is that I know nothing about XAML or the Windows API. To fix this problem, I'm tryi...
To be sure, you'd need to post a little more detail (like what error message you're getting). But I'll take a guess that perhaps your code is missing a namespace qualifier. I'm just going off the UWP Windows namespace types, not the WinUI Microsoft namespace, but this code builds for me: #include <winrt/Windows.UI.h> #...
64,508,541
64,508,658
Input cycle loops twice when given two values
So I just started learning c++ and wanted to make it so you have to enter a number between 1-10, works fine if I run the program. #include <iostream> #include <limits> int main() { int a; do { std::cout << "Enter a number between 1-10"; std::cin >> a; if (std::cin.fail()) // if in...
To avoid the repeated input description you just need remove the if statement, and place the buffer clearence and flag reset routine outside: int main() { int a; do { std::cout << "Enter a number between 1-10"; std::cin >> a; std::cin.clear(); std::cin.ignore(std::numeric_li...
64,509,133
64,509,203
Sorting Array not functioning correctly C++
So, I have been writing a sorting loop for my program. It automatically sorts Arrays and has done it in the past efficently. That being said, once I added it into my American Football Manager program, things did not work out so effectively. So below, I will provide a working version of this sorting loop, and then after...
Here are problems of the second code: Non-standard unused headers are included and they are preventing the code from working in some environments. teams[0].wins is used without being initialized. teams[10].wins = 9; cause dangerous out-of-range access. The sorting routine is accidentally put in the printing routine. O...
64,509,374
64,509,475
Inputting Huge Binary Numbers C++
So I am working on a competitive programming problem where you take two numbers base two and base three, and then do some operations on them. I got the code implementing correctly, however it doesn't work with large inputs. For example, when I try to input 10010111011100101101100011011 (base two) and 211010102022001220...
Depending on what particular operations you want to perform on your base-2 and base-3 numbers, it may be feasible to just operate on string values. The advantage is that you are virtually unbounded. Read your input numbers as strings. Write a function to verify that a given string is a valid number in a given base. The...
64,509,428
64,509,672
What is a good algorithm for traversing outward from a point on a 2D grid?
Suppose I have a 2D array where 0,0 is in the top left corner and the bottom is say 100,100. I have a point in that array such as 10,10. I want to do a test on each element that is 1 away from this point so a 3x3 box. If all my tests fail I want to move out one more rectangular ring so now it would be a 5x5 box. But I...
Suppose you start at the red square (i,j) and need to check for a cover. You need to do what you are asking for. Check each surrounding rectangle. Start from index (i-1, j-1). Do a test on the green squares. If not found, start from index (i-2, j-2). Do a test on the blue squares. If not found, start from index (i-3...
64,509,448
64,509,759
How do I forbid an implicit conversion from int to double in C and C++?
There is a simple a program: #include <iostream> int main() { int i = 1; double x = 2.5; x =i; // I do not want this can be compiled with no warning // I want only x=(double)i, or x=std::static_cast<double>i, that can compiled with no warning. std::cout << "x = " << x << std::endl; return 0; } ...
I believe you are looking for these warning flags: -Wconversion -Warith-conversion -Warith-conversion Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from -Wconversion, -Wfloat-conversion, and -Wsi...
64,509,507
64,523,818
Gtk::Window add grid is not showing my child widgets
I attached two widgets to a grid; a label and a spinbutton, then added the grid to Gtk::Window I get blank output like this: #include <gtkmm.h> class SpinButtonExample : public Gtk::Window { public: SpinButtonExample(); }; SpinButtonExample::SpinButtonExample() { auto grid = Gtk::Grid(); auto label...
Since your grid variable (and all the others) are local variables, they're destroyed once SpinButtonExample::SpinButtonExample() finishes. This is not specific to GTK, it's a C++ memory management issue. Local variables are destroyed at the end of their scopes. You need a way to keep a reference to your widgets after t...
64,509,537
64,509,730
Can I make sure that only reference variable can accept the result of a function?
Let's say I have this function class Entity; Entity& CreateEntity(){ Entity* e = new Entity(); entityVec.emplace_back(e); return *e; } Currently, both of the code below would compile. Entity a = CreateEntity(); Entity& b = CreateEntity(); However, I want to make sure that only a reference variable can ac...
I wish there was a compiler warning for this. Because what you are addressing is a real concern for performance particularly when using the STL. Microsoft Code Analysis could be what you are looking for: https://devblogs.microsoft.com/cppblog/new-safety-rules-in-c-core-check/ https://learn.microsoft.com/en-us/cpp/code-...
64,509,589
64,509,630
Is it allowed to return a moved object as a const lvalue reference?
Is it allowed to return a moved value as a const lvalue reference? include<string> using namespace std; class C { private: string s; public: const string &release() { return move(s); } };
Well, yes but it won't do anything. The std::move function is just a cast to a rvalue reference. So in effect: std::string s; std::move(s); // returns std::string&& to `s` So it just returns a reference to the object you pass in. So in your code, you create an rvalue reference to your string s, but you bind that refer...
64,509,796
64,741,255
How to handle a dynamic number of draw calls in vulkan
I'm currently trying to get into Vulkan, and I've mostly followed this well-know Vulkan tutorial, all the while trying to integrate it into a framework I built around OpenGL. I'm at the point where I can successfully render an object on the screen, and have the object move around by passing a transformation matrix to a...
Generally command buffers are actually re-recorded every frame, and Vulkan allows to multithread recording with command pools. Indirect draws exist: you store data about draw commands (indeces count, instances count, etc.) into a separate buffer, and then the driver reads the data from the buffer when you submit the c...
64,510,477
64,511,027
error: C2061: syntax error: identifier 'concurrent_vector<`template-type-parameter-1',`template-type-parameter-2'>'
A code compiles/runs fine on Linux and macOS. On Windows 10, I'm compiling the code with Visual Studio 2017 toolchain, but I'm receiving this error: ...\deps\tbb-2020.3-win\tbb\include\tbb\concurrent_vector.h:680: error: C2061: syntax error: identifier 'concurrent_vector<'template-type-parameter-1','template-type-para...
This seems to be a visual studio bug. From the issue on the TBB github respository the /Zc:__cplusplus compiler flag is the cause. Enabling that flag causes this code to use the c++14 [[deprecated]] attribute: #if (__cplusplus >= 201402L) #define __TBB_DEPRECATED [[deprecated]] #define __TBB_DEPRECA...
64,510,939
64,518,548
How can i return an error to std::filesystem?
For example, this is how I do it using runtime_error #include <exception> #include <filesystem> std::exception &foo(){ try { if(!std::filesystem::is_directory(std::filesystem::path("sdfsdf"))){ throw std::runtime_error("Error14"); } } catch (std::exception &e) { return e...
std::filesystem::is_directory has a few overloads. If you provide an std::error_code object as the last argument it will not throw, but instead set the value of the error code object if an operating system error occurs. So you could use this overload to set the std::error_code object and create the std::filesystem::fil...
64,511,065
64,511,210
Why functional objects in C++ for arithmetic operations are implemented as templates?
I wonder, why functional objects in c++ are implemented as templated, with void as default type since c++14. For example: https://en.cppreference.com/w/cpp/utility/functional/plus https://en.cppreference.com/w/cpp/utility/functional/minus This object in fact performs arithmetic operation +, -, *, /, when called by op...
It's a design choice. If you specify the type there is no template operator(), instead the whole class is a template. The operator() is simply something like constexpr T operator()(const T &lhs, const T &rhs) const { return lhs + rhs; } This is in several ways different from having a template operator(). If we pa...
64,511,118
64,511,190
Why Visual C++ Redistributables needed?
I'm installing GTA 5 and it's also installed Visual C++ Redistributables. This got me curious about something, because this happens a lot. As far as I know, these are needed for linking to VC++ libraries, but I already have .NET 4.8 installed on my system. I thought when C++ (managed) gets compiled to MSIL, it would th...
Simple answer: ".NET runtime" is to C# as "Visual C++ runtime" is to C++ Explanation: Applications written in C# or "managed code" require a specific version of the .NET runtime installed. The .NET runtime not only includes the interpreter for the virtual machine code, but also provides all the standard class librarie...
64,511,260
64,518,150
How to insert product and sum between every two consecutive elements in an array
In a vector, I must insert product and sum between every two consecutive elements.For example the 1 2 3 4 vector will become 1 3 2 2 5 6 3 7 12 4. This is the code i did till now. You can see that the function which makes the insertion is insertInVector(). #include <iostream> void sumProduct(int a, int b, int* suma_fu...
I changed some things in your code. One of the main things is that you can't insert in the middle of an array as it has a static memory (if you want to change only in the given array without using anything extra then you should use vector instead of array). So for this purpose, I have used an extra temp array and refle...
64,511,350
64,511,437
Array of pointers to an array of pointers to int
If i have array of pointer to an array of pointer to int int **arrs = new int *[n]; and assign each element to new array of pointer to int for i<n arrs[i] = new int[size] Now, when i try to get size of these arrays, give me wrong value int size = sizeof(arrs[0])/sizeof(int); It gives me wrong value. So how can i ge...
You can't. arrs[0] is a pointer, so sizeof(arrs[0]) gives the size of that pointer. It comes as a surprise to some that there is no way to get the size of an array from only a pointer to that array. You have to store the size somewhere else. In C++ the simplest and best solution is to use std::vector. Why reinvent the ...
64,511,411
64,511,478
Why I'm getting TLE even if I'm using memoization?
Here is the question statement Given two strings s1 and s2, return the length of their longest common subsequence. A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subse...
use call by reference in function definition instead of call by value. int lcs(string &s1,string &s2,int n,int m); int longestCommonSubsequence(string &s1, string &s2);
64,511,432
64,511,975
Convert boost::parameter_types to std::tuple
I believe there are some ways to do this with MPL and fusion, but since I'm new to boost, it's kinda hard to figure out. It doesn't matter whether the tuple is of std's or boost's, what I'm trying to ultimately achieve is: template<T> void some_func() { // declare a tuple contains types of which in boost::function_...
Haven't tested it, but the following should work: #include <type_traits> #include <tuple> #include <boost/mpl/at.hpp> // For at namespace detail { template<class ParamSequence, std::size_t ...Indices> auto unpack_params(ParamSequence, std::index_sequence<Indices...>) -> std::tuple<boost::mpl::at<ParamSequence, Ind...
64,511,753
64,511,928
How to output an array with a[0] - a[0]a[1] - a[0]a[1]a[2]
How can I print an array with a[0] then a[0], a[1] then a[0],a[1],a[2].... For example. I have an array is a[] = {1,2,3,4} My output should be: 1 12 123 1234 Here is my code but the output is wrong: #include <iostream> using namespace std; int main() { int a[] = { 1,2,3,4 }; for (int i = 0; i < sizeof(a)/sizeof...
What you should probably do is iterating through i, because it contains your current position in your array. you can then print the array until the i-th position .. like this : int main() { int a[] = {1,2,3,4}; for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) { for (int j = 0; j <= i ; j++) ...
64,512,105
64,512,190
Cannot print out decimal numbers upto 6 in a void function.the value are correct checked by debugging.the problem is with the output
**The void function automatically rounds off the value of a,b,c and prints out 0 instead of 0.5,0.33,0.166. I have checked the value of num1,num2,num3 and g they are correct just the problem is with the rounding off of the decimals of a,b and c.The setprecision function is also not working. The simple concept is when ...
Do you want the code to have an output of numbers; bc in which case, you need to sysout variable num1, num2, and num3.
64,512,217
64,512,301
Overloading virtual method in derived class with different signature
Having a BASE class defining a virtual method a DERIVED class which defines a virtual method with the same name, but different signature the compiler complains that it cannot find the correct function in the BASE class when called from another class using a pointer to the DERIVED class. Example (Constructors etc omit...
print in the DERIVED shadows print in the BASE, even though the signatures are different. To fix, add using BASE::print; to the DERIVED. Note that this line can change the access modifier of the inherited function; if you want the function to be public, the using ... must also be public. Be aware that you don't overrid...
64,512,567
64,512,852
Is there a way to take input from user in vector in C++?
I want to get my iterator to the last occurrence of 1. For example, in a vector A[0, 0, 1, 0, 1, 0, 1, 0, 0] I want to get my iterator to 6th place in 0 based indexing. I want to do this using vector function but the array won't be hard-coded in the program. The program is to take a vector from user consisting of 0s a...
I would suggest you to make a vector funtion with parameter of another vector. like, vector<int>Printvectors(vector<int>vectornew){} // If you want the return type to be // a vector And to accept the value of the users into the vectors what u can do is- vecto...
64,512,591
64,513,100
How to look for an element inside a set of sets in C++?
Following is my code: set<set<int,greater<int>>> output; set<int,greater<int>> k; k.insert(5); output.insert(k); Now how do I find out if element 5 is present in my 'output' set or not? And how do I find out which set, inside my 'output' set, the element 5 belongs to?
Use a simple for loop: size_t ii = 0; for (const auto& inner : output) { if (inner.count(5)) std::cout << "found in set " << ii << std::endl; ++ii; }
64,512,744
64,514,217
Codecov: gcov code coverage for a C++ library
I am writting a small C++ static library. Within GitHub Actions I have a "unit test" workflow which compiles and runs a test program and the code coverage is submitted to the Codecov service afterwards. It runs: g++ test.cpp library/library.cpp --coverage -o test, then ./test, followed by gcov -o . test.cpp. In the nex...
There is no easy way to exclude files at the gcov level, but I solved the issue by restricting the codecov submission: https://docs.codecov.io/docs/ignoring-paths
64,512,861
64,512,956
"Address of local variable may escape the function" in range-based for loop
I want to store a pointer to a vector element, selected in a range-based for loop, all that in a static context. However, CLion gives me the warning Address of local variable may escape the function. Here is an example: struct TestStruct { static std::vector<std::string> _values; static const std::string* _sele...
There's nothing wrong with the code as it stands in terms of object lifetime. CLion isn't omnipotent - it doesn't know what your intent is. What it knows, is that you are storing the address of a local variable (value) in a static var so it's completely right at warning you that "The address of a local variable may esc...
64,513,540
64,516,818
Why does a boost adjacency_list using vecS as OutEdgeList template parameter invalidate edges on traversal?
I'm reading the documentation about adjacency_list and the impact choosing the graph type has on memory consumption, big-O runtime, and descriptor stability. Quoting the first link: The following table summarizes which operations cause descriptors and iterators to become invalid. In the table, EL is an abbreviation fo...
You’re misreading it, as you suspected. The confusion is that the columns “Edge Iter”, “Vertex Iter” and “Adj Iter” are abbreviating for “Iterator”, not “iteration”. The mere act of iteration never changes the adjacency_list, so cannot invalidate descriptors nor iterators. There are graph models where the descriptors a...
64,513,548
64,513,586
Class template value without template arguments error
I have some code: template<typename Container = std::vector> // there is error class SomeClass { struct SomeDataStructure { int a; float b; }; Container<SomeDataStructure> container; // and there }; I want to pass template class type in template arguments of other template class. In this e...
You need template template parameters: template<template<class, class...> class Container = std::vector>
64,514,096
64,560,883
ObjC app project gets build error at its reference to a C function within a .cpp file within ObjC class lib imported into app
Project “app” gets build err: "Undefined symbol: run_mobile_session()" Proj app includes ObjC class lib project hub_lib. Proj hub_lib has folder with main.cpp file that has function "run_mobile_session()" that is undefined in app build I build without error the hub_lib project and did ctrl-drag of its .h and .a from...
Solution was to move the extern from hub_lib.mm to hub_lib.h and mod to be C++: extern "C++" void run_mobile_session(void); Thanks for solution, gnasher729.
64,514,322
64,622,021
How to check if Media Foundation can actually play a file and not just load it
I'm having some problems with MPEG1 videos and Media Foundation: So Media Foundation doesn't support playback of MPEG1 video streams (see here), but for some reason it will still open them and it will even report the correct duration and frame size. So at opening time everything looks like it can play those files. But ...
I have solved this now by using IMFSourceReader. I have found out that trying to set the media type to MFVideoFormat_RGB32 will fail with MPEG1 video streams but it will work fine with MPEG4 so this is probably a feasible way to check if Media Foundation can actually play a file. In code, the solution looks like this: ...
64,514,393
64,514,546
White Screen(OpenGL)
I am new to OpenGL and i want to draw a simple triangle on screen with my shader. I set up buffers and wrote a shaders but it doesn't seem to work. It gives white screen, i tried to change glCreateBuffer with glGenBuffer and screen turned to black screen. I want to create&compile shaders in one function called createAn...
Fragment shader input layout locations qualifiers are not provided in GLSL 3.30. You have to switch to GLSL 4.10 or remove the layout location in the fragment shader: layout(location = 0) in vec4 position; in vec4 position; Furthermore you missed the specification of the fragment shader output color. #version 330 core...
64,514,471
64,514,925
I am using "SparkFun Qwiic Keypad", For Keypad Library some do not understand
I am using "SparkFun Qwiic Keypad", and I am learning about the Arduino_Library provided by "SparkFun". Some do not understand. In "SparkFun_Qwiic_Keypad_Arduino_Library.h",lines 50 and 62, What is "TwoWire *_i2cPort" in it? what is the purpose? I am a super newbie in C & C++, I hope everyone can help explain. Thank yo...
The Sparkfun Qwiic series components use I2C protocol to communicate. So the sensors, actuators, displays are not directly connected to digital or analog pins of the Arduino, but all have a chip which uses I2C protocol to communicate with the MCU. The I2C uses two wires and is a bus where each device has its address. T...
64,514,986
64,515,058
What does the "*" mean in various pointer scenarios?
I know that * is widely used as the multiplication operator, it can be used for so much more though. For example: int number = 5; int* pointer = &number; In this example a int pointer gets declared and defined with the * syntax to the RAM address value of the variable number. Now if we'd want to displ...
Grammatically, the declaration is int *pointer, not int* pointer, and the * conveys essentially the same meaning both in a declaration and in an expression. In an expression, *pointer refers to some object using its memory address. A declaration such as int *pointer means that *pointer will refer to an int. Since *poin...
64,515,062
64,515,155
High performance recursive functions in C++
I am learning C++ and I was toying with linked lists. Consider the following extremely simple implementation: static std::size_t n_constructors {0}; template <typename T> class list { public: list(T n) : item{n} { n_constructors++; } list(T n, list* l) : item{n}, next {l} { n_constructors++; } list(const...
You're not only testing here between recursion and iteration, but between two algorithms that have a different order of growth. Your reverse has the complexity T(n) = T(n - 1) + O(n), and so is quadratic in the number of links. Your reverse_iter has only linear complexity. The comparison is unfair, therefore.
64,515,259
64,515,327
std::default_constructible for templated class parameter
I'm fairly new to c++-templates, and at the point where I'm realizing that I'm probably doing template meta-programming. What I want is to achieve the following definition: #include <type_traits> // T must be default-constructible template<class T, std::enable_if<std::is_default_constructible<T>>> class PoolAllocator ...
std::enable_if is pointless on a class template. It's useful for overloaded function templates, and less commonly, for partial specializations of a class template; that's where SFINAE applies. If you simply want to prevent PoolAllocator from compiling if T is not default-constructible, use static_assert: template<class...
64,515,408
64,515,534
Known sizes at compile time of variadic arrays
I am trying to deduce each array size at compile time, but I do not like the way which I came up with. template <std::size_t Length> struct __helper { __helper(const char (&_sName)[Length]) { memcpy(m_sName, _sName, Length); } char m_sName[Length]; }; template <std::size_t... Lengths> static v...
Syntax to take variadic C array is: template <std::size_t... Ns> static void foo(char (&...args)[Ns]) { // ... }
64,515,489
64,516,208
c++ make_shared<> with 2d array
Using simple pointers when dealing with 2d array allocation is done by new in this way (suppose matrix 10x1000) : double ** dPtr ; dPtr = new double* [10] ; for( size_t i =0 ; i<10 ; i++ ){ dPtr[i] = new double [1000] ; } Now, when using smart pointers, we can define the matrix type (suppose using s...
The direct translation of your code to std::make_shared() would look like this: std::shared_ptr<std::shared_ptr<double[]>[]> dPtr; dPtr = std::make_shared<std::shared_ptr<double[]>>(10); for( size_t i = 0 ; i < 10 ; i++ ){ dPtr[i] = std::make_shared<double[]>(1000); } Which can be cleaned up a little further, eg:...
64,515,628
64,515,706
What is the difference between declaring a copy constructor with "= default" or not declaring it at all?
I am trying to understand the behaviour of auto-generated compiler code for various functions such as: destructor copy constructor assignment operator move constructor move assignment operator Will declaring them with "= default" cause any functional difference compared to non-declared case? Does the answer of this q...
In some cases the copy constructor is deleted by default. The most simplest example: class myClass { public: myClass(); myClass(myClass &&); }; myClass a; void func() { myClass b=a; // ERROR } Rather than explaining the reason for the compilation error, I'll just paste the compilation error, verbatim, ...
64,515,911
64,516,542
Can I store a string in character array but reverse order, such that 0(index) points to last character in string?
I started to learn to program and I'm trying to store a string into a character array but in reverse order, such that array index position 0(zero) points to the last character in the string. I tried using for loops in different terms but getting the desired output. I want to solve this problem in C++. Here is the code ...
I guess you don't wanna use std::reverse mentioned in the comments because you want to practice your algorithmic skills. You can help yourself with this short program. It uses std::malloc to allocate a char array of the size of the input string. Then, you just need to loop backward through the character of the string a...
64,515,942
64,519,577
NMAKE : fatal error U1052: file 'Makefile.vc' not found
I'm trying to do the steps as mentioned in Install pdcurses on Visual Studio 2017, which tells me to boot up the Developer Command Prompt for my VS(2019), and write set PDCURSES_SRCDIR=D:\PDCurses-3.9\PDCurses-3.9(my path for PDCurses) but I was stuck at step 2: Navigate in the command window to the directory of PDCu...
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community>nmake -f Makefile.vc This is running nmake in the wrong directory, causing the file 'Makefile.vc' not found error. The nmake command must be run in "the directory of PDCurses/wincon" as mentioned in a previous step. Assuming PDCURSES_SRCDIR has been set al...
64,516,031
64,516,424
Perfect forward return type but with const
I want to perfect-forward a call to a function, but I always want to return a const version of the returned type. I mean, when returning a reference, I want a const& instead. How can I achieve that? I don't care about non-reference types. After all, returning a const T (without a reference) is not much different than ...
Here is a possible solution. References are transformed to const&. Any other type remains unchanged. However, I would like to hear a second opinion, if there are some corner cases I didn't consider. #include <utility> template<typename T> struct add_const_to_ref { using type = T; }; template<typename T> struc...
64,516,177
64,544,600
call kernel inside CUDA kernel
I am trying to do something like that: __global__ void foo() { // do stuff } __global__ void boo() { foo<<<m, n>>>(); } but I am getting the error "kernel launch from __device__ or __global__ functions requires separate compilation mode" I tried googling for an answer and I saw some results talking about "dyn...
I still don't know what caused the problem but after deleting everything related to Nvidia except for the driver and then reinstalling everything through the CUDA installer the error went away and it now works fine.
64,516,180
64,516,673
Deciding to use at runtime a boost::static_vector or a std::vector
I have an application that I want to minimize dynamic allocation for efficiency. I'm leaning forward using boost::static_vector in one of my classes for that reason. I'm not sure yet exactly how big my array will need to be to accommodate most situations but there are always exceptions... Instead of discarding the inpu...
boost::small_vector may be the combination you are looking for. From https://www.boost.org/doc/libs/1_60_0/doc/html/boost/container/small_vector.html: small_vector is a vector-like container optimized for the case when it contains few elements. It contains some preallocated elements in-place, which can avoid the use o...
64,516,433
64,516,474
Trouble installing C++ libraries from Github
I've used C++ for several courses in university but the libraries we used in these courses were quite simple to install. When we came across libraries which required a bit more complex installation, our teachers always provided detailed instructions. This time I'm doing a project on my own. I have downloaded libraries ...
I'm trying to install libccd so I can then install fcl. In the instructions 3 ways are mentioned: Using Makefile Using autotools Using Cmake In all 3 methods, I see specific commands like this : First of all, where am I supposed to write these commands? These instructions are for a UNIX-like system. Makefiles, aut...
64,516,852
64,517,056
C++20 lambdas with non type template parameters
I'm messing around with new C++20 lambdas, it seems I can declare a lambda taking a non type template param, but then I'm not able to call it. #include <iostream> int main() { // compiles fine auto f = []<bool ok>() { return ok; }; // it even has an address?? std::cout << &f; // f(); // error...
Is explicitly passing template arguments at the lambda call site forbidden? No, but the issue is you're not specifying the template argument for the right entity. Note that f itself is not a template. It's an object of a non-templated type that contains a member operator() that is templated. So when you do: f<true>()...