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 |
|---|---|---|---|---|
74,044,607 | 74,046,828 | gmock multiple sequences with duplicate EXPACT_CALL with same arguments | I have a problem to properly setup a test for a turtle-graphic interface.
As sample I have a simplified interface for just drawing a line.
Now I want to write a test for drawing some grid draw_grid and ensure that each line of the grid is drawn, but the actual order of drawn lines does not matter. I only need to ensure... | Consider the following simplified example of drawing just 2 lines (live example):
void draw_two_lines(ITurtle &t)
{
t.line(0, 0, 10, 0);
t.line(0, 0, 0, 10);
}
TEST(TurtleTest, two_lines)
{
TurtleMock sot;
{
InSequence s;
EXPECT_CALL(sot, move_to(0, 0)); // (2)
EXPECT_CALL... |
74,044,672 | 74,130,000 | Why does shutting down this grpc::CompletionQueue cause an assertion? | At this question, I asked how to unblock a grpc::CompletionQueue::Next() that is waiting on a grpc::Channel::NotifyOnStateChange(..., gpr_inf_future(GPR_CLOCK_MONOTONIC), ...).
That question, specifically, is still unanswered, but I am trying a workaround, where the CompletionQueue is instead waiting on a grpc::Channel... | The documentation for CompletionQueue::Shutdown()`](https://grpc.github.io/grpc/cpp/classgrpc_1_1_completion_queue.html#a40efddadd9073386fbcb4f46e8325670) says:
Also note that applications must ensure that no work is enqueued on this completion queue after this method is called.
In other words, once you shut down the... |
74,046,063 | 74,046,096 | nested For loop pattern in c++ | in c++, when I am making nested For loop and I am trying to calculate the factorial...I don't get the correct factorials...I don't know why. For example factorial of 5 is 120 but here it results in 34560. why?
and here is the code:
int fact=1;
for (int number=1; number<=10; number++) {
for (int i=1; i<=number;... | You need to re-initialize fact for each number.
int fact=1;
for (int number=1; number<=10; number++) {
fact = 1;
for (int i=1; i<=number; i++)
fact=fact*i;
cout <<"factorial of "<<number<<"="<<fact<<"\n";
}
|
74,046,187 | 74,046,251 | type for aliasing constexpr char[] | Modified the question to make it clear. Sorry for my sloppy English wordings.
I am looking for a type of a variable, which is an alias of another variable of constexpr char [] type. I've tried a few but none worked.
Here is an example:
constexpr char FieldX[] = "source";
WhatType OptY = FieldX;
The value of FieldX wi... | If you want an alias of a variable, you want a reference.
constexpr char FieldX[] = "my_field_or_option";
constexpr auto& OptY = FieldX;
static_assert( sizeof FieldX == 19 );
static_assert( sizeof OptY == 19 ); // No array decay
Note that FieldX must be evaluated at compile time to be able to create a constexpr re... |
74,046,668 | 74,047,039 | How to iterate over a parameter pack and switch on parameter type? | I have a variadic function accepting any number of mixed parameters:
the following code works as expected:
template <typename ... Args>
void call_snippet(lua_State *L, const std::string& name, Args... args) {
lua_rawgeti(L, LUA_REGISTRYINDEX, snippets[name]);
int nargs = 0;
for (auto &&x : {args...}) {
... | You should be able create function overloads for calling lua_push... and use a fold expression instead of the loop. The sizeof... operator can be used to determine the number of parameters:
void Push(lua_State* l, std::nullptr_t) = delete;
void Push(lua_State* l, std::string const& str)
{
lua_pushcstring(l, str.c_... |
74,046,805 | 74,047,008 | Wrapping the EXPECT_NE, EXPECT_EQ into a validation function | I have a few unit tests that validate whether certain values equate to 0 or not. In some cases, they're supposed to be 0 and in some, they're not.
Just like the following: testA expects valueA to not contain 0 whereas testB expects valueB to not.
What I am looking to do is to somehow wrap the validation part in a funct... | With FieldsAre and structured binding
With C++17 and a recent GoogleTest version (>= v1.12.0), you can simply use FieldsAre(), in case Object allows structured binding (see live example):
using ::testing::FieldsAre;
using ::testing::Eq;
using ::testing::Ne;
struct Object
{
int valueA;
int valueB;
};
TEST(Unit... |
74,047,043 | 74,066,652 | Error passing an Eigen tensor to function | I am trying to turn the following code to a function:
Update: added full working example to test and run. Thanks.
static const int nx = 4;
static const int ny = 4;
static const int nz = 4;
double Lx = 2*EIGEN_PI;
double Ly = 2*EIGEN_PI;
double A = (2 * EIGEN_PI)/Lx;
double A1 = (2 * EIGEN_PI)/ Ly;
Eigen::Tensor<doub... | I managed to compile this fine by including all the relevant headers (especially #include <unsupported/Eigen/CXX11/Tensor>).
Since you are using const sizes for the Eigen Tensors you could define them as fixed size with
Eigen::TensorFixedSize<double, Eigen::Sizes<nx, ny, nz>>
Also take a look at this: https://www.fftw... |
74,047,120 | 74,288,006 | Mediapipe palm detection model outputs | I want to add Mediapipe hand landmark detection to my C++ project, but mediapipe doesn't support CMake so I had to find another way, I found that the hand landmark detection is a two-model run in serial. the first model is palm detection and the second is landmark detection, from the mediapipe website I reached to th... | the main steps needed to convert the mediapipe palm models output to a rectangle are explained in this repo terryky/tflite_gles_app.git, they used the old models but the main steps are the same, in my repo, I made the necessary changes to run the new models both the palm model and the hand landmark detection you can fo... |
74,047,260 | 74,047,681 | Why is the desctructor being invoked in this scenario? | In the following code , I am not able to understand why the destructor of the class Buf is invoked twice. When debugging I can see that it is being invoked the first time when the running thread is leaving the function Test::produce. The second time is when leaving the main function which essentially is when destructi... | The destructor is called two times because you have two objects to destroy. First - the temporary you created as an argument for the offer function parameter:
void produce(int msg_size) {
m_buf->offer(Buf(new uint8_t[msg_size], 10));
}
Second - when you add this temporary to std::queue container, it makes a copy u... |
74,047,308 | 74,047,340 | Replace pointers with std::optional in a recursive data structure | Is it possible to replace pointers with std::optional in a recursive data structure?
For example, how would I replace the following pointer based Tree
template< typename T >
struct Tree {
T data;
Tree* left;
Tree* right;
};
with a Tree that uses std::optional instead of pointers?
I have tried this:
templat... | It doesn't work this way. The idea behind std::optional<> is that it already contains storage for Tree<T>. Your Tree<T> would be of infinite size this way.
|
74,047,689 | 74,047,763 | How do I get make to just compile? | I want to just compile using make and not link. Within my directory I have the following: Makefile, pi*, pi.cpp, pi.o
In the Makefile this is the code:
pi: pi.o
c++ -O0 pi.o -o pi
pi.o: pi.cpp
c++ -O0 pi.cpp -c
How do I get make to just compile:
c++ -O0 pi.cpp -c
| Do you mean running only part for getting object file? Try runing make pi.o
|
74,047,851 | 74,048,038 | Why does the copy constructor of an object that is being used for intializing another object gets invoked? | class point
{
public:
point(double x, double y) : x(x), y(y)
{
std::cout << "point parameterized constructor of: "
<< getThis() << std::endl;
}
point(const point& that) : x(that.x), y(that.y)
{
std::cout << "point copy constructor of: "
<< getThis() << std::endl;
... | In this constructor of the class line
line(const point& startPoint, const point& endPoint) :
startPoint(startPoint)
endPoint(endPoint)
{
std::cout << "line parameterized constructor: " << getThis() << std::endl;
}
there is used the copy constructor of the type point for data members startPoint and endPoint in this... |
74,048,033 | 74,049,234 | Why is it required to add certain fields as a parameter to the constructor in C++ | Probably a simple a question, but I haven't found anything yet. For the code below, the IDE complains about the field and suggests to "Add as parameter to the constructor".
#include <chrono>
class TestClass {
private:
std::chrono::time_point start;
public:
TestClass(){
start = std::chrono::steady_clock:... | std::chrono::time_point is a template class, meaning you can not instantiate it without giving the required template parameters. In this case that's the first template parameter Clock. I.e. you need to tell for which clock you want to store a time point.
You can fix that by adding your clock:
std::chrono::time_point<st... |
74,048,046 | 74,048,151 | How to know which included header a function comes from? | I have a big class A that has dozens included headers, each header has its own included header as well.
I'm creating a new class that would use a function which is also used in class A. I do not want to include the whole class A in my new class, so I try to find the header who brought that function to class A.
What's t... | If you are not using an IDE or an appropriate editor plugin (you should), then the easiest way is to add a deliberate error to a file and look at the error message. Note, this may or may not work with your compiler.
int foo(); // defined somewhere but we don't know where
// ask the compiler
foo(42);
Error messages:
t... |
74,048,208 | 74,048,246 | Can't understand the behaviour of dynamic_bitset | I am working on a Hill Climber Algorithm and I need to represent data as bitsets.
To sumarize my issue, I have written this piece of code:
#include <iostream>
#include <boost/dynamic_bitset.hpp>
void print(const boost::dynamic_bitset<> bitset)
{
std::cout << bitset[0]; //bitset.at(0) - same result
}
int main()
{
... | As indicated in the comments, boost::dynamic_bitset indexes from the least-significant bit, i.e. the rightmost bit in the usual printed representation of a binary number. So bitset[0] is the zero on the far right of 1010, and the 1 that you expect to be printed is in fact bitset[3].
|
74,048,666 | 74,048,827 | How can I return user to original switch menu from do-while loop? | how can I get user to go back to original switch menu once the user selects N at the end. When user selects N, would I use another loop to get them back to original menu? Any help is greatly appreciated.
cout << "Total Chips: " << chips << endl;
cout << "1) xxxxx" << endl;
cout << "2) xxx" << endl;
cout << "Please ente... |
When user selects N, would I use another loop to get them back to original menu?
Yes, one that is put around the original menu, eg:
bool keepRunning = true;
do {
cout << "Total Chips: " << chips << endl;
cout << "1) xxxxx" << endl;
cout << "2) xxx" << endl;
cout << "Please enter an option" << endl;
... |
74,048,690 | 74,048,709 | Why do I see C++ code in file_reader.cc, shouldn't it be C? | I'm doing an University proyect where professors give us some base code supposedly in C. But inside this C files just see C++ functions like cout instead of printf, vectors from STL, inheritance? This is an example of file_reader.cc:
void read (const char *nombre_archivo_pse, vector <float> &vertices, vector <int> &car... | That is C++ code. The file extension for C++ files can be .cc or .cpp.
|
74,048,795 | 74,051,357 | Verify (EXPECT_NE/EXPECT_EQ) struct members for a Template class in a function | I have a unit test that validates whether certain member values (valueA, valueB) equate to 0 or not. And the object being tested i.e Object is a template and what I am looking to accomplish is to:
wrap the validation part in a function so instead of invoking EXPECT_NE/EXPECT_EQ for each member value, I just invoke a fu... | This is almost the same question as the one you asked a few hours ago and is actually based on my initial answer there, but with the twist that here Object is a template and its members valueA and valueB are in another struct. You cannot form a member pointer to a member within a member variable like you attempt to do ... |
74,049,670 | 74,049,808 | How do I replace all "unsigned long" in my project files with "unsigned long long" without affecting compiler system files? | I need to replace all occurences of "unsigned long" with "unsigned long long" in my solution.
I need to replacement it only in my own files.
Files like "string.h" etc. should not be affected.
How can I make sure that no system / compiler files are affected?
When I press Ctrl + F, a box opens up which allows me to selec... | I have now opened each and every one of my files manually and used "Only this document".
|
74,049,759 | 74,049,780 | Is there any difference between the vsnprintf function under xcode and the vsnprintf of other platforms? | I wrote a very simple test code to test vsnprintf, but in xcode and visual studio environment, the results are very different. The test code is as follows:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <cstdarg>
void p(const char* fmt, ...)
{
static const int DefaultLength = 25... | You must reinitialize the va_list between calls to vsprintf. Failure to do so is undefined behavior.
See https://en.cppreference.com/w/c/variadic/va_list :
If a va_list instance is created, passed to another function, and used via va_arg in that function, then any subsequent use in the calling function should be prece... |
74,050,256 | 74,050,313 | What is the difference between compiling a C++ file with the 'gcc' and 'c++' commands? | While learning C++, I tried to compile a HelloWorld program using the 'gcc' command' and found that I needed to add the '-lstdc++' option for it to compile successfully:
gcc HelloWorld.cpp -lstdc++
However, I idly tried to use 'c++' as a command to compile a file, and much to my surprise, it worked without me needing ... | c++ is a soft link of g++.
Then you can find the difference at this question:What is the difference between g++ and gcc?
|
74,050,371 | 74,072,643 | C++ CMake error in VisualStudio - can't find CRABMEAT library | I'm new to Visual Studio and have had very little experience with C++. I have a project that I'm trying to open in VS Community 2022. All I've done so far is open a folder that has a CMakeLists.txt file in it, so it is automatically running through things. It hits an error and stops:
CMake Error at Lconfig/packages.d/c... | It appears that it's either developed in-house, or at least it's a local version. I was given a Subversion link to download it from their repository, in any case.
|
74,050,391 | 74,050,439 | multi-dimensional array printing negative number in c++ | I am learning was try to print out result from multi-dimensional array.
My code is
int numbers[3][3][4] =
{
{
{5,3,8,7},
{1,2,3,4},
{8,9,10,11}
},
{
{12,13,14,15},
{16,17,18,19},
{20,21,22,23}
},
{
{121,131,141,151},
{161,171,181,119... |
Indices of arrays in C++ (and C) are 0..(n-1), where n is the number of elements.
Therefore your loops should use < instead of <= (to avoid accessing memory out of bounds):
for(i=0;i<3;i++){
for(j=0;j<3;j++){
for(k=0;k<4;k++){
// ...
}
}
}
In order to get the size of the nested a... |
74,050,524 | 74,050,673 | What does the --gpu-architecture (-arch) flag of NVCC do? | I am a beginner at CUDA and I encountered a somewhat confusing behavior of NVCC when trying out this simple "hello world from gpu" example:
// hello_world.cu
#include <cstdio>
__global__ void hello_world() {
int i = threadIdx.x;
printf("hello world from thread %d\n", i);
}
int main() {
hello_world<<<1, 10... | The -arch flag of NVCC controls the minimum compute capability that your program will require from the GPU in order to run properly.
As you can see here, RTX 2060 compute capabilty is 7.5 (i.e. sm_75).
This means that it will not be able to run with higher capabilty (like sm_86).
You can use -arch=sm_75 to specify this... |
74,050,878 | 74,051,835 | Why non-volatile T with conversion from volatile T to T should be non-trivial? | struct T {
int a;
T() = default;
T(const T &) = default;
T(const volatile T &src) { a = src.a; }
};
If we don't provide the copy ctor which takes a cvref parameter, then T is trivial, not otherwise.
By C++ standard, looks like it's expected.
I can understand volatile T is not t... | I don't disagree with Ted Lyngmo's answer, but I think this may provide more context:
A type is trivial if:
it has a trivial default constructor; [*]
every eligible copy constructor, move constructor, copy-assignment operator, or move-assignment operator it has is trivial, and moreover it has at least one of these; an... |
74,050,975 | 74,051,203 | Can someone please tell what is wrong in this(Run time error)(want to get the maximum number out of all four integers) | This Question is from Hacker rank Function in C++ section
I am getting the answer that i want but the output is repeated so many time that i have to stop the code from running manually
#include <iostream>
#include <cstdio>
using namespace std;
int max_of_four(int a,int b,int c,int d){
if (a>b){... | The problem is that you have written max_of_four() as a recursive function. It calls itself over and over in an endless loop, and it is printing on each iteration. The function should not be printing anything at all (the caller is printing the value that is returned), and it certainly should not be calling itself at al... |
74,051,474 | 74,054,090 | How do I execute an existing binary that's in the same location as the main cpp file? | I'm making a program that depends heavily on another C binary. Since I don't feel like learning how to use headers and what not yet, I wanted to take the simple rout and just run a pre-compiled binary from the same folder in my cpp program.
Right now, my folder is setup like this: It has main.cpp, CMakeLists.txt, and t... | In c++ if you want to use a binary you can use std::system() function.
But to do this the binary must be on the PATH.
If your binary is not on the path you can do something like this.
#include <iostream>
int main(){
#if _WIN32
std::system("./mybinarie.exe");
#else
std::system("./mybinarie");
#endif
return 0;
... |
74,052,463 | 74,052,581 | std::string::erase not working when using it inside loop | I have written a simple C++ code which takes an Integer as input and converts it into string, and when iterating through it if it encounters any '0' it erases it.
The program successfully removes multiple zeroes only when they are not in consecutively
Can anyone help me understand why it fails when the zeroes are conti... | When manipulating the string while looping over it, you have to take care not to loose your position in it. In other words, when removing an element, without correcting your iterator, you'll skip one character each time.
Sidenote: Better use a STL function for this (as also pointed to in the comments. Also, problems li... |
74,053,870 | 74,054,629 | Does self-defined headers count as preprocessor directives | All the statements with the symbol # are known as preprocessor directive. My question is does self-defined headers count as preprocessor directive?
# include "example.cpp" // Does it count as preprocessor directive
or is it only the header file defined by programmers allowed to be (called) a preprocessor directive?
|
All the statements with the symbol # are known as preprocessor directive
# include "example.cpp" // Does it count as preprocessor directive
Yes, it is a preprocessor directive. This line starts with #.
|
74,053,930 | 74,054,780 | Same helper methods for two different classes (design problem) C++ | I have a class hierarchy as follows:
struct Arg {
Info someSpecificInfo;
OtherInfo anotherInfo
}
class BaseEvaluator {
public:
BaseEvaluator (Info info) {};
virtual Result evaluate();
}
class SpecificEvaluator1 : public BaseEvaluator {
public:
Derived(Info info): Base(info) {}... | i think what you are trying to achieve is either something like this:
class ArgSpecificEvaluator : public SpecificEvaluator3 {
public:
ArgSpecificEvaluator (Arg arg) : Base(arg.info) {};
Result evaluate() override; // Implementation Uses OtherInfo
}
class SpecificEvaluator3 : BaseEvaluator {
public:
Speci... |
74,053,939 | 74,054,014 | Question about typecast behavior in arithmetic | I have the following code. My main question lies in line 5.
int x1 = extRes1.at(1).toInt(); //A fairly large int value. This is from Qt, where extRes is a QStringList. the key is, the function returns an int value.
int x2 = extRes2.at(1).toInt();
int y1 = extRes1.at(2).toInt();
int y2 = extRes2.at(2).toInt();
double ... | Only the result of (y2*x1-y1*x2) (which is an int) is converted to double.
This is due to the precedence of the casting operator:
As you can see here, casting is priority over all "normal" artihmetic operations like multiplication and division.
Then this double is divided by the result of (x1-x2) (an int promoted to do... |
74,054,832 | 74,055,451 | OpenCV detect which pins are bent | I have this image of a pin header, and I need to detect if there are bent pins in the header using OpenCV.
UPDATE, solved
Thanks to Nick, I have made something that works pretty good, not prefect but oke!
I use the findContours function to find all contours. Then I loop over all the items and find the minAreaRect, and... | Have a look at cv::findContours.
You should be able to extract the pins with that, maybe binarize first with cv::threshold(). Then using center-of-mass and the moment-of-area for the contours found, you can describe the position and angle of the pins. Or just using the bounding rectangle might even be enough.
|
74,055,345 | 74,063,706 | Compact form for read and return frame from VideoCapture | I have for example this easy function, but i would like make it more compact, have you suggestion for me?
VideoCapture camera = VideoCapture(0);
cv::Mat& OpenCvCamera::getFrame()
{
Mat frame;
camera >> frame;
return frame;
}
I'd like to make it inline without using temporary variable "frame".
Is it possib... | It looks like you want to hide the existence of the VideoCapture object.
If so, just do only it.
i.e. Just wrap the VideoCapture::read(). No other change will not be needed.
//This object is invisible from the function user.
VideoCapture camera = VideoCapture(0);
//Type of this function (argument and return) is same a... |
74,056,712 | 74,092,708 | parsing packet to get application layer protocols such as http and tls using the dpdk packet framework without being computationally expensive | I have the following packet inspection function that parses transport layer protocols such as TCP and UDP. I need to get deeper into the packet and get application layer protocols such as HTTP and TLS. My current theory is to implement a pattern matching function on the payload but that would be computationally expensi... | [based on the live discussion]
Question: My current theory is to implement a pattern-matching function on the payload but that would be computationally expensive. Any leads on how to proceed?
Answer: The application logic to identify the protocols and application would be fixed cost. So the first goal is to ensure pre-... |
74,057,063 | 74,117,751 | How to build libcpr/cpr static library using mingw? | I'm trying to build libcpr/cpr on Windows with Mingw64 and the output is always a libcpr.dll libcurl-d.dll libzlib.dll file in the ./lib folder.
How can make the build provide a lib file instead of dll files?
| Use CMake flag -DBUILD_SHARED_LIBS:BOOL=OFF to build static library files (*.a).
|
74,057,119 | 74,057,204 | One liner tuple/pair unpack in c++ with reusing same variable multiple times | I have already seen Is there a one-liner to unpack tuple/pair into references? and know how the unpack values from tuple/pairs in a single line like following
auto [validity, table] = isFieldPresentAndSet(r, "is_federated");
here isFieldPresentAndSet returns a tuple.
Now I want to reuse these two variable in multiple ... | You can use std::tie. It returns a tuple of references, which makes the assignement possible:
std::tie(validity, table) = isFieldPresentAndSet(r, "gslb_sp_enabled");
|
74,057,507 | 74,067,974 | Predefined instances of C++ class enum vs static | I have a class that is a bit complex to initialize. It is basically a tree structure and to create an instance the current constructor takes the root node. Nevertheless there are some instances that will be used more often than others. I would like to make it easier for the user to instantiate this ones faster and easi... | As usual when people ask for the performance benefits, the first rule of optimization of code applies: If you think, you have a performance problem, measure the performance.
So my (and many a a people's) opinion is, that you should treat this problem with other things in mind, e.g. what is more clear to the user and/or... |
74,058,653 | 74,064,250 | Advantage to Declaring Constructors and Destructors inside vs. outside of the class? | I've been following along a class about constructors, destructors and constructor overloading in C++. (Granted, it's from 2018, I don't know if that changes anything.) Is there any reason that he defines constructors and everything else outside of the class (still inside the same .cpp file)? What's the difference betwe... | It makes a difference if you are going to be using the class Human in (possibly many) different .cpp files. In that case the information regarding the structure of the class needs to be placed in a separate header (i.e. .h ) file. Behind the scenes, the information from the .h file is automatically copied to every .cp... |
74,059,547 | 74,059,604 | Why is this code not printing the value returned by the binarySearch() function? | #include<bits/stdc++.h>
using namespace std;
int binarySearch(int [], int, int, int);
int main()
{
int n, ar[50], givensum;
cout << "Enter the size of the array: ";
cin >> n;
for(int i = 0; i<n; i++)
{
cout << "ar[" << i << "] = ";
cin >> ar[i];
}
cout << "Enter the given s... | Your binary search algorithm itself is wrong. It's stuck in an infinite loop.
Corrected code is as follows:
int binarySearch(int arr[], int l, int r, int key)
{
int mid = l+(r-l)/2;
while(l<=r)
{
if(arr[mid]==key)
return arr[mid];
else if(arr[mid] > key)
r = mid-1;
... |
74,060,092 | 74,060,370 | How to find if a program is installed on WIndows via command line/C++ | I'm writing a program in C++ and at one point I want to open a file with a certain program (either Libreoffice or Word, depending on what is installed on the pc). For that I need to check which program is installed on the pc first.
I'm usually using linux and for that I have found
if (!system("which libreoffice --write... | You do not need to check which program is installed on this PC before executing a data file on Windows.
You can use ShellExecute directly on a data file, and the system will find the program that has been associated with that file type, and execute it appropriately.
Depending on your needs, you may prefer to use Shell... |
74,060,402 | 74,061,451 | Accessing private members inside a MATCHER | I am verifying the private members of Object (Values storing the internal state of the class) via a MATCHER in a unit test however I have the following concern:
I created GetValueA() and GetValueB() public interfaces solely so that unit test could access inside a MATCHER. Doesn't sound like a right idea (specially if ... | You can pass the private member to the matcher, and define the test to be a friend class.
Also use FRIEND_TEST macro instead of friend class.
template<typename T>
class Object
{
// internal to the class
struct Values
{
int valueA = 42;
int valueB = 0;
};
FRIEND_TEST(UnitTest, testA);... |
74,061,116 | 74,061,450 | How to resolve ambiguity in template base class template method? | I am trying to figure out how to resolve an ambiguity problem with function names in base classes.
#include <type_traits>
template <typename T, typename PARENT>
class BaseA
{
public:
BaseA(PARENT& p) : _parent(p) {}
public:
template <typename P_ = PARENT>
auto& parent() {
if constexpr (std::is_same_v<P_, ... | If you want member function (templates) of the same name to be considered from multiple base classes you need to explicitly import them into the derived class scope:
class Y : public BaseA<Y, Z>, public BaseB
{
public:
/*...*/
using BaseA::parent;
using BaseB::parent;
};
|
74,061,126 | 74,061,246 | C++ - segmentation fault when using vectors | i was working on a problem from LeetCode about finding intersection elements in two different arrays.
and when i pass the input it throws a segmentation fault.
here is my solution (the solve() function only):
vector<int> solve(){
int n,m;
cin >> n >> m;
vector<int> arr1, arr2;
for (int i = 0; i < n; i++... | This happens because your vectors, arr1 and arr2 start off with a length of 0 each. When you try to set a certain index of them, this assumes that the index is already allocated, meaning the vector is long enough to contain that index, which it doesn't in your code.
To solve this, the best solution would be to simply c... |
74,061,465 | 74,062,448 | CUDA functions failing after initializing Spinnaker API | I am using the C++ Spinnaker API to capture images from cameras, and then using CUDA to process the images. The CUDA code works if I do not call the Spinnaker API, but once I call the Spinnaker API various CUDA functions start crashing (such as cudaMemset, or cudaMemcpy, or my custom CUDA kernels). The Spinnaker API wo... | Downgrading from spinnaker-2.6.0.160 to spinnaker-2.0.0.146 fixed this issue on ARM64 Ubuntu 18.04.
|
74,061,590 | 74,071,302 | QtSql Not Showing Query Results Anywhere | My SQL results were showing on Label but then I decided to drop that specific and made a new one.
Then I changed the query to be executed but nothing shows up anymore!
I have been debugging for the past 2 hours to no avail.
I used boolean to check if the query was executed and it showed '1' however, when I print the qu... | As drescherjm pointed out, query.next() must be used to move the pointer of query forward.
|
74,061,650 | 74,061,731 | How can I constrain one template's variadic 'type-parameters' with various specializations of some certain second template in C++? | I need to have a template struct Lists, whose variadic parameters can only be the types represented by specializations of some certain container template List. Different Lists instances should be able to depend on different (but fixed for one instance) templates List.
That said, I want to produce the code, equivalent t... | template <template <typename...> typename, typename>
inline constexpr bool is_specialization_of = false;
template <template <typename...> typename Template, typename... Ts>
inline constexpr bool is_specialization_of<Template, Template<Ts...>> = true;
template <typename...>
struct Lists;
template <template <typename.... |
74,062,481 | 74,072,393 | How to use python subprocess to run c++ executable file in another folder with providing arguments, inside a python script? | I am running a python script file in which it should run a c++ executable file from another folder with some arguments.
The executable file is located in root home ubuntu i.e. (~/camera_intrinsic_calibration) folder
Generally I run on the terminal in that folder location as follows:
./pngCamCalStep1 /home/nvi/Perceptio... | Well, I have kept the whole argument in a single quote, then it worked, removing, check and capture_output:
subprocess.call(["./pngCamCalStep1 home/nvi/Perception/sensor_0/left-%04d.png 12 8 0.05"], cwd='/home/nvi/camera_intrinsic_calibration/',shell =True)
|
74,062,801 | 74,062,836 | Why isn't a function parameter used here? | I'm going through this tutorial:
https://www.learncpp.com/cpp-tutorial/how-to-design-your-first-programs/
I noticed the author didn't use a parameter in this function:
int getUserInput()
{
std::cout << "Enter an integer ";
int input{};
std::cin >> input;
return input;
}
Would it be okay to do somethin... | It would work, but it wouldn't make much sense.
The first version of your function is used something like this:
int some_number = getUserInput();
That makes sense; the caller isn't providing any input to the function, so it takes no parameters.
The second version takes a parameter though, so the caller has to provide... |
74,063,233 | 74,063,376 | Getting the correct type information for a function returning a function-pointer that uses variadic templates | I have a variadic function defined within class Foo
AddCodeChunkInner(Type, DerivativeStatus, bInlined, Format, args...);
And I am trying to write a function that returns its function pointer
static auto getAddCodeChunkInner(){return &Foo::AddCodeChunkInner;}
However I'm getting an error stating that it "cannot deduc... | Whatever your problem is, it's nothing to do with the function being variadic or the return type of your function being inferred. The following code compiles with no problem on gcc, clang, and MSVC:
struct S
{
void f(int, ...) { }
};
static auto getF() { return &S::f; }
Given the error message you're describing, i... |
74,064,332 | 74,076,369 | How to accelerate array_t construction in pybind11 | I used C++ to call python with Pytorch.
C++ generate a vector and send to Python for neural network to inference.
But send the vector is a time consuming process.
A vector contain 500000 float consume 0.5 second turning to array_t.
Is there a faster way to transfer vector to array_t? Any help will be appreciate!
Here i... | Problem solved
py::array_t<float> args = py::array_t<float>({length}, {4}, &list[0]);
Directly init the array_t will be the best way
|
74,064,467 | 74,064,929 | Converting for loop in R to Rcpp | I've been playing around with using more efficient data structures and parallel processing and a few other things. I've made good progress getting a script from running in ~60 seconds down to running in about ~9 seconds.
The one thing I can't for the life of me get my head around though is writing a loop in Rcpp. Speci... | Here is an the sample Rcpp equivalent code:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix getResult(NumericMatrix x, double const1){
for (int p = 0; p < x.nrow(); p++){
if (p == 0){
x(p, 3) = std::max(std::min(x(p, 1), x(p, 0)), 0.0);
x(p, 4) = std::max(x(p, 2) + (0.0 - co... |
74,064,749 | 74,075,130 | C++ class template specialization with value template parameters - how to prefer one over another? | I have the following code:
template<typename T, typename U>
struct combine;
template<template<typename...> typename Tpl, typename... Ts, typename... Us>
struct combine< Tpl<Ts...>, Tpl<Us...> >
{
using type = Tpl<Ts..., Us...>;
};
template<size_t Ind, size_t Curr, typename Tpl>
struct pack_upto_impl;
// SPECIALI... | First of all, some typos:
The , bool in your definition of remaining_type needs to be removed.
You probably wanted to write using pack_upto = pack_upto_impl<Ind, 0, Tpl >::type;. (Before C++20, you also need typename here.)
The core issue here is that you want specialization 1 to be considered "more specialized" than... |
74,064,946 | 74,064,983 | counting digts in c++ using log10 | #include <iostream>
#include <math.h>
using namespace std;
int main() {
int n, temp, rem, digits=0, sum=0;
cout << "Enter a armstrong number: ";
cin >> n;
temp = n;
digits = (int)log10(n) + 1;
while (n != 0) {
rem = n % 10;
sum = sum + pow(rem, digits);
n = n / 10;
... | Math.
Logarithms are basically "exponents in reverse." Log10(100) is 2.0, as 10 to the second power is 100.
Cast to 'int and add one to that are you get 3, which is the number of digits.
|
74,066,327 | 74,078,612 | UML:Inheritance between template classes with parameter dependencies | Pardon my poor english. Just let me show you the situation what I'm trying to draw in UML class diagram.
template<typename TB1, typename TB2, typename TB3>
class Base { ... };
template<typename TD1, typename TD2>
class Derived : public Base<typename TD1, typename TD2, int> { .... };
I know how to draw UML class diagr... | In short
You could show the relationship between the template Base and the template Derived either with a parameter binding (like in your picture, but between two template classes) or inheritance between template classes.
But neither alternative is completely accurate regarding the C++ and the UML semantics at the sam... |
74,067,291 | 74,067,412 | Can't sort arrays with even numbers followed by odd numbers | I first wrote this: (which works as expected)
#include<iostream>
using namespace std;
int main() {
int a[5],cpy[5],ctr = 0;
for (int i = 0 ; i<5 ; i++) {
cout<<"Enter Value for index "<<i<<": ";
cin>>a[i];
}
for (int i = 0 ; i<5 ; i++)
if (a[i]%2==0) {
cpy[ctr]=a[i... | The problem here is that you will never enter the first loop. The counter is incremented only if the condition is satisfied, otherwise the loop is broken. You should not implement a condition like this.
I suggest you to try the following with std::vector :
#include<iostream>
#include<vector>
using namespace std;
int m... |
74,069,277 | 74,069,673 | Initializing an array of objects created on the heap | Given the non trivial data structure:
claas MyClass
{
public:
MyClass():x(0), p(nullptr)
{}
private:
int x;
int* p;
};
Is there any guarantee provided by the c++ specification that the default constructor will be called for each instance of MyClass in the array pointed by the ptr?
int main()
{
... |
Is there any guarantee provided by the c++ specification that the default constructor will be called for each instance of MyClass in the array pointed by the ptr?
Yes, it is guaranteed as explained below.
From new expression's documentation:
::(optional) new new-type initializer(optional) (2)
The object crea... |
74,069,545 | 74,075,035 | Float results difference on sin function compiled with g++ on two versions of ubuntu | I have tested my code developed on a ubuntu 18.04 bionic docker image on a ubuntu 20.04 focal docker image. I saw that there were a problem with my unit test and I have narrowed the root cause to a simple main.cpp
#include <iostream>
#include <iomanip>
#include <math.h>
int main()
{
const float DEG_TO_RAD_FLOAT = f... | Well, investigating a slightly modified version of your test program:
#include <iostream>
#include <iomanip>
#include <cmath>
int main()
{
const float DEG_TO_RAD_FLOAT = float(M_PI / 180.);
float theta = 22.0f;
theta = theta * DEG_TO_RAD_FLOAT;
std::cout << std::setprecision(20) << theta << ' ' << std::... |
74,070,050 | 74,070,424 | (C++) A question about "insert" function in vector | https://en.cppreference.com/w/cpp/container/vector/insert
Cppreference shows: iterator insert( const_iterator pos, const T& value ); and four other overloads.
But why the parameter is const_iterator but not iterator?
| Whether or not the iterator is const doesn't matter, since the container is the thing being modified (and insert is not a const-qualified member function), not the passed in iterator.
And this just makes it easier to use. A non-const iterator is convertible to a const_iterator (but not the other way around) so you can ... |
74,070,098 | 74,077,178 | Z Buffer Not Working Correctly (Not Displaying Anything) | Here is the code for my Z Buffer, it returns a black screen when I draw it.
sf::VertexArray ZOrder(sf::VertexArray verticies, std::vector<float> z_buffer) {
std::vector<float> order;
for (int i = 0; i < verticies.getVertexCount(); i++) {
order.push_back(i); // {1, 2, 3, 4 ...
}
for (int i = 0; ... | FIXED:
sf::VertexArray ZOrder(sf::VertexArray verticies, std::vector<float> z_buffer) {
std::vector<float> order;
for (int i = 0; i < verticies.getVertexCount(); i++) {
order.push_back(i);
}
for (int i = 0; i < z_buffer.size(); i += 3) {
for (int i = 0; i < z_buffer.size(); i += 3) {
... |
74,070,654 | 74,070,742 | fread struct with vector from binary file gives Access violation reading error | I'm trying to read and write a struct with vectors to a file in C++. I'm getting read violation error, why is that and how can I fix it? Here's the code.
#pragma warning(disable : 4996)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;
struct A
{
vector<int> int_vecto... | std::vector as you know, is dynamic, it simply contains a pointer to the data located on the heap. The sizeof(std::vector) is a constant value, you could not just write it to a file then read it back for that reason.
What you need is serialization, there are some awesome open source library that you could find on githu... |
74,070,977 | 74,071,377 | How to define Iterators for an abstract class in C++ | I'm working on a C++ project where I have an abstract class called Aggregate, which represents a container for another abstract class called Primitive.
I want to be able to iterate through an Aggregate, without worrying with the details of how the Primitive objects are actually stored.
Since I'm not really proficient ... |
First, is it even possible to do something like this?
Second, what exactly should my Aggregate class and its derived classes do in order for this to work?
Yes, you "simply" add to Aggregate two virtual functions returning a begin() and an end() iterator.
struct Aggregate
{
struct iterator { /* ... */ };
vir... |
74,071,230 | 74,071,290 | Understanding what (void) does when placed in front of a function call | My questions is:
Why is the (void) responsible to return a different value? What's exactly happening?
struct S {
int operator,(int) { return 0; }
};
std::cout << (S(), 42) << '\n'; // prints '0'
std::cout << ((void) S(), 42) << '\n'; // prints '42'
| Problem here is that comma operator has been overloaded.
So first line:
(S(), 42)
Will invoke this custom overload of comma operator, since arguments are S and int which matches this overload. Note this version always returns 0 value.
In second line:
((void) S(), 42)
Your custom overload of comma operator doesn't mat... |
74,071,288 | 74,075,421 | Switch context in coroutine with boost::asio::post | I'm trying to understand C++ coroutines. My expectation in the example below would be, that each asio::post will switch the context/thread to the given threadpool. But something very strange happens. I get the following output:
thread0: 7f0239bfb3c0
thread2: 7f02391f6640 (tp2)
thread3: 7f02387f5640 (tp)
thread4: 7f0238... | I have a near identical answer up here: asio How to change the executor inside an awaitable?
I'll leave the explanation there, but your code can act as expected like this:
Live On Coliru
#include <boost/asio.hpp>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
namespace asio = boost::asio;
... |
74,072,188 | 74,076,297 | How to filter and transform cpp vector to another type of vector? | I have a class called InfoBlob and two enums called Action and Emotion. My function is supposed to take in a vector<InfoBlobs> blobs, and return a vector<Action> actions, corresponding to certain attributes of the blob. However, I have to perform this conversion only in the range of 'first HAPPY blob to the last SAD bl... |
How do I apply this to only the range of 'first HAPPY blob to last SAD blob'
You want drop_while. To remove elements past the last SAD blob, you can do a reverse, then a drop_while, then another reverse.
How do I transform the vector of InfoBlobs to the vector of actions given the filter condition 'The blobs must be... |
74,072,212 | 74,073,587 | `uint_fast32_t` not found in namespace `boost` for boost > 1.74.0 | I am trying to compile boost from sources but getting the error below.
It works fine for all versions of boost up to 1.74.0 but it breaks for anything newer than that.
Note that I am compiling a subset of boost modules, std::regex only.
Is there anything that changed on this version that makes these types unavailable?
... | You aren't checking out all of the submodules, the simplest solution is to just follow the docs and run:
git clone --recursive https://github.com/boostorg/boost.git
or:
git clone git@github.com:boostorg/boost.git
git submodule update --init
After adding libs/throw_exception, and libs/assert to the submodules in your ... |
74,072,237 | 74,072,327 | Lifetime of a reference that has been returned from a function | For a function T& f() {...} what will be the lifetime of the reference entity created in T x = f(); ?
According to the standard "The lifetime of a reference begins when its initialization is complete and ends as if it were a scalar object.", and while there is a section concerning temporary objects, a reference is not ... |
Does this mean that according to the standard, in the example above the reference must actually exist throughout the whole scope block in which T x = f(); lies?
Yes, the type of the expression f() is actually T and not T&(because in C++ the type an expression is never a reference type), so you're not actually creatin... |
74,072,830 | 74,076,352 | Multiple arguments to binary fold expression? | I am trying to write variadic template printing using fold expressions rather than template recursion.
Currently I have
template <typename... Ts, typename charT, typename traits>
constexpr std::basic_ostream<charT, traits>& many_print(std::basic_ostream<charT, traits>& os, Ts... args){
os << '{';
(os << ... << args... | In this case, where nothing is being computed, you can just use the comma operator for the fold itself:
((os << args << ", "),...)
With a state variable trick, you can even omit one comma:
int n=0;
((os << (n++ ? ", " : "") << args),...);
|
74,073,045 | 74,092,196 | Is it ok to distribute api-ms-win-core-xxx.dll with my app? | I compile a C++ exe with vs2022 on win11, and run it on a win7 device, but the system prompts that a bunch of api-ms-win-core-xxx.dll is missing.
So, I check the documentation, it says these DLLs are introduced after win7, so can I just distribute them with my app?
| I suggest you don't try to get these dlls, distributing these files is a violation of the Windows End User Agreement.
According to this issue:
Those DLLs are Windows's implementation detail and are subject to
change at anytime. Those files you get from a higher version of
Windows won't work if your Windows version is ... |
74,073,081 | 74,073,703 | How do I parameterize a consteval lambda? | Background
I am using a NTTP (non-type template parameter) lambda to store a string_view into a type at compile time:
template<auto getStrLambda>
struct MyType {
static constexpr std::string_view myString{getStrLambda()};
};
int main() {
using TypeWithString = MyType<[]{return "Hello world";}>;
return 0;
}... | GCC and clang are both not actually incorrect in accepting or rejecting the program. The lambda's type simply has a data member of type char[12], which is allowed to be public or private. It seems that clang treats them as private members.
The obvious solution is to write out the closure type explicitly ensuring the da... |
74,073,275 | 74,089,623 | Keying an (unordered_)map using a multimap iterator | I'm building a software where one class is responsible to log info sources and commands (both are grouped as requests), where all requests are inserted inside a multimap, wherein the multimap is keyed by the request name, and each element points to request structure that holds management information and callback functi... | The iterator requires a custom comparison function _Compare:
struct Compare_REQMAP_I
{
bool operator()(const SYS_REQMAP_I& lhs, const SYS_REQMAP_I& rhs) const {
return &lhs < &rhs;
}
};
using SYS_REQINF_SUBS = std::map<SYS_REQMAP_I, SYS_INFOSUB_CBFS, Compare_REQMAP_I>;
|
74,073,346 | 74,073,948 | Automatic template deduction for function pointers | In the following code
template<class T> void f(T);
int main(){
f(3);
return 0;
}
the template argument int for deduces automatically, as usual.
But in
template<class T> void f(T);
template<class T> void (*p)(T) = f<T>;
int main(){
p(3);
return 0;
}
the compiler (clang++) insists that p(3) needs a tem... | Template argument deduction works with function templates and and with CTAD from C++17. Writing a wrapper is trivial for your example.
template<class T> void f(T);
template<class T> void (*p)(T) = f<T>;
template<typename T> void Wrapper(T&& t)
{
p<T>(std::forward<T>(t));
}
int main(){
Wrapper(3);
}
|
74,073,399 | 74,094,653 | Passing SQLite3 database pointer to a Function having a sqlite3_close(db) gets a 21 error - bad parameter or other API issue | My goal is to have a successful SQLite3 close after an open from functions I created.
I expected the close to return a code of zero.
I'm passing the SQLite3 *db pointer after a successful open to a function of my
construction having an rc = sqlite3_close(db). Seems in the act of passing the
db pointer something ... | As I wrote in my comment, changes to db in openDB do not show up in the variable db in main. There are two important things to understand:
Pointer variables have an address like any other variable, but their value is also an address.
C++ defaults to "pass by value"
I will explain the problem by interpreting your code... |
74,073,670 | 74,074,455 | Iterator returned by std::max_element(vList.begin(), vList.end()) changes value after clearing and updating the vector(vList) | For a BucketSort program using a vector of lists. I used std::max_element to find out the maximum element from the vector.
But it looks like once the original vector is cleared and updated, the iterator returned by max_element also changes the value to the updated value from vector (vList) from same index.
#include <io... | The iterators provided in C++ store an address that is referenced. When you clear the vector and fill it with new values, the iterator is still pointing to the same place and will show the new value in that location. Take a look at this example:
[0,1,2,3,4]
^
You have an iterator pointing to the third element of ... |
74,073,781 | 74,075,487 | malloc fails when asking for over 8 GiB | I am trying to load 1024 matrices into an OpenCV Mat. Each matrix is width*height=2200x2200 and each element is float, so it is about 19.36 MB for each matrix. I need to assign 1024 of these matrices which require over 19 GB of memory. This is okay as I have 128GB RAM in my virtual machine.
However, I have problem gett... | The problem is with this expression:
frames * vpixels * hpixels * sizeof(float_t)
As all those variables are of type int, the result seems to overflow.
Try using types size_t for those variables.
Best regards.
|
74,073,977 | 74,074,018 | Does C/C++ program performance depend on compiler? | I read an article in which different compilers were compared to infer which is the best in different circumstances. It gave me a thought. Even though I tried to google, I didn't manage to find a clear and lucid answer: will the program run faster or slower if I use different compilers to compile it? Suppose, it's some ... | Yes. The compiler is what writes a program that implements the behavior you've described with your C or C++ code. Different compilers (or even the same compiler, given different options) can come up with vastly different programs that implement the same behavior.
Remember, your CPU does not execute C or C++ code. It... |
74,074,312 | 74,077,959 | Standard math functions reproducibility on different CPU's | I am working on project with a lot math calculations. After switching on a new test machine, I have noticed that a lot of tests failed. But also important to notice that tests also failed on my develop machine, and on some machines of other developers. After tracing values and comparing with values from the old machin... | Since you are on Windows, I am pretty sure the different results are because the UCRT detects during runtime whether FMA3 (fused-multiply-add) instructions are available for the CPU and if yes, use them in transcendental functions such as cosine. This gives slightly different results. The solution is to place the call ... |
74,074,633 | 74,078,309 | How do you make a pipeable function like ranges::to<T>() with range-v3 ranges? | My general question is how do you make something like ranges::to<T>() for classes for which ranges::to<T>() does not work?
But specifically I am looking for a pipeable way to construct a boost geometry multi_linestring from a range-v3 range view of linestrings. Somewhat surprisingly ranges::to just works when construct... | The pipeline is just overloaded operator |, you can overload it yourself.
struct to_polyline_tag{} to_polylines;
template<typename Range>
polylines opeator | (Range&& lines, to_polyline_tag) {
// the body of your to_polylines()
polylines polys;
polys.resize(r::distance(lines));
for (auto&& [i, line] : ... |
74,074,742 | 74,075,112 | When Importing a dll to python using ctypes, istream and ostream can be found, but not iostream. Why? | When Importing c.dll to python using ctypes, and iostream has been included in a.cpp, I encounter the following error:
Could not find module 'C:\Test\foo.dll' (or one of its dependencies).
Try using the full path with constructor syntax.
As explained at bugs.python.org this is an ambiguous error, indicative of a dee... | at this moment for python 3.10 the solution for this is to statically link against both libgcc and libstdc++ (or copy them from mingw/bin folder to your dll folder), this doesn't seem to be the case for versions of python prior to 3.10
g++ -shared -o c.dll a.cpp -static-libstdc++ -static-libgcc
it seems like python 3.... |
74,074,885 | 74,075,107 | How can I make my 'for' statement work fine, and how can I calculate the total? | class score {
private:
int marks;
int total;
public:
public:
score(){ marks = 0; total = 0; }
void getM();
void tot();
void displayM();
void cinM();
};
void score::displayM()
{
cout << "The score is " << total << endl;
}
void score::getM()
{
for (int i = 0; i <= subjects; i++)
... | void score::getM()
{
cin >> marks;
tot();
}
And then in main,
// main.cpp
int main() {
score s;
for(int i=0; i<5; i++) {
cout << "Enter the score of the subject " << i+1 << endl;
s.getM();
}
s.displayM();
return 0;
}
Here is a demo with full code:
// main.cpp
#include<... |
74,075,178 | 74,075,858 | How to initialize const data members in initializer list that share common attributes? | Suppose we have a class Bar which has two data members, a and b respectively pointing to two other objects of type A. Within this type A, we have a data member i that points to an integer.
In the code below, in order to allow the data members of Bar, i.e. a and b to share the same pointer i. I have to create another da... | Since A::i is public and is a shared_ptr, you can eliminate the need for Bar::_i like this:
struct Bar {
const unique_ptr<A> a;
const unique_ptr<A> b;
explicit Bar(const int &i):
a(make_unique<A>(make_shared<int>(i))),
b(make_unique<A>(a->i)) {}
};
If A::i is later made private, si... |
74,075,179 | 74,075,323 | Why does referencing an xvalue not extend the lifetime of the object it refers to? | The compiler has no way of knowing whether the xvalue is actually referencing a temporary. Therefore if the xvalue is a reference to some specific persistent "non-temporary" object, we would not want tie the lifetime of this object to the new reference variable - otherwise we could actually end up destroying the persis... | Reference lifetime extension only ever applies to prvalues, and it is only applied immediately when they're created. There's no "transfer of lifetime ownership".
When a temporary object is created, it can immediately bound to a reference. If it is, then it is created with the lifetime of that reference. The object i... |
74,076,082 | 74,076,212 | CPP won't generate text? | I have some CPP code to generate Lorem Ipsum style text. It works when I ask it for one sentence at a time, but when I tell it to mass generate sentences it generates tons of sentences that are just spaces and then periods. Here's the code (modified for confidentiality):
srand(time(NULL));
string a[9327] = {"St... | Okay, I mean, this code doesn't make a lot of sense but to answer the question, note that the only way the inner loop can not issue random strings is if it never runs and it will not run if loop_1 is greater than (rand() % 38) + 2 which is a random number from 2 to 40. Once loop_1 is greater than 40 the inner loop can ... |
74,076,492 | 74,077,617 | Teensy 3.1/3.2 - region `FLASH' overflowed by 86948 bytes while program is 40kb | I’m using Teensy 3.2 and cannot build my teensy code due to two warnings resulting in an error 1 return.
Warning 1 - .pio/build/teensy31/firmware.elf section .text' will not fit in region FLASH’
Warning 2 - region `FLASH’ overflowed by 86948 bytes
Error - collect2: error: ld returned 1 exit status
From what I read it b... |
From what I read it basically means that the file is too large but my
src folder is 40129 bytes and Teensy 3.2 flash size is 262144
The size of your src folder has not much to do with the size of the generated program. If you are interested in where all that memory goes to you can use an ELF viewer.
For example, here... |
74,076,785 | 74,077,136 | Value of a variable is not updating, it is either 1 or 0 | Hey there! In the following code, I am trying to count frequency of each non zero number
My intention of the code is to update freq after testing each case using nested loop but value of freq is not updating. freq value remains to be either 0 or 1. I tried to debug but still ending up with the same bug.
Code:
#include ... |
#include <bits/stdc++.h>
This is not standard C++. Don't use this. Include individual standard headers as you need them.
using namespace std;
This is a bad habit. Don't use this. Either use individual using declarations for identifiers you need, such as using std::cout;, or just prefix everything standard in your c... |
74,077,309 | 74,078,452 | Flatten vector of classes which contain vectors of structs | I have a vector of a class Planters which contain vectors of Plants. My goal is to return a vector of plants containing the plants from planter 1, followed by plants from planter 2, etc.
example: planter{{1,2,3,4}, {2,3,4,5}} should lead to {1,2,3,4,2,3,4,5}. note that the numbers represent plant objects. I'm trying to... | std::vector<Plant> task05(std::vector<Planter> planters)
{
auto plants = planters
| std::views::transform([](Planter const& planter) -> decltype(auto) { return planter.getPlants();})
| std::views::join
| std::views::common
;
return std::vector<Plant>(plants.begin(), plants.end())... |
74,077,404 | 74,077,421 | Is DLL function called from multithreaded application run on same thread? | I have multithreaded application. Now, I have written one function in Windows DLL.
I am calling this DLL function from thread function (called by multiple threads) which is in my application.
So, my question is, does this DLL function also executes on same calling thread?
(And no need to handle multithreading separatel... | Yes, the DLL function will execute on the same thread as the caller. There is no need to handle multithreading separately in the DLL.
|
74,077,744 | 74,077,769 | I got a negative number while trying to return a long long value | I created a function seriesSum to return a sum of the series of a number, and I used long long return data type but it returns a negative number if I insert for example 46341 output will be -1073716337 and what I am expected is 1073767311 here is my code:
#include <iostream>
using namespace std;
long long seriesSum(in... | The argument variable n is an int.
All operations you perform in the function are done using int values. Which you will overflow, leading to undefined behavior.
Change the argument type to unsigned long long.
I also recommend you change the return type to be unsigned as well, if you're not going to get negative results... |
74,077,844 | 74,077,866 | Reuse structured binding variables when using a local struct | I have a function as follows:
auto foo(int i) {
struct s {
int i;
std::string name;
};
return s{i+10, "hello there"};
}
And it works fine with structured bindings:
auto [i, name] = foo(10);
Is there a way to reuse the variables? i.e.
// Later in the code.
[i, name] = foo(20);
It doesn't ... | Since the hidden variable introduced by a structured binding is unnamed, there's no easy way to refer to it to a assign a new value.
You could do
auto x = foo(10);
const auto &[i, name] = x;
Then assign to x to change the meaning of i and name.
|
74,078,097 | 74,078,382 | Is there something like std::unconvertible_to? | I am trying to have a template parameter, that is allowed to be every type, except for one. And I have no clue how.
I'm new to concepts, and don't fully understand them yet, but this is how I implemented std::convertible_to:
template <typename T>
concept notSomeType = requires(T v)
{
{v} -> std::convertible_to<... | You can simply create a concept that is a negation of std::convertible_to:
template<class From, class To>
concept NotSomeType = !std::convertible_to<From, To>;
template<NotSomeType<int> T>
void f(T)
{
std::cout << "Not convertible to int\n";
}
template<std::convertible_to<int> T>
void f(T)
{
std::cout << "con... |
74,078,132 | 74,078,234 | qualified reference to 'Edge' is a constructor name rather than a type in this context | I don't know Java at all, but I need this program in C++. Can anyone help me convert it? I know OOP in C++, but I'm used to another syntax and do not understand exactly what and how to modify it.
class Graph {
class Edge {
int src, dest;
}
int vertices, edges;
Edge[] edge;
Graph(int... | In the case of your mentioned error 1 and 3, "qualified reference to 'Edge' is a constructor name rather than a type in this context" that you mention in your question title the error is because you are using the constructor where the compiler would expect to see a type.
You have:
Graph - this is a class
Edge - thi... |
74,078,223 | 74,078,282 | how to check that const array members grow monotonically at compile time | assume we have const array:
const int g_Values[] = { ... };
how check that members grow monotonically at compile time, i.e. g_Values[i] < g_Values[i + 1]
in runtime this possible to check like this:
bool IsMonotonously()
{
int i = _countof(g_Values);
int m = MAXINT;
do
{
int v = g_Values[--i];... | This is impossible for an array that is just const. You need to make it constexpr to be able to use it in a constexpr context.
All you need to do in addition to this is to implement the function for checking the array as constexpr:
template<class T, size_t N>
constexpr bool IsStrictlyMonotonouslyIncreasing(T (&arr)[N])... |
74,078,523 | 74,078,542 | Is there a way to make a single loop for two different variables? | I am looking for a way to make a single loop for two variables. I have a "p1" (player 1) and a "p2". Both have the particularity to use the same loop to have a certain number of spaces. Is there a solution to make a single loop instead of creating two? Here is the loop in question for the player one:
for (string::s... | Yes, you separate the initialization and updates with commas (,) and convert the condition to a compound one.
for (string::size_type i = 1, j = 1; i < (SIZE - p1.name.length()) / 2 && j < (SIZE - p2.name.length()) / 2; i++, j++) {
cout << " ";
}
|
74,078,646 | 74,078,681 | Why replace an existing keyword in C/C++ with a macro? | I often come across keywords or one-word identifiers defined with another name. For example, boost defines noexcept as BOOST_NOEXCEPT, some C++ standard libraries replace [[nodiscard]] with _NODISCARD, Windows API is prone to introduce their own macros as well, and so forth. I didn't really manage to find anything whic... | The most useful case of these is when you target both compilers that support a new feature and ones that do not.
For instance:
#if CompilerSupportsNoexcept
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif
|
74,079,280 | 74,079,322 | What does this syntax "success |= MAX35101_Read_2WordValue(TOF_DIFF_AVG_REG, &TOF_DIFF_Results->TOF_DiffData);" mean? in C/C++ language? | I am trying to decode the reference code to access the registers in MAX35101 IC.
The code has this syntax at various lines.
What does this mean?
bool MAX35101_Update_TOF_AVG_DIFFData(Flow_ResultsStruct* TOF_DIFF_Results)
{
bool success = false;
success |= MAX35101_Read_2WordValue(TOF_DIFF_AVG_REG, &TOF_DI... | Z |= X(a, &b->c); could be rewritten as Z = Z | X(a, &(b->c));
We have a pointer to a struct Flow_ResultsStruct* b. To access a member of a struct via a pointer we use a ->. So it is get the address of member c of struct b for which we have a pointer.
Pass a and the address to X.
Now logical or (|) the return value wit... |
74,079,454 | 74,091,282 | Qt error while loading shared libraries: __vdso_time: invalid mode for dlopen(): Invalid argument | I packed a very easy Qt application (with shared libraries found by ldd) on my debian 11.
But it failed to run on ubuntu(20.04) virtual machine.
The error is : error while loading shared libraries: __vdso_time: invalid mode for dlopen(): Invalid argument
Both the glibc is version 2.31.
The version of qt is 6.3.2.
I us... | You should never pack GLIBC or its constituent libraries (libc.so.6, libm.so.6, librt.so.1, libdl.so.2, libpthread.so.0) for reasons explained here.
The most likely cause of the error is a mismatch between /lib64/ld-linux-x86-64.so.2 and ./libdl.so.2. Removing the 5 libraries listed above from this directory should mak... |
74,079,605 | 74,079,686 | Optimization of the condition in the if-statement | Well I know that the title makes almost no sense but I could not find a better one to explain my question here.
So I've just started doing challenges on LeetCode and I am on the very first steps for now. But one situation confused me.
So I was solving the question named "Number of 1 Bits" which basically gives you an u... | It's not. Both your code will produce the same machine code.
Your measuring method is wrong, you need to loop that function millions times to get a non-bias result and it will be the same.
The lesson? Don't try to optimize the if statement, in most cases you won't be smarter than the compiler
|
74,079,805 | 74,079,996 | Eigen error while initializing fixed size array | I was following the Eigen documentation, b prints but a doesn't print.
#include <iostream>
#include <eigen3/Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
Vector3d b(5.0, 6.0, 7.0);
MatrixXi a { // construct a 2x2 matrix
{1, 2}, // first row
{3, 4} // second row
... | I solved the problem by deleting Eigen from my system first and then I cloned it from the git repository in a file called eigen I created in home folder. then I included the whole directory with
#include </home/zornic/eigen/eigen/Eigen/Dense>
and it worked, but I'm not sure why my headers didn't work like in the docum... |
74,080,016 | 74,081,147 | How to terminate child process in other child process? (win32api) | I created two child processes called p_1(notepad) and p_2(a clone of parent process) using CreateProcess.
What I want is terminate p_1 in p_2, not in parent process.
First, I created the processes with the following code:
case WM_LBUTTONDOWN:
{
STARTUPINFO si = { 0, };
WCHAR notepad[32] = L"C:\\Windows\\notepad... | Using DuplicateHandle(), the parent can start P1 and P2, then duplicate its P1 handle into P2's context, then pass the value of the duplicate handle to P2 via an IPC mechanism of your choosing, such as a pipe, window message, etc. P2 can then store the value into a HANDLE variable and terminate P1 using that handle.
An... |
74,080,233 | 74,080,560 | Where does the C++ standard state that subobjects of an array declared as static are static objects? | Given the following code (it compiles successfully):
int main(void)
{
const int a{};
const int &r = a;
static int arr[1] = {r};
constexpr const int &ref = arr[0]; // OK
}
The initialization of ref is glvalue designating reference ref. So the full-expression of the initialization has to be a glvalue core consta... |
Here's my question: Is this element a subobject with static storage duration?
[basic.stc.inherit]/1 says:
The storage duration of subobjects and reference members is that of their complete object.
An array element is a subobject of the array it is an element of. So it has the same storage duration as the array.
|
74,080,878 | 74,081,560 | Separating of tests build form application build in CI/CD without rebuilding | I have a project with files:
main.cpp - application
sum.h
sum.cpp
tester.cpp - tester application
I build it with CMake, CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set (ProjectName hello)
project(hello VERSION 1.0)
set(SOURCES sum.h sum.cpp main... | Your CMAkeLists.txt may look like this:
cmake_minimum_required(VERSION 3.10)
project(hello VERSION 1.0)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(CTest) # Sets BUILD_TESTING=0 by default
# Do not build twice.
add_library(sum sum.cpp sum.h)
# There is already PROJECT_NAME CMake variable.
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.