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
66,907,778
66,911,194
Compile time string generator based on templates
I am developing a GUI based on mfc. One of the controls allows a markup languge (XAML) to render text and icons inside it, so I am doing an intensive use of it. The markup string is almost the same for all the controls (12 in a form), so I wondered if it would be an easy way to make a function to generate that string. ...
It's not legal to pass string literals directly as template arguments, ever; however, one may bind the string literal to a constexpr array and pass that (by reference) instead: template<auto const& header, auto const& description, auto const& image> constexpr auto markup2() { ... } int main() { static constexpr ch...
66,908,075
66,908,118
boost::optional vs boost::make_optional
I would like to understand better the difference between creating a boost::optional object using the default constructor: boost::optional<PastaType> pasta = boost::optional<PastaType>(spaghetti) or using the make_optional version: boost::optional<PastaType> pasta = boost::make_optional<PastaType>(spaghetti) Looking a...
make_optional is a convenience or helper function that can reduce the amount of code you have to write by inferring the template parameter of optional. Functionally the two methods are equivalent. auto pasta = boost::make_optional(spaghetti);
66,908,260
66,908,285
C++ Reference Reassignment
I am seeing undefined behaviour in below code. I can't quite pin-point the exact issue, it'd be much help if someone could take a look and assist. Below is built using gcc 6.3.1. DBConn* dbconn = new DBConn(); DBConn& d = *dbconn; //reference .... delete dbconn; dbconn = new DBConn(); d = *dbconn; Assignment (=) opera...
The reference d is dangling once dbconn is deleted. Yes, the behaviour on accessing d after that is undefined. (Note that the pointer value dbconn is indeterminate after the delete.) References cannot be rebound, so the subsequent d = *dbconn; yields a diagnostic.
66,908,401
66,910,308
Creating a matrix class with std::vector, how to set the size of std::vector in the constructor?
I'm creating a class called "matrix" that has a class member of std::vector<std::vector<T>>, what is the best optimized way to set its size in the class constructor? I'm using matrix_.resize(m) in the constructor for m rows and then using a for loop to set its row values(matrix m x n). The question I have is: Is it a ...
The best way to do this is to not. vectors of vectors are a bad idea, especially at small sizes, because you want your memory to be contiguous. template <typename T> class matrix { public: typedef T value_type; // expose this private: std::size_t m_size = 0; std::size_t n_size = 0 std::vector<T> data; public: ...
66,909,592
66,911,575
how to interpret output tensor data packing in tensorflow lite c++?
I am working on a tensorflow-lite model in c++ (I have it working python already) and I was confused about how my output data is packed. I couldn't find any references in the documentation. I looked in the tflite source and learned I could get the output dimension of my tensor using dims for example for(int i=0; i < si...
TensorFlow Lite tensor data is stored in a continuous manner, which means that you can assume as it is flatten. In the other words, you can assume interpreter->typed_output_tensor<float>(0) as float[1][96][96][14].
66,909,666
66,909,758
C++: Way around dependent templates
I have a class template like this: template <typename T1, typename T2> class ClassName { // Members variables and Functions based on the template parameter types }; (T1, T2) can either be (class A, class B) or (class C, class D) only. So, T1 alone is enough to determine T2. Is there any way to only...
If your template only depends on a single parameter, you should not declare it with 2 parameters. You can use std::conditional together with std::is_same to declare conditional aliases. If you want: (T1, T2) can either be (class A, class B) or (class C, class D) only If "only" is meant as: User only ever instantiates...
66,910,041
66,910,973
Wait for timer in other coroutine (Asio)
When using asio::spawn, it possible to wait for a timer in a separate coroutine? E.g., in the code below I want coroutine 2 started to print to the console and then, 5 seconds later, coroutine 2 finished. #include <iostream> #include <boost/asio.hpp> #include <boost/asio/spawn.hpp> int main() { boost::asio::io_cont...
Many ways, most would center on sharing the timer. Easiest way I can think of is by spawning coro2 from coro1 ("forking", if you will), because why not: Live On Wandbox #include <boost/asio.hpp> #include <boost/asio/spawn.hpp> #include <iostream> using namespace std::chrono_literals; using boost::asio::yield_context; ...
66,910,226
66,917,488
Finding diameter of a graph using linear algebra or BFS
I got homework from school saying I need to find the diameter of a graph in CPP. The problem is I need to do it for 5000 graphs with 1000 vertices each. To save my graph I used vector of vectors like this: std::vector<std::vector<int>> graph I was able to find diameter of a graph using BFS on every vertex and returnin...
The fastest algorithm that I can come up with is well known Floyd-Warshall algorithm, which has complexity O(N^3) (N is number of vertices). It computes shortest paths lengths between all pairs of vertices. For the case of your 1000-vertices graphs the time is quite affordable - around 1 billion steps, which will take ...
66,910,323
66,910,562
How do i create a template class with specialized functions created in base classes?
Sorry if my description is not very clear. What i want to do is the following: template <typename T> class SubContainer { public: void add(T item) { mVector.push_back(item); } private: std::vector<T> mVector; }; class Container : public SubContainer<int> , public SubContainer<...
Furthermore, i would like to define the container as Container<int, float> container;. It seems to me that your looking for a variadic template class as follows template <typename ... Ts> class Container : public SubContainer<Ts>... { public: using SubContainer<Ts>::add...; }; so you can write Container<i...
66,910,578
66,911,518
No matching function call for lambda function parameter to template function
Trying to pass a lambda function to a template factory function which is templated on the function arguments of the passed function leads gcc-10.2.0 to report no matching function for call to ‘test(main()::<lambda(int, double)>)’. It does seem to work when I add a + in front of the lambda function forcing the conversio...
In order to support a variety of callables being passed to your factory (e.g., a stateful lambda or a function pointer), your test_type constructor should accept some kind of type-erased function type like std::function<void(int, double)>: template<class... TArgs> struct test_type { test_type(std::function<void(TArgs...
66,910,724
66,910,854
Formatting a parsable float literal
I need to output float numbers using printf formatting, in such a way that the generated string are valid float literals. As the numbers are arbitrary, I use the %g format descriptor, followed by an f. This raises a problem in one specific case: if the mantissa in an integer and no exponent is appended. In this case, t...
if the mantissa in an integer and no exponent is appended. In this case, the number is printed without the decimal point nor exponent So use the alternative form with %#g. It will always print a decimal separator, but it will also disable removing trailing zeros from the output.
66,910,944
66,911,085
Am I wrong with these shiftings?
I have a 14 bits address with leading zeros and I want to divide it into page number and offset. I was trying to solve it with shifting the address but my offset is getting wrong value, however the page number shows up correctly. Can you point where I am wrong here? Page numbers bits are [2:5] Offset bits are [6:15] st...
Shifting left to clear out digits is a dangerous game, in my opinion, because if you happen to be using int instead of unsigned int, you might get a sign extend you didn't intend. I recommend shifting and masking: If your address looks like this: X X P P P P O O O O O O O O O O Where P is page numbers and O is offsets...
66,910,968
66,911,644
Why don't string pointers point to the first address?
I'm trying to understand how string pointers work(std::string*). I created an array of character pointers to a string. The string pointer for some reason points to an address that is 4 addresses before the first character's address, but it still prints the correct string when I deference it(I guess it's programmed to p...
Consider this very simplistic representation of the std::string container #include <cstring> #include <iostream> struct StringContainer{ explicit StringContainer(const char* str) { len_ = strlen(str); data_ = (char*)malloc(len_); for(int i = 0; i <len_; ++i){ data_[i] = str[i]; ...
66,911,037
66,918,467
Using static_assert to verify bitfields in a typedef union of a struct and an uint32_t
I am trying to use static_assert for registers for a FPGA and defined the following unions of struct with bitfields and all variable. But whenever I try to compile static_assert won't compile and I get an error saying the variable doesn't name a type. If I try to forward declare, it doesn't solve the problem. I'm not s...
In C++20, you might use std::bit_cast: struct field { uint32_t do_it : 1; uint32_t fault : 1; }; constexpr field myVar = [](){ field myVar; myVar.do_it = 0x1; myVar.fault = 0x1; return myVar; }(); static_assert(std::bit_cast<uint32_t>(myVar) == 0x3, "Not equal"); Demo (only msvc has std::bit_ca...
66,911,193
66,911,331
Access command line parameters in C++ Windows App
I have a C++ Windows App written in Embarcadero C++Builder, and I would like to pass the arguments given in the command prompt to the application. int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR argv, int argc) { try { Application->Initialize(); Application->CreateForm(__classid(TFormMain), &F...
First off, the last 2 parameters of your _tWinMain entry point are wrong. They are actually defined as LPSTR lpCmdLine, int nShowCmd instead. argv/argc parameters are provided only in a console app's main()-style entry point, not in a GUI app's WinMain-style entry point. The lpCmdLine parameter is a pointer to a sin...
66,911,275
66,911,940
Why doesn't my function work inside a loop?
Code: #include <iostream> char* intToCharArray(int val) { int len=0; bool neg = false; if (val < 0) { val = -val; len = ((int)log10(val)) + 2; neg = true; } else { len = ((int)log10(val)) + 1; } char* cons = new char[len+1]; if (neg) { ...
Ok theres to be 3 bugs in this code, let's tackle the immediate cause of the crash, the mishandled 0. log10(0) outputs a giant negative number which then causes the new char[] to throw bad_alloc. To fix this you can change the line in the else clause (of if (val < 0)) to: len = val == 0 ? 1 : ((int)log10(val)) + 1; An...
66,911,764
66,911,869
Why do i get the error "malloc(): corrupted top size"?
I'm trying to implement stack using dynamic arrays: class stackArray{ public: stackArray(){mainArr = new int[arrSize];} void push(int data){ if(curr > arrSize){ int *newArr = new int[arrSize*2]; for(int i = 0 ; i < arrSize; ++i){ newArr[i] = mainArr[i]; ...
Initially the data member curr is equal tp -1. Now for simplicity let's assume that the initial value of the data member arrSize is equal to 1. That is the constructor dynamically allocated an array with one element. So as curr is not greater than arrSize you are setting mainArr[0] within the function push. Now curr i...
66,912,128
66,912,649
C++: Sort into new array based on template field
I'm looking for a solution to sort a global array into new structure, based on a variable field: struct OutputStruct { int iDestId, ... } struct GlobalData { int A, int B, int C, int iDestId } template < typename FIELD > void SortByField( OutputStruct *& pOutputStruct, int iNumElements, FIELD glbArray:...
I'm not going to even attempt to adapt something to the fantasy code you posted, primarily because none of it compiles anyway. But the hitch that seems to be holding you back is understanding how the member pointer operators work. Below is a simple example of sorting a sequence of structures, each time by a separate te...
66,912,313
66,912,336
How to initialize a const char [] with a string literal
I would like to do the following: const char errorMsg [64] ( useApple ? "Error Msg Apple\n" : "Error Msg Bee\n" ); MyMethod ( errorMsg ); For a method with signature: MyMethod(const char* errorMessageInput ); I have a method which takes a const char* and I would like to create a local variable before I send it in. I ...
Instead of an array you could declare a pointer like const char *errorMsg = useApple ? "Error Msg Apple\n" : "Error Msg Bee\n"; In fact there is no need to declare a constant array if the method parameter has the type const char *. You may write for example #include <cstring> //... char errorMsg [64]; strcpy( erro...
66,912,832
66,915,842
How do I use warpPerspective correctly?
Here are the files The output with the input and here is the image used in the code; The actual card used in the code. . The blue positions are from paint. Output is the output from the code. I have attached the image I am talking about. I want to get the perspective transformation so I can get the card in its canoni...
Your first mistake is that the points you took by using paint ( you may also use opencv imshow to do that ) is not in the correct order. They should be accordingly: left-up , right-up , left-down and right-down. Your second and actual mistake is about the order of getPerspectiveTransform. You should first source then t...
66,913,832
66,913,858
Why can a C++ template class access a private member of its base class?
With Visual Studio 2019 (v 16.7.3), I have found that a template class can access the private members of it non-template base class. Is this an expected behavior or is it a compiler bug? When the derived class is not a template class, the private member of the base class is inaccessible as expected: class A { }; class...
The posted code does not call Derived<int>::get_a() so that template member function does not get instantiated (and there is no "access" of the private parent member to speak of). Adding the following get_a() call causes the same error as in the non-template case. { Derived<int> d; d.get_a(); // error: 'A* Bas...
66,914,001
66,916,617
why Redis use skiplist to implement zset
I study the implementation of Redis, I know that there are two data structure (skiplist and ziplist) behind zset. I know some basic idea of skiplist (keep multiple pointer to access next element faster, avg time complexity of search is O(logN)). My question is : I read the info said that there are two situations that R...
ziplist is O(n) time complexity for searching and updating and skiplist is O(logN) The only benefit for ziplist is memory usage. As zip list implement by linear memory address and no pointers to other nodes, it can save a lot of memory space for Redis. When you only have few members in zset, O(N) and O(logN) will not h...
66,914,361
66,919,886
Makefile generates and output .o files to a subfolder
I have some difficulty generating .o to 'src/build' using Makefile. Below is my structure. Project ├── include │   └── Solution.hpp └── src ├── bin │   └── ├── build │   └── ├── Makefile ├── Solution.cpp └── main.cpp What I want to do is generate main.o and Solution.o under src/build folde...
This is wrong: $(BINDIR)/$(EXECUTABLE) : $(OBJDIR)/$(OBJECTS) I see people do this all the time on SO and I'm not sure why it's so seductive but it clearly cannot work when you think about it. You have this: SOURCES := main.cpp Solution.cpp OBJECTS := $(SOURCES:.cpp=.o) So OBJECTS is main.o Solution.o and...
66,915,248
66,942,343
Formatting ISO time using fmtlib
I'm trying to get a std::string of ISO time using fmtlib. Consider the following code: const auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); const auto creation_time = fmt::format("{:%FT%T%z}", fmt::localtime(t)); I'm getting the following error: ../deps/fmt-src/include/fmt/chrono.h: ...
The problem is that you are compiling with the -Werror=format-nonliteral compiler flag while the chrono formatter calls strftime with a dynamic format string. The solution is to remove -Werror=format-nonliteral or add -Wno-error=format-nonliteral. Alternatively you can use {fmt} 5a37e1 or later where this warning is su...
66,915,714
66,915,982
Why "-flto" silent GCC's warning "stringop-truncation"
I understand that newer GCC versions introduced a warning for possibly wrong string operations "stringop-truncation" And here's the sample code that I can easily trigger this warning: $ cat strncpy-warning.cxx #include <cstring> extern char g_buf[16]; void mycopy ( const char* src_c_str ) { strncpy ( g_buf, src_c...
Roughly speaking, GCC has two kinds of warnings: Warnings generated by simple analysis of the source code Warnings generated by complex analysis of data flow An unused parameter is the first kind: it's trivial to see that a parameter is simply not used in a function. Incorrect usage of strncpy is, except for trivial ...
66,915,733
66,916,104
C++ Unable to display or read the whole txt file
When the system tried to output, it only read the last line twice in the text file since I have two lines. I want to display all the movies. Thanks programming language: C++ Container used: string id, n; std::string line; std::list<videoList> data; std::ifstream f ("output.txt"); while (getline (f, line...
It's pretty simple. Take a look here: for (auto& d : data) /* output all stored data */ std::cout << "video id: " << videoID << " movie title: " << movieTitle << " movie genre: " << movieGenre << " movie production: " << movieProduction<< " number of copies: " << numberOfCopies << '\n'; You are ...
66,915,735
66,915,940
Recursive - I cannot understand how it really works
I can't understand something about the recursive function. Let's assume that i'm calculating the factorial of an x number. The code would look like this: #include <iostream> using namespace std; int factorial(int y){ if(y == 0) return 1; return y * factorial(y-1); } int main() { int n; cin >...
1) x = 5 --> x != 0, return 5 * factorial(4) | 2) x = 4 --> x != 0, return 4 * factorial(3) | 3) x = 3 --> x != 0, return 3 * factorial(2) | 4) x = 2 --> x != 0, return 2 * factorial(1) | 5) x = 1 --> x != 0, return 1 * factorial(0) | factorial(0) will return 1; hence line 5) will be as follows: x = 1 --> x != 0, r...
66,916,031
66,916,897
boost::make_optional with type specification
I'm puzzled about the boost::make_optional() behavior when used with the template specification. In particular, it's still unclear to me why this: int pizza = 5; boost::optional<int> pizza_opt = boost::make_optional<int>(pizza) throws the compile error cannot bind rvalue reference of type ‘int&&’ to lvalue of type ‘in...
Template parameter of boost::make_optional doesn't define exactly type inside optional. This template parameter is responsible for perfect forwarding, here is simple minimal example reproducing issue: #include <iostream> template<typename T> void bar(T&& x) { std::cout << __PRETTY_FUNCTION__ << " " << std...
66,916,424
66,917,051
Is emplace_back faster than setting an index?
Which would be faster? std::vector< std::string > vec; vec.reserve(10); for (int i=0; i < 10; i++){ vec.emplace_back("Some text"); } or std::vector< std::string > vec; vec.resize(10); for (int i=0; i < 10; i++){ vec[i] = "Some Text"; } and if one of them is faster than the other (with size of 10) which one is...
This would be platform, compiler and compile flags-dependent. The emplace_back version would need to increment vector size each time. The indexed version would have to create empty string objects to pre-fill the vector. So there is no way to tell without analyzing the generated code and/or measuring it. According to ...
66,916,509
66,920,419
how to display all active connections in TcpServer using poco library
I am trying to work with the poco library. I started with an example tcpserver. I need to display all active connections, but I did not find the required method in the library classes. how can display all active connections?
This is not currently part of the TCPServer class. You could request an enhancement here https://github.com/pocoproject/poco/issues to TCPServer to add a way to access the connection objects. Or you could define your own factory like TCPServerConnectionFactory to do it in a derived factory.
66,916,638
66,917,201
Time limit exceeded on codeforces
I've been stuck on this problem for a pretty Long while. I always get "Time limit exceeded" when I submit the code. My solution is to input the items of the array then determine the largest number in the array and diplay it along with the elements following it and so on. How can I make my algorithm more efficient? #inc...
You solution is O(n^2), too slow. A O(n) solution is obtained by iteratively calculating the position of the max element until a given index i. #include <iostream> #include <vector> #include <algorithm> //using namespace std; int main() { int T; std::cin >> T; while (T--) { //inputting p[n] ...
66,917,169
66,917,593
Exception being thrown from function that is not being executed
I do not understand why an exception is constantly thrown when, during line-by-line debugging, it does not even enter the function. My code: #include <iostream> #include <string> #include <sstream> #include <stack> #define LENGTH 10 using namespace std; bool is_number(const std::string& s) { try { st...
[...] it does not even enter the function. That's true, because num2 = -2, the string "Your base num less than zero" is thrown but it's not caught, throwing strings around is not something one would recommend. I suggest you wrap it in an actual exception and throw it instead. The conditions will be as follows: if (le...
66,917,431
67,042,132
Why std::string is standard layout type when release, but is not standard layout type when debug?
#include <iostream> #include <type_traits> #include <string> int main() { std::cout << std::is_standard_layout<std::string>::value; system("pause"); return 0; } I use Visual Studio 2017 to compile the code. When in debug mode, it output 0. But when in release mode, it output 1. What make it happened?
The following is a somewhat simplified explanation, because most of the classes described below are templated, and I'm omitting such details for brevity. In MSVC 2017 toolset version 14.16, the std::string class is derived from _String_alloc class, which has a single private data member _Mypair of type _Compressed_pair...
66,917,510
66,917,663
Why don't we develop OpenCV apps only by referencing the OpenCV source code rather than its binaries?
The common workflow explained in most books or sites when developing OpenCV apps is by doing the following: Optionally build OpenCV binaries from the downloaded OpenCV source code. I say it is optional because for those who work on Windows with Visual Studio, the prebuilt OpenCV binaries are included officially by Ope...
OpenCV is quite modular, and you don't have to link with DLLs that you don't use. For example, if you don't use the videoio module, you don't need to link with it and don't need to ship the corresponding DLL. And if that isn't enough of a size reduction, you can link OpenCV statically, which allows the linker to remove...
66,917,577
66,924,221
C++ my Gauss–Seidel method doesn't work wery well
I want to solve system of equations (3x3) in C++ useing Gauss–Seidel method. I read some of pages about this: Wiki Page2 and Page3. By pattern oneself on those pages I wrote this code: #include <iostream> #include <cmath> #define epsilon 0.001 int main() { //declaration and initialization of variables long dou...
There are several issues in your code: The accuracy checking is not correct In calculation of the solution, a term b[i] is missing The matrix is not diagonal dominant, far from it: the algorithm cannot converge In addition, to avoid getting nan when the algorithm doesn't converge, I have added a condition to limit th...
66,917,651
66,919,626
Iterate over all the other objects excluding the current one
In many applications is necessary to compute the mutual interactions between a sequence of objects, that is for each object of the sequence, iterate over all the other objects except/skipping/excluding the current one. That's my current solution to this: std::vector<Object> objects; for( auto icurr=objects.begin(); icu...
With range libraries, you might do something like: for (const Object& curr : objects) { for (const Object& other : objects | ranges::filter([&](const Object& obj) { return &obj != curr; }) ) curr.interact_with(other); } but that would indeed do extra comparison. Your first version seems optimal. With st...
66,918,094
66,918,270
How is a reference and a pointer to an array different from each other and which one is preferable?
I am a cpp beginner and have been experimenting with come very basics. I was exploring how are reference and pointer different from each other in regards to arrays and wrote a simple snippet. int main() { //char * c2 = "C"; //std::cout << &c2<<std::endl; //std::cout << *c2<<std::endl; int arr[]={21,2,3,...
The size of reference is int*10 vs size of pointer which is 8. A reference is an alias, so the size of reference is int*10, which is the same as sizeof(arr) How are these two different and is there a standard practice as to when to use a reference or a pointer? Prefer to use reference when you don't need to control...
66,918,167
66,918,687
How to use std::find_if with a vector of unique pointers?
How do you use algorithms like std::find_if with a vector of unique pointers? For instance: #include <iostream> #include <vector> #include <memory> #include <algorithm> class Integer { public: explicit Integer(int i): i_(i){}; int get() const{ return i_; } private: int i_; }; using IntegerPt...
There are 2 problems in the code both leading to an attempt to copy the non-copyable unique_ptr. unique_ptr can't be passed to vector(initializer_list) constructor, because initializer_list wraps its elements as const objects, and a const object cannot be moved-from. So the move-constructor doesn't participate in over...
66,918,263
66,926,166
std::mutiset vs std::vector.Getting TLE in one code but AC in another
Problem Link: https://cses.fi/problemset/task/1091/ I am assuming there is some kind of issue relating to time complexity but I am unable to identify what I am doing wrong here. Getting Time Limit Exceeded verdict in this code: #include<bits/stdc++.h> using namespace std; #define int long long int main() { int n,m;...
This is due to the tickets.erase(index) statement that you are using. In vectors (no matter sorted or not), erase() is O(n) while for multiset erase() is O(logn) typically. So, when you are using a vector and then using erase() in a for loop of size m, you get extra O(n) for each iteration of i and thus a total complex...
66,918,928
66,920,420
Defined virtual functions cause type_info dependence
I have the following file foobar.cc: struct Foo { virtual int do_something() const = 0; }; struct Bar : public Foo { virtual int do_something() const override { return 1; } }; Bar bar; When I try to build a shared object out of it like so: g++ -shared -fPIC foobar.cc -o foobar.so nm foobar.so outputs the line...
You will see some dependencies on these libstdc++ symbols whenever: A constructor is odr-used for a dynamic class type (has a virtual function or virtual base). Any typeid expression whose operand is a class type or an expression of class type is compiled (so not in a decltype, in an inline function never used, etc.) ...
66,919,574
66,964,866
_popen() returns nothing
This is a Qt program. I am trying to run gcc command and get the result using _popen(on Windows). However, I get no output. After debugging, I find that gcc command runs ok. void editor::on_action_Compile_triggered() { QString str = "gcc \""+curFile+"\" -o \""+outputFile+"\" 2>&1"; //compile curFile FILE *fp ...
According to me, you are not having a problem. Your above code is working for me (as long as I declare a correct curfile and outputFile). You are not having an ouput because gcc has successfully compiled the file. You may want to verify if the file called outputFile has been produced. Indeed, when gcc succeeds, it does...
66,920,666
66,921,544
Is there any shortcut in Visual Studio that implements basic structure of C and C++?
In itself, in Visual Studio Code, there is a shortcut (or emmet, not sure if it's called like this) that creates the basic structure of HTML. Typing exclamation mark and pressing TAB bring all the codes that we need to write when we start to build a web application. However, I am looking for similar shortcut in Visual ...
This page explains how to create your own snippets Those are the steps on macOS: Select User Snippets under Code > Pereferences Select the C language Create the snippet in the JSON file A snippet generating the basic structure of a program could look like this: { "Skeleton": { "prefix": "main", "...
66,921,118
66,957,060
xtensor-blas incorrect computation
I'm trying to use xtensor-blas for the first time. I've had lots of difficulties linking to it, but finally, I've done that and tried to run the sample programs. However, as the output, I get 0 for the first and 0, -inf for the second. I'm using Windows 10 x64, Clion 2021.1 Installed cmake 3.19.7, xtensor 0.23.4, xtens...
The problem is with the example, that uses a singular matrix. Its determinant should be 0 as your code outputs correctly. This case was discussed in a pull request for xtensor-blas, and the solution was to change the example.
66,921,421
66,921,720
Accessing a private struct LinkedList in another Class via function;
Good Day! I'm currently trying to create a database that needs me to create two ADT. One of them has a private struct linkedlist created in this example The problem is I can't seem to access or at least print out the values inside my struct in a function from another class here is a sample code I derived from my origin...
First of all attribute c in class B is private. There is nowhere in the B class to put that value. So I added a constructor that takes a reference to an instance of A. What you were doing wrong: c were always having a null pointer. Now something about raw references and pointers. Always check against nullptr. Else, you...
66,921,468
66,921,643
Which to prefer? An enum class, or a nested unnamed enum type?
enum Color1 { red, blue, green }; // ok // enum Color2 { red, blue, green }; // error, enum conflicts struct Color3 { enum { red, blue, green }; // ok, no conflicts }; enum class Color4 { red, blue, green }; // ok, no conflicts Color1 and Color2 are both weak typing. Color3 and Color4 are both strong typing. M...
Color3 and Color4 are both strong typing No. Try this: int x = Color3::red; // ok int y = Color4::red; // error: cannot convert from 'Color4' to 'int' The legacy enum is implicitly convertible to an integer, but enum class is it's own type. As to which to prefer, refer to Why is enum class preferred over plain enum?...
66,921,787
66,926,086
Problem finding an element in an array - c++20
I am trying to make a program to search for an element in an array. I imagine that this operation is very simple, but I have tried many solutions and every time there is a different error. Could anyone tell me where I'm wrong please? And what is the best way to find an element in an array? Thanks #include <stdio.h> #in...
You use begin() and end() for vectors. You have to write it like below for arrays defined using []. #include <stdio.h> #include <iostream> #include <string.h> #include <algorithm> #include <iterator> using namespace std; int main() { string dec; string array[10] = {"111", "222", "333", "444"}; dec = "33...
66,922,076
66,922,141
Dynamically allocate elements in tuple
I have a simple question since I did not find it online. Is it safe to modify the elements in a tuple if I pass it by reference like this, I put it like that to emulate what I do. #include <functional> #include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; template <typename... Arg...
S, it's member tuple, and its members (vector+map) exist as s for the lifetime of the main method. You pass a reference to the tuple to the function foo which modifies those fully-alive members safely. This is all 100% valid and safe. I do not see any undefined behavior, leaks, or dangling references anywhere.
66,922,455
66,943,193
Passing a struct by reference/pointer using arduino-timer.h for Arduino
I'm building an arduino project with various leds that have to blink. I've decided to use [arduino-timer.h] (https://www.arduino.cc/reference/en/libraries/arduino-timer/). I do not know C++. I know javascript. The arduino-timer.h functions (.in, .at, .every) allow for an third argument to be passed to the timerfunction...
My dear friend Ant#1 solved it by putting the & and * in the right places: #include <arduino-timer.h> Timer<>::Task repeatTask; Timer<>::Task blinkTask; const int DIO_GREEN = 17; const unsigned long Interval = 1000; struct TimerStruct { int total; int color; int colorCount; int inBetween; }; TimerStruc...
66,922,461
66,923,234
C++: duplicate symbol using Makefile and object declaration
I have a struct defined in a.h #IFNDEF #define A_H struct a_struct { int val; int val_b; }a; #endif and both main.cpp and a.cpp included the header #include "a.h" when I use makefile with the following: a.o: a.cpp a.h g++ -std=c++11 -c $< main.o: main.cpp a.h g++ -std=c++11 -c $< main: main.o a.o g++ -...
The problem is that a.h both declares a data type struct a_struct and declares a as a variable of that type. Each translation unit that includes that header -- for example, the one based on a.cpp and the one based on main.cpp will therefore declare its own a, and if two such translation units contribute to the same pr...
66,922,604
67,251,619
error : Debug assertion failed. C++ vector subscript out of range
I get error : Unhandled exception at 0x00007FF89F84AFEC (ucrtbased.dll) in Opencv.exe: An invalid parameter was passed to a function that considers invalid parameters fatal. #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace cv; using name...
You have to change the reorder code Make changes like (0,0,255),5)
66,922,779
66,926,344
How to flatten the nested std::optional?
note: this question was briefly marked as a duplicate of this, but it is not an exact duplicate since I am asking about std::optionals specifically. Still a good question to read if you care about general case. Assume I have nested optionals, something like this(dumb toy example): struct Person{ const std::string f...
The operation you're looking for is called the monadic bind operation, and is sometimes spelled and_then (as it is in P0798 and Rust). You're taking an optional<T> and a function T -> optional<U> and want to get back an optional<U>. In this case the function is a pointer to data member, but it really does behave as a f...
66,922,848
66,926,323
How do I read unicode characters from SQL server using SQLAPI++?
I'm using SQLAPI++ to build a backend application which needs to access a database (SQL Server 2014). When I try to read a string (nvarchar(50)) from a result set that contains non-ascii characters (specifically persian characters), the cmd.Field("MyField").asString().GetxxxChars() methods all return question marks (?)...
So I found the problem! I was linking with sqlapis.lib. I checked this link and found out that I should use sqlapius.lib instead for unicode support. I also needed to define SA_UNICODE. It is now working fine.
66,922,981
66,925,655
Optimise a Python/ C++ algorithm
I was participating in a competitive programming contest, and faced a question where out of four test cases, my answer was correct in 3, but exceeded time limit in 4th. I tried to get better results by converting my code from python to cpp (I know that time complexity remains same, but it was worth a shot :)) Following...
The bounds you posted suggest that linear time is OK in Python. You can simply keep a running track of how many asterisks you have seen in a row. T = int(input()) for _ in range(T): n, k = map(int, input()) s = input() count, ans = 0, False for c in s: if c == "*": count += 1 ...
66,923,185
66,923,326
Cast a string to unsigned char in c++
I have to convert a string to unsigned char in C++: typedef unsigned char BYTE; BYTE Sample1 = 0x01; string a = "0x08"; BYTE Sample2 = (BYTE)a; //have Store the string in the Sample2 .. but unable to convert method 2 int main() { string hex_str = "0x3d"; // hex value unsigned char decimal; stringstream my_ss; my_...
Your first code doesn't work because there is no standard conversion operator defined for converting a std::string to a unsigned char. You need to actually parse the std::string into a numeric value. Your second code doesn't work because your std::stringstream is not in std::hex mode when reading decimal from the stre...
66,923,364
66,923,531
How to remove + from std::string
I want to create a calculator program that is a little more advanced that just the numbers and the tiny expressions. One of the first tasks I needed to accomplish was to check if the expression entered was valid and within this i wanted to make sure that the parentheses are valid. I get a std::string from the console a...
In your loop, you're not modifying the index c when you reach a character that you want to erase. This means you skip over every character following a character that is erased. A simple fix would be to decrement c when erasing. if (!in(s[c], valid) { s.erase(s.begin() + c); c--; // here } Of course, you shou...
66,923,377
66,923,439
Series sum according to the formula C++
I need to write a program/function which calculates the series sum according to the formula: series sum The data that the user types is: m. I am a total beginner and I have no idea how to do it... I am assuming that I need to create a loop (or 2)... but how...? So I would be very grateful if someone could help me.
The symbol Σ (sigma) is generally used to denote a sum of multiple terms. In that way you have to sum all (1+j) / (2*j**3 + 3) for every j from 0 to m. As you see bellow, m is equal to 14, but you can change this parameter. #include <iostream> #include <math.h> using namespace std; int main() { float s = 0; i...
66,923,772
66,923,829
copying a c-style array to new memory
Writing a custom vector class (the underlying structure is a c-style array) and I can't wrap my head around the idea of copying the contents of an array into another new array (dynamically allocated) and then, after deleting the old pointer, simply redirecting it to the new pointer... doesn't that result in two pointer...
The variable newarray is a locally created pointer variable. That just means a place called "newarray" is reserved on the stack to store the address of whatever newarray points to. At the end of the function it will go out of scope and its memory will be reclaimed. The object it is pointing to will be unaffected. It ma...
66,924,236
66,924,311
decltype with C++ array
I have a question about decltype. For the following code: #include <iostream> #include <type_traits> int main() { int a[3]; std::cout << std::is_same_v<decltype((a)), int(&)[3]> << std::endl; std::cout << std::is_same_v<decltype(a + 0), int*> << std::endl; } All of the outputs are 1. But as cppreference s...
a is an array variable, which is not a lvalue a is both a variable name and an expression. Variables themselves don't have value categories, but when used as an expression, it's an lvalue. (a) is an expression, completely equivalent to expression a. (a) is not a variable name, obviosuly. I think decltype((a)) should...
66,924,321
66,924,782
Compile error when define and use class variable in Qt QStyledItemDelegate
I define a MsgNameIdDelegate class that inherits from QStyledItemDelegate: Header file: #include <QStyledItemDelegate> class MsgNameIdDelegate : public QStyledItemDelegate { Q_OBJECT public: MsgNameIdDelegate(QObject *parent = 0); protected: void paint(QPainter *painter, const QStyleOptionViewItem &option...
The const qualifier in the declaration of the paint function of your MsgNameIdDelegate class tells the compiler that that function does not modify the class object on which it is called. However, in the definition of that function, you do (try to) modify the object, in the I = 10; statement. You need to either: (a) rem...
66,924,375
66,924,438
Reading from a file in C++ outputs weird characters
beginner here. I just wrote some simple code to read a file and it is (sort of) working: BUT: No matter what I do, I get "²" at the end of my output. Here´s my file reading code: std::string MSEshaderprogram::readFile(const std::string& filepath) { std::ifstream file{ filepath, std::ios::ate | std::ios::b...
std::string output = buffer.data(); Because data is not null-terminated, your output string is formed incorrectly. Use the constructor which also takes the length, i.e. std::string output(buffer.data(), buffer.size()); Alternatively, make sure buffer is null-terminated (by taking it one byte larger and setting the la...
66,924,422
66,924,481
Naming conflict when editing std
I have a templated class function<D, R>, and I am trying to make a hash for it like so: namespace std { template<typename D, typename R> template<> struct hash<function<D, R>> { // hash related stuff }; } However, function collides with a class inside of std. Can I avoid this without renami...
You can ensure that the name lookup finds your class by using a fully qualified name instead of an unqualified name. Like this: struct hash<::some::ns::function<D, R>> It doesn't necessarily have to be fully qualified as long as it is unambiguous with any function declared in other namespaces.
66,924,760
66,945,586
Vulkan-hpp: cant allocate command buffers with no exceptions
1st of all I rewrote the Vulkan tutorial triangle in vulkan-hpp with unique handles. When closing the program i got the following assertion: Assertion: m_dispatch && m_owner Looking at the code, I found out enabling VULKAN_HPP_NO_EXCEPTIONS would fix it but now I get this error: vk::UniqueHandle<vk::CommandBuffer,vk::...
This seems to work for me: #include <iostream> #include <utility> #include <vulkan/vulkan.hpp> int main() try{ const auto instance = vk::createInstanceUnique( {} ); const auto physical_devices = instance->enumeratePhysicalDevices(); const uint32_t q_family = 0; const uint32_t q_count = 1; const fl...
66,925,214
66,925,299
Can you copy a member of an object that's passed by reference?
Consider below code, void handleConnection(Connection &connection) { // std::vector auto messages = connection->messages; // Do Work messages.clear(); } Why does assigning connection->messages to auto messages creates a copy without implicitly creating a reference? The main reason I asked this q...
The rules for auto state that the following code: auto x = y; will always make a copy of y, and deduce the type of x to be the same as y. Whether y is a member of an object that you're holding a reference to, is completely irrelevant. Similarly, auto &x = y; will make x a reference to y, with the same type. Whether y...
66,925,429
66,933,890
Saving vector of objects using SDL2
Im learning SDL2 and now im trying to save a game ranking into a .bin file. I have placed the ranking data into a vector. But im unable to save the data. Perhabs it has to do with file size, but im unable to solve that. This is the code that im using now: class Player { private: std::string name, faction, dific; i...
Here's an example of how I might serialize a struct containing std::string to/from binary. It doesn't use the SDL functions because I don't use SDL but it wouldn't be difficult to modify if desired. You may have a different problem since you say your file is empty, and I am concerned that you try and read the file befo...
66,926,817
66,926,993
SoloLearn Cpp Jungle Camping Challenge
Task: You are given the noises made by different animals that you can hear in the dark, evaluate each noise to determine which animal it belongs to. Lions say 'Grr', Tigers say 'Rawr', Snakes say 'Ssss', and Birds say 'Chirp'. Input Format: A string that represent the noises that you hear with a space between them. Out...
There are a couple of issues with your approach. Reading an entire line and trying to split it is more difficult than just reading each sound one at a time and outputting the animal. That also helps with the next issue since you don't need the array if you read word by word. Variable length arrays, like string sounds_...
66,927,346
66,927,428
Multiple inheritance with templated template
I want to do multiple inheritance via template arguments and pass reference to this in each base class, so I can call top level object's method from each base class's method. I can do it with manual inheritance, but I want to be able to do this via templates arguments. Godbolt link Godbolt link with manual inheritance ...
Thanks to @Nicol Bolas, he advised to use static_cast and CRTP for this #include <cstdio> template <typename T> struct Foo { void foo() { static_cast<T*>(this)->call("foo"); } }; template <typename T> struct Bar { void bar() { static_cast<T*>(this)->call("bar"); } }; template <templat...
66,927,459
66,927,745
How to insert key value pairs to new unordered_map<int, int>* (pointer) in C++?
I have an unordered_map pointer in a structure since I need it in shared memory to access and modify as the program runs. struct Umaps {std::unordered_map<int, int> *node_index;} ; I then initialize the unordered_map, node_index, in another function. Umapsptr->node_index = new std::unordered_map<int, int>(); Where Um...
Applying [] to a pointer does pointer arithmetic. You want to apply the [] to the pointed at object, so you need to explicitly dereference the pointer: (*Umapsptr->node_index)[5] = 10; If you know the key 5 is already in the map, you can use at instead: Umapsptr->node_index->at(5) = 10; but this will throw an except...
66,927,771
66,929,723
Problem figuring out time and space complexity?
The question was to check whether two strings are rotation of each other or not. So, here is the function I wrote for the same: bool areRotations(string s1, string s2) { int n1 = s1.length(), n2 = s2.length(); if (n1 != n2) return 0; s1 += s1; if (s1.find(s2) != ...
I am not able to figure out the time and space complexity of my code. [...] Is this correct? std::string::length runs in constant time (since C++11). The comparison and the concatenation run in linear time. But the overall algorithm could run in a non-linear time. Indeed, the C++ standard does not actually require an...
66,928,185
66,947,810
visual studio intellisense for c++
I am using visual studio and In the following c++ code using namespace std; void f() { } int main() { // using ctrl + space cin.get(); return 0; } When I use Intellisense suggestions in main function it does suggest f function but when I click on it or press tab it just writes f not f(). Is there anywa...
It is a well-known problem that I have handled it before. For VS, actually, it could not be done automatically now and VS does not have this Intellisense feature by default. As a suggestion, before you click Enter to complete automatic filling from the Intellisense suggestion window, press the key combination Shift + (...
66,928,213
66,928,475
'no known conversion for argument 1 from ‘int’ to ‘const key_type&’ error' when executing code
I'm trying to do an assignment relating to graphs in c++. Currently I get this error when I execute my code. I've been looking around for reasons behind this, but to no avail. Any help will greatly be appreciated. My code snippet is: #include <unordered_set> #include <iostream> using namespace std; map<string,st...
Explanation You declare your variable adj_list as type map<string, map<string, T>>. That is, the map's key is of type string, but you try to access an element of this map via adj_list.at(i), where i (the key) is of type int and not of type string. There is no implicit conversion of int to string. That's why your compil...
66,928,472
66,932,305
C++20: How to split range by size?
I want to split range {1, 2, 3, 4, 5} to range of subranges of <any size> (e.g with size of 2: {{1, 2}, {3, 4}, {5}}). Yet std::views::split only splits by delimiter. Is there no standard "reverse join" or something to do this?
range-v3 calls this algorithm chunk. There is no such range adapter in C++20, but it is part of the set being proposed for C++23 under the same name. For example: #include <vector> #include <range/v3/view/chunk.hpp> #include <fmt/format.h> #include <fmt/ranges.h> int main() { std::vector v = {1, 2, 3, 4, 5}; f...
66,928,957
66,929,003
Error while compiling a Flutter application for Windows
Hello I hope you are well. I have a problem when compiling my Flutter application for the Windows platform. Indeed when I launch my Flutter application by pressing the "Run" button of VScode (or of any IDE compatible with Flutter) I have this error below: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MS...
This seems to be a known bug, it's because you have spaces in your user name Acer Aspire : https://github.com/flutter/flutter/issues/73644 https://github.com/flutter/flutter/issues/75611
66,929,515
66,929,543
When using texture arrays, why do I not have to bind the sampler to the shader?
I am creating an array of textures using GL_TEXTURE_2D_ARRAY in my code: // Load all images ito opengl unsigned int width, height; std::vector<unsigned char> textures; int num = 0; for ( auto each : image_list ) { // Load PNG std::vector<unsigned char> buffer, this_texture; lodepng::load_file(buffer, each....
This has nothing to do with the sampler type. The binding between the texture object and the texture sampler is the texture unit. The texture object must be bound to a texture unit, and the texture unit number must be set to the texture sampler uniform. In GLSL almost everything is initialized with 0 respectively 0.0 b...
66,929,611
66,929,783
Using overloaded + operator in derived class
I was practicing overloaded assignment operator use from derived class(Airplane in my case), and it worked just fine. Problem i have is with overloaded + operator. It should just sum engine_power and seats from two Airplane objects, and then after sum flying_speed(bolded lines). And it really does go to the Base class ...
As pointed out in the comments, you don't store the result of your base class Vehicle::operator+() when called in the derived class. Here is the fixed code: #include <iostream> using namespace std; class Vehicle { protected: int engine_power; int seats; public: Vehicle(int engine_power, int seats) ...
66,929,855
66,973,620
How to load an stb_truetype bitmap into and OpenGL texture
I have the following code that creates a bitmap from an std::wstring using which then is saved into an image. #include <stb_image_write.h> #include <stb_truetype.h> unsigned char buffer[24 << 20]; stbtt_fontinfo font; fread(buffer, 1, 1000000, fopen("../assets/fonts/unibody_8.ttf", "rb")); stbtt_InitFont(&font, buffe...
This std::vector<unsigned char> pixels( (size_t)(texture.width * texture.height), (unsigned char)0); sets up your pixel data as a monochrome bitmap width * height with 8 bit per pixel. But here: glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());...
66,929,926
66,930,106
C++ weird linker errors, multiple definition of
I'm trying to use makefile for compilation of project in C++, it works fine while I have only main.cpp, but once I add somethink more it break and I can't figure out why. Notice that it even doesn't recognize main. The error image (maybe better for reading): The error text (just in case): make --jobs=9 build mkdir -p ...
$(OBJS_DIR)/%.o: $(SRC_DIR)/*.cpp $(COMPILER) $(CPPFLAGS) -c $< -o $@ Here you use a wildcard to compile all object files using all cpp files as dependencies. This results every .o file containing only the definitions of the first cpp file listed by $(SRC_DIR)/*.cpp resulting in the name conflict. Instead of doing...
66,930,308
66,930,406
GCC false positive warning on strncpy usage?
Yet another question regarding strncpy warning. Here's the code: #include <cstring> extern char g_dest[16]; extern char g_src[16]; char* mycopy() { char * x = strncpy ( g_dest, g_src, sizeof ( g_dest ) - 1 ); return x; } Compile it with g++ version 8.3: $ g++ --version g++ (GCC) 8.3.0 Copyright (C) 2018 Free...
The best (most efficient, simplest, easiest to understand for both success and error cases) is to use memcpy when your source and destination are the same fairly small size. GCC won't warn you about that. If you simply want GCC to not complain about your strncpy() call even if it is unsafe, you can enclose it in paren...
66,930,563
66,930,803
How to assign size to a globally declared 2d vector in the main function in C++?
#include <bits/stdc++.h> using namespace std; vector< vector<int> >Adj; int main() { int n; cin>>n; Adj.assign(n); } This code doesn't work for assigning size to the vector.
Use resize method 'Adj.resize(n)'. The function alters the container’s content in actual by inserting or deleting the elements from it. If the given value of n is less than the size at present then extra elements are demolished. If n is more than current size of container then upcoming elements are appended a...
66,930,733
66,930,841
Move value under std::unique_ptr
I have a function foo(T value), where T is move-only. I want to (for some reasons) allocate value of type T and call foo. Can I do it like this? { std::unique_ptr<T> ptr = make_unique<T>(T()); foo(std::move(*ptr)); } If it's not clear: I want to get rid of new and delete in this code: void ServeForever(uint16_t po...
There is no reason to involve pointers at all: void HandleCLient(Socket socket){ //... } //... while (true) { //Construct in-place Spawn([s=Socket(acceptor.Accept)]() mutable { HandleClient(std::move(s)); }).Detach(); } Thanks @rafix07 for pointing out the need for adding mutable.
66,930,818
66,931,320
Trying to pass data from a multimap to a map is not working as suggested
In this post Convert a multi_key map into a "normal" map joining the multiple keys They suggest how to convert a multimap to the map by passing the values of the first to the second one. I tried that in my code, but it doesn't work: multimap<double, Point>::iterator it; for(it = _mapIntersectionVertices.begin(); it ...
_mapNewPoints[it->first].insert would imply that Point has an insert method which is not the case. I believe you may want something like this: for (it = _mapIntersectionVertices.begin(); it != _mapIntersectionVertices.end(); ++it) { _mapNewPoints.insert(*it); }
66,931,082
66,934,635
SDL_Renderer works as global variable, but not if declared in main, and passed to the functions that require it instead
I've been going back over some SDL tutorials I did a while back to practice pointers/references, but I got stuck on something. If I declare the SDL_Renderer globally everything works, but if I try to declare it in main, and pass the renderer to the functions that need it, I eventually get an SDL_Error saying "invalid r...
In the second snippet, if init changes the variable renderer, it will only change its local copy of the variable. It will not change the original variable renderer in the function main. This is because you are passing the variable by value. If you instead pass it by pointer or by reference, you will also modify the ori...
66,931,298
66,931,504
When specialization of template class is allowed with more template arguments than it's been declared?
The code is very simple and concise (YATC means yet another template class :)) template<typename T1, typename T2> class YATC; /*declaration*/ template<typename T1> class YATC<T1,T1> {}; template<typename T1, typename T2, typename T3> class YATC<T1, YATC<T2, T3>> {}; int main() { YATC<int, YATC<int, double>> yat...
I've expected that I can make specializations for YATC class based on idea that I can specificate definition of the class on two template arguments only; And this is correct. I've found out that actually I can make specialization using infinite template arguments like typename T1, typename T2, typename T3 but with s...
66,931,318
66,931,637
No matching function for call to ‘DiscreteFourierSeries(std::array<float, 8>&)’
I am trying to create a function which does Fourier transformation but I am getting this error when I try to perform a dummy test. What am I doing wrong? I cannot seem to find out the error, I tried putting value in the array 'a' but it didn't help. Any help will be greatly appreciated. Thank you #define _USE_MATH_DEFI...
Before I answer your question, I would strongly encourage you to learn C++ a bit more before proceeding further. The reason I say this is because your code has very basic errors, and me fixing it for you will not really advance your knowledge in C++. When I compile your code, I get the following error: error: no match...
66,931,492
66,931,557
C++ lambda as std::function in template function
Let's say we have this simplified version of my code: template<typename R> R Context::executeTransient(std::function<R(VkCommandBuffer)> const &commands) { ... R result = commands(commandBuffer); ... return result; } I tried to pass a lambda function as a parameter to the function Context::executeTrans...
What about simply as follows ? template <typename F> auto Context::executeTransient (F const & commands) { ... auto result = commands(commandBuffer); ... return result; } This way your method accept both standard functions and lambdas (without converting them to standard functions, that is preferable, ...
66,931,782
66,931,917
Function to calculate average of Sum of all elements in sub-matrix
I want to make a function that take three arguments 2-D array. (int array[rows][cols]) an integer. (int n) address of array[i][j]. Means my function prototype should look like this double Sub_avg(int arr[rows][cols], int n, int *arr[i][j]) Function Explanation first argument is 2D array that represents data which ...
Of cause usually in C++ you will use std::vector or std::array to store arrays and pass them around. But if you really need to work with plain old arrays and pointers then I'm providing next my solution of your task. Also when passing plain arrays you may use templates magic but I thought you want to have something ver...
66,931,992
66,932,387
Find the number of even parity numbers between two integers
I want to find the number of even parity numbers between two integers. Here is what I've written so far: #include <bits/stdc++.h> using namespace std; #define fastio \ ios_base::sync_with_stdio(false); \ cin.tie(NULL) #define ll long long int bool findParity(ll x) { ll y = x ^ (x >> ...
All you need is a function which calculates the even parity numbers from [0-x] interval, let's call it sumParity, then simply return sumParity(b)-sumParity(a-1). (If I understood properly you are looking for the [a,b] closed interval.) If start counting the parity from zero, and pair the numbers, (0-1), (2,3), (4,5) t...
66,932,106
66,932,141
How to print out the result of a pair function in C++?
This is the piece of code I've got in a Russian website, I've tried to cout the pair function but all of my attempt failed. Please guide me how to do this. #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<char> vc; typedef vector<ll> vll; typedef vector<int> vi; typedef pair<int, int> i...
You have to get the result in the pair and then print using first and second property. #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<char> vc; typedef vector<ll> vll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; pair<int, int> fib (int n) { if (n ==...
66,932,243
66,932,895
I am getting this error in my code saying Invalid use of void expression
In the function vector in_to_post(vector infix) (the vector=(1 + 2) * 3 ^ 4 ) is being converted to an output vector which is of the form (Postfix: 1 2 + 3 4 ^ *) and i am getting an error saying invalid use of void expression . I have commented the lines where i am getting this error. char get_optr(Token t) { ...
The issue is that pop on a std::stack simply pops the top element off the stack, but doesn't return it. This function has a void return type, and if you try to use it in a context that requires a value, you get an error output.push_back(b.pop()); //error Instead, you can use top to get top element of the std::stack o...
66,932,946
66,932,985
C++: What does a const reference to the return value of a function mean?
Here's a snippet from my C++ code: std::queue<std::string> get_file_names(const std::string &indir) { std::queue<std::string> file_names; fs::recursive_directory_iterator end; for (fs::recursive_directory_iterator it(indir); it != end; it++) { const std::string &extn = it->path().extension().string...
Your code: const std::string &file_name = it->path().string(); extends the lifetime of the temporary std::string returned by std::filesystem::path::string(). Since you've marked that as const, it can't be moved into file_names, it must be copied. Assuming you want a move, you would write: auto&& file_name = // ... fi...
66,933,292
66,933,365
Why does OMP nested parallelism execution outputs differently than linear execution?
I'm attempting to compare values of execution time when detecting edges of an image in a linear way and in a parallel way. Everything works fine in a linear way, but in a parallel way the image written has too much white pixels in a part of the image. To better show what I'm saying, see image below: The left image is ...
Without more context, is hard to tell. Nonetheless, those two nested parallel regions do not make sense, because you are not distributing tasks among threads; instead you are just executing the same code by multiple threads, with possible race-conditions on the updates of the variables gradient_x and gradient_y among o...
66,933,656
66,933,736
C/C++ Compressing Integer to Short and Decompressing to Integer
I'm trying to find a way to send a value through the network that is 16bit in length (short), whilst its original value is determined by 32bit in length (Integer). The idea is to save traffic size through the network as much as possible by compressing/decompressing values for Client and Server communications. I was thi...
For 16 bits, there are 216 = 65,536 possible settings. Each setting of bits can represent at most one value. So 16 bits of data can represent only 65,536 values. 32 bits have 232 = 4,294,967,296 possible settings. If your 32-bit data uses more than 65,536 of the possible values that could be represented, it is not poss...
66,933,885
66,933,950
C++ Dynamic Allocation with vectors and containers
1.What is the use of dynamic allocating vectors on the heap and is it a good practice? 2.What is the difference between the following:- vector<Object> *col = new vector<Object> vector<Object*> col 3.Does vectors dynamically allocate items on the heap in the following example:- vector<Object> x; or vector<int> x;
You should almost always write vector<Object> or vector<int> (and maybe vector<vector<Object>>. Your other syntaxes (vector<Object>* and vector<Object*>) are often inappropriate in C++. See std::unique_ptr (or std::shared_ptr) for preferred alternatives.
66,934,028
66,934,590
Cannot access public method from another class
I have the following classes: class Point { private: Vector2d _coordinates; int _label; public: Point(const double x = 0.0, const double y = 0.0); Point(Vector2d coordinates); void setCoordinates(const double x, const double y) {_coordinates(x, y);} cons...
in AddLabels method, vector points is const. setPointLabel is non-const member function. non-const member functions can only be invoked for non-const objects. Either remove const from const vector &points , or mark function setPointLabel const.
66,934,033
66,934,107
GCC does not compile
I have a MAC OS Mojave machine and gcc does not work on it. When i run the following code it does nothing and goes to new terminal line #import <iostream>; using namespace std; int main() { cout << "Hello World!!"; return 0; } PLS HELP!! I even tried using code from w3Schools
Two things: Your code had some errors. #import is deprecated, use #include instead. You don't need a semicolon after #include statements. Also, you need to use << to give "Hello World!!" to cout, not >>. If you don't use using namespace std;, you need to specify the namespace for cout. In this case, it would be std::c...
66,934,538
66,934,704
C++ c_str of std::string returns empty
So, I'm running into an issue with the following code whereby the result of std::cout << cstr << std::endl is the single character PyObject * CKKSwrapper::SerializeContext() { std::string s; // 1 std::ostringstream os(s); // 2 Serial::Serializ...
Presumably the string contains one or more nul characters, resulting in strcpy() not copying all of the bytes. You also have a memory leak from not freeing cstr before you return from the function. You can avoid both problems by bypassing the unnecessary string array and calling PyBytes_FromStringAndSize: return PyByte...
66,934,563
68,387,998
Comparing returned vectors from recursion tree branches
Suppose I have a given sum, say sum = 4. I am also given a vector = {2,4}. There are two ways to generate the given sum from the given vector (elements may be reused). One way is just {4} cause 4 = 4. Second way is {2,2} cause 2 + 2 = 4. I have to find the shortest possible combination, therefore in this particular cas...
I took a stab at this. I do have a working solution, hopefully it is what you want: #include <iostream> #include <vector> #include <algorithm> void howSum(int targetSum, const std::vector<int> & elementVector, const std::vector<int> & howSumVector, std::vector<std::vector<int>> & allSums) { static int originaltar...
66,934,944
66,935,093
Partial template specialization based on lval/rval?
I'm writing an adaptor class to allow me to write this: for (auto item : ButFirst(myvec)) { ... } The following class definition works well when, as above, the argument is an lval: template <typename Container> class ButFirst { const Container& container_; public: ButFirst(const Container& container) : container_(c...
template <typename Container> class ButFirst { Container container_; public: ButFirst(Container container) : container_(std::forward<Container>(container)) {} typename std::decay_t<Container>::const_iterator begin() { return std::next(container_.begin()); } typename std::decay_t<Container>::const_iterator end()...
66,935,052
66,935,532
Why does a "child" object destructor execute after the "parent" object destructor?
I have a class (the "parent") which has as a member another class (the "child"): class Engine // THE "PARENT" CLASS { public: // CONSTRUCTOR ------------------------------------ Engine() : mConfig {} // "CHILD" CLASS INITIALIZED HERE { // ... return; } ...
(I'm going to avoid using "parent" and "child" since those terms typically refer to classes that are related by inheritance, not by composition.) Destroying a C++ object involves executing its destructor's body and additional destruction work that is automatically generated by the compiler, such as destroying member ob...
66,935,265
66,935,425
two-dimensional arrays in CUDA
I'm practicing this simple code which takes a two-dimensional array and sums them up with CUDA. In the end, the result of C is not what I accepting. Also, I was wondering whether I can use vector instead of c-style arrays. #include <iostream> using namespace std; #define N 2 __global__ void MatAdd(double** a, doubl...
You must not use the double** type in this case. Alternatively, you should use a flatten array that contains all the values of a given matrix in a double*-type variable. The heart of the problem is located in the following line (and the similar next ones): cudaMemcpy(a_d, a, d_size, cudaMemcpyHostToDevice); Here you a...
66,935,347
66,937,669
how can I find the minimum distance between two point by using inheritance?
I would like to return a pointer to the object for which the distance is smallest by using getDistanceTo() method from Shape.cpp. But my findClosestTo() method will be core dumped. So how can I fix findClosestTo() method? ShapeList.cpp Shape* ShapeList::findClosestTo (double p_x, double p_y) const{ Shape* distance ...
I see a few problems. First: Shape* ShapeList::findClosestTo (double p_x, double p_y) const{ Shape* distance = nullptr; for ( const auto& item : *this ) { double longest = item->getDistanceTo(p_x, p_y); double previous = item->getDistanceTo(p_x, p_y); longest = item->getDistanceTo(p_x, ...