question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
67,579,860 | 67,580,809 | sum of an array elements in cpp return wrong value | I tried to write a simple code to calculate an array elements' sum. every thing looks normal but the function return the sum value wrongly (it always multiply it by two). Although if I want just print the value, it works fine.
this is the code:
#include <iostream>
using namespace std;
void getElements(int[],int);
in... | You defined int sum globally and were calling sumOfElementstwice, so sum contained twice what you expected.
Here is a modified version of your code that does what you want:
#include <iostream>
using namespace std;
void getElements(int[], int);
int sumOfElements(int[], int);
int main() {
int numbers[5];
getElement... |
67,579,993 | 67,580,149 | C++ spaceship operator multilevel compare? | Does the new C++20 spaceship operator allow a concise way of expressing short-circuited multiple-criteria comparison? Something better than this:
const firstCriteriaComparisonResult = lhs.x <=> rhs.x;
return firstCriteriaComparisonResult != 0 ? firstCriteriaComparisonResult : lhs.y <=> rhs.y;
| The usual tie-and-compare approach works with spaceship too:
return std::tie(lhs.x, lhs.y) <=> std::tie(rhs.x, rhs.y);
|
67,580,426 | 67,580,770 | GNU GCC Codeblocks win32 function not declared | This is a snippet of code from a library in my project (Implot):
#ifdef _WIN32
t.S = _mkgmtime(ptm);
...
#ifdef _WIN32
if (gmtime_s(ptm, &t.S) == 0)
...
#ifdef _WIN32
if (localtime_s(ptm, &t.S) == 0)
and this project was just ported from Visual Studio 2019 to Codeblocks (C++17). For some reason this can't ... | If you read the Visual Studio predefined macros documentation you can find compiler-specific macros which ben be used to identify if your code is being built by the Visual Studio C++ compiler.
For example the _MSC_VER macro, which you can check for instead of _WIN32.
As in:
#ifdef _MSC_VER
auto result = gmtime_s(ptm, &... |
67,580,619 | 67,580,948 | Modulo strength , want explanation in the algorithm used to compute the answer | I was trying to solve the problem Modulo strength at hackerearth ,
https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/golf/modulo-strength-4/ , so basically we have to find all such pairs of no. (say i,j) such that A[i]%k=A[j]%k where k is a no. given in th... | There are a few problems with that;
"bits/stdc++.h" is not a standard header
Variable-length arrays, like int a[n], are non-standard and prone to runtime errors (this one is also completely unnecessary)
#define int long long makes the code have undefined behaviour.
Here is a fixed version, with some minor renaming an... |
67,581,070 | 67,581,518 | how to make this number shape? | Write a program to display the below pattern with n rows, where n is
in the range between 1 and 100. The variable n should be entered by
the user. If the user input is between 1 and 100 then output the
pyramid as given below, otherwise prompt the user to enter n again.
Here is the sample output: Enter the number of ... | int num = 1, counter = 1, temp = 1;
cout << "Enter the number of rows: ";
cin >> num;
for (int i = 0; i < num; i++)
{
for (int j = 0; j <= i; j++)
{
cout << temp << " ";
temp++;
}
counter++;
temp = counter;
cout << endl;
}
The variable temp serves as a counter for the rows, mea... |
67,581,128 | 67,581,495 | How does reassigning static variables work? | Since the lifetime of a static variable is that of the program what exactly happens when you try to reassign it?
Some how in the program below, the test.loc ends up becoming 6 before getting destroyed eventhough the constructor is the only thing that can change that value. It is the original object itself so how does o... | Your program does not define an assignment operator (operator=), so the compiler creates one for you. That assignment operator will copy the value of loc from the source instance of Test and will change the value of loc in the destination instance.
If you add the following to your Test class, you'll see what is happen... |
67,581,410 | 67,581,538 | Difference between: std::make_unique<char>(size_t size) and std::make_unique<char[]>(size_t size)? | I was implementing the circular array data structure whose code looks like this:
struct CircularArrayException : public std::exception {
std::string msg;
CircularArrayException(const std::string arg_msg)
: msg{"CircularArrayException: " + arg_msg} {}
const char * what () const throw () {
retu... | std::make_unique<char>(65); creates a pointer to a single character initialised with the value 65 ('A'). std::make_unique<char[]>(65) creates an array with 65 elements.
If you run this code:
#include <memory>
#include <iostream>
int main()
{
auto a = std::make_unique<char>(65);
std::cout << *a << "\n";
aut... |
67,581,501 | 67,581,571 | Does stoi(char*) necessarily construct a temporary string? | Does calling stoi with a (NULL-terminated) char* necessarily construct a temporary string and hence lead to a performance penalty?
| Conceptually yes it would. There is no overload of std::stoi that takes a const char* as an argument, so an anonymous temporary std::string is created.
That indeed is a string copy.
You could check the assembly code to see if that's what your compiler does. It might optimise to
std::strtol
or
std::strtoll
If your com... |
67,581,506 | 67,581,650 | Initialize static constexpr member variable of class template | Here is the situation: A class Foo with a template param int N has a static member variable float val. The value of val is corresponding to N and never changes, so I expect it to be constexpr.
I know the common way of initializing static constexpr member variable is:
// ok, but not what I want
template <int N>
struct F... | You can specialize the class template as
template <int N>
struct Foo {
static constexpr float val { 0.0f };
};
template <>
struct Foo<0> {
static constexpr float val { 3.14f };
};
template <>
struct Foo<1> {
static constexpr float val { 0.1f };
};
Or make a function helper for initialization.
template <int... |
67,581,658 | 67,590,619 | How can I have CMAKE_BUILD_TYPE being propagated to sublibraries included via add_subdirectory? | My build consists of several sub-libraries being first build and then linked together.
In the main cmakelists.txt they're added with
add_subdirectory (src/submodules/CanTp/CanTp CanTp)
and a linker dependency is added with
target_link_libraries(my_app_name PRIVATE CanTp/${CMAKE_BUILD_TYPE}/CanTp
The cmakelists.txt fo... | As noted by @Tsyvarev the Visual Studio CMake generator is a multiconfiguration generator which means it provides all configurations at once. CMAKE_BUILD_TYPE only has an effect for single configuration generators like Unix Makefiles.
To support both types of generators you shouldn't read CMAKE_BUILD_TYPE unless you've... |
67,581,753 | 67,581,870 | How to write multiple lines to file in C++ without losing previous lines | I need to write multiple lines in a txt and binary file and I created a function (I'll attach it below) that's supposed to write a few array items into the file. The problem is, I used fprintf while I open and close the file in the same function and so every time my for (because it's an array) calls the function, it ov... | Use :
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
Above method will append the file
|
67,583,590 | 67,584,666 | Copy bits of uint64_t into two uint64_t at specific location | I have an input uint64_t X and number of its N least significant bits that I want to write into the target Y, Z uint64_t values starting from bit index M in the Z. Unaffected parts of Y and Z should not be changed. How I can implement it efficiently in C++ for the latest intel CPUs?
It should be efficient for execution... | There's at least a four instruction sequence available on reasonable modern IA processors.
X &= (1 << (N+1)) - 1; // mask off the upper bits
// bzhi rax, rdi, rdx
Z = X << M;
// shlx rax, rax, rsi
Y = X >> (64 - M);
// neg sil
// shrx rax, rax, rsi
The value M=0 causes a... |
67,583,707 | 67,583,948 | Accessing elements in Vector of derived structs? | My goal is to store elements of different data types in one vector.
A ball as well as an cuboid is an object.
//header.h
struct Object {
};
struct Ball : Object {
int diameter;
int surface;
};
struct Cuboid : Object {
int length;
int width;
int height;
int surface;
};
std::vector<Object *> myObjects;
/... | You need to think about why you need to access diameter.
Once you figure that out, you should add a virtual member function for Object that would use that member. Then, you override that virtual member function in Ball, and use the diameter there.
Example:
struct Object {
virtual float
volume() const = 0;
... |
67,583,790 | 67,584,099 | Passing weak_ptr by reference to lambda | I observe an undefined behavior at runtime on my program and I suspect it might have caused by the weak_ptr.
The send function of socket get called but it can't map the socket, but if I remove Lambdas it can map the socket.
The worker function was synchronous before and had no issues, but it cause undefined behavior n... | As noted in the comments
std::weak_ptr<s::Channel> socket is a local variable, it is destroyed after the function returns. When the callback is called later, it is referring to a non-existent weak_ptr instance.
You can fix it by capturing socket by value:
void worker(std::weak_ptr<s::Channel> socket)
{
auto &requ... |
67,584,033 | 67,588,400 | arrow::py::import_pyarrow() cause a SEGMENTATION FAULT | I'm trying to use arrow-cpp to build a Table then transfer it back to python.
In order to do that, I need to call arrow::py::import_pyarrow() beforehand, but this will cause a SEGFAULT.
Can anyone help to find where I did wrong?
here is a minimal example
CMakeLists.txt
cmake_minimum_required(VERSION 3.20.0)
project(TES... | The C++ application does not initialize the Python interpreter. Here's an example C++ executable which does this correctly:
https://github.com/apache/arrow/blob/8e43f23dcc6a9e630516228f110c48b64d13cec6/cpp/src/arrow/python/util/test_main.cc
This was also answered on
https://lists.apache.org/thread.html/ra6a5d523a1cf9a3... |
67,584,437 | 67,587,723 | std::chrono nanosecond timer works on MSVC but not GCC | I have a simple program that uses chrono for timing that I had ported from MSVC to Code::Blocks. The display of the program shows the delta time from when it was started to 16 decimal places. After getting it to compile, I noticed that the timer was only moving up from the first 6 decimal places. The code remains uncha... | That's a known MinGW issue #5086.
It mentions these possible workarounds:
use std::chrono::steady_clock
use Boost.chrono
build your own clock using QueryPerformanceCounter Win32 API
Regarding MSVC:
First of all, on Windows, the best possible user-space timer resolution is 100 ns.
In MSVC system_clock and steady_clock... |
67,584,593 | 67,584,627 | Creating an Array of Vector Pointers | I have to input a number "N" and create an array of vector pointers so that by using Polymorphism I am able to place different objects at different indexes of the vector.
What I'm trying to do:
vector<Vehicle> *ptr(N);
This gives an error, how can I create an array of vector pointers of type ?
| The standard C++ doesn't support Variable-Length Array (VLA), so you should create a vector of vector pointors instead.
std::vector<vector<Vehicle> *> ptr(N);
If your compiler supports VLA and you want to use that for some reason, you should use [] instead of ().
vector<Vehicle> *ptr[N];
|
67,584,695 | 67,585,055 | What is allowed to do in destructors in C++? | I'm trying to understand what is allowed to do in destructors.
The standard says: "For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor finishes execution results in undefined behavior".
cppreference describes destruction sequence this way: "Fo... | The destructor of Bar has not finished, and therefore referring to a member of Bar, and indeed calling a member function of Bar within its destructor is OK.
Calling member functions of the super object can be a bit precarious though, since member functions may access sub objects, and some sub objects may have already b... |
67,584,706 | 67,585,842 | How to implement full specialization templates member function within partial specialization templates class | Suppose I have a template class Foo with two template args and one template member function.
I want to make member function specialization while the template class is partial specialization, but the following code compiled failed by g++
template <typename A, typename B>
class Foo
{
public:
tem... | [temp.expl.spec]/17:
In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member templa... |
67,584,723 | 67,587,247 | The C++17 compiler (gcc or Microsoft Visual C++), does it have an option that prohibit the feature "not produce a temporary" | How can I told to С++17 compiler to create temporary in the following case
(i.e. The C++17 compiler must considered copy/move operation, like C++11 and C++14 compilers do)
class A{
public:
A(){}
A(const A&)=delete;
A(A&&)=delete;
};
A f(){
return A();
}
int main(){
auto a=f();
}
Out... | You cannot (and should not) deactivate guaranteed elision. However, if you want to prevent it in a specific case, all you need to do is not use a prvalue:
A f(){
A a{};
return a;
}
That will require that A can be moved, though the move can (and almost certainly will) still be elided.
One of the main points of ... |
67,584,972 | 67,592,012 | Object not moving according to mouse position when using shaders in raylib | I'm creating a few glowing particles in raylib using shaders and the particles are supposed to move along with the mouse but when compiling it gets stuck to the bottom left corner and the particles dont move.
How it Looks
The c++ code
#include <raylib.h>
#include <vector>
const int W = 400;
const int H = 400;
std::v... | The uniform particle is of type vec2[30]. An uniform array can needs to be set with SetShaderValueV instead of SetShaderValue:
SetShaderValue(shader, particleLoc, particles, SHADER_UNIFORM_VEC2);
SetShaderValueV(shader, particleLoc, particles[0], SHADER_UNIFORM_VEC2, 30);
|
67,585,059 | 67,585,238 | boost::gregorian::date constructor with Warning C4244 | This code snippet works well on my test project. But it compiles with warnings on my working project
auto current_date = boost::gregorian::day_clock::local_day();
const auto nMinYear = current_date.year(); const auto nMonth = current_date.month(); const auto nDay = current_date.day();
const auto nMinYear1 = nMinYear + ... | The type of
nMinYear + 1
will be an unsigned int due to implicit widening of the terms in that expression. So nMinYear1 is a const unsigned int, and the compiler emits a warning when that's used in the boost::gregorian::date constructor.
decltype(nMinYear) nMinYear1 = nMinYear + 1;
is a fix.
|
67,585,085 | 67,585,142 | Why is this null termination in c++ char array not recognized | I have a very simple C++ code like so:
#include <iostream>
using namespace std;
int count_occurrences(char *pc, char c) {
int count = 0;
while (pc != '\0') {
if (*pc == c) {
++count;
}
++pc;
}
return count;
}
int main() {
char v[6] {'h', 'e', 'l', 'l', 'o', '\0'... | try to check this out this
while(*pc != '\0')
|
67,585,317 | 67,585,499 | Unable to use make_index_sequence as a default argument to a function (instantiation of undefined template) | I have the following C++ code, which correctly prints out the 3 values of the tuple, comma-separated.
#include <iostream>
#include <utility>
#include <tuple>
std::tuple<int, const char*, float> t(10, "ten", -0.0);
#define SEQ std::make_index_sequence<std::tuple_size_v<decltype(t)> >{}
template <typename... Ts, size_... | You can overload the print_tuple-function:
#include <iostream>
#include <utility>
#include <tuple>
std::tuple<int, const char*, float> t(10, "ten", -0.0);
template <typename... Ts, size_t... Is>
void print_tuple(const std::tuple<Ts...>& t, std::index_sequence<Is...>) {
((
std::cout << (Is == 0 ? "" : ", "... |
67,585,415 | 67,587,324 | c++ istream operator overloading unresolved | source.h:
#include <iostream>
class date{
public:
std::string str_time;
friend std::istream& operator >> (std::istream& para_stream, date& para_date);
};
source.cpp:
#include "source.h"
std::istream& operator >> (std::istream& para_stream, date& para_date)
{
istream >> para_date.str_time;
return istream;
}
ERROR:... | The linker is complaining about src::DB having an "unresolved external symbol"
You have defined a function inside source.cpp, so it remains internal to this file (translation unit).
If you add a declaration to the header file, like this
std::istream& operator >> (std::istream& para_stream, date& para_date);
it becomes... |
67,585,641 | 67,587,072 | Distribute periodic messages on cycles | I'm currently facing a problem:
I have messages that have to be sent periodically. There are multiple (different) intervals which each have multiple messages. There is a limit how many messages can be put into one cycle. That means I have to offset the interval start by a few cycles to distribute the messages to avoid ... | It’s possible to formulate instances of this problem as a packing
problem and solve them via integer programming. I used OR-Tools. The
minimum number of messages per instant for the instance you give is 4.
import math
import pprint
from ortools.linear_solver import pywraplp
def distribute(period_to_messages):
so... |
67,585,913 | 67,586,136 | Compiled file is too large [202493852 bytes] error from on-line submission | While using a 2-D array, I tried using a static array assigning -1 to it's first element:
int dp[5001][5001] = {-1}; //setting dp[0][0] to -1
int calc(int i, int j){
//Some operations are happening here which utilize dp array.
}
int main(){
cout << calc(0,0);
}
When I submit this code-snippet as a solution on... | When you declare a static array with an initializer, like
int dp[5001][5001] = {-1};
the whole array is put into a data section of the executable file. Its size is (5001×5001=25010001) × sizeof(int) of your compiler. If sizeof(int)==8, then the size of the array in bytes, 200080008, comes close to the limit you cited.... |
67,585,986 | 67,586,432 | Removing constness from reference returned by const accessor method versus adding a non-const accessor method | Let's consider the following code:
Class MyVeryAccessibleClass
{
public:
const std::vector<int>& getVect() const {return vect_m;};
private:
std::vector<int> vect_m;
};
Class MyInitClass
{
MyInitClass() : importantInt_m{10}{};
void init();
protected:
int importantInt_m;
};
My project is built in a wa... | You can declare your class MyInitClass as a friend of MyVeryAccessibleClass.
Let's see the code in action.
class MyVeryAccessibleClass
{
friend class MyInitClass;
private:
const std::vector<int> vect_m;
}
Now Let's look at the MyInitClass constructor.
MyInitClass::init()
{
MyVeryAccessibleClass* class_l = m... |
67,586,659 | 67,586,958 | Is there a difference between char a[n][m] & char a[][m]? | Also why it is not printing garbage when I provide m > my column values like in the second case? Any specific reason?
#include <iostream>
using namespace std;
int main()
{
char a[2][5] = {{'a', 'b', 'c', 'd', 's'}, {'e', 'f', 'g', 'h', 'q'}};
cout << a[0] << endl; // abcdsefghq!V
cout << a[1] << endl; // e... |
Is there a difference between char a[n][m] & char a[][m]?
Depends on context. First is an array of n arrays of m chars. Second is an array of unknown bound of arrays of m chars. So, they are different types.
However given a braced init list such as in the example, the array of unknown bound will be adjusted to be an ... |
67,587,465 | 67,587,516 | Error in reading input to an array in c++ | I was writing sorting algorithm when I encountered the following error.
Code:
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int a[100];
cin >> n;
for (int i = 1; i < n; ++i) {
cin >> a[i];
}
//or use getlinee as getline (cin, fullName);... | You are reading elements only from a[1], but your sorting begins from a[0].
Change
for (int i = 1; i < n; ++i)
{
cin >> a[i];
}
to
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
to read data also to a[0].
|
67,587,485 | 67,592,419 | Why does boost::spirit::unicode::char_ no longer work with UTF-8 char* strings? | With boost version 1.60 I could use #define BOOST_SPIRIT_UNICODE and boost::spirit::unicode::char_ to process UTF-8 input strings without any further preprocessing. With boost version 1.72 this fails with an exception.
The solution seems to be to use boost::u8_to_u32_iterator and let spirit work with wide strings. But ... | Running on my local box with Boost 1.65.1 parses successfully AND without apparent ASAN/UBSAN trippings.
I bisected the commits in the Git repo foor Spirit and found first breakage at tag for 1.72.0 (SPIRIT_VERSION 0x2058).
I found the commit that breaks it was
commit 16159fb335c9bb2040cf061e30fdd4deea9087e1 (HEAD)
Aut... |
67,587,557 | 67,587,658 | How can I fix my code so I don't get a C6385 warning? | I'm having trouble with a C6385 warning in my code. I'm trying to see if two arrays will equal each other. The warning I keep getting is on the line where if(p[i] == inputGuess[j]). I have tried redoing these line but I keep getting the same warning. Does anyone know what I'm doing wrong. This is also my first time pro... | Your second if statement compares i < n instead of j < n and since i is never modified inside it will run forever. This causes the warning since you’ll access memory out of bounds. Fix the comparison.
|
67,587,640 | 67,588,299 | Preprocessing: Is defining a shorthand for `import` legal? | For solving a code-golf challenge, I want to produce the smallest possible code. I had the idea of defining a shorthand for import:
#define I import
I<vector>;
short godbolt example
Of course, the intention here is to reuse I to actually save bytes.
Is this legal in C++20?
Thoughts / What I found out so far:
Accordin... | No.
[cpp.pre]/1:
A preprocessing directive consists of a sequence of preprocessing
tokens that satisfies the following constraints: At the start of
translation phase 4, the first token in the sequence, referred to as a
directive-introducing token, begins with the first character in the
source file (optionally after wh... |
67,588,208 | 67,588,376 | How to create ImGui window and render to it at any time you want? | I don't know much about ImGui, and it's also poorly documented.I'd like to know if there is a way to create an ImGui window, and then render to it anytime you want. I only know this way of creating a window:
ImGui::Begin("Window");
ImGui::Button("Button");
ImGui::End();
| You can simply use ImGui::Begin and ImGui::End with the appropriate window title again if you want to append to a window.
The following works:
ImGui::Begin("Window A");
ImGui::Text("This is window A");
ImGui::End();
ImGui::Begin("Window B");
ImGui::Text("This is window B");
ImGui::End();
ImGui::Begin("Window A");
ImG... |
67,588,465 | 67,588,501 | I got a memory error and i dont know whats cauising it in c++ | Hello this code is part of a big code and it causing a lot of problem i dont know why. i tried to use structer and vectors its ggot an error about vector out of range then i switched to class but still got same error im now compiling just problematic and its looks like a memory error. how can i fix this ?
#include <tim... | işlemler[işlemler.size()] is out-of-range. The initial value of size should be işlemler.size() - 1, not işlemler.size().
|
67,588,815 | 67,591,402 | Is there any performance penalty for using std::stack rather than the underlying std::deque? | I want to implement a LIFO stack object. The C++ standard lib provides a convenient stack structure (std::stack) with a very simple interface. By default, it uses std::deque as its underlying container.
Is there any performance penalty to using std::stack rather than using std::deque directly?
My use case would involve... | As commenters pointed out, you should always benchmark first in such cases. As an example I used a tool called Quick Bench, as it is online and can be embedded in here. You should always pick the tool that fits the particular need the best.
In this case the answer depends on whether you have optimizations turned on. Pl... |
67,588,906 | 67,588,969 | Difference between two stack size (using size()) in std::cout | I am confused why the two print statements give different output. Attaching the code snippet below. Any help would be appreciated. Thank You.
stack<int>st1;
stack<int>st2;
st2.push(222);
cout<<"st1 size:"<<st1.size()<<endl;
cout<<"st2 size:"<<st2.size()<<endl;
int a=st1.size();
... | Take a look at the return type of the member function size. I bet that you'll find it is an unsigned type.
What happens when you calculate 0u - 1 with unsigned integers? The result cannot be -1 because that number isn't representable by an unsigned type. The result will be a positive number that is congruent with -1 mo... |
67,588,996 | 67,589,135 | Template argument deduction/substitution failed with std::set | I've looked through a lot of posts that get the same error, but couldn't find one that applied to my problem, apologies if this is a duplicate regardless.
Anyway my task is making a class called set_helper which makes std::sets a little easier to use.
set_helper takes a set as its constructor parameter, and to help wit... | std::set<T> and std::set<T, std::greater<int>> are completely different types. Here's a more generic version:
template<
class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
>
auto make_set_helper(std::set<Key, Compare, Allocator>& s)
{
return set_helper(s);
}
The class itse... |
67,589,713 | 67,589,758 | How to handle multiple inheritance when both inherited classes need a distinct member? | I have the following classes:
class ServoPart {
protected:
virtual void doJob(byte* job) = 0;
private:
bool moving;
Servo servo;
};
// the following classes only have a constructor so I can use two ServoParts to inherit from
class Major: public ServoPart {};
class Minor: public ServoPart {};
class Arm: p... | Yes, it is ambiguous and the compiler will complain.
You can write Major::moving or Minor::moving within the code of Arm's member functions to specify which you want.
I question whether you have a proper "isa" relationship here. An arm is not a motor. An arm has two motors. You should be using composition here inste... |
67,589,862 | 67,599,254 | "Illegal value" of blas functions called by Armadillo | I'm using Armadillo (10.4.1) in Visual Studio 2019 to do some matrix stuff. I used OpenBlas from NuGet manager, but everything was slow. I now want to switch to an up-to-date version of OpenBlas. I took the last one (0.3.15) and compiled it with minGW following this tuto : https://github.com/xianyi/OpenBLAS/wiki/How-to... | I finally manage to fix the issue:
First, I downloaded the pre compiled binary (x86) here:
https://github.com/xianyi/OpenBLAS/releases/download/v0.3.10/OpenBLAS-0.3.10-x86.zip
I put the dll in my project folder, renamed the "libopenblas.dll.a" into "libopenblas.lib". It worked well, but was still slower than Matlab ...... |
67,590,671 | 67,590,828 | Message id's in the main application loop | I've written a simple Win32 App in Visual Studio 2019 on Win 10. In the main message loop inside the WinMain function i have:
while (Msg.message != WM_QUIT) {
if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE) > 0) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
swprintf_s(msgbuf, _T("In the Pe... | 799 is WM_DWMNCRENDERINGCHANGED.
49300 is a registered message (i.e. its value is in the range 0xC000-0xFFFF).
|
67,590,896 | 67,591,938 | `std::async` for asynchronous replies in C++ | Overview :
I have a client-server implementation, which uses DBus(sdbus-c++) to send asynchronous requests to a server. Now my server interacts with hardware APIs which behaves synchronously and also takes significant time to generate a reply. So I have a std::queue at server, that holds all the asynchronous requests r... | std::async returns a future that completes with the return value of the function passed to std::async.
The second assignment to the future will block until the call to sendRequestA completes (it blocks because of the destructor of the previous std::future instance). It does not wait until the reply callback is received... |
67,591,017 | 67,591,055 | validate string input with while loop | I wanted to validate a string that will be inputted by the user which follows two conditions. The condition would be whether the string is empty or the string has a space char. My current problem is that I can validate the string but it would require me to press enter once more time to reiterate my question "2. Enter P... | Being inside the if statement if(getline(cin, newNode->product_name)) { means that the reading of a line succeeded. Therefore, you don't need the lines
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
They will request an extra line to ignore, so remove that lines.
|
67,591,398 | 67,593,453 | undefined reference to cv::plot::Plot2d::render bur for cv::plot::Plot2d::create everything was ok | I use OpenCV 4.5.1 and I want to create a plot, but I've recive an error:
undefined reference to cv::plot::Plot2d::render
with code like that:
Mat plot_img(2, 100, CV_8U);
Ptr<plot::Plot2d> plotCOLs;
plotCOLs = plot::Plot2d::create(colX, colY);
plotCOLs -> cv::plot::Plot2d::render(plot_img);
imshow("KM controller", p... | Dan Mašek, was right. I follow wrong suggestion from net.
Mat plot_img(2, 100, CV_8U);
Ptr<plot::Plot2d> plotCOLs;
plotCOLs = plot::Plot2d::create(colX, colY);
plotCOLs -> render(plot_img);
imshow("KM controller", plot_img);
But the answer have second part, I've had to recompile library, becouse there was an error in ... |
67,591,507 | 67,626,504 | ShowWindow() showing blank app until is interacted with via mouse/keyboard after restoring from systray in C++ - Flutter App | I've been wanting to incorporate systray functionality into my Flutter app so I went to modify the native C++ code that initiates the window etc to see if I could hook into it.
Despite not having much prior experience in C++ I have been able to create an icon for my app in the systray with a menu that allows the window... | Ok so I've worked out why it wasn't working. When closing the window, I couldn't just use SW_HIDE, but SW_MINIMIZE too. Otherwise attempting to redraw the window wouldn't work correctly:
ShowWindow(hwnd, SW_MINIMIZE);
ShowWindow(hwnd, SW_HIDE);
After that, when showing the window it got drawn but wasn't the active win... |
67,591,689 | 67,592,575 | How to declare a tensor with Eigen without specifying the dimension? | I have a function that takes as input a tensor of dimension n, I have to store this tensor to reuse it later.
However, I don't know in advance the dimension of my tensor.
I would like to do this:
//in class.h
Eigen::Tensor<double, N> mytensor;
//in class.cpp
mytensor = input;
Is there a way to do this?
| As the parameter N is a non-type template parameter, it must be a value known at compile time. This means that you cannot really store an Eigen::Tensor with unspecified N in a variable, as each instantiation with a different size is a different type.
You can work around this by using containers such as std::variant and... |
67,591,698 | 67,591,808 | Initializing parent class' pointer using initializer list | I have a class strings:
class strings
{
protected:
string *ptr;
int size;
public:
strings() {
ptr = NULL;
size = -1;
}
strings(int size) {
this->size = size;
ptr = new string[size];
}
string* retPtr() {
return ptr;
}
void setPtr(int... | Both stringsFromNumbers::~stringsFromNumbers and strings::strings call delete[] on ptr, so the array is attempted to be freed twice; the second time causes an issue.
Only one of these classes should be responsible for managing the lifecycle of ptr. Remove the delete[] from stringsFromNumbers::~stringsFromNumbers.
If in... |
67,591,899 | 67,593,053 | Unable to figure out StructuredBuffers in DirectX11 | I'm trying to create a StructuredBuffer in an attempt to do some skeletal animations in D3D11. I'm doing solid progress on the skeleton part, but creating a StructuredBuffer has me stumped, and I don't seem to be able to find any solid advice when searching the web.
As it stands I've gotten only a guess of how to use i... | You cannot have both D3D11_BIND_UNORDERED_ACCESS bind flag and D3D11_USAGE_DYNAMIC at the same time.
If you want to write to your buffer from CPU side by mapping your buffer, you leave D3D11_USAGE_DYNAMIC and D3D11_CPU_ACCESS_WRITE and remove D3D11_BIND_UNORDERED_ACCESS.
If you want to write to your buffer from GPU by ... |
67,592,482 | 67,592,688 | Assembly - Are there any languages other than C and C++ that allow for interaction with Assembly using inline code? | I recently read this document titled Embedded Systems/Mixed C and Assembly Programming
It basically deals with how C and C++ allow the user to use Assembly code via a technique called inline assembly that looks sort of like this:
#include<stdio.h>
void main() {
int a = 3, b = 3, c;
asm {
mov ax,a
... | Yes, D, Rust, Delphi, and quite a few other ahead-of-time-compiled languages have some form of inline asm.
Java doesn't, nor do most other languages that are normally JIT-compiled from a portable binary (like Java's .class bytecode, or C#'s CIL). Code injecting/assembly inlining in Java?.
Very high level languages lik... |
67,592,872 | 67,592,928 | Including a class requiring a input argument to its constructor in another class | I have a third party libary which defines a class as follows
class ClassA{
public:
explicit(std::string token) : _token(token);
inline const std::string& getToken() const{
return _token;
}
// Other functions
// ...
private:
const std::string _token;
// other members
... | As written, your ClassB will not work, as ClassA does not have a default constructor, so you will have to initialize m_classA in the member initialization list of ClassB's constructor. If you want setBot() to reset m_ClassA, it will have to construct a new ClassA object.
class ClassB{
ClassB(std::string token) : m... |
67,592,884 | 67,603,206 | How to set value dynamically with JsonCpp? | I need to write a function that will take two arguments, a key path and a value, and will populate a JSON object. However, it does not work because the values I'm using are passed by value; I do not know how to refactor the function so pointers are used instead.
This is what I have, it does not produce any error, but i... | In the end, this is what I wrote, and it seems to work.
void JSONConfig::setValue(string key, Json::Value value)
{
stringstream tokenizer(key);
string token;
string lastToken;
Json::Value *node = &root;
while (getline(tokenizer, token, '.'))
{
if (!lastToken.empty()) node = & ((*node)[lastToken]);
... |
67,593,168 | 67,593,223 | How to make some threads do work before other threads? | Let's say I have 4 threads that should read from an array and 4 threads that should update something inside of an array. How should one go about making the read threads do all their work before the update threads but with calling all 8 at the same time.
thread t1 = thread(func,args);//READ
thread t2 = thread(func2,args... | To do this, you will have to use one of the many synchronization objects present in the standard library. There is a lot to choose from, but the one that suits this use case the best is std::latch.
This synchronization primitive works by holding an internal counter (initialized in the constructor) which can be decremen... |
67,594,210 | 67,594,268 | Inherited Static Factory Method Returning Child Class Type | I have a Logging class that is inherited by LoggingString, LoggingInt, etc. which each have a writeLog function that takes in the corresponding type:
class Logging {
public:
explicit Logging(const LoggingConfig& config);
...
}
class LoggingString : public Logging {
public:
using Logging::Logging;
writeLog... |
it seems redundant to have to specify LoggingString twice.
You wouldn't have to specify LoggingString twice (thrice if you count the logger variable declaration). You can replace LoggingString:: with Logging::, and use auto for the variable, eg:
class Logging {
public:
explicit Logging(const LoggingConfig& confi... |
67,594,228 | 67,599,869 | Change the metavars in boost::program_options | This is a purely aesthetic issue.
I have written a CLI program in C++ and use boost::program_options to pasrse its args.
Per default, boost names all meta variables arg. I'd like to change that.
Here's the code:
#include <iostream>
using std::cerr;
using std::cout;
#include <optional>
using std::optional;
#include <s... | @prehistoricpenguin's answer brought me onto the right track. In boost, the typed_value class has a method value_name() to set the argument name, which works analogous to setting the defaults, i.e. it modifies the value object and returns it for subsequent operations:
static auto parseArgs(int argc, const char *argv[])... |
67,594,496 | 67,594,731 | grpc and Intel compiler | I would like to use gRPC as a bridge/glue between C++ and Java components (on both Windows and Linux although at the moment I'm more interested in Windows solution) but the main blocker I'm currently facing is lack of support for Intel compiler (I guess mainly due to third party dependencies like abseil for example whi... | Dlls on windows need special care when it comes to their exposed API. Some libraries prefer not to bother and do not officially support building as a dll.
I know from previous experience that grpc doesn't support building as a dll. You can read about it here. It should be possible to compile, but there's an extremely h... |
67,594,526 | 67,597,667 | Visual Studio opencv project build | Is it possible to build opencv c++ application (for windows) without environment variable for opencv executables. I want my own executable to run on another machine without opencv installed.
| As far as I'm concerned you have two options:
1, It is possible using static linking, but usually OpenCV doesn't distribute the compiled static libraries. You will have to compile your own .lib and link against those to create a standalone executable.
2, You could use Dependency Walker tool to find dlls your program de... |
67,594,588 | 67,594,805 | Counting characters, words and lines in a string using a do-while loop | C++ | I'm trying to convert a while loop that counts characters, words, and lines in a string, into a do-while loop.
Here is my while loop:
#include <stdio.h>
#include <string>
#include <typeinfo>
using namespace std;
int main()
{
int c;
int characters = 0;
int words = 1;
int newlines = 0;
printf("Input ... | There are two main problems with the posted do-while loop.
The first one is that you are reading two characters but processing only character in each iteration of the loop.
The second one is that while (c = getchar() != EOF) does not do what you are hoping it would do. Due to operator precedence, that is equivalent to
... |
67,595,005 | 67,595,123 | How to change the real value of Complex array elements in c++ | Hey I have a Complex double array and I want to change the values of it from another basic float array, so basically I want to copy all the float array values into the real value of each complex element.
I tried to iterate in a for loop and copy the value but I get errors such lvalue required as left operand of assignm... | There are two issues with your code:
You cannot assign to the result of calling std::complex::real() - it returns a value, not a reference. You need to use the void real(T value); overload instead, see: https://en.cppreference.com/w/cpp/numeric/complex/real.
test is declared const so you cannot assign to it in any c... |
67,595,217 | 67,595,541 | C++ How to enable a user to enter the values which would be placed in multidimensional arrray | this is probably a very beginner-like question.
However, I have an algorithm that works with graphs, and what I currently have is just the pre-entered values. I want to make it so a user would be able to enter the edges of the graph and a multidimensional array would be filled up with the values.
Here are some bits of ... | A technique you could use to collect a variable amount of data would be to first ask the user how many vertices they require, and then std::cin in a for loop to collect the actual data.
std::vector<bool> graph;
int vertex_count = 0;
std::cout << "How many vertices?\n";
std::cin >> vertex_count;
std::cout << "Enter the ... |
67,595,749 | 67,595,773 | Why nothing happens if I return EXIT_FAILURE at the end of my main function entry point in my program? | There are two macros in C++ that represent a number to return in the last line of your entry point. EXIT_FAILURE and EXIT_SUCCESS. If I return EXIT_FAILURE, which is 1, absolutely nothing happens. I explicitly wrote that the exit of my program was not successful, why is nothing happening?
| The return code from your process has absolutely no effect on your process. It's only for the parent process which initiated your process to know how your run turned out.
The parent process is often the shell, though it could be any other mechanism that made the exec (or equivalent) call. Your EXIT_FAILURE indicates to... |
67,595,876 | 67,599,427 | Does LocalAlloc with LMEM_FIXED prevent paging | I'm using the LocalAlloc function to allocate some memory, and I noticed the LMEM_FIXED flag.
Microsoft states that the LMEM_FIXED flag does the following:
Allocates fixed memory. The return value is a pointer to the memory object.
I was wondering if this meant that the memory could not be paged to the disk. What I m... | The hint is in the documentation, specifically the description for the uFlags parameter. You'll find the following:
LMEM_MOVEABLE: [...] This value cannot be combined with LMEM_FIXED.
In other words: LMEM_FIXED and LMEM_MOVEABLE are mutually exclusive. So then, what does LMEM_MOVEABLE amount to? It's a hint to the me... |
67,595,945 | 67,596,028 | Having trouble with decimal float in struct array | I am having some trouble and I cant really even figure out what is wrong, so I needed some help.
I need to take a percentage of a number that one of the structs in my array has, for each one.
my struct looks like
struct person{
int number;
string name;
float share;
}
So I use a for loop to get the total of... | I presume your type of totalnumber is int and person.number is int as well.
For operation between ints, the return value is still int
Expanding people[i].share = 100 * ((people[i].number)/totalNumber);
It would be something like people[i].share = 100 * ( 1/10 );
=> people[i].share = 100 * ( 0 );
=> people[i].share = 0;... |
67,596,668 | 67,597,160 | Instruction/intrinsic for taking higher half of uint64_t in C++? | Imagine following code:
Try it online!
uint64_t x = 0x81C6E3292A71F955ULL;
uint32_t y = (uint32_t) (x >> 32);
y receives higher 32-bit part of 64-bit integer. My question is whether there exists any intrinsic function or any CPU instruction that does this in single operation without doing move and shift?
At least CLan... | If there was a better way to do this bitfield-extraction for an arbitrary uint64_t, compilers would already use it. (At least in theory; compilers do have missed optimizations, and their choices sometimes favour latency even if it costs more uops.)
You only need intrinsics for things that you can't express efficiently... |
67,596,731 | 67,596,841 | Why is `std::optional<T>::operator=` deleted when T contains a `const` data member? | The following code would lead to compiler errors:
#include <optional>
class A {
};
class B {
private:
const A a;
};
int main()
{
B b;
std::optional<B> bo1;
bo1 = b;
}
On gcc, for example, the error reads:
main.cpp: In function 'int main()':
main.cpp:12:7: error: uninitialized const member in 'class B... | optional uses the object's =.
A class with a const data member cannot be assigned to. It can only be constructed.
Try this:
B b0;
B b1;
b0=b1;
optional doesn't work because B doesn't.
Also, try static_assert(!std::is_copy_assignable_v<B>);, which passes.
now, std::optional has a "back door" here.
B b;
std::option... |
67,597,280 | 67,599,303 | Is it possible to create a concept that is only a lambda? | Since C++ 20, the concepts have been released to constrain templates and auto.
I wanted to create a concept that only defines a lambda, is it possible?
template <typename T>
concept lambda = /* ... */ ;
And then I could apply like this:
int add(int x, int y) {
return x + y;
}
lambda auto func1 = []{ return 5; }; ... | You can get the type name of T at compiler time, and then determine whether it contains the mangled name of lambda, which starts with <lambda in gcc and (lambda in clang:
Although it is feasible, it is actually not recommended.
#include <string_view>
template <typename T>
consteval bool is_lambda() {
std::string_v... |
67,597,884 | 67,598,780 | Get Process PID With PsLookupProcessByProcessId | #include<Ntifs.h>
#include <ntddk.h>
#include <WinDef.h>
void SampleUnload(_In_ PDRIVER_OBJECT DriverObject) {
UNREFERENCED_PARAMETER(DriverObject);
DbgPrint("Sample driver Unload called\n");
}
extern "C"
NTSTATUS
DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) {
UNREFERE... |
but in the 30 line he doesn't print anything
you try say that
DbgPrint((CHAR*)UniqueProcessId);
doesn't print anything.
DbgPrint accept pointer to the format string to print in first argument. but (CHAR*)UniqueProcessId not a string, even if you cast it to (CHAR*). if UniqueProcessId valid value - it small number, u... |
67,598,615 | 67,598,761 | What is the difference between regular "for" statement and range-based "for" statement in C++ | So, what is the difference between these two statement:
for(auto i : VectorName){}
for(auto i = VectorName.begin(); i != VectorName.end(); i++){}
For example, I have this program:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<char> vec = {'H','e','l','l','o','W','o... | The difference in your case is, that the first version with iterators, well, uses iterators (that's why cout << i << endl; is not working), and the second version (the range-based for loop) gives you either a copy, a reference, or const reference.
So this:
for(auto i = vec.begin(); i != vec.end(); i++)
{
cout << i ... |
67,598,718 | 67,599,372 | Is there is a better approach to do a task after x seconds? | I want to do execute this function after x seconds.
this is my pseudo code.
object x;
std::thread([&]() {
std::this_thread::sleep_for(std::chrono::seconds(5));
//execute some code
x.removeEffect();
}).detach();
Is there is better way to do this, since create new thread is expensive.
UPD... | You can create a thread-pool and push a functor as a task for this thread-pool.
This will solve 2 your problems:
Don't need to create a new thread for each execution.
Your Task can receive delay as an argument and thread-pool will execute task with required delay.
|
67,598,982 | 67,627,039 | How can new gnome terminal receive command in C | I have tried to write a program that run in ubuntu terminal .Program will open a new gnome terminal and run command in that new terminal to open new abcd.txt using vim.And then when i Ctrl+C in the first terminal which run the program ,new gnome terminal will shut vim down and have an announcement in the first terminal... | Not sure what you are trying to achieve in the end. But here are a few ideas, starting from your code:
The terminal command (in system()) should be something like Mark Setchell pointed out, like for example system("gnome-terminal -e vim file.txt");
The system() command is blocking further execution of your code, so t... |
67,599,003 | 67,599,711 | filtering linked list by letting user input number | I wanted to filter my linked list based on the category. I managed to do it but I wanted to improve it to let user filter using a number instead of typing the category. Basically, I will output the available category by traversing through the linked list once and the category will be output along a number. User input a... | since you are printing the product list after creating the unordered_set order will be the same as long as you do not invalidate it (ie. not inserting or removing the element from the set).
you can use n which the user has entered to iterate through set.
note: I will prefer vector over unordered_set for this scenario. ... |
67,599,356 | 67,600,017 | Is there any point of "reference of pointer"? | I can't understand how reference of pointer type works.
Is there any performance difference?
Is there any assembly level difference if they compiled?
Is there any point to reference of pointer type?
vector<Figure*> vFigureList;
//auto&
for(auto& pFigure : vFigureList)
{
pFigure->draw();
delete pFigure;
}
... | Once compiled, references are just like pointers, they provide a level of indirection. However they have different use in C++:
They must be initialized upon definition, hence safer, like a const pointer.
No need to use the address of & operator to declare where they point to.
No need to deference using *.
Is there ... |
67,599,384 | 67,599,531 | Distinguish between Clang CL and MSVC CL | There is CLang-CL which is a drop-in replacement for MSVC's CL.
Does anyone know how to distinguish if my code is currently compiled by clang-cl or msvc's cl? Without passing any extra defined macros on command line.
Using
#ifdef _MSC_VER
//.....
#endif
doesn't work, both compilers define _MSC_VER.
Also in regular CLa... | The macro you're looking for is __clang__.
Note that the regular Clang (not only Clang-CL) also defines it, so you want to check for both __clang__ and _MSC_VER at the same time.
|
67,599,539 | 67,599,663 | C++ unique_ptr; Why this sample codes get compile error?? error codes are so long that I can't specify it | I'm studying about smart pointer now, and I just built the sample codes in the book.
But when I use unique_ptr like this code below, it makes compile error. The error codes are so long that they are almost cut, so I can't write down them all.
I wonder why this codes got error... please help me.
compiler and OS : g++ (U... | There is no operator << for an object of the type std::unique_otr.
If you need to output the value of the owned pointer then write
cout << "smart pointer 1: " << p1.get() << '\n';
If the template argument of the class template std::unique_ptr is char then you need to cast the returned expression of the member function... |
67,599,679 | 67,612,946 | Basic windows include can't be found in release mode | I have a C++ project developed under VS2019 that works fine using debug mode (x64 with Windows SDK 10.0.18362.0).
But when I try to compile it using release mode I get hundreds of errors such as :
Error (active) E1696 unable to open source file "ctype.h" SYABOT_ScanAndControl C:\Program Files (x86)\Microsof... | I suggest you should check the configuration options in the property page when setting the Windows SDK version.
I suggest you could choose All Configurations. And you could also choose Release then set the Windows SDK version.
|
67,599,765 | 67,599,815 | I have search about auto for but still here is coming segmentation fault | can anyone see my code why it is showing segmentation fault
input: 3 def de fgh
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string> v;
int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
for(auto x : v)
cout << x << endl;
return 0;
}
| In this line,
cin >> v[i];
you request a reference to the ith element in v, but the vector is empty. You can change the part before the loop to
vector<string> v;
int n;
cin >> n;
v.resize(n); // <= this one is required.
to setup the vector such that it contains n default-constructed elements (in this case, zeros). T... |
67,599,780 | 67,606,848 | Filter a tuple list of types given a template template predicate | I was going to ask a question, but have found an answer on my own while writing it.
The question is how to filter a tuple given a template template predicate without specializing it.
Example usage:
using tuple_list_t = std::tuple<std::string, int, none, double, char, abc, bool>;
using tuple_found_expected_t = s... | Sorry but your solution seems to me over-complicated. Particularly regarding the SFINAE part (why the void?).
What about simply as follows?
template <typename, template <typename...> class>
struct filter;
template <typename ... Ts,
template <typename...> class Pred>
struct filter<std::tuple<Ts...>, Pred>
{... |
67,599,943 | 67,600,760 | Forcing loop unrolling in MSVC C++ | Imagine following code:
for (int i = 0; i < 8; ++i) {
// ... some code
}
I want this loop to be unrolled in MSVC. In CLang I can add #pragma unroll before loop. But how to do same in MSVC?
I understand that anyway compilers often will unroll this loop for me even without any pragmas. But I want to be really sure a... | You can't directly. The closest #pragma is #pragma loop(...), and that doesn't have an unroll option. The big hammer here is Profile Guided Optimization - profile your program, and MSVC will know how often this loop runs.
|
67,600,207 | 67,600,638 | How to correctly calculate struct size using Marshal.SizeOf() in C#? | I'm banging my head with this one.
I have a C# structure:
[StructLayout(LayoutKind.Sequential)]
public struct Enroll
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 101)]
public char[] Name;
public UInt16 Port;
public byte Num;
public byte Max;
public UInt6... | As Matthew Watson suggested, Pack=1 fixed my issue. Link by Sinatr explains:
The Pack field controls the alignment of a type's fields in memory. It
affects LayoutKind.Sequential. By default, the value is 0, indicating
the default packing size for the current platform. The value of Pack
must be 0, 1, 2, 4, 8, 16, 32, 6... |
67,600,480 | 67,601,343 | Is it possible to use a method from one parent class to implement an abstract method from another parent class? | I've got the following classes:
class ServoPart {
private:
bool move() {
/* move implementation for a singular servo */
}
}
struct RoboPart {
virtual void doJob() =0;
virtual bool move() =0;
}
class Claw : public ServoPart, RoboPart {
private:
void doJob() {/* implementation */}
}
class A... | The main problem here, is that all your methods are private, so no of them can be called from outside the defining class, not even from a subclass.
Assuming that the blocking private: declarations can be removed, there is no problem in using a method from a superclass to implement a method from another superclass provi... |
67,600,754 | 67,601,228 | Break line of CMake/Build output in output view in VSCode | Visual studio code displays the output of CMake/Build without breaking long lines at window width, something like:
[build] FAILED: /path/to/the/source/code/that/caused/the/error/long_source_file_name_with_description_of_functionality.cpp This is the reason why compilation stopped etc etc etc ... In member function 'vo... | Was able to find a solution through a Python related question. The setting to tweak is this:
"[Log]": {
"editor.wordWrap": "on"
}
|
67,601,007 | 67,601,153 | Is it better to store data as "60 * 60 * 24" or 86400 | I have a piece of code exactly:
static constexpr uint32_t secondsInADay = 60 * 60 * 24;
static constexpr uint32_t secondsInAnHour = 60 * 60;
static constexpr uint32_t secondsInAMinute = 60;
Would it be faster/efficient to store it like this:
static constexpr uint32_t secondsInADay = 86400;
static constexpr uint32_t se... | Your constants are completely hardcoded, i.e. you assign them an explicit value in the code, which allows the compiler to compute the value at compile time.
60*60*24 is exactly the same as 86400
if you declare variables as:
uint32_t a = 60*60*24;
uint32_t b = 86400;
the assembly will have the following definitions:
a:... |
67,601,221 | 67,601,283 | C++ getline function continuous loop | I am trying to use a getline function in the following code, however it just enters an indefinite loop. Should I enter 1, it will then jump to the another iteration of the loop and ask for my menu choice again, rather than asking for my name.
Does anyone have any idea where I'm going wrong?
#include <iostream>
#include... | Add cin.ignore(); before getline line.
|
67,601,232 | 67,601,269 | Python 3: How to check if file is open? Python equivalent of C++ ifstream.is_open() function? | How do I check if a file has been opened correctly after opening the file in Python3?
with open("filename" as f:
# check that file is opened correctly here
C++ ifstream provides the is_open() function for this purpose. Is there a Python equivalent of the C++ ifstream::is_open() function?
In C one would do
FILE *fd... | f = open('file.txt')
if f.closed:
print 'file is closed'
if not f.closed:
print 'file is opened'
|
67,601,279 | 67,701,873 | Splitting class definition into multiple module units in C++ | Is there any way to split class definition (implementation) into more than one module unit? It can be helpful in case if one or more class's methods are big enough to be placed in separate source files.
The best solution I see could be class declaration in module interface file and one of its methods definition in sepa... | Big thanks to everyone answering my question. The example published in my initial question works. As I wrote in one of my answers to Davis Herring (thank you, Davis, for correcting class method's name in my example) the problem was in my compiling environment. There is absolutely no need to use module partitions to sol... |
67,601,497 | 67,601,875 | Rule of zero - default constructor not generated | I was reading this: https://en.cppreference.com/w/cpp/language/rule_of_three
And my understanding from this is that, if you want to have a base class with a virtual destructor, the you need to define all 5 special functions (extracted from the rule of 0 section):
class base_of_five_defaults
{
public:
base_of_five_... |
I guess this means if base_of_five_defaults(const base_of_five_defaults&) = default; is declared then it is considered user-declared even though its "default"?
Yes. base_of_five_defaults(base_of_five_defaults&&) = default; declares a1 defaulted user-declared constructor.
The = default makes the compiler generate the ... |
67,601,612 | 67,613,360 | Visual Studio: Unable to start program, the system cannot find the file specified visual studio error? | Here I'm Using visual studio 2019 community edition. I open a folder from file->new->existing project. But whenever i build and run my program. it says
Unable to start program 'O:\1.Fourth
semester\programminh\main\Debug\Main2.exe'
the system cannot find the file specified
There are lots of programs. like bubble.cpp,... |
I open a folder from file->new->existing project.
As far as I'm concerned you should open a .sln file instead of a folder.
You could only run the .sln file (Visual Studio Solution) not a .cpp file.
|
67,601,645 | 67,601,773 | Semantics of std::bind and/or std::forward | I find it very confusing that the following code fails to compile
#include <functional>
class Mountain {
public:
Mountain() {}
Mountain(const Mountain&) = delete;
Mountain(Mountain&&) = delete;
~Mountain() {}
};
int main () {
Mountain everest;
// shouldn't the follwing rvalues be semantically equivalent?
... | Yes, arguments to std::bind would be copied (or moved).
The arguments to bind are copied or moved, and are never passed by reference unless wrapped in std::ref or std::cref.
You can use std::cref (or std::ref) instead. E.g.
int j = (std::bind([](const Mountain& c) {return 1;}, std::cref(everest)))();
// ... |
67,601,659 | 67,603,280 | How to define a 3D decision variable in C++ (using CPLEX concert technology)? | I have to define a decision variable a[kij] which must be binary in nature
indices
i = {0,1,2,3...9}
j={0,1,2,3...9}
k= {0,1,2}
N_CARTONS=10
N_C=3
have written this much code so far
// Define a
IloArray<IloNumVarArray> a(env, N_C);
for (k = 0; k < N_C; k++)
{
a[k] = IloNumVarArray(env, N_C);
for (i = 0; ... | You could use the IloArray<> template to build an array with as many dimensions as your compiler will allow.
As said in technote How do I create and use a multi dimensional IloNumVarArray?
And full example in CPLEX distribution : facility.cpp
Or you could also write simply
int N_CARTONS=10;
int N_C=3;
range i=0..N_CAR... |
67,601,871 | 67,601,926 | Why is it not possible to compare the output of .what() method of thrown exception with a string? | The code fails to print True because the comparison fails for some reason. I don't know what it's, but it works if I change e.what() == "Something Bad happened here" to e.what() == std::string("Something Bad happened here")
#include <iostream>
#include <string>
#include <stdexcept>
int main() {
try
{
... | Because std::exception::what() returns a const char*, and a "string literal" is a const char[N]. Operator == on them does a comparison of two pointers. You must use strcmp() on them
if (strcmp(e.what(), "Something Bad happened here") == 0) // ...
std::string OTOH has an operator== to compare with a const char*
If you ... |
67,601,946 | 68,785,964 | Why cuda-gdb shows unexpected memory values? | I am compiling the following fragment of code with nvcc -g -G gdbfail.cu.
#include <cstdio>
#include <cinttypes>
__global__ void mykernel() {
uint8_t* ptr = (uint8_t*) malloc(8);
for (int i = 0; i < 8; i++) {
ptr[i] = 7 - i;
}
for (int i = 0; i < 8; i++) { // PUT BREAKPOINT HERE
printf... | Evidently, not all gdb command features that are usable in host code are also usable in device code. When used in device code, the supported commands may have different syntax or expectations. This is indicated in the cuda-gdb docs.
Those docs indicate that the way to inspect memory is the print command and indicate ... |
67,601,968 | 67,602,099 | Typechecker for a C/C++ like language | Currently I am working on a compiler for a C/C++ like language to be more specific a typechecker.
I have generated a parser with a grammar and the bnfc tool. For my typechecker I need to infer the type of expressions. All expressions are derived from a abstract base class Exp like the following:
class Exp {
...
}
clas... | You got polymorphism the wrong way around.
Instead of this:
class Base {};
class Derived1 : public Base {};
class Derived2 : public Base {};
class Derived3 : public Base {};
//...
void foo(Base* b) {
if(dynamic_cast<Derived1*>(b)) {
do_something( dynamic_cast<Derived1*>(b));
} else if (dynamic_cast<De... |
67,602,079 | 67,606,388 | [OpenCV][C++] Record only the detected motion | I'm working on a project to detect motion on a camera.
I need to start recording video when motion is detected for example:
Record while motion is being detected
Continue recording for 10 seconds after the motion detection is stopped
I have a working example that only detects the motion and draw rectangles on the mov... | I resolved the issue,
I was opening the output video with a specific dimensions (320,240) and I was saving the captured frame which is bigger.
So the solution is to resize the captured frame to fit into the output video.
Here is the final solution if anyone is interesting:
Turn the laptop camera into an IP camera with... |
67,602,373 | 67,602,638 | How to make function be able to accept raw poniters as iterators? | I have two functions that split a string and add tokens into vector:
template < typename InputIterator, typename ContainerType >
void Slice(InputIterator begin,
InputIterator end,
typename InputIterator::value_type delimiter,
ContainerType& container)
{
using CharType = InputIterato... | SFINAE kicks in. The signature
template < typename InputIterator, typename ContainerType >
void Slice(InputIterator begin,
InputIterator end,
typename InputIterator::value_type delimiter,
ContainerType& container)
is not a possible candidate because there is no nested member ::value_ty... |
67,603,027 | 67,603,135 | How do I create a directory in a given path in C++? | I need to make a function that creates a directory in a subdirectory of the current location. Here is what I've tried:
#include <iostream>
#include <cstring>
#include <dir.h>
#include <stdlib.h>
using namespace std;
void create(){
char nume[50];
int directory1,directory2;
directory1=mkdir("folder1");
d... | I would suggest using the <filesystem> library which is available as of C++17, in this case using std::filesystem::create_directories
#include <filesystem>
void create()
{
std::filesystem::path subfolder = "/folder1/name1";
std::filesystem::create_directories(subfolder);
}
int main()
{
create();
}
Note t... |
67,603,140 | 67,603,684 | Ambigious call to overloaded function when using lambda | Never used lambdas before and I can't understand where I'd have to add it.
My Error is "Show: Ambigious call to overloaded function"
Show() can take 2 types CustomizeToast and CustomizeToastAsync. So I guess I need to specify CustomizeToast somewhere but I can't for the life of me see where.
This is my current code:
To... |
Show() can take 2 types CustomizeToast and CustomizeToastAsync.
This is clearly an oversight on the API's developpers end. Now since both classes can be constructed from a lambda the compiler doesn't know which one to use, so you have to guide it:
ToastContentBuilder()
.AddText(L"Hello World!")
.Show(Customiz... |
67,603,226 | 67,604,129 | Cannot link against grpc conan | i tried to build default hello world (https://github.com/grpc/grpc/tree/master/examples/cpp/helloworld) grpc example but with conan grpc.
I reworked cmakelists:
# Copyright 2018 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | Here is answer https://stackoverflow.com/a/30175210/8524139
I really dont know why conan contains protobuf for legacy gcc and there is nowhere information about this
|
67,603,398 | 67,603,603 | sregex_iterator next and end.. How does this work? | Folks, I am new to C++. So please excuse me for my ignorance here. I am trying to understand the below code that I got online. What does while (next != end) line exactly do? When I printed the address of &next and &end they were always different (even post while loop). I take std::sregex_iterator next and std::sreg... |
Just to let you know I am from Java world but have been taking courses to understand C++
That seems to be the reason for your confusion. C++ in contrast to Java is using value semantics. This means, when you compare two object via == then it does not test identity, but equality, ie the values are compared.
Consider t... |
67,603,711 | 67,603,744 | OpenGL line drawing issue when using glDrawArrays | When I am trying to draw a line using legacy openGL , lines are drawing fine.
glEnable(GL_LINE_STIPPLE);
glBegin(GL_LINE_LOOP);
for (size_t idx = 0; idx < m_spline_cvs.size(); idx++) {
glVertex2f(m_cv_positions[0][idx].x,m_cv_positions[0][idx].y);
}
glEnd();
glDisable(GL_LINE_STIPPLE);
Correct Line Loop in Stipple... | The 3rd argument in glDrawArrays is the number of vertices, but not the number of elements (floats) in the array. Each vertex coordinate consists of 2 components (x, y):
glDrawArrays(GL_LINE_LOOP, 0, cv_tracker_target_line.size());
glDrawArrays(GL_LINE_LOOP, 0, cv_tracker_target_line.size() / 2);
|
67,604,123 | 67,605,657 | c++ struct - modify inside for loop using counter | I am bit new to C++. I am trying to use struct to keep my data better organised.
in the following code I am trying to modify a struct member. all members are named using an int.
I have two problems:
My counder currentParticleCount wont increment after adding to the struct.
there seem to be errors in the way I am using ... | Here's a version that will run. It is far from a proper C++ version, it doesn't use the standard library or any of the newer C++ standards niceties but will hopefully show you where you're going wrong:
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
// Declare the struct
struct particle
... |
67,604,478 | 67,604,922 | C++: Can I use smart pointers with templates? | I have an abstract base class distributions with two derived classes, continuous_distribution and discrete_distribution. I have a function make_distribution with an unordered_map that returns a smart pointer to a (continuous) distribution,
std::shared_ptr<continuous_distribution> make_distribution(std::tuple<std::strin... | Template parameters can only be deduced from the calling function parameters, they are NOT deduced from the return type. And none of the parameters in your function depend on template parameters, hence no match.
In your case you have to specify template parameter EXPLICITLY and it should work:
std::shared_ptr<continuou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.