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 |
|---|---|---|---|---|
63,221,443 | 63,221,475 | Forgot do in do... while loop | I had an annoying bug, where I forgot to write do in a do ... while loop.
int main() {
int status=1;
/*do*/ {
status = foo();
} while (status);
}
Why does this still compile and run? It seems to me that the compiler should reject this as nonsensical or at least raise a warning (I have -Wall in my compiler op... | I'm assuming you actually had int status outside of the loop body, otherwise the code wouldn't compile. (Not even with the do in place.)
With that fixed, the code you wrote is still valid without do, but does something differrent, as you already correctly noted. Let me rewrite it slightly to show how it is interpreted:... |
63,221,607 | 63,221,678 | GLSL Error : Undefined layout buffer variable in compute shader, though it is defined | I'm trying to make a simple compute shader using a Shader Storage Buffer (SSBO) to pass data to the shader. I'm coding in C++ with GLFW3 and GLEW. I'm passing an array of integers into an SSBO, binding it to the index 0, and expecting to retrieve the data in the shader from a layout buffer variable (as explained on var... | params is not a variable. Nor is it a struct or class. It is the name of an interface block. And the name of an interface block is not really part of GLSL itself; it's part of OpenGL. It's the name used by the OpenGL API to represent that particular block.
You never use an interface block's name in the shader text itse... |
63,221,693 | 63,222,005 | How do I get all characters after a space in C++? | In C++, how do I get ALL of the text after a space. I am trying to make my own coding language, so I want the user to be able to enter (/print (text here)) and print the text the user has entered. I want this to be all in one line; without having the user to input the command, then input the thing they want to output. ... | Leveraging <algorithm>
The following will work with C++11:
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
bool is_blank(char ch)
{
return std::isblank(static_cast<unsigned char>(ch));
}
int main() {
std::string inp = "print foo";
auto it = std::find_if(inp.begi... |
63,221,771 | 63,222,461 | How to create a dynamic array using new C++? | I'm trying to initialize an array of integers dynamically, since the size of the array changes based on input.
The program is as follows:
int main()
{
int* list = createList("dis.bin");
for (int i = 0; i < sizeof(list) / sizeof(int); i++)
{
printf("%d\n", list[i]);
}
}
With createList() functio... | This question is tagged as C++, but OP is showing C code and says they need it in C, so I will show this in C... but the pre-req is that it uses new and not malloc
int* createList(const char* file_name, int& count)
{
// initialize count, so that way if we return early, we don't have invalid information
count = ... |
63,221,804 | 63,221,843 | How to use overload operator as condition in a if statment? | Here is the class
#include <fstream>
#include <cstdlib>
#include <math.h>
#include <iomanip>
#include <iostream>
using namespace std;
class Point {
protected:
int x, y;
double operator-(const Point &def){
return sqrt(pow((x-def.x),2.0)+
pow((y-def.y),2.0));
}
};
class Circle... | A == needs two arguments (even if the overload is a member), you would write the if as any other if statement:
if(circle1 == circle2) { ... }
and if there's a matching overload the compiler would transform that into something like:
if(circle1.operator ==(circle2)) { ... }
|
63,222,155 | 63,230,017 | How to get the current database name from a C function/extention? | I'm writing a C function/extension. It's a function that'll be called by a trigger. In it, when a trigger is fired, I need determine the name of the current database.
It's a requirement that using SPI_prepare(), SPI_exec() isn't allowed in this case, therefore querying current_database() won't work.
Some other SPI_get*... | It's not clear to me which of postgresql's server-internal programming interfaces are usable in SPI extensions. However, the implementation of the current_database SQL function does this:
Name db;
db = (Name) palloc(NAMEDATALEN);
namestrcpy(db, get_database_name(MyDatabaseId));
PG_RETURN_NAME(db);
So, I think get_d... |
63,222,271 | 63,222,364 | Finding the intersection of 2 vectors algorithm critique/explanation | I have 2 vectors in cpp: [1,2,2,1] and [2,2]. I want the intersection to be: [2,2]. Here is my algorithm that I implemented but I get a heap overflow, I am not sure why. Can someone explain to me what is going wrong?
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
//... | If nums2 becomes empty before nums1 does, your program exhibits undefined behavior by accessing nums2[0]. an index out of bounds.
|
63,222,289 | 63,222,886 | declaring scope resolution operator without including standart header | I Learn C++ programing and I was a beginner, and my question is can I use scope resolution operator without including Standart library? can someone help me?.
| The scope resolution operator is as the name says, an operator, and is not part of any library but rather the basic syntax of the C++ language. It's hard to tell exactly what your issue is based off your question, but when you don't know what you're doing wrong it can be hard to find the right words to ask. Try reading... |
63,222,579 | 63,231,382 | Can C++ structs have different alignments at different compilation times? | I had some code that works at the low level that used to work with glm. I switched all uses of glm to Eigen And I am now observing a strange behaviour where the same struct seems to have different alignments at different points in the code.
This is what gdb gives me after initializtion:
(gdb) p sizeof(CellShadingInfo)
... | The issue was a compilation problem. For unknown reasons an object file was failing to compile, as a result the linker was finding the old object file and linking against that. Since that object file was made from old source code, the structure didn't have the same alignment anymore in different sections of the code.
|
63,222,763 | 63,222,989 | Class composition, giving unkown override specifier error | I am trying to use some of my methods in my App class inside of my Chart class, so I am using composition to create a private member (Chart chart) inside of my App class but I'm having some problems. Also, if I wanted to have that chart member be a nullptr until I need it in my code would I just do it like this Chart* ... | Your code idea is very similar to the observer pattern. In order to avoid circular dependencies, you can try replacing one or more data members with pointer members or references as members.
You need to change your code to somewhat like this:
class Chart; // forward declaration for chart
class App {
Chart* chart;
};
... |
63,223,074 | 63,223,130 | how to distinguish among two similar operator overloading in C++ | I have this piece of C++ code to overload the pre-increment and post-increment operators.
The only difference between those methods is the number of their arguments.
I want to know how C++ understands which method (pre-increment or post-increment) it should call when running y=++x and z=x++ commands.
class location {
... | Essentially missing the argument in the ++ overload tells c++ that you are creating a prefix overload.
Including the argument tells c++ that you are overloading the postfix operator. therefore when you run ++x it will run the prefix while x++ will run postfix.
Also might i add that the int in the argument is not an int... |
63,223,094 | 63,275,861 | Embedding JVM into C++ application: How to link it properly? | Goal
Let's say, we have a large C++ application that does some large things, that are good to be done using C++. But, there are a plenty of logic, that we'd prefer to run on JVM.
Issue
To test approach described above, I created small C++ project using CLion.
Scenario is:
Build (automated by CMake):
link code snippet ... | Solution for Windows:
write C++ code that:
includes <jni.h> from JDK.
loads "${JRE_HOME}/bin/server/jvm.dll" using LoadLibrary from WinAPI.
gets pointers to JNI_CreateJavaVM using GetProcAddress from WinAPI.
calls JNI_CreateJavaVM and does whatever you want with JVM.
compile it with access to ${JAVA_HOME}/include/*... |
63,223,162 | 63,224,003 | How to init base class staic inline data member in derived class? | Say I am having a class like
#include<iostream>
#include<string>
template<typename CharT>
class base
{
//.....
public:
using string_type = std::basic_string<CharT>;
static inline string_type var;
//.....
};
class derived : public base<char>
{
private:
using base<char>::var;
public:
static base<char>... |
How to init base class inline static data member?
Remove the inline and you should be able to initialize the var
template<typename CharT>
class base
{
public:
using string_type = std::basic_string<CharT>;
static string_type var;
// ^^^^^^^^^^^^^^^^^^^
};
template<>
base<char>::string_type base<char>::var = ... |
63,223,169 | 63,223,206 | If a pointer value is passed as reference, how long does the value live? | I think I understand the basic ideas behind pass-by-value and pass-by-reference. I have created a toy code to explain my question:
class C2 {
public:
int val;
C2() {}
~C2() {}
};
class C1 {
public:
C2 * x;
C1(C2 & x_) {
x = &x_;
}
C1() {}
~C1() {}
};
void func (C1 & y) {
C2... |
How can the first cout print 5.
Because the behaviour of the program is undefined.
... Since z is deleted in func_p shouldn't this also result in segmentation fault?
There is no requirement for there to be a segmentation fault. The behaviour of the program is undefined.
|
63,223,573 | 63,224,993 | Visual Studio - static library won't link | I created a static library (designated A) in Visual Studio that includes some header files from another library (designated B). Because that is a static library I didn't need to worry about the .lib file from A. When I created a console app (designated C) and added the .lib and header files from B as well as the header... | To link with a .lib file, you just need to:
1,Add the path to the header file to the Additional Include Directories(property - >c/c++ -> General -> Additional Include Directories)
2,Add the path to the .lib file to the Additional Library Directories (property -> linker -> General -> Additional Library Directories)
3,Ad... |
63,223,954 | 63,226,681 | How to add functionality from combination of different derived class? | I have multiple handlers derived from base Handler class which can do single data updates individually.
For eg.
class Handler {
public:
Data_t dbdata_;
public:
virtual void updateFlags() = 0;
}
class AHandler: public Handler {
.....
public:
void updateFlags() { dbdata_.flagA = 1; }
}
class BHandler: public H... | You may want to consider a policy-based class design. For this, we define both a variadic function template, execute(), and a class template, HandlerHolder, that inherits from Handler and overrides the updateFlags() member function:
template<typename FlagUpdater, typename... FlagUpdaters>
void execute(Data_t& data) {
... |
63,224,066 | 63,224,081 | What is the purpose of const here? | I've seen the following:
void function_name(std::string& txt) const;
What is the purpose of the const in the above prototype? The return type of the function is void so there is no return type, it looks completely pointless to me, I've seen this a lot, also when passing in parameters like:
void function_name(const in... | void function_name(std::string& txt) const;
const mostly means this is a const member function and it's not supposed to change the state of the object. So if the function changes any of the member variables it will lead to compile error.
For the second case:
void function_name(const int a);
This const means that the ... |
63,224,255 | 63,224,555 | undefined reference to c header file's | I want to make a library for testing and for this purpose, I wanna make a c program just returning some char*. I have built it based on cmake. this is my cmake file:
cmake_minimum_required(VERSION 2.8)
project(smc)
add_executable(${PROJECT_NAME} "main.c" "info.cpp")
target_link_libraries(${PROJECT_NAME}
-lssh
)... | First of all, the error message comes from linker, it does not find symbol getcpuusage.
The reason for this is, your info.cpp is C++ source file, while main.c is C source file. By default (to allow for example function overloading) C++ does so called name-mangling to all C++ functions, basically combining function name... |
63,224,293 | 63,224,340 | C2143 syntax error missing ';' before namespace | I'm compiling a project that was originally developed using MSVC 2008. I'm trying to update it to MSVC 2017. When I try to build I am seeing:
Severity Code Description Project File Line Suppression State
Error C2143 syntax error : missing ';' before 'namespace' Debug Service Group c:\program files (x... | c:\program files (x86)\microsoft visual studio 12.0\vc\include\yvals.h 568 tells you the fault is in a header shipped with an old Visual Studio version.
That's unfortunately entirely expected to fail, as the old headers contain a lot of syntax errors which a non-conforming compiler like pre-VS2015 MSVC could still han... |
63,224,477 | 63,224,591 | virtual functions, when to use them? | Suppose I have two classes Animal and Dog while The latter inherits Animal.
So running the following code:
Dog* d = new Dog(3,4);
Animal* a = d;
a->makeSound();// Will run Animal.makeSound()
d->makeSound();// Will run Dog.makesound()
In order to run Dog.makesound() I need to declare Animal.makeSound() as virtual. But ... |
I don't understand when a function should be virtual and when not...
So think of Animal as base class and Dog and Cat etc. are derived classes from Animal. Dog and Cat can all makeSound() but clearly their sound are different. So a typical Object Oriented design is to make Animal as base class and makeSound() a (pure... |
63,224,557 | 63,224,697 | Are these two loops equivalent: off-by-one | Are these two loops the same? For some reason the second loop is off-by-one and I cannot figure out why.
while ( !b && ++n < WORD_COUNT ) b = mWords[n];
n++;
while ( !b && n < WORD_COUNT ) {
b = mWords[n];
n++;
}
| When the predicate b was not successful, then a logic short-circuit may apply in the first form and the final increment of n may be skipped.
In the second form, the increment happens before predicate b is evaluated, so n is off-by-one when the loop exits.
|
63,224,608 | 63,224,626 | How to Fix Blank Results when use for loop in c++ | I am Alvin and I was a beginner in C++ Programing Languange and I have a code:
#include <iostream>
#include <string>
using namespace std;
int main(){
for (int i=0; i == 5; i++){
cout << i << ", ";
}
system("pause"); // i add this code to avoid program close when i try to run it
return 0;
}
and when I ... | You have a logic error in the loop test condition:
for (int i=0; i == 5; i++){ // the `==` will cause it to never enter the loop
should be:
for (int i=0; i <= 5; i++){
|
63,224,684 | 63,224,778 | How to modify this C++ class to be as efficient as C code? | Today I've wanted to check if it is possible to write C++ code that is as efficient as C code. Because I'm working on an embedded system, I want to make sure using C++ will not impact performance too much.
So I've written a C code for manipulating fake GPIOs registers, as well as its C++ counterpart.
#include <stdbool.... | The following change helps
class gpio
{
const unsigned int port;
const unsigned int pin;
public:
gpio(unsigned int port, unsigned int pin) : port(port), pin(pin)
{
}
By declaring the member variables as const (and consequently using an initialisation list in the constructor) it helps the compiler o... |
63,224,736 | 64,580,660 | Infrared not returning 1 as correct value | I am trying to create a glove that when you turn your wrist down it sends 1 as an IR signal and if you turn your wrist up it returns a 0 for the glove I used javascript:
input.onGesture(Gesture.TiltDown, function () {
music.playMelody("E B C5 A B G A F ", 262)
network.infraredSendNumber(1)
light.showRing(
`blue red... | Have you tried:
Problems with Receiving
If receiving isn't working, first make sure the Arduino is at least receiving raw codes. > The LED on pin 13 of
the Arduino will blink when IR is being received. If not, then there's
probably a hardware issue.
If the codes are getting received but cannot be decoded, make sure t... |
63,225,119 | 63,225,438 | converting string to sentence case in c++ | I wrote this code for converting string to sentence case but i don't know where is the problem
for (int i = 0; s[i] != '\0'; i++)
{
if (i == 0 && s[i] >= 'a' && s[i] <= 'z')
{
s[i] -= 32;
cout << s[i];
}
else if (s[i] == '.')
{
if (s[i+1] == ' ')
{
if (s[i... | Just comment out or remove two lines(becuase they are generating that extra character) and the code will work as you want :
cout << s[i + 2]; and
cout << s[i + 1];
Here's is the example for the same :
for (int i = 0; s[i] != '\0'; i++)
{
if (i == 0 && s[i] >= 'a' && s[i] <= 'z')
{
s[i] -= 32;
... |
63,225,204 | 63,225,741 | How to do visible nested-class for container-class in inheritance level? | I have some template class
template <typename T> class Base { };
I trying to inherit Derived class from Base and use Internal class that is nested of Derived as a generic argument of Base.
class Derived : Base<Internal> {
public: class Internal { };
}
But compiler doesn't see Internal in Base.
Is it possible to solve... | You can! Nope
(similar question)
I don't think that this can work. In order to define the class Derived you need to know the base class ("it must be a complete type") first; to instantiate the template Base into a class you need to have a type. Inner however is only a type "inside" of Derived; it's part of it's defin... |
63,225,515 | 63,237,679 | BOOST::CRC creating checksum with process.block() method | I am currently trying to create a checksum over the length of a custom struct UMGR_s. I did use the BOOST::crc method process.block() with the start and end address of my struct.
The problem is that I will get a different checksum every time I run this method even though the data in the struct remains consistent. I am ... | Looking back at your older question:
#include <string>
#include <type_traits>
struct UMGR_s {
std::string name;
std::string description;
std::string dlt_id;
std::string log_mode;
std::string log_level;
std::string log_dir_path;
uint ipc_port;
uint reconnection_retry_offset;
uint msg... |
63,225,848 | 63,226,202 | Using class member pointers in nested templates gives GCC error "mismatched types Child and Base" | Weird problem on a kind of retro environment. I'm coding against a given library with GCC 4.8.2 in gnu++11 mode.
The library has this kind of interface code:
template<class somecls>
class LibraryInterface
{
public:
template<class var>
void someFunc(somecls *obj, var somecls::* member)
{
std::cout <<... | Here is you solution. It works on GCC, CLang and MSVC.
int main()
{
LibraryInterface<Child> lib_if;
Child my_var;
my_var.member1 = "data1";
my_var.member2 = "data2";
lib_if.someFunc(&my_var, static_cast<std::string Child::*>(&Child::member2));
}
The standard states that the type of the expression... |
63,225,869 | 63,225,997 | How is dynamic memory allocated in two dimensional array? | Tried to understand the allocation memory in heap but confused
What is the difference them :
int** p=new int*[n];
vs
int*p=new int[n];
2)the first line of code int** p=new int*[n] this is confusing a lot what does int*[n] return and new int*[n] return.
| The difference is exactly as the code shows
int* p = new int[n];
allocates int, but
int** p = new int*[n];
allocates int*.
You can allocate anything (more or less). If you allocate T then what you get back is a pointer to T, i.e. T*.
But there's nothing special about pointers, they can be allocated too. So if you all... |
63,226,323 | 63,226,380 | Difference between a pointer to a standalone and a friend function | I don't understand why the following does not compile (e.g. in gcc 9.10 or MS VS C++ 2019):
class X {
public:
friend bool operator==(int, X const &);
};
int main() {
2 == X(); // ok...
static_cast<bool (*)(int, X const &)>(&operator==); // Error: 'operator==' not defined
return 0;
}
but the following co... |
What I'm missing?
An inline friend declaration does not make the function available to ordinary name lookup.
Pay close attention to the error. It does not say that the function is of the wrong type, it simply can't find anything named operator==. This is by design.
Inline friend definitions are only found by argument... |
63,226,418 | 63,229,806 | Function template accept and return different lambdas | I have the function GetThing as follows:
auto GetThing(size_t index, auto&& l1)
{
return l1;
}
auto GetThing(size_t index, auto&& l1, auto&&... rest)
{
if (index == 0)
return l1;
return GetThing(index - 1, rest...);
}
I want it to be able to work with different lambdas too while being able to handl... | You may store your functions in an array of variants. This comes with some overhead of course. But this enables to have functions also using captured vars.
This enable to pick a function from such function collection and execute it with given parms as follows:
template < typename ARR_T >
struct Collect
{
template <... |
63,226,518 | 63,226,595 | how do I tell the string to read the 0 and not abort? | I have a string with numbers, including 0.
Unfortunately the string recognize the number 0 as \0 and finishes reading in.
Is there a way to interpret the 0 as 0 and read it?
My program is written in C++.
char buf[] = { 23, 4, 0, 234, 8}
string test(buf);
For this case the string 'test' will contain 23 and 4.
But for m... | You need to specify the amount of characters:
string test(buf, size(buf));
The use of std::size here requires #include <iterator>.
Instead of size(buf) you can simply write 5, or obtain the array size in some different way.
|
63,226,566 | 63,732,438 | Prevent Simple Macro Substitution | How does one prevent simple macro substitution?
e.g.
#define number 0x10
int number = 0x5;
I know this can be done for function-style macros, like min and max, by surrounding the macro with parentheses (thus, separating it from the adjacent parentheses that would've been used for the args):
#define max(...)
void (ma... | There is no standard way for this but you can do the following:
#define number 0x10
#pragma push_macro("number")
#undef number
int number = 0x5;
#pragma pop_macro("number")
|
63,226,995 | 63,227,553 | How the post-increment operator works exaclty. Are there some exceptions? | Consider this piece of code
int j = 0;
int x = 0;
for(int i=0;i<5;i++){
j = x++;
cout<<x<<" ";
}
Output:
1 2 3 4 5
Now consider this
int j=0;
for(int i=0;i<5;i++){
j = j++;
cout<<j<<" ";
}
Output:
0 0 0 0 0
My doubt is why is j not being incremented after it is assigned the value 0. Isn't j=... |
Isn't j=j++; equivalent to j = j; j++;
No absolutely not, and this is one of the most common misunderstandings about the pre and post increment operators.
The true equivalent of j = j++; is
int temp = j;
++j;
j = temp;
Beginners think that the post increment happens after everything else. But it's not true. The incr... |
63,227,008 | 63,228,027 | Exclude project from build by Premake | I have two projects in the solution. One of them is a debug lib, which should be built only in Debug workspace configuration. In VS I can just disable the 'Build' checkbox in Configuration Manager.
But I need this to be done with Premake 5.0, which include all project in build by default.
I tried to use filter by conf... | I have dived into project kind and find out that None kind can suit my needs.
A configuration which is not included in the build. Useful for
projects containing only web pages, header files, or support
documentation.
I changed my config, and put kind under the filter by configuration, which solved the problem. Now
it... |
63,227,102 | 63,229,144 | Connection refused ESP32 | I have project using GSR sensor with ESP32. Data from ESP32 is saved in database.
But, in my code I have an error. When using static IP, HTTPClient.begin() always returns connection refused.
I've seen this question asked a few times but never got a good answer.
#include <ssl_client.h>
#include <WiFiClientSecure.h>
#in... | Try to delete :
IPAddress local_IP(192, 168, 43, 113);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(8, 8, 8, 8); // Google DNS
and :
WiFi.config(local_IP, gateway, subnet, dns);
After this modification it works perfectly for me.
|
63,227,417 | 63,281,173 | C3536 cannot be used before it is initialized | I am working on an old source code project which originally was written using MSVC 2008 and Boost 1.42, today I'm trying to port this to MSVC 2017 with Boost 1.73
There are many issues to resolve, one of which is below:
Severity Code Description Project File Line Suppression State
Error C3536 'binding':... | The actual fix was just to change _1 to std::placeholders::_1
|
63,227,594 | 63,227,717 | Time Complexity for random call | What will be the time complexity for the given code
int func(int n){
int i;
if(n<=0)
return 0;
else
{
i=random(n-1);
return func(i)+func(n-1-i);
}
}
I think O(n) but how can I prove it?
| In order to prove that your time complexity is O(n), you need to prove that
return func(i)+func(n-1-i);
won't be called more than n times.
As long as n is decreasing by at least 1 (i being an int, from 0 to n, and n decreasing by i+1 every time) at each call, then you'll use this line maximum n times.
And, because wit... |
63,227,675 | 63,228,895 | Is there a way to rotate an sf::FloatRect | I'm making a collision detection system in my project, and I need to detect collisions on a rotated texture.
To detect to collisions, 4 sf::FloatRect objects are made around the main character texture (for detecting collision to the left, right, up and down), and a sf::FloatRect is made using the position of a texture ... | sf::FloatRect in SFML represents an AABB (AABB stands for Axis-Aligned Bounding Box). So no, it cannot rotate. What you need is OBB (Oriented Bounding Box) collision detection. You're gonna need to either
Write your own code for it (difficult)
or
Find a library that does the job for you !
I found this after searchi... |
63,227,676 | 63,227,677 | HTTPS Giving Segfault in cpp-httplib | I'm trying to do some HTTP(S) requests with cpp-httplib. Why does
#include <iostream>
#include "httplib.h"
using namespace std;
int main()
{
cout << "hi" << endl;
auto res = httplib::Client("http://stackoverflow.com").Get("/");
cout << res << endl;
return 0;
}
print
hi
0x5605c058db50
(OK), but
#in... | Following the README on cpp-httplib github:
add #define CPPHTTPLIB_OPENSSL_SUPPORT,
link libssl and libcrypto.
So the code would be so:
#include <iostream>
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.h"
using namespace std;
int main()
{
cout << "hi" << endl;
auto res = httplib::Client("https://s... |
63,228,412 | 63,229,283 | Are compilers allowed to support a feature, that is removed in the standard? | In the first paragraph cppreference.com clearly states that throw(T1, ..., Tn) is removed in C++17.
It confuses me, that some compilers support throw(T1, ..., Tn) in C++17 mode (see demo).
MSVC supports it by default, but you can turn on a warning for it, see C5040. It can be turned into an error with /we5040.
Clang r... |
Are compilers allowed to support a feature, that is removed in the standard?
The standard doesn't allow that. AFAIK in general it doesn't give any special treatment to features that used to be in the language (doesn't separate them from non-existent features).
If a compiler doesn't diagnose this error (i.e. doesn't g... |
63,228,424 | 63,240,615 | How can I find the path to DLL generated by a different project? | I have a VS solution that includes two projects (A and B) that generate DLLs, plus one project (C) that is dependent on those two DLLs at runtime.
I also have a project to test C and to make it work across all computer on my team I need to be able to find the path to the DLLs generated by A and B dynamically. How can I... | I suggest that you could try to use the function GetModuleFileNameA to get the path to DLL.
DWORD GetModuleFileNameA(
HMODULE hModule,
LPSTR lpFilename,
DWORD nSize
);
You could refer to the example:
char szPath[MAX_PATH];
GetModuleFileNameA(dllhandle, szPath, MAX_PATH);
|
63,228,461 | 63,228,544 | Alias to complicated Template Typename | I have the following definition in file Segment.h
template<typename T, typename VecType = mat::vec3_gen<T> > class Segment
{
// class
}
Instead of having typename VecType = mat::vec3_gen<T> I want to use some alias for the type
and be able to use it outside the file also. how can I do it?
| Since the type VecType depends on T, you can make the type alias a member of Segment.
template<typename T>
class Segment {
public:
using VecType = mat::vec3_gen<T>;
};
Now you can use it in other code:
auto vec = Segment<int>::VecType;
|
63,228,577 | 63,236,233 | How to get the alpha value of a pixel in libpng? | How can I get the alpha value of a pixel with the libpng.
The pixels values are stored int a std::vector<std::vector<uint8_t>>.
The RGB values are correctly decoded but the alpha value is sometimes 255 !
I thought that the alpha value should be between 0 and 1.
Thanks !
| This comment from Benny K solved my issue :
Both RGB and alpha values are generally 8-bit values, meanning integers in 0-255, where 255 is 1.0 or 100%.
|
63,228,618 | 63,228,927 | Disable Visual Studio green arrow button moving instruction pointer | Recently Visual Studio is displaying a green arrow while debugging, when hovering with the mouse.
If you click on it it moves the instruction pointer to that line, I think.
Is there a way to disable this feature?
| Run execution to here can be disabled the following way:
Tools -> Options -> Debugging -> General
And unticking Show Run to click button while debugging.
This is in VS Community 2019, slight variations can occur in other versions.
|
63,228,741 | 63,234,252 | How to change mouse buttons behaviour using winapi? | I would like to click my left mouse button, but get action like after clicked right mouse button and the same in the other side. So I would like to open folder clicking on it two Times my right mouse button.
When I try something like:
case WM_LBUTTONDOWN:
mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
... | Have a look at the SwapMouseButton() function:
Reverses or restores the meaning of the left and right mouse buttons.
...
Parameters
fSwap
Type: BOOL
If this parameter is TRUE, the left button generates right-button messages and the right button generates left-button messages. If this parameter is FALSE, the buttons ar... |
63,228,892 | 63,446,625 | SLF4J: Failed to load class at Eclipse | Using win10, Eclipse June 2020 C++ IDE, jdk-13.0.2, IAR plugin.
I have a project that contains several sub-projects and it doesn't compile using the command line (eclipsec.exe).
The running command
C:\eclipse\eclipsec.exe -nosplash --launcher.suppressErrors -application org.eclipse.cdt.managedbuilder.core.headlessbuild... | The project didn't compile because some of the files were "locked".
Example of a locked file:
Error[Ms003]: could not open file "Components\folder\file.o" for writing
After removing Eclipse .metadata folder or the specific file .metadata\.plugins\org.eclipse.core.resources\.safetable\org.eclipse.core.resources, the fil... |
63,229,011 | 63,256,802 | Wrong dynamic memory size allocated for Mbed BufferedSerial object | I'm trying to allocate two instances of mbed::BufferedSerial object in heap on nrf52840. First allocation succeeds and first instance of serial port works fine, however, after creating the second serial port object instance, the first instance stops working. Debugging shows that the second object overwrites the 16 last... | David Schwartz's comment gave me a clue to look for mismatched pre-processor MACRO definitions.
The problem was with DEVICE_SERIAL_FC pre-processor macro. When mbed was built as a library, the macro was enabled. However, when the library and its header files were used in the project, it was disabled. This mismatch caus... |
63,229,168 | 63,229,700 | C++ custom range type MSVC compiles but G++ doesn't | I'm using Visual Studio 2019 to learn C++ because it's a great IDE that catches errors on the spot. My program below shows no error and compiles just fine using MSVC, but when I tried compiling with G++ 10.1 it won't do it
#include <cstdio>
class FiboIterator {
int current{ 1 };
int last{ 1 };
public:
bool... | I agree with @vlad-from-moscow, this is probably a MSVC bug, because default settings of Visual Studio 2019 is C++14. It shouldn't compile.
Your code is correct since c++17.
If you use c++17 your code would compile on GCC and CLang.
The realization of range-based for loop has changed.
C++11:
{
auto && __range = rang... |
63,229,362 | 63,241,237 | How can encode bitmap blocks in a multi-threaded fashion? | I am trying to to encode a bitmap image block and save it to memory (inside of a vector). It all works fine, until I try to do this in a multi-threaded fashion. I keep getting the following errors:
Error C2672 'std::invoke': no matching overloaded function found
Error C2893 Failed to specialize function template... | There's a lock inside GDI+ that prevents two threads from using the same Graphics object or the same Bitmap. Whatever thread gets to it first grabs the lock, the other one will die with an exception.
Refer: GDI+ objects and multithreading
And Thread Synchronization also pointed out:
Some GDI+ methods return ObjectBus... |
63,229,532 | 63,229,741 | conjunction type traits in C++11 | I need to check variadic arguments in std::enable_if:
With C++17 I would write:
template <typename A, typename ...B>
class Foo : public A, public B...
{
public:
template <typename = std::enable_if_t<std::is_default_constructible_v<A> &&
(std::is_default_constructible_v<B> && ...)>>
Foo()
{}
... | You need a tool which will do the conjunction operation on variadic arguments.
#include <iostream>
#include <type_traits>
template<class...> struct conjunction : std::true_type { };
template<class B1> struct conjunction<B1> : B1 { };
template<class B1, class... Bn>
struct conjunction<B1, Bn...>
: std::conditional... |
63,229,940 | 63,230,549 | Using cryptopp-cmake and crypto++ toghter a CMakeLists.txt project file | I'm using Clion and I'm trying to use cryptopp-cmake for cryptopp in my CMakeLists.txt file, since Cryptopp doesn't have a CMakeLists.txt file in its default project repository. My CMakeLists.txt has this Cryptopp related content:
# Include usage of external projects
include(FetchContent)
# Get the cryptopp CMakeLists... | If a project creates a library with add_library, then link with that library using the target name. Do not use the library file in that case.
According to the cryptopp project's CMakeLists.txt, the name of the library target is cryptopp-shared, so just link with it:
target_link_libraries(hmmenc-client PRIVATE cryptopp-... |
63,230,003 | 63,237,969 | Drawing multiple shapes using SFML | I want to draw 5 Rectangles using SFML library in C++. When I run the code only 3 Rectangles a drawn. A part of code is below. An array of rectangles is declared and using a for loop, I have fixed there size. The conditonal statement in while loop is executed 5 times but only 3 rectangles are shown in my window. The si... | The main problem is that you are calling window.display(); every time you draw one of the rectangles. This isn't needed because SFML has a hidden buffer that keeps track of what has been drawn. More importantly, this is problematic because SFML uses double buffering.
According to SFML
Calling display is also mandatory... |
63,230,462 | 63,231,856 | include a header file built in c++ using extern in c program | I have a class in C++ which I want to make a shared library from it and use in C or other languages. this is the class that I want to make a library from it:
getinfo.h
#ifndef GETINFO_H
#define GETINFO_H
#include "info.h"
char* getMaximumSpeedCpu();
char* getCoreNumbers();
#endif
getinfo.cpp:
#include <iostream>
#inc... | Theory
You can only access functions written in C from the world of C. Whenever calling C++ code from C, you must go through a wrapper function, in your case smc_* functions.
Now, note that the declaration of the wrapper functions, which is in the wrapper's header file smc.h does not need to include getinfo.hpp. This i... |
63,231,310 | 63,245,193 | How to catch sdbus::Error exception in c++? | I'm new in c++. I'm trying to process some errors which can occurs in my java application with jni. This is my try/catch block:
std::future<lib::LibVector> libVectorFuture;
try {
libVectorFuture = some::lib::getVector(param1, param2);
} catch (...) {
// report... | Finally, I wrote a solution. Thanks for your replies.
std::future<lib::LibVector> libVectorFuture;
try {
libVectorFuture = some::lib::getVector(param1, param2);
lib::LibVector vector = libVectorFuture.get(); // here I get error
} catch (...) {
// report problem back t... |
63,231,440 | 63,231,600 | What is the error being produced in my c++ class? | I am writing a compiler and have written a c++ class in it consisting of several functions. While compiling, it is producing two errors saying [Error] expected primary-expression before 'name' and [Error] expected ')' before 'name' in the same line of the function definition string typeof(string name). And also just a... | I think you're being bit by a gcc compiler language extension. Try using a name other than typeof, such as type_of or typeOf.
You can also use the -fno-gnu-keywords compiler option:
-fno-gnu-keywords
Do not recognize typeof as a keyword, so that code can use this word as
an identifier. You can use the keyword _... |
63,231,468 | 63,231,539 | Cannot convert int(*)[5] to int* | When i tried to access array elements using pointer I got this error i don't understand how can i access with the help of pointer.
Error: cannot convert ‘int (*)[5]’ to ‘int*’ for argument ‘1’ to ‘void addd(int*, int)
Any guidance on the matter would be greatly appreciated!
#include <iostream>
using namespace std;
... | Your function receives a pointer to int, so you should just pass the address of the first element.
You can do that:
addd(&arr[0],5);
or simply:
addd(arr,5);
|
63,231,657 | 63,655,590 | Does the WinRT Clipboard History only support text and images? | I'm making a C++/WinRT app that makes use of the Window 10 clipboard history but for some reason I can only grab text and images.
My code is a bit like this..
auto history = Clipboard::GetHistoryItemsAsync().get();
if (history.Status() == ClipboardHistoryItemsResultStatus::Success)
{
auto historyItemList = history... | As observed by my esteemed colleague Faywang - MSFT, Windows' clipboard history and cloud clipboard sync implementation supports only a limited number of clipboard data formats, and this is reflected in the UWP clipboard API in the Windows Runtime Clipboard class.
It's important to remember that what clipboard formats ... |
63,231,693 | 63,231,789 | Return a reference to std::variant that holds non-copyable alternatives | Let's consider this code:
#include <iostream>
#include <variant>
struct Foo {
#if 0
Foo() = default;
Foo(const Foo&) = delete;
#endif
void foo() { std::cout << "foo" << '\n'; }
};
using MyVariant = std::variant<Foo>;
MyVariant& getVariant() {
static MyVariant variant{Foo{}};
return variant;
}
in... | Statement MyVariant variant{Foo{}}; requires Foo to have an available copy or move constructor, but there isn't one. When you delete the copy constructor that also makes the move constructor non-declared, so that you need to declare that move constructor explicitly for to compile.
auto foo = std::get<Foo>(variant) req... |
63,232,248 | 63,234,725 | how to throw java exception as jobject in JNI | I'm new in c++ and jni. I need to return java exception as jobject, not jint. I have a method which returns jobject. So I get compilation error when trying to return ThrowNew:
JNIEXPORT jobject JNICALL Java_com_my_get(JNIEnv* env, jobject obj) {
some::SomeObject returnObject;
try {
//... trying to... | Don't try to return the result of ThrowNew back to Java. Its return value only tells you whether the call succeeded. The documentation for ThrowNew states:
RETURNS:
Returns 0 on success; a negative value on failure.
Calling ThrowNew will cause control flow in the JVM to go to an exception handler upon return from the... |
63,232,285 | 63,232,644 | Error compiling Rcpp library with g++: Rcpp.h not found | I'm following Hadley's chapter for Rcpp in Advanced R, and cannot understand some of the implications of using Rcpp to call C++ functions into R.
In particular, why the C++ files including the directives:
#include <Rcpp.h>
using namespace Rcpp;
Will lead to a Rcpp.h not found error when these files are compiled with g... | This is an error in your understanding.
if g++ -o example example.cpp is used
No R documentation (that I know of) states you can do that. If you start where many of us recommend one starts, namely the Writing R Extensions manual that also came with your copy of R, you will see that the equivalent commands would be
R... |
63,232,329 | 63,232,606 | How to get the first element in a std::set of pointers, where the pointer points to a specific value? | Say you have a C++ std::set of unique pointers e.g.
auto my_set = std::set<std::unique_ptr<std::string>>
{
std::make_unique<std::string>("monkey"),
std::make_unique<std::string>("banana"),
std::make_unique<std::string>("orange")
};
Using the std::find_if function, how would you go about finding the firs... | The question lacks a proper minimal reproducible example. When we make one MCVC: https://godbolt.org/z/bfYx39
The problem is coming from lambda return
return *(*ptr) == food;
as the auto there is std::unique_ptr<std::string>. Therefore you need to just dereference once:
auto find_orange = std::find_if(my_set.begin(),... |
63,232,392 | 63,254,312 | discrete distribution returns integers out of bound | I wrote the function below to sample without replacement. It returns a vector<int> representing a sample being picked among some points. As input, I have a vector<double> containing the probabilities and an integer for the desired sample size. For the function, I use the discrete distribution:
http://www.cplusplus.com/... | In the C++ Standard, we can read about std::discrete_distribution at 26.6.8.6.1 [rand.dist.samp.discrete] (emphasis mine)
A discrete_distribution random number distribution produces random integers i, 0 ≤ i < n, distributed according to the discrete probability function
P(i | p0, …, pn−1) = pi.
Unless specified other... |
63,232,916 | 63,233,066 | When printing array there is a extra line and array changing unknown reason | Here is my class
#include <fstream>
#include <cstdlib>
#include <math.h>
#include <iomanip>
#include <iostream>
using namespace std;
class Point {
protected:
int x, y;
double operator-(const Point &def){
return sqrt(pow((x-def.x),2.0)+
pow((y-def.y),2.0));
}
};
class Circle:... | when you define an array of 13 elements.
You really only have 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 (0-12) indices.
An index accesses a specific element in an array.
This line here myCircleArry[13].printCircleInfo(); actually should say,
myCircleArry[0].printCircleInfo();
0 is where the array actually starts.
|
63,232,917 | 63,232,951 | C++ function hidden by function with same name in another DLL | I've got C++ code separated into 2 libraries (DLLs) and each library has a function w/ the same name, although each is in a different namespace. So in library 1, I have something like the following.
namespace LibOne
{
void Foo(ClassOne& src);
}
In library 2, I have classes that were accessing LibOne::Foo w/o a pr... | No, only the innermost scope that contains a name will be examined. There is Foo in namespace LibTwo, so the compiler doesn't even notice there's also a Foo imported into the global namespace.
In general, avoid using namespace, and prefer to explicitly qualify names. LibOne::Foo
|
63,233,599 | 63,234,197 | How to change keyboard behaviour? | OS: Windows 10
Programming language: c++
Interface: winapi
My goal is to create callback function to WH_KEYBOARD_LL. In this function I want to change behaviour key "B". Of course I know that I have to use
wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
int code = p->vkCod... | You can't change the key from inside a low-level hook. But, what you can do is have your hook simulate your own input events for A using SendInput() when it receives input events for B, and then have the hook return a non-zero value instead of calling CallNextHookEx() to block the input events for B.
Have a look at Wh... |
63,233,606 | 63,233,769 | How to print a vector of vector? error shows this "no matching function for call to ‘begin(std::vector<Arc*>**&)" | I want to print this vector vector< vector< Arc * > * > _adjacences;
when I do
for (auto j : _adjacences[i])
cout << " --> " << j ;
an error shows saying this
no matching function for call to ‘begin(std::vector<Arc*>**&)’
for (auto j : &_adjacences[i])
What can i do ?
|
How to print a vector of vector?
vector< vector< Arc * > * > _adjacences;
That's not a vector of vectors. That's a vector of pointers (to vectors).
for (auto j : &_adjacences[i])
The problem here is that you attempt a for-each loop on a pointer to pointer to vector. That's not possible.
If you want to iterate ove... |
63,234,328 | 63,234,382 | C++ Atomic operations within contiguous block of memory | Is it possible to use atomic operations, possibly using the std::atomic library, when assigning values in a contiguous block of memory.
If I have this code:
uint16_t* data = (uint16_t*) calloc(num_values, size);
What can I do to make operations like this atomic:
data[i] = 5;
I will have multiple threads assigning to ... | You're not going to be able to do exactly what you want like this.
An atomic array doesn't make much sense, nor is it what you want (you want individual writes to be atomic).
You can have an array of atomics:
#include <atomic>
#include <array>
int main()
{
std::array<std::atomic<uint16_t>, 5> data{};
data[1] =... |
63,235,165 | 63,235,253 | Stable sort custom comparator using pass by reference with lamdas gives compile error | https://leetcode.com/problems/move-zeroes/ was solving this question.
But this doesnot compile.
void moveZeroes(vector<int>& nums) {
stable_sort(nums.begin(), nums.end(),[](int& a, int& b){
if(a == 0 && b != 0){
return false;
}
if(a != 0 && b == 0){
... | The lambda can take its arguments as refs. The problem is that in your example, they are not const-ref, and std::stable_sort passes const values,
comp
[...] The signature of the
comparison function should be equivalent to the following:
bool cmp(const Type1 &a, const Type2 &b);
While the signature does not need to h... |
63,235,400 | 63,235,434 | How do I solve this inheritance problem with explicit initialization? | When I'm creating a constructor for a child class I get this error under the MyBook method:
Constructor for 'MyBook' must explicitly initialize the base class 'Book' which does not have a default constructorclang(missing_default_ctor)
Solution.cpp(8, 7): 'Book' declared here
Here's the code below
#include <cmath>
#incl... | When constructing a base class object, you have to do it before entering the constructor body, which means you need to use a member-initializer-list, like this:
MyBook(string t, string a, int p) : Book(t, a) {}
Also note that in order to instantiate an object of type MyBook, you need to override the virtual display me... |
63,235,478 | 63,236,187 | Segmentation fault while submitting code snippet in online compiler, even if it works in local machine | I was implemeting a graph theory question in Cpp using STL. While compiling the following code snippet in my local machine, I am not getting any compile time error, even with compiling using the following flags:
-Wall -Wextra -pedantic -std=c++11 -O2 -Wshadow -Wformat=2 -Wfloat-equal -Wconversion -Wlogical-op -Wshift-o... | Your code has several errors, I've removed them all and run the code. It compiled fine and work properly on provided input. But there are some problems with your implementation style and also with problem. To understand what is wrong with your code(actually, its not only your code's fault, the problem is also wrong), l... |
63,235,532 | 63,235,924 | Replace to_utf8string to ensure proper string encoding on Windows 7 in a C++ DLL | I have a legacy C++ code that was written as a dll that can be called on Windows 10. A new requirement is to allow this dll to function properly on earlier Windows (7 Embedded, optionally XP as well). In short, the code is supposed to display body of a REST response.
The problem is, when called on Windows 7 without any... | The problem has nothing to do with character encoding, or OS used. The function is returning a dangling pointer to invalid memory!
The function is declaring a local std::string variable that goes out of scope when the function exits. It is returning a pointer to the std::string's internal character data, which is free... |
63,235,692 | 63,235,838 | How does the visual studio debugger detect function calls? | When ive attached the visual studio debugger to a process, then add a new function breakpoint, and choose e.g. "system" as the function name. Visual studio will then detect whenever the system() function is called from the target process.
Is there any efficient way to detect function calls from a process using c++?
| A debugger detects that a breakpoint has been hit in several ways.
The basic strategy is the software breakpoint. This means that the debugger replaces an instruction at the breakpoint target with a breakpoint trap instruction.
When the execution hits the breakpoint instruction, a CPU exception is caused which is then ... |
63,236,006 | 63,236,218 | Receiving error about OpenSSL when trying to run step 3 of installing Socket.IO C++ Client | I want to install Socket.IO C++ Client from https://github.com/socketio/socket.io-client-cpp, but I have some difficulties following the steps from https://github.com/socketio/socket.io-client-cpp/blob/master/INSTALL.md.
I have successfully installed Boost version 1_73_0 (step 1) and run step 2. Boost is installed at /... | The contents of the BOOST_VER cache variable in the cmake command line are provided to CMake's find_package command as an argument:
1_73_0
However, per the find_package documentation, the format must use periods to separate the version components:
The [version] argument requests a version with which the package found... |
63,236,206 | 63,236,238 | How to avoid this kind of code repetition? | In order to avoid code repetition, I need to do something like this (in my real code I have much more complex types similar to T1 and T2):
template <class T1, class T2>
struct A
{};
template <class T1, class T2>
struct B
{};
template <class X>
struct C
{
using p1 = int;
using p2 = char;
using some = X<p1... | Your class C needs to use a template template parameter in order to accept A and B as input to its own template so it can then pass parameters to them, eg:
template <template<typename T1, typename T2> class X>
struct C
{
using p1 = int;
using p2 = char;
using some = X<p1, p2>;
};
Now you can do this:
C<A> o... |
63,236,456 | 63,236,506 | Debug Assertion Failed: Vector subscript out of range | Getting a failure alert that I unfortunately have no idea what it means. I tried to search other questions about debug assertion failures, but could not find anything that I understood as being the same issue that I have. It specifically states Line: 1501 Expression: Vector subscript out of range.
I have used vectors b... | This line:
vector <string> anotherVec;
declares a vector of size 0. Then indexing into the vector like this:
anotherVec[0] = "Fred";
invokes undefined behavior. Instead, you can do:
anotherVec.push_back("Fred");
Or else, you can allocate enough space for the vector when you declare it, like this:
vector <string> ano... |
63,236,494 | 63,236,602 | Is the output of the libjpeg always RGB (or luminance for monochrome images)? | I use he libjpeg to manipulate jpeg images.
My question is simple :
Is the output of the libjpeg always RGB (or luminance for monochrome images) ?
I'm not an expert with the color spaces...
Thanks !
| Strictly speaking, JPEG is always YCbCr (YUV), so that's the output. You may apply other colorspaces, but typically only RGB or (less commonly) CMYK are supported, and the underlying data in the file will remain YCbCr. Grayscale simply leaves the second two channels out and only encodes Y.
|
63,236,669 | 63,236,717 | SDL runtime binaries, what are they used for? | I am following a tutorial that takes me to this SDL page (https://www.libsdl.org/download-2.0.php). In there, I can see three things I can download:
Source code
Runtime Binaries
Development libraries
I am trying to make sense out of them. My understanding is this:
Source Code: Is the original code made by the creato... | The runtime binaries / libraries are the files that your application needs to use at run-time to access the library functions. They are the files that contain the actual compiled code of the library that your application will call when it is executed.
|
63,236,688 | 63,236,715 | CRTP derived templated method call yields expected primary-expression before ‘>’ token | The following example does not compile with error error: expected primary-expression before ‘>’ token. I do not understand why. I'm trying to call a derived CRTP templated method. I'm doing it this way with CRTP because you can't have virtual templated methods.
https://godbolt.org/z/PMfsPM
#include <iostream>
#include ... | makeTImpl is a function template, and is used in a dependent context. So instead of:
d.makeTImpl<T>(x, y);
you need to write:
d.template makeTImpl<T>(x, y);
//^^^^^^^^
Here's a demo.
See this post for details on which contexts require the template keyword.
|
63,236,794 | 63,237,250 | Could anyone please explain me this function, I am not able to understand this | unsigned long fileSize = file.size();
byte buf[4];
buf[0] = (byte) fileSize & 0xFF;
buf[1] = (byte) (fileSize >> 8) & 0xFF;
buf[2] = (byte) (fileSize >> 16) & 0xFF;
buf[3] = (byte) (fileSize >> 24) & 0xFF;
can anyone explain me this code.assuming a file with a size of your choice
| Supposing you wanted to split a decimal number 8375 into digits. You could do it this way:
unsigned value = 8375;
unsigned digit_0 = value % 10; // Gives 5
unsigned digit_1 = (value / 10) % 10; // Gives 7
unsigned digit_2 = (value / 100) % 10; // Gives 3
unsigned digit_3 = (value / 10... |
63,237,209 | 63,237,427 | OpenMP parallelization inside for loops takes too long | I am preparing a program which must use OpenMP parallelization. The program is supposed to compare two frames, inside of which both frames must be compared block by block, and OpenMP must be applied in two ways: one where frame work must be split across threads, and the other where the work must be split between the th... | Remember that every time your program executes #pragma omp parallel directive, it spawns new threads. Spawning threads is very costly, and since you do getCost() many many times, and each call is not that computationally heavy, you end up wasting all the time on spawning and joining threads (which is essentially making... |
63,237,234 | 63,237,305 | How to hide exe dll in C++? | I have my program (.exe) and it depends on 3 DLLs to work, but, I want to hide these DLLs, is there any way for me to "put them in .exe" these dlls? Only have the .exe,is there any method to do this?
Info:
Program's ling: C++
DLLs: {libcrypto-1_1-x64, libcurl-x64, libssl-1_1-x64}
| If you use the static versions of the libraries, their code will be compiled directly into your EXE, and then you won't need DLLs at all.
But, if you need to use DLLs, then you can compile them into your EXE's resources, and then extract them at runtime to temp files before using them. You won't be able to statically ... |
63,237,420 | 63,237,505 | dynamic 2d-array - missing segmentation fault? | I have the following code:
int **a = new int*[n+1];
for(int i = 0; i <= n; i++) a[i] = new int[1];
Now - to my understanding - the first statement allocates memory for n+1 int pointers, in the loop, for each of these int pointers there 1 * sizeof(int) memory is allocated (a[i] is pointer to the first int).
If I output... | Your code has undefined behavior.
When creating the arrays, your loop allocates an int[1] array for each int* pointer in the outer array. That is OK.
When accessing the arrays later, accessing the int* pointers via a[i] is fine since i does not go out of bounds of the a[] array. But [j] does go out of bounds as 0 is ... |
63,237,625 | 63,238,546 | ESP8266 ESPAsyncWebServer does not toggle GPIO in callback | I am simply trying to turn a pin off and on when I press a button from a webpage. I know the hardware works as I am able to toggle it in a different program. I am new to using this library, so I am sure I am missing something small here.... Why will it not toggle my output in the callback. I have executed the code t... | Don't call delay() (or yield()) inside callbacks from the async web server. Doing so blocks the event handler task and may cause the TCP connection or HTTP protocol to fail. The async web documentation calls this out in the "Important things to remember" section.
Instead, set a flag that indicates that the work needs t... |
63,237,805 | 63,237,937 | Writing uint32_ts and uint_8ts to file as chars & then converting them back into uint32_ts and uint_8ts | I'm writing ints to a file like this:
for (int i = 0; i < 4; i++) {
writeInt8ToFile(126, ofst);
writeInt32ToFile(12500, ofst);
writeInt8ToFile(139, ofst);
}
(Relevant functions):
void writeInt32ToFile(std::uint32_t i, std::fstream &fstr)
{
fstr.write(reinterpret_cast<char *>(&i), sizeof(std::uint32_t))... | Your loop
for (int i = 0; i < btVec.size() / MAP_BYTE_SIZE; i++) {
is wrong. You have to move the starting position of each block MAP_BYTE_SIZE elements, not 1.
Try
for (int j = 0; j < btVec.size() / MAP_BYTE_SIZE; j++) {
int i = j * MAP_BYTE_SIZE;
|
63,237,845 | 63,246,610 | Printing floats with setw and setprecision - output doesn't line up | I'm trying to print matrix in C++ using std::cout, but I have no idea how to do this correct.
I tried such variants as setw() and setprecision(), but still not achived desired appearance(You can see it on the bottom of this question).
Matrix.cpp
template<class T>
class Matrix
{
public:
...
void print(int prec... | It turns that I just need to call function with bigger argument:
cout << setw(10) << fixed << data.at(i*cols + j) << " ";
Output:
-21.426937 -11.908819 -14.880438 -11.171500 3.775967
16.176332 10.679954 7.998794 -0.849034 -11.975848
15.751815 -19.103265 6.278383 -3.865339 21.471623
And yes, answer under li... |
63,237,856 | 63,238,100 | Read Windows UDP Buffer Size | I'm finding difficulty figuring out how to check the UDP Buffer size in Windows via Command Prompt. I am looking for something similar to the linux command "sysctl net.core.rmem_max". I do not need to set the UDP buffer size, I just need to check it in order to throw a warning if it is smaller than my recommended size.... | I don't know how to do this from the command line (looks like PowerShell can do it), but you should be able to do this in C++ as follows (note: untested):
#include <iostream>
#include <WinSock2.h>
#include <Ws2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")
int main ()
{
WSADATA wsaData;
int err = WSAStartup (MAK... |
63,238,217 | 63,238,226 | How to make use of an accessor method of an object when that object is encapsulated within a const class? | Let me pose the question more clearly.
I have a Datarow object:
Class Datarow {
private:
vector<string> vals;
public:
std::string getVal(int index); //returns vals.at(index)
};
I have a Section object that holds datarows:
Class Section {
private:
vector<Datarow> rows; ... | The correct way to do this is make the necessary Datarow methods into const methods, like this:
std::string getVal(int index) const;
// ^^^^^ add this
Now these methods can be called on a const object, as you are doing in operator<<.
Also, your operator<< is a friend function, and should n... |
63,238,371 | 63,238,467 | Do constexpr values cause binary size to increase? | I know that templatized types such as the below cost nothing on the compiled binary size:
template<auto value>
struct ValueHolder{};
I'm making a program that will use a LOT of such wrapped types, and I don't think I want to be using integral_constants for that reason, since they have a ::value member. I can get away... | This depends entirely on:
How much the compiler feels like optimizing the variable away.
How you use the variable.
Consider the code you posted. You created a constexpr array. As this is an array, it is 100% legal to index it with a runtime value. This would require the compiler to emit code that accesses the array a... |
63,238,547 | 63,238,597 | C++ function call wrapper object with function as template argument | I want to build a template helper object using only C++11 that can be used to wrap C functions.
I'm trying to extend the answer given here from a wrapper function to a wrapper object, so that it can contain state:
#include <iostream>
#include <functional>
int foo(int a, int b) { return a + b; }
template<typename Fn, ... | At no point in the program you specify Args and it can’t be deduced so it turns out to be an empty pack.
You can capture the arguments of the function using a partial specialization:
template<auto F> class C;
template<typename RV, typename ...Args, RV (*F)(Args...)>
class C<F>
{
...
|
63,238,594 | 63,238,649 | How to change object property based on function parameter C++ | I have a function:
int bitCpy(Inst a, int b, int c, int d)
{
int range = d - c;
b <<= (32 - d);
b >>= (32 - range);
a.(PROPERTY HERE) = b; // a.num1, a.num2, a.num3 ... etc
return a;
}
The function simply copies bits from one section of an integer and then shifts those bits to the beginning. Inst i... | You can use a pointer-to-member, eg:
int bitCpy(Inst &a, int Inst::*member, int b, int c, int d)
{
int range = d - c;
b <<= (32 - d);
b >>= (32 - range);
a.*member = b; // a.num1, a.num2, a.num3 ... etc
return a;
}
And then you can call it like this:
Inst i;
bitCpy(i, &Inst::num1, ...);
bitCpy(i, &... |
63,238,667 | 63,238,855 | How can I validate the type of a template function argument at compile time | I'm writing a class for communicating sensor data and I want to make it so that a user of the class can't use an incorrect data type for sending sensor data.
I want to set up my class sort of like this:
private:
static const _sensor_bytes[] = {2, 4, ...};
public:
enum sensor_name_t {
SENSOR1 = 0,
... | You can't do this with function void writeData(sensor_name_t sensor, T data), because value of sensor is known at runtime, so it can't by validated in compile-time and rise an error.
Variant 1
You can try to use std::enable_if, move sensor from function parameter to template parameter and use constexpr for _sensor_byte... |
63,238,696 | 63,238,763 | C++ mark a function as experimental/not fully implemented | I have a function I will need to leave partially implemented for a variety of reasons and I want to prevent future users (read as me in the future when I have forgotten that I did this) to know the function is incomplete, buggy and untested.
Option n1 is merely adding a comment // Warning this thing is partially implem... | The [[deprecated]] attribute is exactly what this is for (emphasis mine) :
https://en.cppreference.com/w/cpp/language/attributes
[deprecated]
[deprecated("reason")]
indicates that the use of the name or entity declared with this attribute is allowed, but discouraged for some reason
You can still use the function, you... |
63,238,755 | 63,238,861 | Can this bitset generation be made better or more efficient? | Problem: Given an integer led as input, create a bitset (16 bits) with led bits set to 1. Then, create the following sequence (assume in this case led = 7):
0000000001111111
0000000000111111
0000000001011111
0000000001101111
0000000001110111
0000000001111011
0000000001111101
0000000001111110
Note that it is a "zero" ... | This is what I came up with:
void createMask(int len) {
std::bitset<16> bitMap;
for (int i = 1; i < len; i++)
{
bitMap.set();
bitMap >>= 16 - len;
bitMap[len - i] = false;
std::cout << bitMap << std::endl;
}
}
bitMap.set() sets all bits in the bitset to 1 (or true)
bitMa... |
63,239,555 | 63,239,646 | How to init unknown string type? | Say i have a class like this
template<typename CharT>
class basic_class
{
public:
using char_type = CharT;
using string_type = std::basic_string<CharT>;
private:
const char_type ch = '?';
const string_type str{"How to init"};
};
It is okay if it is char but not for wchar_t.
How can i do this ... | You may define a function that returns the value of correct type:
template<typename CharT>
class basic_class
{
public:
using char_type = CharT;
using string_type = std::basic_string<CharT>;
private:
constexpr auto getInitString() {
if constexpr (is_same<CharT, wchar_t>::value) {
re... |
63,239,823 | 63,316,461 | Constructors can only be inherited DIRECTLY from the base? | I have a base class A, that defines some constructors.
Then I have classes B1, B2, B3 that inherit from A.
None of these are meant to be instantiated. Instead, I have classes C11, C12, C13 inheriting from B1, and so on.
C11, C12 etc. all need A's constructors.
I don't think I can write using A::A; in class C11, for in... | If you are looking for a quote from the standard, then here goes:
[namespace.udecl]/3 ... If a using-declarator names a constructor, its nested-name-specifier shall name a direct base class of the class being defined.
|
63,240,036 | 63,240,157 | Why is inserting into a vector in C++ efficient? | From https://learn.microsoft.com/en-us/cpp/cpp/value-types-modern-cpp?view=vs-2019, we have:
#include <set>
#include <vector>
#include <string>
using namespace std;
//...
set<widget> LoadHugeData() {
set<widget> ret;
// ... load data from disk and populate ret
return ret;
}
//...
widgets = LoadHugeData(); ... |
I assume returning the set creates a copy of the set where each pointer in the underlying array ...
Your assumption is wrong. A std::set doesn't have an "underlying array". It is generally implemented as a balanced search tree.
where each pointer in the underlying array refers to the same memory locations as the set... |
63,240,370 | 63,240,442 | no known conversion for argument 1 - Passing 'this' to a method | I'm trying to get hands on C++. Sorry if the post already exists, that's could be because I don't have the necessary C++ background to put the exact words on it.
I'm creating a class to handle math vectors. So I have a Point struct, and a Vector struct. I want to be able to create an instance of a Vector by giving two ... | between is defined as this:
static Vector2D between(Point a, Point b){...}
You are calling it like this from Point implementation:
Vector2D vector = Vector2D::between(this, point);
this is a pointer to a Point in it's current context -- between doesn't take a pointer to a Point, it takes a Point. So you need ... |
63,240,411 | 63,257,622 | Execute cl command with Java Runtime from anywhere | I am trying to call/execute a C++ compiler command with the Java Runtime.
Runtime runtime = Runtime.getRuntime();
String[] command = { "cl", "/P", "/EP", "/C", "-D", "LOC" + loc_file, file};
Process process = runtime.exec(command);
process.waitFor();
However I always get following error message:
"Cannot run program "c... | In your situation, I think there are two solutions to your issue:
1 Change the PATH on your system and launch the program in this updated environment
This what you did already judging by your comment under the question.
You can manually add the program you want to launch in the "PATH" of your system by adjusting the en... |
63,240,416 | 63,240,512 | What's the difference between unique_lock and shared_lock in C++ | Trying to understand when one might use shared_lock over unique_lock or vice versa. The C++ doc is very cryptic! I'm aware that the general guideline is to use lock_guard over the two if we desire immediate, scoped (or RAII) mutual exclusion.
Does this have something to do with condition_variable? I've seen all three b... | Its pretty simple, really. unique_lock calls lock() on the mutex. shared_lock calls shared_lock().
The difference between them is that shared_lock is designed to support readers in a read/write lock. You can have multiple threads all acquire the shared lock and reading the same data, but if anyone wants to write to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.