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 |
|---|---|---|---|---|
72,578,796 | 72,578,872 | Zero cost non-macro solution for calling a function in the correct order | I have a code base where some common functions need to be called in order before and after some unique function
Eg:
common1();
common2();
unique(); // note: unique returns void but can have any number of arguments
common3();
common4();
A problem is, anytime a new unique is made, or anytime more commonX functions are... | The decorator you presented can be easily extended to pass an arbitrary amount of arguments to your invocable:
template<typename Func, class... Args>
void DoUniqueCorrectly(Func&& fn, Args&&... args)
{
common1();
common2();
std::invoke(std::forward<Func>(fn), std::forward<Args>(args)...);
common3();
common4(... |
72,578,875 | 72,579,043 | C++ - weird thread behavior when pass vector to method | I wrote the following code and noticed a weird behavior.
#include <iostream>
#include <vector>
#include <thread>
void withVectorArg(double waitTime, std::vector<int> q = {}) {
std::cout << "[withVectorArg] waitTime: " << waitTime << "s" << '\n';
std::thread thread([&waitTime]() {
std::cout << "[withVec... | Both your functions are undefined behavior.
The reason is that you're starting a thread, detaching it and exiting the function immediately. The thread however is capturing the parameter BY REFERENCE and thus when the code in the thread body is executed (that MAY happen AFTER you already returned from the function) the ... |
72,579,592 | 72,579,654 | dependent types without helper type | Given typename T and int N, the templated value below generates a null function pointer of the type:
int (*) (T_0, ..., T_N)
While the code works, I don't like that it pollutes the namespace with the Temp bootstrap helper - Temp is required because types can't be enclosed in parentheses. For example, none of the follo... | You can replace Temp<T,I> with std::enable_if_t<(void(I), true), T>.
Function type declarations won't parse extra parentheses
that actually works! Why?
Types can't be enclosed in parentheses. But the first argument of enable_if_t is an expression rather than a type, so ( ) is allowed there.
|
72,579,804 | 72,585,799 | How can I fix a C++20 compile error involving concepts and friends? | Let's say I start with this simple example of the use of a C++20 "concept":
template <typename T>
concept HasFoo = requires( T t )
{
t.foo();
};
template <HasFoo T>
void DoFoo( T& thing )
{
thing.foo();
}
class FooThing
{
public:
void foo() {}
};
int main(int argc, const char * argv[]) {
FooThing ... | Yes! This friend declaration compiles and links:
class FooThing
{
//public:
void foo() {}
template<HasFoo T>
friend void DoFoo(T&);
};
I would have to poke around to find the exact standardese, but I know there is a rule that multiple declarations referring to the same template must have the same c... |
72,579,840 | 72,581,405 | What is the best way to create a 'using' declaration involving members of incomplete types? | I have a very simple CRTP skeleton structure that contains just one vector and a private accessor in the base class. There is a helper method in the CRTP class to access it.
#include <vector>
template<typename T>
class CRTPType {
// Will be used by other member functions. Note it's private,
// so declval/decl... | If you don't care so much where and how exactly the using declaration appears, then you can avoid the issue without much changes for example by putting the using declaration into a nested class:
template<typename T>
class CRTPType {
//Will be used by other member functions
auto& _v() {
return static_cast<... |
72,580,240 | 72,581,421 | include SFML Library in VSCode "SFML/Graphics.hpp no such file or directory" gcc | I've seen other question's relating to this and most if not all that I could find have some round about way of getting SFML to compile and run in VSCode I'm hoping that there is a way to simply append the SFML/include directory to the compilers includes this works with the intelliSense code completion and it correctly ... | In VS Code, c_cpp_properties.json specifies parameters used by the editor itself (like compiler path, C++ standard, include directories for IntelliSense purposes; see documentation here), but doesn't specify build tasks - that is the job of tasks.json. In your .vscode folder, create tasks.json file like this:
{
"ve... |
72,580,340 | 72,586,142 | Issues reimplementing some C# encryption stuff in C++ using cryptopp | So I have this piece of C# code:
void Decrypt(Stream input, Stream output, string password, int bufferSize) {
using (var algorithm = Aes.Create()) {
var IV = new byte[16];
input.Read(IV, 0, 16);
algorithm.IV = IV;
var key = new Rfc2898DeriveBytes(password, algorithm.IV, 100);
... | So I found the solution! First of all, as @mbd mentioned, C# uses CBC by default. Additionally, I need to cut away the rest of the data like this:
while ((cipher.size() % 16) != 0) {
cipher.pop_back();
}
|
72,580,779 | 72,581,131 | Binaries missing after successful build? | I have a CMake project that I use to generate a Visual Studio solution, which I then try to compile. For some reason, the library file after compilation is nonexistent. I've searched my entire project folder, and cannot find any library files. Here's my CMake setup:
Project root:
cmake_minimum_required(VERSION 3.22)
pr... | I was able to find the issue. CMake (and conventions for that matter) do not see a .tpp as a code file (similarly to how they treat header files). Thus, I was trying to compile a target with no legitimate code files. Template-only libraries are not libraries at all, so I should not be attempting to compile this standal... |
72,580,796 | 72,580,861 | Template class as a function parameter [C++] | The premise of the question is how to pass a templated class as a parameter to another function or at least get the same effect:
Below is a stripped-down version of my code
template<uint8_t _bus>
class Com {
public:
uint8_t write() { return _bus; /* does something with template param */}
};
class Instruction
{
pu... | You appear to be trying to call write on the Com class directly, rather than an instance.
You likely want to pass an instance of Com to transmitFrame, but to do that you have to pass the template info.
template <uint8_t N>
void transmitFrame(Com<N> &com, char *msg) {
com.write(msg); /* need to pass in Com object s... |
72,580,871 | 72,580,922 | C++ substring not giving me the correct result | I have the following code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file;
string s;
//file contains the following
//id="123456789"
//Note: There is no spaces at the end
file.open("test.txt", ios::in);
getline(file, s);
s = s.sub... | The 2nd parameter of string::substr() is a count, not an index, like you are treating it.
In your example, s.length()=14, so you are asking for 14-1=13 characters starting at the index +1 past the 1st " character (3+1=4), but there are only 10 characters remaining from that position onward. That is why the 2nd " chara... |
72,580,960 | 72,580,991 | Why is my class an incomplete type inside itself? | class test {
public:
test(int i) : t(10) {
cout << "cst" << i << endl;
}
static test ins;
const test t;// 1
};
On line 1, the compiler fails with an error:
incomplete type is not allowed
Why is that?
| The compiler parses code from top to bottom. When the compiler encounters the declaration of t, it hasn't yet seen the end of the declaration of test, hence why test is an "incomplete type" at that location. The compiler doesn't know yet if there are any more data members following t, so it doesn't know how much spac... |
72,581,214 | 72,581,549 | Should I mark the move constructor & move assignment operator as deleted in this case? | I hope to prevent the users from creating new instance through the constructor, so I mark the constructor as a private method.
What's more, I need to provide a method to return an type which is used to automatically manage the life of the instance. I don't hope the user to use the instance of Foo class directly, I hope... | I think your question answers itself.
I don't hope the user to use the instance of Foo class directly, I hope they always use std::shared_ptr<Foo> instead.
followed by
Foo foo1(std::move(foo));
demonstrating the ability to use an instance of Foo directly, not managed by a shared pointer. Defining the move construc... |
72,581,561 | 72,581,569 | Xtensor random::randn returning number number below lower bound and above upper bound | I am trying to generate random numbers of shape {10} and range between -0.5 and 0.5
#include <iostream>
#include <xtensor/xio.hpp>
#include <xtensor/xrandom.hpp>
int main() {
xt::xarray<double> a = xt::random::randn<double>({10}, -0.5, 0.5);
std::cout << a;
return 0;
}
but it's returning an array
{-0.4327... | According to the documentation for randn:
template<class T, class S, class E = random::default_engine_type>
auto xt::random::randn(const S& shape, T mean = 0, T std_dev = 1,
E& engine = random::get_default_random_engine())
The function draws numbers from std::normal_distribution and you've set t... |
72,582,238 | 72,878,217 | Opencv Decode Gray code pattern tutorial 3D scanner Problems | I used a ready-made tutorial code from the opencv library in C ++, the link is as follows:
https://docs.opencv.org/3.4/dc/da9/tutorial_decode_graycode_pattern.html
This is the title of this code (Decode Gray code pattern tutorial)
The job of this code is to take photos as a pattern and then read the calibration values ... | The correct parameters passed to the program should be
./main images.yml calibrationParameters.yml 1280 800
The parameters 1280 and 800 represent projector's width and height
I found this information in the author's github repo, you can find it here
I compile the code in the tutorial and use the parameter above, works... |
72,582,371 | 72,582,394 | How to catch datatype overflow exception in C++? | Here, base may overflow beyond limits of int, causing runtime error, at which point I intend to catch the Runtime error raised, and handle it, so I tried the try-catch block, but it is not being caught.
int base=1;
try
{
base *= 10;
//some code
}
catch(...)
{
//some code
}
| You can't. Arithmetic overflow on signed integral types causes undefined behavior, not an exception. If such overflow happens in your program, it is too late. You can't do anything to save the program. It is already in undefined state at that point.
You should check for potential overflow before you perform the multipl... |
72,582,599 | 72,596,707 | Why is there segmentation fault in this merge sort? | I compiled this code on different compilers, but all of them gave runtime error. Can someone tell me what's wrong with this code?
void merge(int *str, int beg, int mid, int end) {
int *arr = new int[end - beg + 1];
int k = 0;
int i = beg;
int j = mid + 1;
while (i <= mid && j <= end) {
if (s... | Your computation of the mid point in merge_sort is incorrect: instead of int mid = (end - beg) / 2; you should write:
int mid = beg + (end - beg) / 2;
Note also that your API is confusing as mid seems to be the end of the index of the last element of the left half and end the index of the last element of the right... |
72,582,729 | 72,582,743 | ‘int main()’ previously defined here | I did this code and faced an error that I can't understand what it is. I run this program in VS code and compilation was successful but getting an compilation error in GFG portal.
#include <iostream>
using namespace std;
/*
* Create classes Rectangle and RectangleArea
*/
int l,b, result;
class Rectangle
{
public:
... | Don't paste the main function, the portal adds it again to the source so it appears twice.
|
72,582,804 | 72,585,305 | How to add parameters to section names in Catch2 | I'm using Catch2 to create a set of tests for some C++ legacy code and I have a function that I would like to test for a good amount of values. I have found that I can use the GENERATE keyword to create a data generator variable that will repeat the following scenario for each of the generated values, but my only issue... | This is possible, but not very obvious from the documentation. What you're looking for is a dynamic section:
TEST_CASE("Evaluate output of is_odd() function") {
auto i = GENERATE(1, 3, 5);
DYNAMIC_SECTION("Check if " << i << " is odd"){
REQUIRE(is_odd(i));
}
}
|
72,582,935 | 72,583,195 | How can I store a std::bind function pointer? | Here is the code I am using
#include <functional>
#include <iostream>
#include <thread>
class Context {
private:
std::thread thread;
bool running;
void run() {
while (running) {
if (function != nullptr) {
function();
function = nullptr;
}
}
}
void (*function)();
public:
... | You can make use of std::function. In particular, replace void (*function)() with std::function<void ()> function as shown below:
class Context {
private:
//other code here
std::function<void ()> function;
};
Working demo
|
72,582,947 | 72,584,212 | How to make contiguous data in class C++ | I am using Visual C++ on Windows 10.
I want to make class Vector4 such that it has members x, y, z, t and they stored contiguously to provide operator[] and other functions:
class Vector4
{
public:
float operator[](size_t idx)
{
return &x + idx;
}
public:
float x, y, z, t;
}
But I found out that ... | From: C++ - Class contiguous data
You can use #pragma pack(1) with e.g. MSVC and gcc, or #pragma pack 1 with aCC.
As said in the answer #pragma pack(1) will disables padding and guarantees that the members are contiguous:
That basically disables padding and guarantees that the floats are contiguous. However, to ensu... |
72,582,965 | 72,583,061 | 8/16-bit atomics on 32/64-bit processors | In C++11 and C11 it is possible to use 8- and 16-bit atomics. Are there any pitfalls of using them on actual modern 32- and 64-bit CPUs? Are they lock-free? Are they slower than native-size atomics? I'm interested in both what standard says about it and how it's actually implemented on common architectures.
| There are no common pitfalls or any reason to expect any.
The standard say nothing about it, but basically nothing about performance guarantees in general. But in practice, if atomic<int> is lock-free, it's almost certain that atomic<int16_t> and atomic<int8_t> are also lock-free. I'd be surprised if there are any ma... |
72,583,780 | 72,584,018 | Getting stdout using vscode mingw gcc | I wanted to extent my c knowledge to c++. Using Win10, I installed VSCode and mingw following the tutorials.
Next I created a Hello World test file.
It compiles properly without errors. However when I run it from a terminal window, I do not get any output.
I am sure its a stupid beginners mistake...
#include <iostream>... | Thanks quimby! that did the job!
actually ist not my c++ vscode ignorance but the one of powershell (coming from cmd...)
so you are right: powershell did NOT run my program but rather just echo the quoted string.
so ones needs the & operator to do the job.
Problem solved
Thanks again.
|
72,583,820 | 72,584,186 | C# references to C++ CLR x32 and x64 | I created a C++ project in Visual Studio Class library CLR (.NET Framework):
#pragma once
using namespace System;
#ifdef _M_X64
namespace MyDLL64 {
#else
namespace MyDLL32 {
#endif
public ref class MyClass
{
public: static String^ Foo(String^ arg)
{
String^ str = arg->ToUpper();
... |
So how properly add x32 and x64 C++CLR dlls to my Any CPU C# DLL?
You can't. AnyCPU just means that the self process can be executed either as a 32 or 64 bit one depending on the architecture but once a 64 bit process is spawned it cannot access 32 bit images and vice versa.
If your C# project references native image... |
72,584,080 | 72,673,998 | Ambiguous Class Template Conversion | How would one add a template constructor to the class so that copy initialization from complex to complex is performed explicitly and without ambiguity? Is there a solution that is compiler and C++ version/standard agnostic? Is there an approach that only requires definition of a constructor without an additional opera... | This is the solution I was looking for, this works with the C++11 standard and compiler versions as old as x86_64 gcc 4.7.1 and clang 3.4.1. The only difference apart from the use of static_cast is the use of getters.
using namespace std;
template <typename T> class complex{
public:
typedef complex<T>... |
72,584,085 | 72,584,167 | std::bit_cast vs reinterpret_cast in file I/O | How should one cast pointers to char*/const char*? Using reinterpret_cast? Or probably std::bit_cast?
A simple example:
#include <iostream>
#include <fstream>
#include <bit>
int main( )
{
std::uint32_t var { 301 };
{
std::ofstream file { "myfile.bin" };
file.write( std::bit_cast<const char*>( &var ),... | First of, of course all of this only applies if var and var2 have the same type and this type is trivially-copyable. A very common mistake is to try to write and read non-trivially-copyable types like std::string in this way, which is fundamentally wrong.
std::bit_cast is not generally safe, because there is no guaran... |
72,584,271 | 72,601,353 | OpenGL: Access violation reading location when calling glDrawArrays | I'm trying to make a Minecraft-like game, and currently, I am stuck on getting chunks to work in a list. It works fine when I do it like this:
Chunk ch1(0, 0, 0);
ch1.fillVertices();
ch1.updateVBO();
Chunk ch2(0, 0, 17);
ch2.fillVertices();
ch2.updateVBO();
ch1.draw();
ch2.draw():
but I can't put them in a list and ... | The buffer bound to GL_ARRAY_BUFFER isn't part of the VAO state. The VAO stores the buffer used for each attribute (the GL_ARRAY_BUFFER at the time glVertexAttribPointer was called), and the GL_ELEMENT_ARRAY_BUFFER.
So your updateVBO is writing to the latest constructed chunk's VBO instead of writing to VBO of the chun... |
72,584,272 | 72,584,296 | Color disappears when light is used in opengl | glLoadIdentity();
glTranslatef(0.0f + deltaA - deltaD, 0.0f + deltaQ - deltaE, 0.0f + deltaW - deltaS);
glRotatef(_rotate_x, 1, 0, 0);
glRotatef(_rotate_y, 0, 1, 0);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidSphere(20, 15, 15);
If I write the code like this, the red color looks good.
glEnable(GL_LIGHTING);... | See Basic OpenGL Lighting. When lighting (GL_LIGHTING) is enabled, the render color is taken from the material parameters (glMaterial). If you still want to use the current color attribute (set by glColor), you need to enable GL_COLOR_MATERIAL
and to set the color material parameters (glColorMaterial):
glEnable(GL_LIGH... |
72,584,831 | 72,584,861 | Why i can't assign value to the 2d vector of char? | I am working on a code that needs vectors of vectors (2d vector) and I am trying to initialize this with '.' with the below code.
vector< vector< char >> vec;
for(int i=0; i < N ; i++)
{
vector<char> temp('#', N);
vec.push_back(temp);
}
I also tried
vector< vector < char >> vec;
for(int i=0; i<N ; i++)
{
v... | The problem is that you have supplied the arguments in the wrong order when creating the temp vector.
Replace vector<char> temp('#', N); with
vector<char> temp(N,'#');
Do the same with std::vector::assign.
|
72,585,207 | 72,586,102 | Extending 2 arguments [x, y] into variable size parameter pack [x, ... x, y] | I'm writing a custom multi layer perceptron (MLP) implementation in C++. All but the last layer share one activation function foo, with the final layer having a separate activation bar. I'm trying to write my code such that it's able to handle models of this type with a varying number of layers, like at this Godbolt li... | You can't return a parameter pack from functions, so makeActivationSequence as you described is impossible. However, you can pass mid and last directly to computeIndexedLayers, and there utilise pack unfolding pairing them with, respectively, midIndex template parameter pack and lastIndex template parameter (in this ca... |
72,585,673 | 72,585,890 | Modifying a cv::Rect inside a cv::Mat in C++ | I'm pretty new to openCV and would like to ask what seems like a easy question.
I have an image in the form of a cv::Mat and I would like to change only a small part of the matrix. I've read that using a cv::Rect is the correct way but I can't seem to find a way to only modify that little ROI.
Here's the code:
cv::Mat ... | OpenCV's cv::Mat has a constructor that creates an ROI image referncing another image:
cv::Mat::Mat(const Mat & m, const Rect & roi)
Using this constructor will cause the new cv::Mat to share the data with the original one:
No data is copied by these constructors. Instead, the header pointing to m data or its sub-arr... |
72,585,860 | 72,599,834 | Change the number type of a CGAL mesh (lazy exact -> double) | I have a triangle CGAL mesh with the exact kernel (EK, EMesh3, EPoint3) and I want to convert it to the same mesh with the inexact kernel (K, Mesh3, Point3). My solution consists in taking each vertex and each face of the exact mesh and adding them one by one to an empty inexact mesh. Is there a more straightforward wa... | You can either create a new mesh like you did but with the function copy_face_graph() or you can use the vertex_property_map() parameter of PMP functions to have one mesh with different point map (exact and inexact).
|
72,585,873 | 72,586,016 | Constructability of trivial types | In regards to C++17; GCC, Clang, and MSVC consider a trival class type not to be constructible by any of its data member types. Since C++20, GCC and MSVC changed this, allowing the example below to compile.
#include <type_traits>
struct t {
int a;
};
static_assert(std::is_constructible<t, int>{});
Unfortunately,... | Constructibility is based on the ability to use constructor syntax (T(values)). In C++20, aggregates can be initialized using constructor syntax, but in C++17 and before, they must use {} syntax.
Clang's C++20 implementation is simply not up to the standard yet.
|
72,585,937 | 72,586,000 | Create a `map` using `unique_ptr` | I originally had a problem creating a map of classes, with some help
I realized I actually need a map<string, unique_ptr<myclass>>.
To be more precise:
I have a bunch of specialized classes with a common ancestor.
specialized classes are actually specialized from the same template.
I have a std::map<std::string, uniqu... | In this loop you try to copy unique_ptrs, but the unique_ptr copy constructor is deleted.
for (auto i : instances) {
You need to take them by reference instead:
for (auto& i : instances) {
|
72,586,393 | 72,586,483 | Tribonacci number program doesnt return false | For each number read from the standard input the program should print YES if it is a Tribonacci number and NO otherwise. What am I doing wrong in my program, it prints YES, but it wont print NO when the number is not a tribonacci number. For example when number is 45, it should print no.
Tribonacci number formula
T0=0
... | you're mixing two things: actual tribonacci numbers and "true"/"false" answer to question "whether N is tribonacci", for example variable trib in your code can be either 0, 1, 2 or 3, it cannot take any other values, but you're trying to compare it with real number, which is apples to oranges
here is fixed version:
boo... |
72,586,974 | 72,587,460 | Building FLTK Project with CMAKE/CONAN | I'm fairly new to C++ / CMake, but I'd like to create a project with FLTK using CMAKE and CONAN as package manager. I'm using Windows 11, but trying to get it to run under WSL (Ubuntu 20.04). My WSL-version supports GUI applications.
When I install everything without Conan and compile the official "fltk-hello-world" fr... | The conan recipe for fltk does not correctly deal with the cmake system of fltk.
Fltk auto-detects if the system it compiles on has Xft. If it does, then it enables the HAS_XFT variable and compiles some code into the library that uses it.
Conan does not pick up on this and doesn't add Xft to the dependent libraries.
T... |
72,587,313 | 72,587,874 | Generate header only library in c++ that output a single hpp file | I want to write a small library in c++ then "compile" it and release it as a single .hpp file. I can't figure out an easy way to create a single .hpp file from a code base though.
I'm attempting to make something similar to catch.hpp. When I look at their code base they seem to be doing something similar. They seem to ... | @UnholySheep's answer above:
catch.hpp is generated via a script: github.com/log4cplus/Catch/blob/… which essentially just concatenates all the files together into a single file
Paired with @fabian's answer:
Don't even get started with adding .cpp files into your header only lib. There are things usually in cpp file... |
72,587,590 | 72,587,639 | How to get started with C++ unit tests | I am just starting with c++ unit testing. I want to create simple tests (without using any framework) using assert commands. How can I start with that?
Should I make different functions for tests and call them in the main in a single file or should I make separate file for each test?
| Just use it like assert(<output-to-test>==<expected-value>)
#include <cassert>
int square(int x){return x*x}
void test1(){
assert(square(1)==1)
assert(square(2)==4)
}
void main(){test1();}
|
72,587,811 | 72,587,875 | Consecutive lines printing same pointer with "std::cout" produce completely different output | I apologize for the vague title of my question. I don't know a better way to phrase it. I've never asked a Stack Overflow question before but this one has me completely stumped.
A method in class Chunk uses the Eigen linear algebra library to produce a vector3f, which is then mapped to a C-style array with the followin... | You create the vector x in the function on the stack. It is destroyed after the function exited. Hence your pointer is invalid.
Here an example with shared_ptr
ColPivHouseholderQR<MatrixXf> dec(f);
Vector3f x = dec.solve(b);
shared_ptr<float> fit(new float[3],std::default_delete<float[]>());
memcpy(fit,x.data(),sizeof(... |
72,587,926 | 72,587,988 | Datatype for vector<vector<int> > not matching | So, in the following piece of code i am calculating the exponent of a matrix. Here,
long long mod = (1e+9)+7;
vector<vector<int>> matrixMultiply(vector<vector<int>>& A, vector<vector<int>>& B){
vector<vector<int>> ans(2, vector<int> (2));
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 2; ++j)
... | The parameters of matrixMultiply are of type vector<vector<int>>& - i.e. "reference to vector of vector of int". (The & means reference.)
This means that instead of the compiler making a copy of the matrix, and giving that copy to matrixMultiply to use, it instead just gives it a reference (basically just the memory ad... |
72,588,075 | 72,588,141 | for loop not taking any floating point variables | I have this problem, where I can input "2 10 8" and it will output "8", but I want to be able to input "2 -25.2 -38.4". This immediately crashes the for loop and the program displays "-25.0" instead of "-25.2", effectively deleting the number in the decimal place.
Is there anyone that can help?
int main() {
int num... | You are trying to read -25.2 to a numVals variable of type int. It reads -25 to numVals, but then tries to read .2 next time, which is not a valid integer. When you tried this, the input stream variable cin goes to a failure state, and doesn't take any more input.
Change numVals from type int to double:
#include <iostr... |
72,588,289 | 72,588,324 | Why do variadic templates fail to find an appropriate constructor? | If you look at main you'll see I can call write with 4, t2 (or t) but not both in the same call, why? Is there anything I can do outside of breaking them up into seperate calls?
template<class T>
struct Test
{
T data;
constexpr Test()=default;
Test(Test&)=delete;
void Write() { }
template<typenam... | As you've deleted the copy-constructor the last line will not work. One way to fix it is passing the variadic args as reference like:
#include <iostream>
template<class T>
struct Test
{
T data;
constexpr Test()=default;
Test(Test&)=delete;
void Write() { }
template<typename...Args>
void Writ... |
72,588,408 | 72,778,459 | vcpkg how to edit package file when compilation fails when installing package? | I'm installing dependencies for some project which downloads dependencies with vcpkg (the project is Hyperledger Iroha, but it does not matter). Unfortunately when compiling dependencies with my compiler (g++ 12.1.0) one of packages (abseil) is not compiling.
The reason why it is not compiling is easy to fix in code - ... | This is how I do it:
Run install with --editable
vcpkg install abseil --editable
Initialize git repo in source dir:
cd buildtrees/abseil/src/_random_string_/
git init .
git add .
git commit -m "init"
Patch the library
Verify the library builds by calling install with --editable again
vcpkg install abseil --edit... |
72,588,604 | 72,597,786 | A 'for' loop that looks at numbers and assigns them a Boolean statement it can compare several inputs | Would someone please look at the below code and see why it works most of the time but not always?
It works when I input something like "7 1000 1002 896 897 1004 987 960", it shows Unallowed value(s) like it's supposed to.
But if I input "7 896 1003 1004 899 897 898 906", it should say Unallowed value(s), but it works p... | Your initial value of range, 896, isn't between 900 and 1000 and satisfies the condition
else if ((range < 900) || (range > 1000)), making allAllowed = 1,
meaning it will always return "Only allowed values".
Something else you should consider is that your program will only consider the last inputted number to determine... |
72,588,650 | 72,588,689 | C++ long double precision difference with and without using namespace std; | I have stumbled upon quirky C++ behavior that I cannot explain.
I am trying to calculate the dimensions of an image when resizing it (maintaining its ratio) to fit as much screen as possible. The x, y variables are dimensions of the image and X, Y variables are dimensions of the screen. When the resulting dimensions ar... | In the first case you are calling double round(double) function from the global namespace, which is pulled in by the cmath header.
In the second case you are calling overloaded long double std::round(long double) function from the std namespace since your are using namespace std.
You can fix your code by adding std:: i... |
72,588,866 | 72,589,118 | How to save XmlTextReader strings inside a variable or vector in C++/CLI? | I am currently working on a project in which I have to receive a XML file and sort one of the elements.
Before actually getting to the sorting part, I have to parse the XML file, so I am using XmlTextReader, which is working well. However, I need to save each element's attribute in a variable or in a vector to be able ... | reader->Value is a .NET System::String (a 16bit Unicode string).
You are trying to assign it to, and store it in a std::vector of, std::string (an 8bit string).
Those two string types are not directly compatible with each other, which is why you are having troubles.
You need to either:
change your myText variable to S... |
72,588,919 | 72,588,970 | Abstract class selectively expose methods based on derived type | I am writing an program that implements a factory TimeManager to generate two types of objects; a Timer and a StopWatch. Both of these objects are derived from an abstract class TimePiece, and share common methods. I would like the factory to return type TimePiece, but because Timer implements extra methods, I cant. Ho... | You should not return TimePiece* because the two subclasses are sharing TimePiece for its implementation, not for its interface.
A simple approach is to give TimeManager two separate methods:
Timer* AddTimer();
StopWatch* AddStopWatch();
You can exploit polymorphic behavior if you need the Remove method:
void RemoveTi... |
72,588,971 | 72,589,063 | vector push_back add new items | I need add items to a vector who are created as std::vector<char*> Lista;
then i do:
char txt[10];
for (int x = 0; x <= 5; x++)
{
sprintf(txt, "num%d", x);
printf("Add %s\n", txt);
Lista.push_back(txt);
}
but if i loop Lista items it show show:
for (int x = 0; x <= Lista.s... | You're pushing five pointers to the same array into your vector, so when you print the contents of the array pointed to by each pointer they're all the same.
You only have a single array: txt. Each time through your loop, you write new contents into that array and push a pointer to it into Lista. So the first time th... |
72,588,979 | 72,591,682 | nppi resize function with 3 channels getting strange output | I'm getting a strange error when using nppi geometry transform functions from nppi cuda libraries. The code is here:
#include <nppi.h>
#include <nppi_geometry_transforms.h>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <vector>
void write(cons... | The issue is that mat.total() equals the total number of pixels, and not the total number of bytes.
According to OpenCV documentation:
total () const
Returns the total number of array elements.
In you code sample, mat.total() equals 256*256, while total number of bytes equals 256*256*3 (RGB applies 3 bytes per pixel... |
72,589,416 | 72,640,109 | about pybind11 Return to the c++ array modification problem question | c++
How to return the xyz array without changing the definition of the Tile structure? You can use the subscript to modify the value
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
struct Tile {
float xyz[3];
};
struct Vector3d
{
float x;
float y;
float z;
Vec... | c++
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
struct Tile1 { //Assume that the imported library cannot modify the definition
float xyz[3];
};
struct Tile2 { //Assume that the imported library cannot modify the definition
short xyz[6];
};
template<typename TT, typena... |
72,590,080 | 72,590,112 | C++ STL Map : Map.count(element) takes less time than Map[element] | I was trying this problem on leetcode,
https://leetcode.com/problems/naming-a-company/description/ .
I've observed the following
My Code :
long long distinctNames(vector<string>& ideas) {
unordered_map<string,bool> isPresent;
vector<vector<long long>> dp(26,vector<long long>(26,0));
int n = idea... | isPresent[ts] returns a reference to a map value object (so you can write isPresent[ts] = something. So if ts is not present in the map, then isPresent[ts] must default construct a map entry so that it has something to return a reference to. This is the reason that map::operator[] is not const.
isPresent.count(ts) has... |
72,590,220 | 72,590,294 | What happens during the process of cin.get()? | The code is as follows, when I enter "101010^Z000", my output becomes "000". Obviously, my input is invalid after it becomes "^Z". However, why can I continue typing after typing "^Z"? According to the code, shouldn't it have jumped out of the loop and ended the program at this time? I'm curious.
int main()
{
const in... | Input is usually buffered. There is nothing in C++ that says it must be buffered but usually it is. What this means is that when your program is waiting for input it waits for a whole line of input. That whole line of input goes into a buffer and subsequent reads take characters from the buffer until it is empty. Then ... |
72,590,345 | 72,590,522 | Using std::ranges algorithms with custom containers and iterators | I have the following simplified code representing a range of integers that I want to use with various std algorithms. I am trying to update my code to use C++20's ranges versions of the algorithms so I can delete all of the begin() and end() calls. In the below code, std::any_of works with my container and iterator, bu... | To use your range with any_of it must satisfy the input_range concept:
template< class T >
concept input_range =
ranges::range<T> && std::input_iterator<ranges::iterator_t<T>>;
Then via the input_iterator concept:
template<class I>
concept input_iterator =
std::input_or_output_iterator<I> &&
std::indir... |
72,590,567 | 72,644,193 | use mariadb-connector-cpp with cmake project | github repo. i am using c++20 with cmake on visual studio to program on wsl and getting error loading shared library. can't find file libmariadb.so.3.
I used the build instructions to build it for Debian & Ubuntu on wls and it was installed in these paths.
so in my cmake I included
find_package(mariadbcpp)
include_di... | to get it working you just need to add this to your cmake
include_directories("/usr/include/mariadb") #path to include folder
add_library(mariadbcpp STATIC IMPORTED)
set_property(TARGET mariadbcpp PROPERTY IMPORTED_LOCATION "/usr/lib/libmariadbcpp.so") #path to libmariadbcpp.so
then just include
#include <conncpp.hpp>... |
72,591,064 | 72,591,154 | Strange behavior between `std::make_unique` and `std::unique_ptr` with forward declaration | std::make_unique<T> needs C++ 17 feature.It's a pity that I have to use C++11. When I am porting the code snippet to C++11, I found a strange thing.
The code snippet which uses make_unique works well:
#include <iostream>
#include <memory>
struct View;
struct Database : public std::enable_shared_from_this<Database>
{... |
Why std::make_unique<View>(shared_from_this()) works even if there is only a forward delaration for View before Database's definition, whereas the compiler complains about std::unique_ptr<View>(new View(shared_from_this()) under the same condition?
Consider this simplified example:
#include <memory>
struct foo;
std... |
72,591,378 | 72,591,457 | The game loop designing | There is the simple game loop proposal:
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
double current = getCurrentTime();
double elapsed = current - previous;
previous = current;
lag += elapsed;
processInput();
while (lag >= MS_PER_UPDATE)
{
update();
lag -= MS_PER_UPDATE;
... | The whole point of games loops with fixed-size step is to decouple rendering and physics to retain stability, determinism in face of variable FPS.
You cannot simply update physics with 5 times larger step and expect it to be equal to updating 5x with the original step. That is simply not possible. With high enough step... |
72,591,704 | 72,609,958 | QT Creator C++ : Passing information from QDialog to MainWindow | I'm trying to make a program with the following:
In MainWindow (QMainWindow), I have a button AddUser that's opens a secondary window (QDialog) where I have 3 spaces to write the name, email and mobile number of user to add to program.
I want that, after introduce all those information, I click in Add button and the wi... | Just to leave an answer for future visitors... The issue here was that QDialog's exec() function does not return until the user closes the dialog. In this case the simple solution is to make any signal connections before calling exec().
However, its documentation recommends using open(), or alternatively show() for mod... |
72,591,993 | 72,592,166 | How do I link different nodes of an std::list? | If I have an std::list of size 6 (contains 6 elements). I want to take the front node, disconnect it from the second node so that the second node becomes the front/head), and attach the original front node to the back so that the front node is now the back() or tail. In plainer language, I want to remove the node from ... | Use std::list::splice:
#include <iostream>
#include <iterator>
#include <list>
int main()
{
std::list<int> x = {1,2,3,4,5,6};
x.splice(x.end(), x, x.begin());
for (int elem : x)
std::cout << ' ' << elem;
std::cout << '\n';
// Prints 2 3 4 5 6 1
}
|
72,592,195 | 72,593,625 | Trying to match on a c-style array in gmock is failing at compile time | Background:
I'm mocking a hardware i2c transmit function, and trying to match on an array passed into it. This is in an embedded context, hence the c-style arrays and lack of STL containers.
Trying to match my second parameter, a c-style array (the buffer below), is failing at compile time.
Setup:
The interface defined... | No, it should not work - the matcher documentation refers to the case where the argument being matched is an STL container, whereas const uint8_t buffer[] is a pointer.
The ElementsAreArray(readStatusCommand, 1) is a matcher for a container of length 1. However the second argument that it is being compared with doesn't... |
72,592,338 | 72,593,924 | Getting Segmentation Fault while Inserting Elements in 2d Vector in Microsoft Visual Studio 2019 | I am writing a program in which I sum all of the elements in a 2d vector and find out whether the sum of them is 0 or not.
Getting Error which I mentioned above in the title as well as in online editor I am getting error - Segmentation Fault
#include <iostream>
#include<vector>
using namespace std;
int main()
{
in... | #include <iostream>
#include<vector>
using namespace std;
int main()
{
//User Input
int num {};
cout << "Enter a Number: ";
cin >> num;
//Init Vector
vector <int> V1;
vector <int> V2;
vector<vector<int>> V2D;
//Instead of std:cin we use push back;
for (int i {}; i < num; i++)... |
72,592,481 | 72,592,764 | How to do typecast with prestored typeid(T) during runtime? | I created a resource system in CPP:
template<typename T>
class Resource{
public:
Resource() {}
void push(std::shared_ptr<T> pRes) {
_items.emplace(_nextId++, pRes);
}
friend class ResourceManager;
private:
size_t _nextId{ 0 };
std::unordered_map<size_t, std::shared_ptr<T>> _items;
};
cla... | You can't because the type needs to be known at compile time, and the keys of the map are not.
There are a few issues with your implementation: you're deleting a void* in your destructor (which is UB), and your getResource function returns a T instead of a Resource<T>.
A solution is to have some type erasure (via virtu... |
72,592,535 | 72,599,961 | Can I get the namespaces/function/classes hierarchy of an object instance? - c++ | I have an external Parameter class I need to define as global objects (instances) inside different namespaces. I insert a pointer to each instance of the class to a map.
the problem:
not all parameter names are unique and I need a unique name as key to each instance, can I get the namespace hierarchy of the object name... | OK, this is my solution to this case.
hope it will help someone.
I defined a macro for every internal namespace that will define a function inside the namespace to get current __PRETTY_FUNCTION__ path.
then I used How to get a fully-qualified function name in C++ (gcc) with some modifications (you can see the f(__PRETT... |
72,592,536 | 72,592,814 | Thread-safety of reference count in std::shared_ptr | Looking at this implementation of std::shared_ptr https://thecandcppclub.com/deepeshmenon/chapter-10-shared-pointers-and-atomics-in-c-an-introduction/781/ :
Question 1 : I can see that we're using std::atomic<int*> to store the pointer to the reference count associated with the resource being managed. Now, in the destr... | Question 1:
The implementation linked to is not thread-safe at all. You are correct that the shared reference counter should be atomic, not pointers to it. std::atomic<int*> here makes no sense.
Note that just changing std::atomic<int*> to std::atomic<int>* won't be enough to fix this either. For example the destructor... |
72,593,516 | 72,593,601 | Reading space-separated numbers from cin in C++ | I have to put the numbers from each line of input into different vectors without knowing how many numbers there will be in one line of input. For example:
1 2 3
4 5 6 -7
should result in
a = {1, 2, 3};
b = {4, 5, 6, -7};
Note that the number of integers in each line is unknown.
I've tried using stringstream but for s... | When you use lineOfInput as a condition in a while loop it will run until it enters the fail state, so the second while with the same stringstream will never run because it doesn't return true. Just add lineOfInput.clear() and everything will be all right.
Also when you run into a problem like this it's helpful to debu... |
72,593,803 | 72,593,946 | Prime number check doesn't work as it should | I'll try to keep this short. So my task is to find the last prime number in an array, if there's any. But right now my program assigns any number it wants from the array to the lastPrimeNumber variable. Any ideas?
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
srand(time(NULL));
int n... | For starters this for loop
for (int i = 0; i < numbersCount; i++)
{
if (numbers[i] % 2 != 0)
{
cout << "\nNot all numbers are even" << endl;
areEven = false;
break;
}
if (areEven)
{
cout << "\nAll numbers are even" << endl;
break;
}
}
contains a logical e... |
72,594,333 | 74,320,491 | Arduino RP2040 Pico Unique ID | I am using Raspberry pi pico on Arduino IDE. I am using this library githublink for it. There is 3 examples in this link, ArduinoUniqueID and ArduinoUniqueID8
doesn't print anything. Ide says
WARNING: library ArduinoUniqueID claims to run on avr, esp8266, esp32, sam, samd, stm32 architecture(s) and may be incompatible ... | A unique ID for the Pico (and most RP2040 boards) is determined by the serial number of the flash. The Pico SDK has functions to get that ID. Either you can retrieve it directly from the flash by using flash_get_unique_id(uint8_t* id_out) which is what the library linked above did. The documentation for that is here.
A... |
72,594,484 | 72,594,727 | How to calculate prefix sum of tuple of std::integral_constant | I would like to calculate the prefix sum of std::integral_constants.
Given is a collection of std::integral_constant in a std::tuple.
Example
using in_t = std::tuple<
std::integral_constant<unsigned __int64,1>,
std::integral_constant<unsigned __int64,1>,
std::integral_constant<unsigned __int64,2>
>;
How ca... | There is already an algorithm for prefix sum in the standard, i.e., std::inclusive_scan
#include <numeric>
#include <array>
#include <tuple>
using in_t = std::tuple<
std::integral_constant<int,1>,
std::integral_constant<int,1>,
std::integral_constant<int,2>
>;
template<int... values>
constexpr auto prefixSum(
... |
72,594,660 | 72,594,749 | How to put multiple inputs in one variable C++ | I'm rather new to C++ and don't really know much about it. I want a solution where the user could type in something like this (on separate lines):
AAA
BBB
CCC
And store it in a variable like this:
AAABBBCCC
Each of the lines in the input are a separate cin. There is only one variable that will store all of this. Is i... | Did you mean that 1 variable will store the result, or use just 1 variable throughout the whole program? If you meant the first one, given your inputs res will have AAABBBCCC at the end of the run:
std::string tmp;
std::string res;
for (int i = 0; i < 3; i ++) {
std::cin >> tmp;
res += tmp;
}
std::cout << res <... |
72,594,662 | 72,595,036 | condition in for loop with if operator | basically I have this function repeat I understand what it does, what I don't understand is the this part of the condition in the for loop v ? sizeof(g) / 8 : 0, if someone could explain it me I would appreciate a lot because I don't get what it does.
program:
char g[1024];
double *repeat(double *v) {
for (int i = ... | This is somewhat obscure code, as illustrated by the number of incorrect attempts at answers. The key here is that the ?: operator makes an expression, that is, it's code that produces a value. So, first look at the value of the expression:
(v ? sizeof(g) / 8 : 0)
where v is a pointer. When a pointer is used in a cont... |
72,594,913 | 72,595,445 | What is the best type of pointers to use in this situation | I'm currently making a small "Game Engine". I was wondering if I should use smart pointers and which type I should use. or do I just use raw pointers for this GameObject class. every instance of GameObject have Component attached to it Transform, sprite etc. should I use smart pointers or just raw pointers. because I h... | First things first. In general early failure is preferred over late failure. Failure after delivery is catastrophy. The most welcome form of failure is at compile-time. Good code tried to prevent runtime or logic errors by asserting errors at compile-time. So don't be frightened by compile errors.
Next, you have to mak... |
72,594,916 | 72,595,018 | Reverse linked list in a function, that also has to work with a linked list | I had to create a function, that deletes nodes that have a greater element to the right. I achieved this by creating 2 functions:
1st function reverses a list
2nd function that deletes nodes, that have a lesser value than the current node.
In order for this to work I reverse a list, call the 2nd function and reverse th... |
I had to create a function, that deletes nodes that have a greater
element to the right. I achieved this by creating 2 functions: 1st
function reverses a list 2nd function that deletes nodes, that have a
lesser value than the current node.
It is an inefficient approach. Your task is to delete nodes that have a greate... |
72,595,127 | 72,596,537 | Where do I put the -lncurses to properly link the ncurses library | I can't find a way to properly link the ncurses library. The same code compiled just right on mac, but won't compile on linux. I am getting an error saying undefined reference to waddnwstr. In the example I only use the mvwaddwstr function that expands to waddwstr and then to waddnwstr.
This is the error message I am g... | Apple's bundled copy of ncurses (5.7) is configured for wide-character ncurses. For that platform (and perhaps a few others), the makefile could just use -lncurses.
But waddwnstr uses wchar_t parameters, which makes it a wide-character function. For the usual case, that is in the wide-character library, so you would ... |
72,595,228 | 72,595,457 | How to find the count number of entries in map iterator in C++ | I am new in C++.I am using STL Containers.I am mapping the AnimalWeightCAT to unique values of distance travel in km.Using this code
#include <iostream>
#include <map>
#include <sstream>
int main() {
std::istringstream file(
"3 138 3 239 3 440 3 241 3 462 3 432 3 404 2 435 2 514 2 565 3 328 3 "
"13... | For count of the second map adit->second.size() will be sufficient so your last loop, in order to look like you desire must be:
for(AWeightDistance::iterator adit = AWeightDistanceCount.begin();
adit != AWeightDistanceCount.end(); ++adit)
{
std::cout << "AnimalWeightCAT: " << adit->first
<< " cou... |
72,595,324 | 72,595,374 | I'm having troubles trying to compile this C++ program with g++? | I'm using a macOS operating system & within the terminal I have installed g++, when trying to compile my C++ Program File, which has separate compilation; the following error message occurs:
main.cpp:3:10: fatal error: 'Item.h' file not found
#include "Item.h"
^~~~~~~~
1 error generated.
with the following co... | If Item.h is not in your current directory, you will need to specify the directory containing it as an include directory in the g++ command. For example, if your folder structure is this:
.
├── headers
│ └── Item.h
├── items.cpp
└── main.cpp
Then your g++ command(s) should be
g++ -o main.o -std=c++11 -Iheaders -c ma... |
72,595,495 | 72,597,790 | fatal error: Eigen/Dense: No such file or directory: Eigen/Dense VS code and Ubuntu | I know this question been answered like a million time, and I have followed with each suggestion to no avail. I am trying to set up Eigen in my c++ code using VS code while running commands on Ubuntu 20.04 on windows. I was following with this specific post:
Post
This is my c_cpp_properties.cpp file:
{
"configurati... | what helped me is compiling my program with the following command line:
g++ -I /path/to/eigen/ my_program.cpp -o my_program
It's not efficient but there is a way around it I believe.
|
72,595,888 | 72,599,005 | How to manipulate large Eigen matrices with functional programming in C++? | When dealing with large data structure, I always prefer to pass a buffer by references in order to manipulate it from a function. However, in functional programming this is forbidden because of the use of pure functions.
How would it be possible to implement a function in C++ like
value(const Eigen::VectorXd& _input, E... | It seems like you are asking the impossible: How to access an existing buffer without passing that buffer.
There are a few options that go into that direction but I'm pretty sure you won't like them:
1 Just give up
Eigen::MatrixXd value(const Eigen::Ref<const Eigen::VectorXd>&) will cause a new allocation, which you ma... |
72,596,785 | 72,596,870 | Cannot find a logical sense | i already studied c++ in school and during the last days i have been doing the beginner c++ course of codecademy. On codecademy there is an exercise in which i have to identify palindrome words and return true or false. I haven't been able to resolve it so i saw the solution and it was:
#include <iostream>
// Define i... | for (int i = text.size() - 1; i >= 0; i--) {
reversed_text += text[i];
text is basically the string that you receive as input via function. size() is function that returns the size of the string i.e text.size() so in our test cases it will return
5 for madam
3 for ada
8 for lovelace
If you think about the string... |
72,596,946 | 72,627,348 | QGraphicsScene doesn't removeItem() immediately | I have a simple node graph editor in c++/Qt that uses QGraphicsView/QGraphicsScene to draw the graph and I'm experiencing a weird issue where QGraphicsItems sometimes remain on the scene for a split second after calling scene.removeItem(Item). I'm deleting the the items right after removing them from the scene so it's ... | I've solved the problem.
Qt Docs for
void QGraphicsItem::prepareGeometryChange()
state that you need to call this method before changing the bounding rectangle of the item so that the graphics scene updates its index. I didn't do this. So when I added this before the code that adjusts the connections to match node por... |
72,597,185 | 72,606,213 | Xcode cannot find cstdint included in bridging header | I am building an iOS app in Swift using Swift UI. This app needs to call C++ code available through a static lib. So, I've setup my Swift code to call an Objective C bridging layer that in turn calls the C++ code. It mostly works ok i.e. I am able to make calls to my own C++ library.
Except I am not able to include a n... | TIL (from elsewhere), that my Objective C shim header file for the C++ code, cannot include C++ headers like cstdint because there is no C++ parsing in the swift compiler. Including stdint.h worked because that is a C header.
|
72,597,256 | 72,597,286 | Why I can't use constructor initializer list to initialize a in-class struct? | I'm trying to do this:
class test{
public:
struct obj{
int _objval;
};
obj inclassobj;
int _val;
test(){}
test(int x):_val(x){}
test(int x, int y): _val(x), inclassobj._objval(y){}
};
It doesn't work. Unless I put in-class struct part in to the body of the constructor like this... | In your 2-param constructor, you can use aggregate initialization of the inner struct, eg:
test(int x, int y): _val(x), inclassobj{y}{}
Online Demo
In your second example, adding a constructor to the inner struct is fine, you just need to call it in the outer class's constructor member initialization list, eg:
test(int... |
72,597,513 | 72,597,529 | Converting an integer to Char Pointer using C | I am trying to convert an integer to a char pointer as shown below. The data results are different. I am not sure what is going wrong. Please help me in correcting the code.
int main(){
char *key1 = "/introduction";
std::ostringstream str1;
str1<< 10;
std::string data=str1.str();
std::cout <<"Th... | In C++, when trying to print all the contents of a char * with cout, you should pass the pointer, i.e. cout << intro << endl.
What you've done here is dereferenced the char *, so cout << *intro << endl is equivalent to cout << intro[0] << endl, which is equivalent to printing the first character, 1.
|
72,598,253 | 72,601,919 | Why can std::function bind functions of different types? | I saw a special usage about std::bind(), just like the following code:
using namespace std::placeholders;
class Test {
public:
Test() {
_state_function_map[0] = std::bind(&Test::state_function, _1, _2);
}
void test_function() {
auto it = _state_function_map.find(0);
int result = it->... |
func_type has two parameters, and Test::state_function only has one parameter,I can't understand how it works.
For binding purposes, the non-static member function state_function has an additional first implicit object parameter of type const Test&.
Now, when we define a std::function object, we specify the function ... |
72,598,429 | 72,599,699 | Exception with OpenCV4.5.5 DnnSuperResImpl - ReadModel (C++) | I have a issue when using OpenCV dnn module.
Here are my settings:
Building OpenCV 4.5.5 with extra module opencv_contrib-4.x (clone from github)
Downloading EDSR_x4.pb and EDSR_x3.pb from EDSR_tensorflow
move .pb files to root directory of my project
However, no matter I used relative path or absolute path, readMode... | The solution is really simple.
Just check if the integrity of EDSR_x4.pb is a pb file or a html, and I incorrectly used the later.
So, I download from the github again, and it worked.
|
72,598,498 | 72,599,350 | Behaviour of friend function template returning deduced dependent type in class template | I've happened across the following code, the behaviour of which is diagreed upon by all of GCC, Clang, and MSVC:
#include <concepts>
template<typename T>
auto foo(T);
template<typename U>
struct S {
template<typename T>
friend auto foo(T) {
return U{};
}
};
S<double> s;
static_assert(std::same_as... |
Which compiler has the correct behaviour? Or, is the code ill-formed NDR or undefined behaviour? (And, why?)
As @Sedenion points out in a comment, whilst touching upon the domain of CWG 2118 (we'll return to this further down) this program is by the current standard well-formed and GCC is correct to accept it, wherea... |
72,598,746 | 72,812,603 | In google benchmark, what is the meaning of Iterms_per_seconds and Why we need fixture? | In google benchmark:
there is a Iterms_per_seconds result and we can use the fixture way to test the bench.
What is the meaning of Iterms_per_seconds in google bench? Is it stands the throuput?
Why need the fixture to test benchmark? In this way , can we get more convenience?
|
items per second is the throughput. items is defined by the benchmark author and is completely optional. the benchmark author can also define bytes processed for bytes per second, if that is more meaningful.
you don't need fixtures, but they provide a way to do one-off setup and teardown.
|
72,599,064 | 72,600,213 | Capturing boost::asio::thread_pool in lambda function | I'm trying to capture thread_pool object in a lambda function. This lambda function is called inside a thread. Upon this call, it creates(obtains) a new thread with asio::post. However, it throws segmentation fault. I tried create weak ptr with shared_ptr<thread_pool> but it didn't work as well. Simple example written ... | I'd simplify:
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>
void thread1(std::function<void()> createThread) {
createThread();
while (true) {
std::cout << "Sleeping" << std::endl;
sleep(1);
}
}
void thread2() { std::cout << "You made it" << std::endl; }
int ... |
72,599,099 | 72,601,223 | efficiently updating inplace certain blocks of a large sparse matrix in Eigen? | Suppose that I have a large sparse matrix with the following pattern:
the number of nonzeros per column and their locations are fixed
only matrix block A and B will change and the rest of the matrix stays static; (blocks A and B themselves are also sparse with fixed nonzero locations)
As instructed in the document, ... | From what I can tell, the InnerIterator can be used used for this and runs in constant time.
Eigen::Index col = 1;
Eigen::Index offset_in_col = 1;
using SparseMatrixD = Eigen::SparseMatrix<double>;
SparseMatrixD mat = ...;
SparseMatrixD::InnerIterator i =
SparseMatrixD::InnerIterator(mat, col) + offset_in_col;
... |
72,599,809 | 72,600,078 | Downloading my programs data from a webserver (Its basically just a .exe turned into .txt) but when I put it into a .exe it does not run? | So currently I am using a basic Http request to pull the exe data from my server weblink.com/Program.exe
it returns my program in .txt form but when I put it into a file it will not run.
I assume this is because I need metadata but have no clue how to find that process or even how to google something as specific as tha... | You need to open your file in binary mode otherwise newline translation will screw up your executable:
OutFile.open(XorStr("C:\\Users\\Program.exe").c_str(), std::ios::out | std::ios::binary);
|
72,599,825 | 72,600,031 | compiler error with C++ template says that is not the member of struct | I'm a newer of using C++ template and I got trouble with template compiling.
I want to write a similar factory method with template but compiler error says that 'ip is not the member of _FileWriterInfo'. I was confused because it has be defined in NetWriterInfo struct but not in FileWriterInfo. And if I cancel the 'ip'... | The CreateWriter function instantiates the FileWriter and NetWriter classes with the FileWriterInfo structure. Accordingly, the compiler tries to instantiate the NetWriter::Write function with the type FileWriterInfo, and we get an error.
You can place Write methods directly to FileWriterInfo and NetWriterInfo stucture... |
72,600,182 | 72,600,601 | How to draw an arc between known points to draw XNOR gate in Qt? |
I want to draw an arc between point E to point G , F to H ( I want to draw XNOR gate symbol )
I tried this way
path.moveTo(72,10); // for E --> G
QRect bound1 (52,10,20,60);
path.arcTo(bound1,90,-180);
QPainterPath path1; // for F --> H
path1.moveTo(104,10);
QRect bound2 (72,10,32,60);
path1.arcTo(bound2,90,-180);... | I think the problem is your QRect. Your hand-drawn picture has the arc E--->G to the right of X coordinate 72. But QRect bound1 starts at 52, not 72. Per the docs
Creates an arc that occupies the given rectangle ...
Note that this function connects the starting point of the arc to the current position if they are not ... |
72,600,207 | 72,600,382 | c++11 std::notify_all and spurious wakeup | with c++11.
As std::notify_all would cause spurious wakeup, then why std::notify_all is remained but not std::notify_one all the time?
And could std::notify_one cause spurious wakeup by the way?
elaborating my doubts:
When I call std::condition_variable.wait/wait_for/wait_until and std::notify_XXX, my purpose is gene... | On void std::condition_variable::wait(std::unique_lock<std::mutex>& lock); from
thread.condition/8.3:
The function will unblock when signaled by a call to notify_one() or a call to notify_all(), or spuriously.
So calling notify_one() or notify_all() is not a prerequisite. It can unblock without any of those being... |
72,601,518 | 72,606,581 | Rabin-Miller-Prime test | It runs perfectly but when the numbers are 6 digits and more it "crashes". I have no idea why it doesn't work. I also haven't tried a lot of things to fix it because i don't no where to begin. I know, the test has some weaknesses, I already did some research. There are certain numbers, that cant be detected by the test... | Well (int)pow(2, primenumber_mod) will overflow a signed 32-bit integer if primenumber_mod is greater than 31. If the input is a 6-digit integer it is very likely primenumber_mod will be much larger than that.
|
72,602,548 | 72,603,200 | Strange compilation errors when instantiating a variadic function template | Let's first introduce a helper type that represents a parameter pack:
template<typename... T> struct Pack { };
Now, here's the function with the weird behaviour:
template<typename... TT, typename T>
void f(Pack<TT...>, Pack<T>, std::type_identity_t<TT>..., std::type_identity_t<T>);
std::type_identity_t is used here t... | std::type_identity<TT>... is mentioned in the comments as an way to remove the third function parameter (which is a pack) from argument deduction, but this has no effect as a function parameter pack that does not occur at the end of a parameter list is in a non-deduced context anyway; as per [temp.deduct.type]/5.7:
/5... |
72,603,357 | 72,603,454 | unique_ptr can't instantiate class because it's abstract | I have an abstract class(Component)
and this class should be owned by another class(GameObject).
Every GameObject has a vector of components.
Header:
class Component;
class GameObject{
public:
GameObject();
virtual ~GameObject();
void addComponent(std::unique_ptr<Com... | Your issue is here:
void GameObject::addComponent(Component* component) {
components.push_back(std::move(std::make_unique<Component>(*component)));
}
When you dereference component, as far as the compiler knows you still just have a Component, not the actual instantiation--it can't call the proper copy constructor... |
72,603,420 | 72,618,255 | How could tell which way is condition_variable.wait_for unblocked by, spurious wakeup or cv_status::timeout? | As far as I know, only condition_variable.wait_for with predicate(because double check inside) could avoid to be unblocked by spurious wakeup, but not the version without predicate(use if not while).
But what if I want to do something when only cv_status::timeout happened and do something else by notify_XXX?
because co... | Condition variables are best used as a triple. The cv, the mutex, and the payload.
Without the payload (implicit or explicit), there is no way to determine if the wakeup is spurious or not.
The predicate version makes it easy to check the payload, but in some complex situations checking the payload might be easier wit... |
72,604,511 | 72,604,641 | Understanding enable_if implementation in C++98 | I have seen this given as a self-explanatory implementation of enable_if for C++98 :
template<bool b, typename T = void>
struct enable_if {
typedef T type;
};
template<typename T>
struct enable_if<false, T> {};
But alas I personally don't understand it. I don't see where the boolean kicks into play. Would really ... | First consider this:
template<bool b>
struct foo {
static const bool B = b;
};
template <>
struct foo<false> {
static const bool B = false;
};
Its a primary template and a specialization. In the general case foo<b>::B is just b. In the special case when b == false the specialization kicks in and foo<false>::B... |
72,605,087 | 72,605,160 | WinEventHook: what happen when the thread that installed the event hook ends? | I did some testing and noticed that when the thread that installed an event hook ends (or is killed) the callback function is no longer called, as if the hook ended together with the thread.
However, the documentation says to call UnhookWinEvent from the same thread that installed the event, which is not possible if th... | You probably ought to have read that documentation you linked to:
If the client's thread ends, the system automatically calls this
function.
|
72,605,454 | 72,605,972 | Wrap a C++ lambda with another lambda | I am trying to get the contents of a lambda in c++ and creating another function from it. A minimal example that would be ideal is something like:
auto A = []{ some_function(args); };
auto B = []{ return /*Contents of A*/; };
// Ideally this would translate to
auto B = []{ return some_function(args); };
Macros could w... | After C++ code has been compiled, there is no standard way to get information about its source code or modify the source code in the ways you are looking for. Most C++ implementations turn the source code into machine code (i.e. assembly instructions) and run it through an optimizer that can reorder or remove the code... |
72,605,666 | 72,607,622 | Does the camera face the x axis when the yaw is 0? | so I’ve been reading about the camera in learnopengl and noticed that in the yaw image, it seems as the though camera is facing the x axis when the yaw is 0. Shouldn’t the camera be facing the negative z axis? I attached the image to this message. In the image, the yaw is already a certain amount of degrees but if the ... | First, let's bring a little bit more context into your question so that we know what your are actually talking about.
We can assume that when you say
so I’ve been reading about the camera in learnopengl
that by this you are specifically referring to the chapter called "Camera" in the https://learnopengl.com/Getting-s... |
72,605,722 | 72,607,702 | Eigen Error: static assertion failed C++ after replacing fftw_malloc array with eigen | I am trying to switch my code and start using Eigen library in C++ since I have heard it is really good with matrices. Now my old C++ code used mostly fftw_malloc to initialize my arrays like the following:
static const int nx = 10;
static const int ny = 10;
double *XX;
XX = (double*) fftw_malloc(nx*ny*sizeof(double)... | The assertion message THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD already tells you what the error is: Do not use operator[] but instead use operator(), like so:
#include <Eigen/Core>
int main()
{
static const int nx = 10;
static const int ny = 100;
Eigen::Matrix<double, nx, n... |
72,606,522 | 72,606,588 | Inserting values to 2D array using pointers | I successfully entered values to a 2D array without pointers
int main(){
int A[2][3];
for (int i=0; i<2; i++){
for(int j=0; j<3; j++){
A[i][j] = 2*i+3*j;
cout<<" "<<A[i][j]<<" ";
}
cout<<endl;
}
}
And the output is
0 3 6
2 5 8
Then I tried to reach t... | This left operand of the assignment expression
*(*A+j)= 2*i+3*j;
does not depend on the index i. In fact it is equivalent to A[0][j]
Thus elements A[1][j] stay uninitialized.
Instead write
for (int i=0; i<2; i++){
for(int j=0; j<3; j++){
*( *( A + i) + j )= 2*i+3*j;
cout<<" "<<*(A[i]+j)<<" ";
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.