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 |
|---|---|---|---|---|
69,206,266 | 69,348,778 | Subgroups with the same name in different groups | I just started using Doxygen for the first time and ran into the following problem: I'm trying to create multiple subgroups with the same name like this:
- Group 1
- Constructors
- Other
- Group 2
- Constructors
- Other
Instead what I get is this:
- Group 1
- Constructors
- (Constructors both from Group 1 and 2)
- Other
- (Others from both Group 1 and 2)
- Group 2
- Constructors
- (Constructors both from Group 1 and 2)
- Other
- (Others from both Group 1 and 2)
My current code looks like this (in separate .h files)
/** @defgroup Group1
* Description for Group 1
*/
/** @defgroup Group2
* Description for Group 2
*/
/* @defgroup Constructors
* @ingroup Group1
*/
/* @defgroup Constructors
* @ingroup Group2
*/
/* @defgroup Other
* @ingroup Group1
*/
/* @defgroup Other
* @ingroup Group2
*/
/**
* @ingroup Group1
* @{
*/
class Class1 {
/**
* @ingroup Constructors
* @{
*/
Class1();
(other constructors)
/** @}*/
/**
* @ingroup Other
* @{
*/
void Random();
(other functions)
/** @}*/
}; /** @}*/
/**
* @ingroup Group2
* @{
*/
class Class2 {
/**
* @ingroup Constructors
* @{
*/
Class1();
(other constructors)
/** @}*/
/**
* @ingroup Other
* @{
*/
void Random();
(other functions)
/** @}*/
}; /** @}*/
I tried to keep the code short, but I hope my question is still clear.
Thanks in advance!
| Short answer:
Make sure to declare groups in doxygen commments (/**), not just C comments
group definition takes a name and a title. The name (Constructors_1) must be globally unique, and acts as an identifier. The title (Constructors) is what is rendered, and does not need to be unique.
Nesting groups can be used to manually organize some doc. Doing that on C++ methods of a class, however, is counter productive, as it will confuse doxygen (see how group 1 and 2 are broken in the example below), which naturally documents methods of a class with the class, not elsewhere.
use groups to organize entire classes (with all the content) or functions into several sub groups, but do not try to break down classes into smaller parts.
Long answer:
/** @file foo.cc
Doxygen example.
*/
/** @defgroup Group1
* Description for Group 1
*/
/** @defgroup Group2
* Description for Group 2
*/
/** @defgroup Constructors_1 Constructors
Constructors from group 1.
* @ingroup Group1
*/
/** @defgroup Constructors_2 Constructors
Constructors from group 2.
* @ingroup Group2
*/
/** @defgroup Other_1 Other
Misc from group 1.
* @ingroup Group1
*/
/** @defgroup Other_2 Other
Misc from group 2.
* @ingroup Group2
*/
/** @defgroup Group3
* Description for Group 3
*/
/** @defgroup Stuff_3 Stuff
Stuff.
* @ingroup Group3
*/
/** @defgroup More_stuff_3 More stuff
More stuff.
* @ingroup Group3
*/
/**
* @ingroup Group1
* @{
*/
class Class1 {
/**
* @ingroup Constructors_1
* @{
*/
/** This is Class1. */
Class1();
/** @}*/
/**
* @ingroup Other_1
* @{
*/
/** This is Random 1. */
void Random();
/** @}*/
};
/** @}*/
/**
* @ingroup Group2
* @{
*/
class Class2 {
/**
* @ingroup Constructors_2
* @{
*/
/** This is Class2. */
Class2();
/** @}*/
/**
* @ingroup Other_2
* @{
*/
/** This is Random 2. */
void Random();
/** @}*/
};
/** @}*/
/**
* @ingroup Group3
* @{
*/
void init_group_3();
/**
* @ingroup Stuff_3
* @{
*/
/** This is some stuff. */
void do_something_here();
/** @}*/
/**
* @ingroup More_stuff_3
* @{
*/
/** This is more stuff. */
void do_something_more_here();
/** @}*/
};
/** @}*/
Tested with Doxygen 1.9.2, group 3 works as expected, group 1 and 2 do not render the content properly, because of manually assignment of methods of a class to another group.
|
69,206,296 | 69,206,563 | Are uninitialized references zero-initialized and uninitialized scalars default-initialized? | Are the following statements correct?
An uninitialized reference is considered zero-initialized.
An uninitialized scalar is considered default-initialized.
Any other uninitialized entity is not considered zero-initialized nor default-initialized.
They are based on [dcl.init.general/6] (bold emphasis mine):
To zero-initialize an object or reference of type T means:
if T is a scalar type, the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;
if T is a (possibly cv-qualified) non-union class type, its padding bits are initialized to zero bits and each non-static data member, each non-virtual base class subobject, and, if the object is not a base class subobject, each virtual base class subobject is zero-initialized;
if T is a (possibly cv-qualified) union type, its padding bits are initialized to zero bits and the object's first non-static named data member is zero-initialized;
if T is an array type, each element is zero-initialized;
if T is a reference type, no initialization is performed.
and on [dcl.init.general/7] (bold emphasis mine):
To default-initialize an object of type T means:
If T is a (possibly cv-qualified) class type ([class]), constructors are considered. The applicable constructors are enumerated ([over.match.ctor]), and the best one for the initializer () is chosen through overload resolution ([over.match]). The constructor thus selected is called, with an empty argument list, to initialize the object.
If T is an array type, each element is default-initialized.
Otherwise, no initialization is performed.
|
Are the following statements correct?
No, you are flipping the logical connections on their heads.
The definitions of "zero-initialization" and "default-initialization" specify what it means if something else in the standard says "the object is zero-initialized". When the standard says that, you use the definition of zero-initialization to see what it means. For a reference, it means no initialization is done. So a zero-initialized reference is uninitialized (and therefore ill-formed).
That does not imply the inverse though. An uninitialized reference is not zero-initialized. This is a fallacy: https://en.wikipedia.org/wiki/Affirming_the_consequent
A reference is zero-initialized when the standard says zero-initialization is performed.
|
69,207,095 | 69,207,307 | c++ code not working, my output screen crashes | My output screen crashes whenever I try to execute my code. This is the part of the question:
Declare a class named House for a real estate locator service. The
following information should be included:
Owner: (a string of up to 20 characters)
Address: (a string of up to 20 characters)
Bedrooms: (an integer)
Price (floating point)
b) Declare available to be an array of 100 objects of class House.
c) Write a function to read values into the members of an object of
House.
d) Write a driver program to test the data structures and the
functions you have developed.
The driver program should read in house entries into the available
array. After the code for entering the data, you should write code to
output the data that you have entered to verify that it is correct.
Here's my code:
class House {
private:
string owner;
string address;
int bedrooms;
float price;
public:
House(string owner = "", string address = "", int bedrooms = 0, float price = 0.0)
{
this->owner = owner;
this->address = address;
this->bedrooms = bedrooms;
this->price = price;
}
void setOwner(string owner)
{
this->owner = owner;
}
void setAddress(string address)
{
this->address = address;
}
void setBedrooms(int bedrooms)
{
this->bedrooms = bedrooms;
}
void setPrice(float price)
{
this->price = price;
}
string getOwner()
{
return owner;
}
string getAddress()
{
return address;
}
int getBedrooms()
{
return bedrooms;
}
float getPrice()
{
return price;
}
void getData()
{
cout << "Enter Owner : ";
getline(cin, owner);
setOwner(owner);
cout << "Enter Address : ";
cin >> address;
setAddress(address);
cout << "Number of Bedrooms? : ";
cin >> bedrooms;
setBedrooms(bedrooms);
cout << "Price : ";
cin >> price;
setPrice(price);
cout << endl;
}
void display()
{
cout << "Owner \t Address \t Bedrooms \t Price" << endl;
cout << getOwner() << "\t" << getAddress() << "\t" << getBedrooms() << "\t" << getPrice() << "\t" << endl;
}
};
int main()
{
House* h[100];
int time = 0;
char yesorno;
do {
h[time]->getData();
h[time]->display();
cout << "Do you wish to continue ?";
cin >> yesorno;
time++;
} while (yesorno == 'y' || yesorno == 'Y');
return 0;
}
| The most obvious problem is that you do the following:
House* h[100];
/* ... */
h[time]->getData();
The definition of h creates an array of 100 pointers to House; it does not create a single house! With h[time]-> you try to access a house supposedly pointed to by h[time] but that house does not exist.
A "C solution" would be to simply declare h as an array of houses and access them via the . operator:
House h[100];
/* ... */
h[time].getData();
In C++ one would typically use a vector and add houses via push_back().
Additionally, there is one minor hiccup: After entering a string or a number on its own line, which is the typical way (you enter the number and press enter), the newline at the end of that line is still in the pending input; a successive getline() will see that immediate newline and read an empty line.
This happens after each loop in your program because the input ends with entering a number; at the beginning of the next house input, however, is a getline() because a name can have more than one word. Therefore the program does not wait for any user input but assigns an empty string as the name.
The easy fix is to loop until the line is not empty. (As a side effect, that catches the user hitting enter more than once):
do
{
getline(cin, owner);
}while(owner == "");
You probably want to read an entire line for the address as well, with the same logic.
Otherwise your program is working fine!
|
69,207,222 | 69,207,390 | Insert (dynamic) command string in ShellExecute function in C++ | Using C++ (on Windows 10), I'm trying to execute a command in cmd.exe that execute a python file that takes in another file (in csv format).
What I would like to do is the same thing as if I were typing on the command line something like this:
python3 .\plotCSV.py .\filetoplot.csv
Or in better mode:
python3 C:\...\Documents\plotCSV.py C:\...\Documents\filetoplot.csv
For this I'm using ShellExecute like this:
ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", "/c \"python3 C:\...\Documents\plotCSV.py C:\...\Documents\filetoplot.csv\"", NULL, SW_SHOWDEFAULT);
And for the csv file selected (filetoplot.csv for example) this works. Except that, for what I need, the name of the csv file is generate and changes every time in my C++ program and is saved in a variable file_name.c_str(). So, if I use this in ShellExecute I have:
ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", "/c \"python3 C:\...\Documents\plotCSV.py C:\...\Documents\file_name.c_str()\"", NULL, SW_SHOWDEFAULT);
But unfortunately (obviously) it doesn't work because there really isn't a csv file renamed "file_name.c_str()".
I found also the function ShellExecuteEx and wanting to repeat the same procedure I think the function should be used like this:
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.hwnd = NULL;
info.lpVerb = NULL;
info.lpFile = "cmd.exe";
info.lpParameters = ("python3 C:\...\Documents\plotCSV.py C:\...\Documents\file_name.c_str()");
info.lpDirectory = NULL;
info.nShow = SW_SHOW;
info.hInstApp = NULL;
ShellExecuteEx(&info);
But even here it doesn't work (I probably misinterpret how the function works).
Hoping I have explained myself well, I kindly ask for your advice on how to proceed in this regard.
Thank you very much
| You are trying to write code inside a string literal.
That is not possible in C++!
You need to first create your dynamic parameter string, then pass it to a function.
std::string has an overloaded + operator that supports string literals (const char *).
std::string param1 = "/c \"python3 C:\\...\\Documents\\plotCSV.py C:\\...\\Documents\\" + file_name + '\"';
ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", param1.c_str(), NULL, SW_SHOWDEFAULT);
|
69,207,733 | 69,208,214 | How can i store data in a 2d vector? | I have a piece of code where i read a CSV file and prints it contents. Now the issue is that I want to run my code on ESP32 and because of some limitations of micropython I can't upload my file in the spiffs storage. So is there any way I can store the csv file content in the code itself instead of reading it from the outside?
My code:
vector<vector<double> > read_csv(const char *filename)
{
ifstream read_file(filename);
vector<vector<double> > csv_data;
std::string lineStr;
while (getline(read_file, lineStr))
{
stringstream ss(lineStr);
std::string d;
vector<double> a_line_data;
while (getline(ss, d, ','))
{
a_line_data.push_back(atof(d.c_str()));
}
csv_data.push_back(a_line_data);
}
//cout << csv_data << endl;
return csv_data;
}
This is how i print the contents:
vector<vector<double> > csv_data = read_csv("A00068.csv");
// print tests
printf("CSV:%d\n", csv_data);
printf("SIZE:%d\n", csv_data.size());
| The most obvious possiblities are ....
Hardcode the values directly in your code:
std::vector<std::vector<double>> csv_data{ { 0.2,....},{....}, ...};
Another possiblity is to include your text file as string. For details I refer you to this answer: https://stackoverflow.com/a/25021520/4117728. You basically would add some token in the beginning of the file and at the end, the linked answer suggests this:
R"=====( 0.2, 0.1, ... your numbers
... more numbers...
0.42, 3.141)====="
Then include the file like this:
std::string csv_contents =
#include "test.txt"
;
Now you have a string that you need to parse just as you had to parse the file contents before. Hence the only advantage is that now your data can be embedded with the executable instead of being placed in a seperate file. If you worry about cost of doing the parsing then you might consider the alternative mentioned first.
|
69,208,079 | 69,208,731 | After fork, execv communicates with the parent process when executing the target program | I know that the signal handler cannot be inherited when call execv in the child process of fork, so I wonder if the execv process can be piped to communicate with the parent process.
As far as I know, pipe communication requires parenthood or a common ancestor. But I don't know if the pipe mechanism still works in execv.
Here's what I'm trying to do:
Contains an breakpoint signal in the target program execv will execute.Is it possible that I want to be able to tell the parent process this message when a breakpoint is triggered? What can I do with it?
| I'm not sure if I fully understand your question, but I think you're trying to set up signal handlers in the child process, then call execv, with your signals handlers still ready ?
You can't.
Upon calling execv, the calling process is replaced by the executed program. Your file descriptor manipulation are preserved by default, so you can pipe stdout or stderr to wherever you want(file, parent stdin, ...) but everything else is wiped.
execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded. The program invoked inherits the calling process's PID, and any open file descriptors that are not set to close on exec. Signals pending on the calling process are cleared. Any signals set to be caught by the calling process are reset to their default behaviour. The SIGCHLD signal (when set to SIG_IGN) may or may not be reset to SIG_DFL.
EDIT: So read the history of your question (why did you edited it ? I was much clearer, imo). But you should take a look at the ptrace syscall (on linux, don't know the equivalent on windows)
|
69,208,445 | 69,208,571 | Is there a way to call a template constructor from a specialized constructor? | Lets say I have this class:
template <class T>
class Test
{
Test(T* x);
const T* const t;
int i{0};
};
I want t to always be initialized with x:
template <class T> Test<T>::Test(T* x) : t{x} {}
And I have two specializations:
template <> Test<Foo>::Test(Foo* x) : t{x} { i = 1; }
template <> Test<Bar>::Test(Bar* x) : t{x} { i = 2; }
Next, I'm extending the class with some other stuff, and that first (templated) constructor does a lot more than just setting t.
All things that I want to do for both T = Foo and T = Bar.
Is there some way that I can call the templated constructor from the specialized constructors?
//This does not work, since it will create a delegation cycle
template <> Test<Foo>::Test(Foo* x) : Test(x) { i = 1; }
template <> Test<Bar>::Test(Bar* x) : Test(x) { i = 2; }
| You can use a delegating constructor for this.
You can create a private constructor, that takes the pointer for t, and an int for i. Then you can use that to set x and i, and run all of the shared code.
That would look like:
template <class T>
class Test
{
public:
Test(T* x) : Test(x, 0) { /*code for default case, runs after delegate*/ }
private:
Test(T* t, int i) : t(t), i(i) { /*code to run for everything*/ }
const T* const t;
int i;
};
template <> Test<Foo>::Test(Foo* x) : Test(x, 1) { /*code only for Foo, runs after delegate*/ }
template <> Test<Foo>::Test(Bar* x) : Test(x, 2) { /*code only for Bar, runs after delegate*/ }
Can the delegate constructor be the generic/templated constructor (with the same signature as the specific, specialized constructors for Foo and Bar)?
No, that isn't possible. When you specialize a function template, you aren't creating a new function, but instead specifying that if T gets deduced to the type you specify in the specialization, then use the specialization definition in place of the generic one.
That is why I have "all three constructors" (the generic and the two specializations) call Test(T* t, int i), which handles the code that is shared by all cases.
|
69,208,473 | 69,208,801 | How to enter commands/(SSH password) within the output of a command when using system() in C++? | My objective is to connect to an ssh server and enter commands automatically using c++ and system. When running:
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main()
{
string user = "user";
string forwarded = "0.tcp.ngrok.io";
string port = "00000";
string command = "ssh "+user+ "@" +forwarded+ " -p "+port;
system(command.c_str());//connects to ssh server
system("password");//Would like to enter pass within the output of ssh
}
It only enter first command and only after exiting the ssh it enters the password (as a command).
Is it possible to add the password within the ssh command (maybe with popen) ?
After that, will it be able to enter commands into the ssh server?
| No, you can not.
But perhaps you can use std::cin and std::cout for that, which I would NOT recommend.
I assume you are looking for a library similar to paramiko which is, however, in python.
|
69,208,576 | 69,208,752 | How to search a substring of a LPWSTR? | Is there any function that is used for searching a substring of LPWSTR?
LPWSTR a_string = _T("abcdef");
if (a_string .find(L"def") != std::string::npos)
{
}
| That initialization of a_string is invalid, LPWSTR can't be initialized pointing to a string literal, you need LPCWSTR.
This being a glorified pointer to wchar_t, or more accurately a macro that will end up expanding to wchar_t*, it does not have member methods, it is not a class like std::string. You will need to do it another way, like the one pointed out by Dialecticus, example:
LPCWSTR a_string = L"abcdef";
// or better yet
// auto a_string = L"abcdef";
if (wcsstr(a_string, L"def"))
{
//...
}
You can avoid this altogether, if possible, by using std::wstring like pointed out by Panagiotis Kanavos in the comment bellow.
|
69,209,070 | 69,209,828 | Is there some std::count_if() for counting multiple different properties in a single scan? | Is there some std::count_if-like function for counting multiple different properties in a single scan?
E.g. it might expect a tuple of function objects and return a tuple of ptrdiff_t.
Or the passed function might return a tuple of bool.
| You can use accumulate, as suggested:
#include <array>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v{1,2,3,4,5,6,7,8,9,10};
// two properties, each returning a bool
auto constexpr is_even = [](int x){ return x % 2 == 0; };
auto constexpr is_div_by_3 = [](int x){ return x % 3 == 0; };
// the function which combines the accumulator with the current value
auto constexpr lam = [is_even, is_div_by_3](auto a, int x){
return std::array{a[0] + is_even(x),
a[1] + is_div_by_3(x)};
};
auto res = std::accumulate(v.begin(), v.end(), std::array{0,0}, lam);
std::cout << res[0] << ' ' << res[1] << std::endl; // prints 5 3
}
|
69,209,072 | 69,214,787 | Omnet++ fatal error: 'inet/common/INETDefs.h' file not found | I am trying to extent a mobility module in Inet 4.2 under Onmet++ v5.6, the issue is that I get the "fatal error: 'inet/common/INETDefs.h' file not found" error during importing the INETDefs.h file.
#ifndef CustomizedMobility_H_
#define CustomizedMobility_H_
#include "inet/common/INETDefs.h"
#include "inet/mobility/single/TractorMobility.h"
namespace inet{
class CustomizedMobility : public TractorMobility{
protected:
virtual void setTargetPosition() override;
virtual void move() override;
Coord vLastPosition;
};
}//ns inet
#endif /* CustomizedMobility_H_ */
| Solved just wright click on the project, choose properties, then under omnet++ section choose MakeMake and click on the src folder. After that choose option from the right side section. then have a look at the following figure.
|
69,209,172 | 69,209,215 | Do I need a .h for a class with only a main method in C++ | I need to create 2 classes, with their respective .h and .cc, and then another class with a main, let's call them A, B and C, being the C class the one with the main.
Given that the C class is used only to contain that main and doesn't need either instance or class variables, or other methods, do I need to create C.h or with C.cc it's enough?
| Well technically, you don't need headers ever, you could simply copy-paste declarations in every .cpp files.
If you don't need a declaration in any other file, I'd suggest this is a good practice to place it in the relevant .cpp file to keep it private. This can be couple with a namespace { ... } or declare them as static (static as in private to translation unit). This hides irrelevant details from your header code, and prevent misuse of private functions and private variable that should only be used in one .cpp file.
|
69,209,414 | 69,209,547 | How to write function with rest/spred operator (from js) on c++? | How to write such function on C++?
function executor (foo, ...args) {
return foo(...args)
}
I don't understand how to declare template on C++
| Your question is not really clear to me what you are asking, or what you are trying to do.
Here's an example of an invoke template function that calls the passed function and passes in the arguments to the function's parameters. That seems to be what your code snippet is trying to do.
The code is just for quick-and-dirty example. It is not optimal, because it is not using perfect forwarding of the arguments. Not sure what you want to do with the result of the invoked function, or handle exceptions.
#include <iostream>
using std::cout;
template <typename F, typename... Ts>
void invoke(F fn, Ts... args) {
fn(args...);
}
void print(int a, int b) {
cout << "print:" << a << " " << b << "\n";
}
void bigprint(int a, int b, int c) {
cout << "bigprint:" << a << " " << b << " " << c << "\n";
}
int main() {
invoke(print, 1, 2);
invoke(bigprint, 1, 2, 3);
}
|
69,209,713 | 69,210,181 | Converting a TCHAR to wstring | TCHAR path[_MAX_PATH+1];
std::wstring ws(&path[0], sizeof(path)/sizeof(path[0]));
or
TCHAR path[_MAX_PATH];
std::wstring ws(&path[0]);
While converting a TCHAR to wstring both are correct?
I'm asking just for clarification, I'm in doubt if I'm converting it correctly.
| The code is problematic in several ways.
First, std::wstring is a string of wchar_t (aka WCHAR) while TCHAR may be either CHAR or WCHAR, depending on configuration. So either use WCHAR and std::wstring, or TCHAR and std::basic_string<TCHAR> (remembering that std::wstring is just a typedef for std::basic_string<WCHAR>).
Second, the problem is with string length. This snippet:
WCHAR path[_MAX_PATH];
std::wstring ws(&path[0], sizeof(path)/sizeof(path[0]));
will create a string of length exactly _MAX_PATH + 1, plus a terminating null (and likely with embedded nulls, C++ strings allow that). Likely not what you want.
The other one:
WCHAR path[_MAX_PATH+1];
...
std::wstring ws(&path[0]);
expects that path holds a null-terminated string by the time ws is constructed, and copies it into ws. If path happens to be not null-terminated, UB ensues (usually, either garbage in ws or access violation).
If your path is either null-terminated or contains _MAX_PATH-length string, I suggest using it like this:
WCHAR path[_MAX_PATH+1];
... // fill up to _MAX_PATH characters
path[_MAX_PATH] = L'0'; // ensure it is null-terminated
std::wstring ws(path); // construct from a null-terminated string
Or if you know the actual length, just pass it:
WCHAR path[_MAX_PATH];
size_t length = fill_that_path(path);
std::wstring ws(path, length); // length shouldn’t include the null terminator, if any
See the docs (it’s the same for string and wstring except of different char type).
|
69,209,803 | 69,213,264 | Launch file to start ROS Services? | I created ROS Service with a client and server node. I created a ROS Service that pass the IMU sensors values from the Server to Client. And Im able to call the server and client node and get the values. But when call them with the launch file I got zero
Here the server node
#include "ros/ros.h"
#include <sensor_msgs/Imu.h>
#include "imu_service/ImuValue.h"
ros::ServiceServer service;
double current_x_orientation_s;
double get_imu_orientation_x;
bool get_val(imu_service::ImuValue::Request &req, imu_service::ImuValue::Response &res)
{
ROS_INFO("sending back response");
res.current_x_orientation_s = get_imu_orientation_x;
//.. same for the other IMU values
}
void imuCallback(const sensor_msgs::ImuConstPtr& msg)
{
current_x_orientation_s= msg->orientation.x;
get_imu_orientation_x=current_x_orientation_s;
// ..same for other IMU values
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "imu_status_server");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/thrbot/imu", 10, imuCallback);
service = n.advertiseService("imu_status_server", get_val);
ROS_INFO("Starting server...");
ros::spin();
return 0;
}
Client
#include "ros/ros.h"
#include "ros_services/ImuValue.h"
#include <cstdlib>
ros::ServiceClient client;
int main(int argc, char **argv)
{
ros::init(argc,argv,"imu_client_node");
ros::NodeHandle n;
ros::NodeHandle nh_;
//ros::Subscriber joy_sub_ = nh_.subscribe<sensor_msgs::Joy>("/thrbot/joy", 10, joystick_callback);
client = n.serviceClient<ros_services::ImuValue>("imu_status_server");
ros_services::ImuValue srv;
client.call(srv);
std::cout << "Got accel x: " << srv.response.current_x_orientation_s << std::endl;
return 0;
}
And the launch file
<?xml version="1.0"?>
<launch>
<node name="ImuServerService" pkg="ros_services" type="ImuServerService" output="screen">
</node>
<node name="ImuClientService" pkg="ros_services" type="ImuClientService" output="screen"/>
</launch>
I got 0 as response.
[ INFO] [1631800449.207350420]: Starting server...
[ INFO] [1631800449.212336478]: sending back response
Got accel x: 0
But when manually run the Server and the Client with
rosrun ros_services ImuServerService and rosrun ros_services ImuClientService the value is correct one
Any help?
| The reason you're getting 0 back is because the client immediately calls the service on startup. Since it also immediately returns the last cached value and they're both started at almost the same time via roslaunch this means there's essentially no way a message will be received on the topic by the service is called. This works with rosrun because having to manually launch the nodes gives it enough time to actually receive something on the topic. You can observe it by adding a delay to the start of your client like so:
#include "ros/ros.h"
#include "ros_services/ImuValue.h"
#include <cstdlib>
ros::ServiceClient client;
int main(int argc, char **argv)
{
ros::init(argc,argv,"imu_client_node");
ros::NodeHandle n;
ros::NodeHandle nh_;
//ros::Subscriber joy_sub_ = nh_.subscribe<sensor_msgs::Joy>("/thrbot/joy", 10, joystick_callback);
client = n.serviceClient<ros_services::ImuValue>("imu_status_server");
ros_services::ImuValue srv;
ros::Duration(5).sleep(); //Sleep for 5 seconds
client.call(srv);
std::cout << "Got accel x: " << srv.response.current_x_orientation_s << std::endl;
return 0;
}
|
69,209,842 | 69,209,929 | C++ Find & Change Value in Map | I've scoured but not finding a solution; this is part of a homework assignment so looking more for tips/explanation than outright solution.
Problem:
I am parsing a file and extracting key elements into a map. I've declared my standard non-const map as : map<label,element>. In a second phase of the program, I am needing to locate if exists in "map" and replace its value.
I'm able to find the element, and print it, but I can't seem to get it to change. It's not a constant, so it should be editable, but maybe I'm using the wrong function?
((For reference, i is a line number (19, current value stored in map), value_i is a stored int variable I'm trying to insert into my second element (current value is 0) ))
for (auto &el : labels) {
if (el.second == i) {
el.second == value_i;
std::cout << "Label " << el.first << " value changed to: " << el.second << std::endl;
}
Output:
Label n value changed to: 19
Desired Ouput:
Label n value changed to: 0
Thanks in advance!!
| you made a simple mistake which is el.second == value_i; - you didn't assign value for second, you checked if its equal value_i. If your compiler didn't give you any warning about it, I recommend setting a higher level of warnings ( you can read online on how to do it on probably every compiler), that way you won't miss such small mistakes.
If you change this line of code to:
el.second = value_i;
It will do what you desired.
|
69,209,852 | 69,211,855 | C++ How to correctly print value of templated type from module | I have a vector class inside a module:
// other_library.cpp
module;
#include <iostream>
export module mylibrary.other;
export template<class T> class Vector
{
private:
T x, y;
public:
Vector(T _x, T _y) : x(_x), y(_y) {}
void Write()
{
std::cout << "Vector{" << x << ", " << y << "}\n";
}
};
And inside main, I create a vector and print its contents:
// main.cpp
import mylibrary.other;
int main()
{
Vector<int> vec(1, 2);
vec.Write();
return 0;
}
However, I get the unexpected print to terminal:
Vector{10x55a62f2f100c20x55a62f2f100f
These are the build commands used:
g++-11 -std=c++20 -fmodules-ts -c other_library.cpp
g++-11 -std=c++20 -fmodules-ts -c main.cpp
g++-11 -std=c++20 -fmodules-ts *.o -o app
./app
Naturally, if I move the vector class to the main file the print works as expected. I know that module support is still somewhat experimental. But I would expect something simple like this to just work. But perhaps I'm doing something wrong?
EDIT:
A kind-of broken hack is to manually include iostream at the top of the main file, before importing the module, like this:
// main.cpp
#include <iostream>
import mylibrary.other;
int main()
{
Vector<int> vec(1, 2);
vec.Write();
return 0;
}
This will correctly print the contents of the Vector. But why is this necessary? The point of putting stuff in module is to avoid the trouble of header-inclusion.
Thus, my question is now two-fold.
| So it seems that there are still some challenges with modules. Example: I cannot use std::endl inside the Vector.Write member function.
A solution is to precompile the iostream standard header, which can be done like this:
g++-11 -std=c++20 -fmodules-ts -xc++-system-header iostream
The precompiled module will be stored in the gcm.cached/ directory, and will be an implicit search path for consecutive gcc-commands.
Now, I can completely avoid including the standard header, so the library file will look like this now:
// other_library.cpp
export module mylibrary.other;
import <iostream>;
export template<class T> class Vector
{
private:
T x, y;
public:
Vector(T _x, T _y) : x(_x), y(_y) {}
void Write()
{
std::cout << "Vector{" << x << ", " << y << "}"
<< std::endl;
}
};
And I don't need to do anything further in the main file - simply importing my library module is sufficient.
A big thank you to Šimon Tóth for writing about this in his article on modules.
|
69,210,118 | 69,215,395 | Linking .res file with an Executable (CMake) | i've been trying to link compiled .res file with CMake for some time, i searched internet but there is no much info bout it.
I tried adding this into my CMakeList.txt
SET(RESOURCE_FILE scac.res)
file(GLOB src_files
"${RESOURCE_FILE}"
ADD_EXECUTABLE( FOO ${FOO_SRCS} )
TARGET_LINK_LIBRARIES( FOO ${FOO_LIBS} )
SET( FOO_LINKFLAGS ${CMAKE_CURRENT_SOURCE_DIR}/modules/scac-module/scac.res )
SET_TARGET_PROPERTIES( FOO PROPERTIES LINK_FLAGS ${FOO_LINKFLAGS} )
)
.res file contains VERSIONINFO and also ICON, CMAKE doesn't give any error after compiling, and . res file is also succesfully compiled without any error, but simply version info doesn't show on application
Note: I don't have much experience with cmake, problem may be simple, or complicated
Thanks for your time, and help.
| After 6 hours, problem is solved just added "${CMAKE_CURRENT_SOURCE_DIR}/res.rc" into line
add_executable(${EXAMPLE_TARGET} ${EXAMPLE_HEADER_FILES} ${EXAMPLE_INLINE_FILES} "examples/${EXAMPLE_SOURCE_FILE}"
to finally get
add_executable(${EXAMPLE_TARGET} ${EXAMPLE_HEADER_FILES} ${EXAMPLE_INLINE_FILES} "examples/${EXAMPLE_SOURCE_FILE}" "${CMAKE_CURRENT_SOURCE_DIR}/resource.rc"
|
69,210,212 | 69,210,494 | Double linked list in Data Structures and Algorithms in c++ | So i saw this code fragment in Data Structures and Algorithm in c and c++:
class DLinkedList { // doubly linked list
public:
DLinkedList(); // constructor
~DLinkedList(); // destructor
bool empty() const; // is list empty?
const Elem& front() const; // get front element
const Elem& back() const; // get back element
void addFront(const Elem& e); // add to front of list
void addBack(const Elem& e); // add to back of list
void removeFront(); // remove from front
void removeBack(); // remove from back
private: // local type definitions
DNode* header; // list sentinels
DNode* trailer;
protected: // local utilities
void add(DNode* v, const Elem& e); // insert new node before v
void remove(DNode* v); // remove node v
};
and my question is: why are the member functions add() and remove() protected (and when I should use the keyword protected)
edit: DNode is defined here:
typedef string Elem; // list element type
class DNode { // doubly linked list node
private:
Elem elem; // node element value
DNode* prev; // previous node in list
DNode* next; // next node in list
friend class DLinkedList; // allow DLinkedList access
};
| you use protected when you don't want the API to view certain methods but do want to access the method from the class and its subclasses(outside or within package) and classes from the same package
the reason add() and remove() are protected is to provide data abstraction and to prevent unauthorized personnel from using these functions
|
69,210,475 | 69,215,787 | Using std::span with buffers - C++ | I am exploring a possibly safer and more convenient way to handle buffers, either with
fixed size known at compile time
size known at runtime
What is the advice of using static extent vs dynamic extent? The answer may seem obvious but I got confused when testing with examples below. It looks like I can manipulate extent by my own choice by choosing how I initialize the span. Any thoughts about the code examples? What are the correct ways to initialize the span in the examples?
Note that even if the examples use strings the normal use should be uint8_t or std::byte. The Windows and MS compiler specifics are not crucial.
edit:
Updated code
#define _CRTDBG_MAP_ALLOC
#define _CRTDBG_MAP_ALLOC_NEW
// ... includes
#include <cstdlib>
#include <crtdbg.h>
enum appconsts : uint8_t { buffersize = 0xFF };
HRESULT __stdcall FormatBuffer(std::span<wchar_t/*, appconsts::buffersize*/> buffer) noexcept
{
_RPTFN(_CRT_WARN, "FormatBuffer with size of buffer=%d, threadid=0x%8.8X\n", buffer.size(), ::GetCurrentThreadId());
errno_t er = swprintf_s(buffer.data(), buffer.size(), L"test of buffers with std::span, buffer size: %zu", buffer.size());
return er > 0 ? S_OK : E_INVALIDARG;
}
extern "C" int32_t __cdecl
wmain([[maybe_unused]] _In_ int32_t argc,[[maybe_unused]] _In_reads_(argc) _Pre_z_ wchar_t* argv[])
{
_RPTFN(_CRT_WARN, "Executing main thread, argc=%d, threadid=0x%8.8X\n", argc, ::GetCurrentThreadId());
int32_t ir = 0;
wchar_t buffer1[appconsts::buffersize];
ir = FormatBuffer(buffer1);
wchar_t* buffer2 = new wchar_t[appconsts::buffersize];
ir = FormatBuffer(std::span<wchar_t/*, appconsts::buffersize*/>(buffer2, appconsts::buffersize));
delete[] buffer2;
std::unique_ptr<wchar_t[]> buffer3 = std::make_unique<wchar_t[]>(appconsts::buffersize);
ir = FormatBuffer(std::span<wchar_t/*, appconsts::buffersize*/>(buffer3.get(), appconsts::buffersize));
std::vector<wchar_t> buffer4(appconsts::buffersize);
ir = FormatBuffer(std::span<wchar_t/*, appconsts::buffersize*/>(buffer4/*, appconsts::buffersize*/));
_CrtDumpMemoryLeaks();
return ir;
}
New code
Things get a bit clearer with a new version of the example. To get static extent, the size needs to be set in FormatBuffer and only the fixed buffer1 will fit. The cppreference text is a bit confusing. The following is giving dynamic extent.
enum appconsts : uint8_t { buffersize = 0xFF };
HRESULT __stdcall FormatBuffer(std::span<wchar_t/*, appconsts::buffersize*/> buffer) noexcept
{
_RPTFN(_CRT_WARN, "FormatBuffer with size of buffer=%d, span extent=%d, threadid=0x%8.8X\n",
buffer.size(), buffer.extent == std::dynamic_extent ? -1 : buffer.extent, ::GetCurrentThreadId());
errno_t er = swprintf_s(buffer.data(), buffer.size(), L"test of buffers with std::span, buffer size: %zu", buffer.size());
return er > 0 ? S_OK : E_INVALIDARG;
}
HRESULT __stdcall CreateBuffer(size_t runtimesize) noexcept
{
_RPTFN(_CRT_WARN, "CreateBuffer with runtime size of buffer=%d, threadid=0x%8.8X\n", runtimesize, ::GetCurrentThreadId());
HRESULT hr = S_OK;
wchar_t buffer1[appconsts::buffersize]{};
hr = FormatBuffer(buffer1);
std::unique_ptr<wchar_t[]> buffer3 = std::make_unique<wchar_t[]>(runtimesize /*appconsts::buffersize*/);
hr = FormatBuffer(std::span<wchar_t/*, runtimesize*/>(buffer3.get(), runtimesize));
std::vector<wchar_t> buffer4(appconsts::buffersize);
hr = FormatBuffer(std::span<wchar_t/*, appconsts::buffersize*/>(buffer4/*, appconsts::buffersize*/));
return hr;
}
extern "C" int32_t __cdecl
wmain([[maybe_unused]] _In_ int32_t argc,[[maybe_unused]] _In_reads_(argc) _Pre_z_ wchar_t* argv[])
{
_RPTFN(_CRT_WARN, "Executing main thread, argc=%d, threadid=0x%8.8X\n", argc, ::GetCurrentThreadId());
//(void)argc;(void)argv;
int32_t ir = 0;
ir = CreateBuffer(static_cast<size_t>(argc) * appconsts::buffersize);
return ir;
}
| (the part on runtime error was removed from the question)
In a nutshell: use dynamic extent, and initialize in the simplest way, like:
wchar_t buffer1[appconsts::buffersize];
ir = FormatBuffer(buffer1);
wchar_t* buffer2 = new wchar_t[appconsts::buffersize];
ir = FormatBuffer({buffer2, appconsts::buffersize}); // won’t compile without the size
delete[] buffer2;
std::unique_ptr<wchar_t[]> buffer3 = std::make_unique<wchar_t[]>(appconsts::buffersize);
ir = FormatBuffer({buffer3.get(), appconsts::buffersize}); // won’t compile without the size
std::vector<wchar_t> buffer4(appconsts::buffersize);
ir = FormatBuffer(buffer4);
Out of these examples, only the first will work if the function expects a fixed-extent span (and only if that extent is exactly the same as array length). Which is good as according to the documentation, constructing a fixed-extent std::span with wrong size is an outright UB. Ouch.
Fixed-extent span is only useful if its size is a part of the API contract. Like, if your function needs 42 coefficients no matter what, std::span<double, 42> is the right way. But if your function may sensibly work with any buffer size, there is no point in hard-coding the particular size used today.
|
69,210,489 | 69,213,038 | Using base class constructor in derived class contructor | Let's say that I want to make use of base class constructor in order to create derived class objects.
This is my approach on how to do it:
class base
{
int x, y, z;
public:
base(int x, int y, int z)
:
x(x),
y(y),
z(z)
{
std::cout << "base class constructor called\n";
}
int get_x() const { return x; }
int get_y() const { return y; }
int get_z() const { return z; }
};
class derived : public base
{
int value;
public:
derived(int x, int y, int z, int value)
:
base(x, y, z),
value(value)
{
std::cout << "derived class constructor called\n";
};
int get_val() const { return value; } ;
};
My question: Is this the correct way of solving that problem? Or, is there some better approach on how to use base class constructor in derived class constructor?
| Adding an appropriate base class constructor 'call' in the initialization list for your derived class constructor is perfectly acceptable and normal. (In fact, for the example that you've shown, omitting that constructor from the initialization list will cause the code to be ill-formed: the compiler will then attempt to default-construct the the base object and, since you have specified an explicit, argument-taking constructor, the default constructor for your base class is deleted.)
One thing to note, however, is that that base class constructor will be executed first, even if you rearrange the specification order in that initialization list.
Take the slightly modified code below:
class derived : public base {
int value;
public:
derived(int x_, int y_, int z_, int value_) // IMHO, using argument names same as members not good
:
value(value_), // Rearrange list to have this appear first ...
base(x_, y_, z_) // ...but this is STILL called before the above
{
std::cout << "derived class constructor called\n";
} // Note: Unnecessary semicolon after function (as also after getter).
int get_val() const { return value; } // ; unnecessary
};
For this code, clang-cl gives this:
warning : field 'value' will be initialized after base 'base'
[-Wreorder-ctor]
And MSVC gives:
warning C5038: data member 'derived::value' will be initialized after
base class 'base'
|
69,210,553 | 69,211,443 | How do I change variables in main function that are in a struct? | I'm quite new to C++ and coding in general and I have been stuck on this bug for forever it seems.
My eventual goal is to create a tic-tac-toe algorithm but at the moment I am having an issue with using struct variables outside of the struct.
I have tried using classes and structs, using static etc., I know I am missing something I just don't know what it is.
Heres the code, it's not exactly beautiful but I'm pretty sure it should work.
#include <iostream>
#include <string>
int userResponse;
//Class to monitor board positions
struct boardPos
{
bool Pos1 = 0;
bool Pos2 = 0;
bool Pos3 = 0;
bool Pos4 = 0;
bool Pos5 = 0;
bool Pos6 = 0;
bool Pos7 = 0;
bool Pos8 = 0;
bool Pos9 = 0;
};
//Changing bool values
void boolChange()
{
if (userResponse == 1)
{
boardPos::Pos1 = 1;
}
if (userResponse == 2)
{
boardPos::Pos2 = 1;
}
if (userResponse == 3)
{
boardPos::Pos3 = 1;
}
if (userResponse == 4)
{
boardPos::Pos4 = 1;
}
}
//std::string A, B, C, D, E, F, G, H, I
int main()
{
//Variable to Print Position Board
std::string posBoard = "\n 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9\n";
std::cout << posBoard;
std::cout << "Enter Position Number\n";
std::cin >> userResponse;
}
| I have made some changes and below is the complete working program. You can see that depending on the user input the corresponding Pos data member is changed.
#include <iostream>
#include <string>
//Class to monitor board positions
struct boardPos
{
bool Pos1 = 0;
bool Pos2 = 0;
bool Pos3 = 0;
bool Pos4 = 0;
bool Pos5 = 0;
bool Pos6 = 0;
bool Pos7 = 0;
bool Pos8 = 0;
bool Pos9 = 0;
};
//Changing bool values
void boolChange(int userResponse, boardPos &tempbPos)
{
if (userResponse == 1)
{
tempbPos.Pos1 = 1;
}
if (userResponse == 2)
{
tempbPos.Pos2 = 1;
}
if (userResponse == 3)
{
tempbPos.Pos3 = 1;
}
if (userResponse == 4)
{
tempbPos.Pos4 = 1;
}
}
int main()
{
int userResponse;
//create struct variable/object whose data member you want to change
boardPos bPos;
//lets check the pos member values before calling the function boolChange. Note all Pos members are 0
std::cout<<"pos1: "<<bPos.Pos1<<" pos2: "<<bPos.Pos2<<" pos3: "<<bPos.Pos3<<" pos4: "<<bPos.Pos4<<std::endl;
//Variable to Print Position Board
std::string posBoard = "\n 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9\n";
std::cout << posBoard;
std::cout << "Enter Position Number\n";
std::cin >> userResponse;
boolChange(userResponse, bPos);//note here we have passed bPos by reference
//lets check if the pos member is changed. Now since we have called boolChange(), note corresponding Pos member value has changed
std::cout<<"pos1: "<<bPos.Pos1<<" pos2: "<<bPos.Pos2<<" pos3: "<<bPos.Pos3<<" pos4: "<<bPos.Pos4<<std::endl;
}
|
69,211,027 | 69,214,336 | Problem with multi-threading and waiting on events | I have a problem with my code:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <windows.h>
#include <string.h>
#include <math.h>
HANDLE event;
HANDLE mutex;
int runner = 0;
DWORD WINAPI thread_fun(LPVOID lpParam) {
int* data = (int*)lpParam;
for (int j = 0; j < 4; j++) { //this loop necessary in order to reproduce the issue
if ((data[2] + 1) == data[0]) { // if it is last thread
while (1) {
WaitForSingleObject(mutex, INFINITE);
if (runner == data[0] - 1) { // if all other thread reach event break
ReleaseMutex(mutex);
break;
}
printf("Run:%d\n", runner);
ReleaseMutex(mutex);
Sleep(10);
}
printf("Check Done:<<%d>>\n", data[2]);
runner = 0;
PulseEvent(event); // let all other threads continue
}
else { // if it is not last thread
WaitForSingleObject(mutex, INFINITE);
runner++;
ReleaseMutex(mutex);
printf("Wait:<<%d>>\n", data[2]);
WaitForSingleObject(event, INFINITE); // wait till all other threads reach this stage
printf("Exit:<<%d>>\n", data[2]);
}
}
return 0;
}
int main()
{
event = CreateEvent(NULL, TRUE, FALSE, NULL);
mutex = CreateMutex(NULL, FALSE, NULL);
SetEvent(event);
int data[3] = {2,8}; //0 amount of threads //1 amount of numbers
HANDLE t[10000];
int ThreadData[1000][3];
for (int i = 0; i < data[0]; i++) {
memcpy(ThreadData[i], data, sizeof(int) * 2); // copy amount of threads and amount of numbers to the threads data
ThreadData[i][2] = i; // creat threads id
LPVOID ThreadsData = (LPVOID)(&ThreadData[i]);
t[i] = CreateThread(0, 0, thread_fun, ThreadsData, 0, NULL);
if (t[i] == NULL)return 0;
}
while (1) {
DWORD res = WaitForMultipleObjects(data[0], t, true, 1000);
if (res != WAIT_TIMEOUT) break;
}
for (int i = 0; i < data[0]; i++)CloseHandle(t[i]); // close all threads
CloseHandle(event); // close event
CloseHandle(mutex); //close mutex
printf("Done");
}
The main idea is to wait until all threads except one reach the event and wait there, meanwhile the last thread must release them from waiting.
But the code doesn't work reliably. 1 in 10 times, it ends correctly, and 9 times just gets stuck in while(1). In different tries, printf in while (printf("Run:%d\n", runner);) prints different numbers of runners (0 and 3).
What can be the problem?
| As we found out in the comments section, the problem was that although the event was created in the initial state of being non-signalled
event = CreateEvent(NULL, TRUE, FALSE, NULL);
it was being set to the signalled state immediately afterwards:
SetEvent(event);
Due to this, at least on the first iteration of the loop, when j == 0, the first worker thread wouldn't wait for the second worker thread, which caused a race condition.
Also, the following issues with your code are worth mentioning (although these issues were not the reason for your problem):
According to the Microsoft documentation on PulseEvent, that function should not be used, as it can be unreliable and is mainly provided for backward-compatibility. According to the documentation, you should use condition variables instead.
In your function thread_fun, the last thread is locking and releasing the mutex in a loop. This can be bad, because mutexes are not guaranteed to be fair and it is possible that this will cause other threads to never be able to acquire the mutex. Although this possibility is mitigated by you calling Sleep(10); once in every loop iteration, it is still not the ideal solution. A better solution would be to use a condition variable, so that the thread only checks for changes of the variable runner when another thread actually signals a possible change. Such a solution would also be better for performance reasons.
|
69,211,303 | 69,211,459 | Why does the following program - passing c string to function - not produce the desired output? | I have a simple question C++ (or C).
Why does the following program, passing c string to function, not produce the desired output?
#include <cstdio>
#include <cstring>
void fillMeUpSomeMore( char** strOut )
{
strcpy( *strOut, "Hello Tommy" );
}
int main()
{
char str[30];
//char* strNew = new char[30];
fillMeUpSomeMore( (char**) &str ); // I believe this is undefined behavior but why?
//fillMeUpSomeMore( (char**) &strNew ); // this does work
std::printf( "%s\n", str );
//std::printf( "%s\n", strNew ); // prints "Hello Tommy"
//delete[] strNew;
}
All I'm doing is passing the address of the char array str to a function taking pointer to pointer to char (which after the explicit conversion should be just fine).
But then the program prints nothing.
However this will work with the strNew variable that has been dynamically allocated.
I know that I shouldn't be doing this and be using std::string instead. I'm only doing this for study purposes. Thanks.
I'm compiling with g++ & C++17 (-std=c++17).
| char ** is a pointer to a pointer to a character. This means, if it is not a null pointer, it should be the address of some place in memory where there is a pointer.
char str[30] defines an array of 30 char. &str is the address of that array. There is no pointer there, just 30 char. Therefore, &str is not a char **.
So (char**) &str is bad. It tells the compiler to treat the address of the array as if it were the address of a pointer. That is not going to work.
If you instead use char *strNew = new char[30];, that says strNew is a pointer, which is initialized with the address of the first char of an array of 30 char. Then, since strNew is a pointer, &strNew is the address of a char *, so it is a char **, and (char **) &strNew is not wrong.
Generally, you should avoid casts and pay attention to compiler warnings. When the compiler tells you there is a problem with types, work to understand the problem and to fix it by changing the types or expressions involved, rather than by using a cast.
|
69,212,169 | 69,212,191 | How does happen the destruction of variables with a goto statement in C++? | #include <iostream>
using namespace std;
int main() {
if (true) {
int b = 3;
label_one:
cout << b << endl;
int j = 10;
goto label_one;
}
}
In the code above goto jumps to label_one, making the variable j be destroyed and reconstructed in each cycle. But what happens to the b variable ? Is it destroyed and reconstructed too or it is never destroyed? According to C++ ISO:
Transfer out of a loop, out of a block, or back past an initialized
variable with automatic storage duration involves the destruction of
objects with automatic storage duration that are in scope at the point
transferred from but not at the point transferred to.
My interpretation is that all variables in if scope should be destroyed, but if thats the case, when are they re-initialized(variable b in my code)?
| As the quoted text says, a variable is destroyed during the goto only if it is in scope at the point of the goto statement, but not in scope at the destination label. b is in scope at both points, so it is not destroyed. Only j is destroyed.
|
69,212,217 | 69,212,342 | How Can I Write a C++ Template Which is Inferred From a Function Argument? | I'm trying to write a C++ function which generates a vector from two calls to an argument function. The argument function accepts an integer pointer and a pointer to an array of elements. If called with nullptr for elements, it will fill the integer with how many elements it has to produce. Then on the second call, it will populate the element memory with that many instances.
So, this pattern can be used to get a vector of elements. I'm repeating this code a lot so I wrote a function which does this for me:
template<typename TElement>
std::vector<TElement> LoadArray(std::function<void(uint32_t*, TElement*)> const func) {
uint32_t count;
func(&count, nullptr);
std::vector<TElement> elements(count);
func(&count, elements.data());
return elements;
}
However, when calling this function, I have to specify TElement in the template as well as the function:
std::vector<Cat> cats = LoadArray<Cat>([](uint32_t* const count, Cat* const cats) {
LoadCats(count, cats);
});
How can I make this type inference automatic in C++20?
Edit: All of the functions have different signatures. Some have return types, others don't; some take an argument before the count and array, some take arguments after.
| A simple-ish way to do this is to delay the lookup until you are within the function by having it return auto.
Something along these general lines:
// The stolen function_traits struct...thing
template<typename T>
struct load_array_cb_traits;
template<typename Ret, typename Arg2>
struct load_array_cb_traits<std::function<Ret(uint32_t*, Arg2*)>> {
using return_type = Ret;
using elem_type = Arg2;
};
template<typename FuncT>
auto LoadArray(const FuncT& func) {
using traits = load_array_cb_traits<decltype(std::function{func})>;
using TElement = std::decay_t<typename traits::elem_type>;
using TRet = std::decay_t<typename traits::return_type>;
uint32_t count;
func(&count, nullptr);
std::vector<TElement> elements(count);
func(&count, elements.data());
return elements;
}
|
69,213,150 | 69,213,872 | std::vector of Derived class instances whose Bases contain a (raw) pointer | Say I had the following structure
class BaseKernel {
// .......
}
class DerivedKernel : public BaseKernel {
// .......
}
class A {
public:
A(BaseKernel* kernel) : kernel(kernel) {}
A(const A& a) : kernel(a.kernel) {}
~A() {delete kernel;}
BaseKernel* kernel;
}
class B : public A {
public:
B(BaseKernel* kernel) : A(kernel) {}
B(const B& b) : A(b) {}
~B() = default;
}
class C : public B {
public:
C() = default;
C(BaseKernel* kernel) : B(kernel) {}
C(const C& c) : B(c) {}
~C() = default;
}
class D {
public:
D() = default;
D(std::vector<C> collection) : collection(collection) {}
std::vector<C> collection;
}
class E {
public:
E(std::vector<D> dollection) : dollection(dollection) {} // lmfao, dollection for the lack of a better word
std::vector<D> dollection;
}
With the following usage
BaseKernel* kernel1 = new DerivedKernel(...);
BaseKernel* kernel2 = new DerivedKernel(...);
C c_obj1(kernel1);
C c_obj2(kernel2);
std::vector<C> collection1(1, c_obj1);
std::vector<C> collection2(1, c_obj2);
std::vector<D> dollections = {collection1, collection2};
// At this point kernel1 and kernel2 are deleted.
E e_obj(dollections) // Useless now
As im relatively new to C++ and therefore unfamiliar with smart pointers (i believe the solution is with the latter, however), how would I handle such a case with raw pointers? (Better yet, a solution using the appropriate smart pointer would be great)
The initialization of c_obj1 and c_obj2 were fine (kernel1 and kernel2 still lives), but specifically for dollections I would need to initialize the vector with brackets (as I would have different collections) and after debugging it first goes through the copy constructors then ultimately the destructor ~A()?
| I see some problems. I'll see if I can understand your real question. Let's start with this:
class A {
public:
A(BaseKernel* kernel) : kernel(kernel) {}
A(const A& a) : kernel(a.kernel) {}
~A() {delete kernel;}
BaseKernel* kernel;
}
This is bad. If you use your copy constructor, you'll end up deleting the same data twice. Imagine this:
BaseKernel * k = new BaseKernel();
A first(k);
A second(first);
This this point, both first.kernel and second.kernel point to k. Now, when they go out of scope, both destructors will attempt to delete their kernel pointer, so k will get deleted twice.
I don't quite understand the question you're asking. However, I discourage the use of raw pointers and encourage smart pointers. std::unique_ptr is more efficient, but I tend to always use std::shared_ptr as follows:
class A {
public:
A(std:: shared_ptr <BaseKernel> kernelIn) : kernel(kernelIn) {}
A(const A& a) : kernel(a.kernel) {}
~A() { /* Nothing needed */ }
std:: shared_ptr <BaseKernel> kernel;
};
Then later...
std::shared_ptr<BaseKernel> kernel1 = std::make_shared<DerivedKernel>(...);
You'll probably need to do a dynamic_pointer_cast, though. I usually don't like using the datatype I'm pointing to so would normally not do it here but instead:
std::shared_ptr< DerivedKernel> kernel1 = std::make_shared<DerivedKernel>(...);
And then dynamic_pointer_cast it as necessary later.
I'm not sure if this gets you further.
|
69,213,287 | 69,215,058 | merge sort algorithm: std::out_of_range | I am currently making a merge sort algorithm but when i run the code i get an error says "terminate called after throwing an instance of 'std::out_of_range". This is my code.
template<typename T>
void merge(std::vector<T> &vec, int l, int m, int r){
int i = l;
int j = m + 1;
int k = l;
//CREATE TEMPORARY MEMORY
int temp[vec.size()];
while(vec.at(i) <= m && j <= r){
if(vec.at(i) <= vec.at(j)){
temp[k] = vec.at(i);
i++;
k++;
}else{
temp[k] = vec.at(j);
j++;
k++;
}
}
while (i <= m){ //first half: Copy the remaining elements of first half, if there are any
temp[k] = vec.at(i);
i++;
k++;
}
while (j <= r){ //second half: Copy the remaining elements of second half, if there are any
temp[k] = vec.at(j);
j++;
k++;
}
for(size_t p = 1; p <= r; p++){ //copy temp array to original array
vec.at(p) = temp[k];
}
}
Merge Sort Function
template<typename T>
void mergeSort(std::vector<T> &vec, int l, int r){
if(l < r){
int m = (l + r) / 2; //find midpoint
mergeSort(vec, l, m); //first half
mergeSort(vec, m + 1, r); //second half
merge(vec, l, m, r); // merge
}
}
| A few issues in your merge function (which you can spot easily through debugging):
vec.at(i) <= m compares a value with an index. These two are unrelated. So change:
while(vec.at(i) <= m && j <= r){
with:
while(i <= m && j <= r){
The final loop starts with p = 1 which is an index that in many cases is out of the range that is being merged. So change:
for(size_t p = 1; p <= r; p++){
with:
for(size_t p = l; p <= r; p++){
The body of that same loop uses k as index, but that variable is unrelated to the loop, and has a value that is out of the range that is under consideration. So change:
vec.at(p) = temp[k];
with:
vec.at(p) = temp[p];
With those changes your code will work.
However, it is a pity that temp always has the size of the complete vector, while you only use a subsection of it. Consider reducing the memory usage.
|
69,213,313 | 69,213,430 | Pointer to a Superclass object may serve as pointers to subclass objects. But can't call memeber functions of the subclass. why? | I am enrolled in a C++ course, where i have the following code snippet:
class Pet {
protected:
string name;
public:
Pet(string n)
{
name = n;
}
void run()
{
cout << name << ": I'm running" << endl;
}
};
class Dog : public Pet {
public:
Dog(string n) : Pet(n) {};
void make_sound()
{
cout << name << ": Woof! Woof!" << endl;
}
};
class Cat : public Pet {
public:
Cat(string n) : Pet(n) {};
void make_sound()
{
cout << name << ": Meow! Meow!" << endl;
}
};
int main()
{
Pet *a_pet1 = new Cat("Tom");
Pet *a_pet2 = new Dog("Spike");
a_pet1 -> run();
// 'a_pet1 -> make_sound();' is not allowed here!
a_pet2 -> run();
// 'a_pet2 -> make_sound();' is not allowed here!
}
I'm not able to figure out why this is invalid. Please suggest suitable references for this that have ample explanation about why this is happening.
| In C++, the types and names of variables at any point is what the compiler permits itself to know.
Each line of code is checked against the types and names of variables in the current scope.
When you have a pointer to a base class, the type of the variable remains pointer to the base class. The actual object it is pointing at could be a derived class, but the variable remains a pointer to the base class.
Pet *a_pet1 = new Cat("Tom");
a_pet1 -> run();
// 'a_pet1 -> make_sound();' is not allowed here!
the type of a_pet1 is Pet*. It may be pointing at an actual Cat object, but that is not information that the type of a_pet1 has.
On the next line, you are using a_pet1. You can only use it in ways that are valid for a Pet pointer on this line. a_pet1->make_sound() is not a valid operation on a Pet pointer, because the Pet type does not have a make_sound method.
You could do this:
Cat *a_pet1 = new Cat("Tom");
a_pet1 -> run();
a_pet1 -> make_sound(); // it now works!
because we changed the type of a_pet1 from Pet* to Cat*. Now the compiler permits itself to know that a_pet1 is a Cat, so calling Cat methods is allowed.
If you don't want to change the type of a_pet1 (which is a reasonable request), that means you want to support make_sound on a Pet, you have to add it to the type Pet:
class Pet {
protected:
string name;
public:
Pet(string n)
{
name = n;
}
void make_sound();
void run()
{
cout << name << ": I'm running" << endl;
}
};
now, a_pet1->make_sound() will be allowed. It will attempt to call Pet::make_sound, which is not Dog::make_sound, and as we didn't provide a definition for Pet::make_sound, this will result in an error at link time.
If you want Pet::make_sound to dispatch to its derived methods, you have to tell the compiler this is what you want. C++ will write the dispatch code for you if you use the virtual keyword properly, like this:
class Pet {
protected:
string name;
public:
Pet(string n)
{
name = n;
}
virtual void make_sound() = 0;
void run()
{
cout << name << ": I'm running" << endl;
}
};
here I both made make_sound virtual, and made it pure virtual. Making it virtual means that the compiler adds information to each Pet and Pet derived object so, when it is actually pointing to a derived object type and not a Pet, the caller can find the right derived method.
Pure virtual (the =0) simply tells the compiler that the base class method Pet::make_sound intentionally has no implementation, which also means that nobody is allowed to create a Pet, or a even Pet derived object instance, without providing a make_sound implementation for its actual type.
Finally, note that I mentioned "permits itself to know". The compiler limits what it knows at certain phases of compilation. Your statement that a_pet1 is a Pet* tells the compiler "I don't want you to assume this is a Cat, even though I put a Cat in there". At later stages of compilation, the compiler can remember that fact. Even at runtime, it is sometimes possible to determine the actual type of an object (using RTTI). The forgetting of the type of the object is both intentional and limited.
It turns out that "forced forgetting" is quite useful in a number of software engineering problems.
There are other languages where all method calls to all objects go through a dynamic dispatch system, and you never know if an object can accept a method call except by trying it at runtime. In such a language, calling make_sound on any object whatsoever would compile, and at runtime it would either fail or not depending on if the object actually has a make_sound method. C++ intentionally does not do this. There are ways to gain this capability, but they are relatively esoteric.
|
69,213,645 | 69,228,455 | how do I forward the templates arguments onto the std::make_unique when creating policy based class? | Lets assume I'm using policy based templates design pattern (see https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design).
I'm having some issue related to how would I use std::make_shared (or std::make_unique for that matter) for creating new type Bar, that has some optional template arguments.
If I don't want to change default policy, then that's no problem, simple line would work:
auto bar = std::make_unique<Bar>();
However if I want Bar accept different "policy" as template args, how can I pass them into std::make_unique ??
tried the following (with no luck):
auto bar = std::make_unique<Bar<Policy2, Policy3>>();
or:
auto bar = std::make_unique<Bar>(Policy2, Policy3);
Here are some sample code to demonstrate the problem:
// Bar.hpp
template<PolicyConcept1 T = policy1_default, PolicyConcept2 V = policy2_default>
class Bar
{
public:
Bar();
private:
// Data Members
std::unique_ptr<T> _policy1;
std::unique_ptr<V> _policy2;
};
// bar.cpp
#include "bar.hpp"
template<PolicyConcept1 T, PolicyConcept2 V>
Bar<T, V>::Bar() :
_policy1{ std::make_unique<T>() },
_policy2{ std::make_unique<V>()}
{
}
// Foo.hpp
template<PolicyConcept1 T = policy1_default, PolicyConcept2 V = policy2_default>
class Foo
{
public:
Foo();
private:
// Data Members
std::unique_ptr<Bar> _bar;
};
#include "Foo.hpp"
template<PolicyConcept1 T, PolicyConcept2 V>
Foo<T, V>::Foo() :
// problem is here, how do I change the default policy and forward it into std::make_unique ??
_bar{ std::make_unique<bar>() }
{
}
The question is inside initializer of Foo CTOR:
how do I forward the T & V template arguments onto the std::make_unique ??
appreciate any help :)
| Figured this out.
It's turns out the syntax:
auto bar = std::make_unique<Bar<Policy2, Policy3>>();
works after all (on C++20, using MSVC v16.10.2).
It requires the following declaration to work:
std::unique_ptr<Bar<T,V>> _bar;
in addition I had to provide on CPP this as well (to avoid linker error):
template class Bar<concrete_policy1, concrete_policy2>;
|
69,213,753 | 69,214,034 | Understanding segmentation fault in core dump on NULL pointer check | I am having difficulty understanding how this segmentation fault is possible. The architecture of the machine is armv7l.
The core dump:
Dump of assembler code for function DLL_Disconnect:
0x6cd3a460 <+0>: 15 4b ldr r3, [pc, #84] ; (0x6cd3a4b8 <DLL_Disconnect+88>)
0x6cd3a462 <+2>: 00 21 movs r1, #0
0x6cd3a464 <+4>: 15 4a ldr r2, [pc, #84] ; (0x6cd3a4bc <DLL_Disconnect+92>)
0x6cd3a466 <+6>: 30 b5 push {r4, r5, lr}
0x6cd3a468 <+8>: 83 b0 sub sp, #12
0x6cd3a46a <+10>: 7b 44 add r3, pc
0x6cd3a46c <+12>: 01 91 str r1, [sp, #4]
0x6cd3a46e <+14>: 04 46 mov r4, r0
0x6cd3a470 <+16>: 9d 58 ldr r5, [r3, r2]
=> 0x6cd3a472 <+18>: 28 68 ldr r0, [r5, #0]
0x6cd3a474 <+20>: c0 b1 cbz r0, 0x6cd3a4a8 <DLL_Disconnect+72>
0x6cd3a476 <+22>: 21 46 mov r1, r4
...
0x6cd3a4b6 <+86>: 00 bf nop
0x6cd3a4b8 <+88>: 96 b6 00 00 .word 0x0000b696 <- replaced from objdump, as gdb prints as instruction
0x6cd3a4bc <+92>: 1c 02 00 00 .word 0x0000021c <- also replaced
The registers:
r0 0x0 0
r1 0x0 0
r2 0x21c 540
r3 0x6cd45b04 1825856260
r4 0x0 0
r5 0x1dddc 122332
...
sp 0x62afeb40 0x62afeb40
lr 0x72a3091b 1923287323
pc 0x6cd3a472 0x6cd3a472 <DLL_Disconnect+18>
cpsr 0x600c0030 1611399216
fpscr 0x0 0
The segmentation fault is caused when "ldr r0, [r5, #0]" tries to access the memory address pointed to by r5. In GDB I get a similar message when trying to access it in GDB:
(gdb) print *$r5
Cannot access memory at address 0x1dddc
However, all offending register values are calculated by static values. So I don't understand how the memory address is not accessible.
The source code is loaded and executed via a shared library using dlopen and dlsym:
CClient* gl_pClient = NULL;
extern "C" unsigned long DLL_Disconnect(unsigned long ulHandle)
{
CProtocol* pCProtocol = NULL;
unsigned long ulResult = ACTION_INTERNAL_ERROR;
if (gl_pClient == NULL)
{
return ACTION_API_NOT_INITIALIZED;
}
...
| The assembly code resolves the address of global variable gl_pClient using dll relocations, which are loaded using program-counter-relative addressing. Then the code loads from that address and crashes. It looks like the relocations got corrupted, so that the resolved address is invalid.
There isn't much else can be said without a reproduction.
You may like to run your program under valgrind which may report memory corruption.
|
69,214,107 | 69,214,194 | How do you declare a generic type of an expression in a `requires` constraint? | I may be asking a wrong question here, but what exactly am I doing wrong that it causes the compiler to think that the constraint I'm expecting on pop method of the stack is std::same_as<void, T>?
#include <concepts>
#include <stack>
template <typename S, typename T>
concept generic_stack = requires(S s, T t) {
s.push(t);
{ s.pop() } -> std::same_as<T>; // error seems to stem from here
};
template <typename T, generic_stack<T> S>
void compile_if_stack(S) {}
int main() {
compile_if_stack<int>(std::stack<int>{});
}
I tried std::same_as<decltype(s.pop()), T>; and it appears to work, but what I don't understand is what's wrong with the former approach.
Full error
# clang 12.0.1
$ clang++ -std=c++20 main.cpp
main.cpp:14:5: error: no matching function for call to 'compile_if_stack'
compile_if_stack<int>(std::stack<int>{});
^~~~~~~~~~~~~~~~~~~~~
main.cpp:11:6: note: candidate template ignored: constraints not satisfied [with T = int, S = std::stack<int>]
void compile_if_stack(S) {}
^
main.cpp:10:23: note: because 'generic_stack<std::stack<int>, int>' evaluated to false
template <typename T, generic_stack<T> S>
^
main.cpp:7:25: note: because type constraint 'std::same_as<void, int>' was not satisfied:
{ s.pop() } -> std::same_as<T>; // error seems to stem from here
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../include/c++/11.1.0/concepts:63:19: note: because '__detail::__same_as<void, int>' evaluated to false
= __detail::__same_as<_Tp, _Up> && __detail::__same_as<_Up, _Tp>;
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../include/c++/11.1.0/concepts:57:27: note: because 'std::is_same_v<void, int>' evaluated to false
concept __same_as = std::is_same_v<_Tp, _Up>;
^
1 error generated.
C++ compiler from GCC 11.1.0 comes up with semantically identical error message.
| This is because stack.pop() returns void, as per documented in std::stack::pop.
The constraint is not right, you should check for top instead:
template <typename S, typename T>
concept generic_stack = requires(S s, T t) {
s.push(t);
{ s.top() } -> std::same_as<T const&>;
};
|
69,214,574 | 69,215,279 | Why does std::function not work with function templates? | I am starting to work with templates and I am trying to figure out why the following does not work.
class testclass1
{
public:
template <typename...Ts>
using TFunc = std::function<void(Ts*...)>;
template <typename...Ts>
void SetFunction(TFunc<Ts...> tf)
{
// Do something
}
};
template<typename...Ts>
class testclass2
{
public:
using TFunc = std::function<void(Ts*...)>;
void SetFunction(TFunc tf)
{
// Do something
}
};
void some_function(std::string*, double*)
{
}
int main()
{
testclass1 tc1;
testclass2<std::string, double> tc2;
testclass1::TFunc<std::string, double> tf1 = some_function;
tc1.SetFunction<std::string, double>(tf1);
tc1.SetFunction<std::string, double>(testclass1::TFunc<std::string, double>{tf1});
tc2.SetFunction(some_function);
tc1.SetFunction<std::string, double>(some_function);
}
All works fine except the last version
tc1.SetFunction<std::string, double>(some_function);
which is actually what I would like to do since it has much less boilerplate and since I don't want testclass1 to require template arguments.
The last line gives the following compilation error:
No matching member function for call to 'SetFunction'
Candidate template ignored: could not match 'function<void (std::__1::basic_string *, double *, type-parameter-0-0 ...)>' against 'void ()(std::__1::basic_string *, double *)'
I don't understand what is the additional "type-parameter-0-0". Intuitively, this looks much like problems linked to an implicit *this pointer, but I don't see why TFunc would be a member function and have an implicit *this pointer (or is this linked to std::function?). Also, moving the code template <typename...Ts> using TFunc = std::function<void(Ts*...)>; outside of testclass1 does not change anything.
From browsing different related Q&As, it seems that you cannot use std::function with template functions. Is this the problem here?
Is there a way to make tc1.SetFunction<std::string, double>(some_function);work within testclass1?
Thanks in advance.
UPDATE: I'm trying to wrap my head around the explanation, I think I sort of get it but then---thinking about it---I'm still not 100% sure. Consider the following code:
template <typename...Ts>
using test_tuple = std::tuple<Ts...>;
template <typename...Ts>
void test_func(test_tuple<Ts...> tup)
{
// Do something
// e.g., PrintTuple(tup);
}
int main()
{
test_tuple<std::string, double> tt{"Hi", 3.1459f};
test_func<std::string>(tt);
}
In that case, only std::string is specified in the parameter pack and the double is deduced (so not all parameters are specified in the pack). But why does it work in this case and I don't get an error?
|
it seems that you cannot use std::function with template functions
No, the issue has nothing to do with std::function.
The problem is the failed deduction of the template parameter pack. Normally, when you specify all template arguments explicitly, no deduction is performed.
tc1.SetFunction<std::string, double>(some_function); // no deduction needed, right?
But in case of a pack, a deduction is always performed. It's because it's possible to specify some pack arguments and let the compiler deduce the rest, and there's no way to know if you specified only some or all the arguments.
But std::function<void(std::string*, double*)> can't be deduced from void(*)(std::string*, double*) (and user-defined conversions are not considered during deduction). Hence the error:
template argument deduction/substitution failed:
mismatched types 'std::function<void(Ts* ...)>' and 'void (*)(std::string*, double*)'
(note - there is no mention of "type-parameter-0-0" in GCC 11 output, so your compiler might be outdated).
Now, to fix this, we can introduce a non-deduced context to the parameter of SetFunction. Then the substitution will be performed from the provided type arguments.
For example using an identity template:
template<typename T>
struct type_identity {
using type = T;
};
class testclass1
{
public:
template <typename...Ts>
using TFunc = std::function<void(Ts*...)>;
template <typename...Ts>
void SetFunction(typename type_identity<TFunc<Ts...>>::type tf)
{
// Do something
}
};
(Live demo)
With regard to the update and the follow-up question - test_tuple parameters are happily deduced from a test_tuple argument - there's no conversion involved, it's just pattern matching. But std::function is a class, it can be constructed from a function pointer, but these are different types, so one cannot be deduced from the other.
|
69,214,646 | 69,230,979 | C++ Is it a bad idea to initialise class members by assigning them other constructor initialised class members? | I discovered a query way of initialising a class member q by assigning it to a different class member that is initialised through the constructor i:
class test{
public:
test(int c) : i(c) {
}
int i;
int q = i;
};
int main() {
std::cout << test(1).q << std::endl; //outputs 1
}
However if I swap around the order of declaration of i and q:
int q = i;
int i;
Printing out i outputs 0.
Is it a bad idea to initialise class members this way? Clearly in this example its probably easier to just add : i(c), q(c) to the constructor.
But for situations where there is a class member that rely on i e.g. some object with a constructor that takes a int (i) and has a private = operator and copy constructor might this approach be a good way of initialising that object? Or is this a bad idea and should always be avoided?
| Yes, you've outlined the conditions of failure. It's not hard to imagine someone unintentionally breaking your code due to reordering.
If you wanted to do something like this, it's best to assign both in the constructor from the input source.
test(int c) : q(c), i(c) {}
This has less confusion about initialization order and the two variables are no longer dependent.
|
69,214,921 | 69,215,089 | Array of Arrays for use in a For loop | array<string, 7> month31={"January","March","May","July","August","October","December"};
array<string, 4> month30 ={"April","June","September","November"};
array<string, 1> month29 = {"February"};
array<string, 1> month28 = {"February"};
array<string, 4> months= {month31,month30,month29,month28};
I know in python this would work but it keeps crashing. Is there a syntax I am missing?
End goal is to use a for loop to move between the arrays, but if I can't figure that out in time I will have to hard code it all and that will be a pain.
| You'll likely be better off using std::vector<std::string> for your (individual) month lists and then a std::array< std::vector<string> > for your composite (note that a std::array of std::array<string, n> would require the element arrays to all be the same length).
Here's a short, illustrative example:
#include <iostream>
#include <string>
#include <array>
#include <vector>
int main()
{
std::vector<std::string> month31 = { "January","March","May","July","August","October","December" };
std::vector<std::string> month30 = { "April","June","September","November" };
std::vector<std::string> month29 = { "February" };
std::vector<std::string> month28 = { "February" };
// The composite list can be a container of the above vector types ...
std::array< std::vector<std::string>, 4 > months = { month31, month30, month29, month28 };
for (auto& vec : months) { // Take REFERENCES (&) to avoid copying.
std::cout << "--- Next List... ---" << std::endl;
for (auto& month : vec) {
std::cout << month << std::endl;
}
}
return 0;
}
Or, you could also use std::vector for the composite; with all other lines in the above code unchanged, just use this for the declaration of months:
std::vector< std::vector<std::string> > months = { month31, month30, month29, month28 };
The (main) difference between vector and array is that, for array, the size, which is fixed at compile time and specified as a template parameter, is also part of the actual type of the object. So, for your 4 components of different lengths, defining each as a std::array would make them types of 4 (or 3, actually) different classes (so they would not be suitable as members of a 'composite' array / vector container).
|
69,214,987 | 69,215,138 | Initialization order: An array with a separate pointer to that same array | I have a line of code that declares a static array of char, like so:
char buf[7];
I would like to traverse this array using a pointer, but buf itself obviously can't be incremented or decremented. My question is basically, is this legal, or is this undefined behavior:
// Does this guarantee ptr == buf?
char buf[7], *ptr = buf;
// ... because if not, then this could crash my program!
std::cout << *ptr << '\n';
This and similar examples compile and run just fine on my computer (WSL, gcc 9.3.0) with all optimization flags. In every test I've run, buf == ptr. But technically, would the compiler be allowed by the C++ standard to reorder these declarations so that ptr is initialized to some junk value?
I could obviously split this up into two lines and avoid any doubt, but I'm wondering if this one-line declaration is valid.
|
is this legal
Yes
is this undefined behavior
No
would the compiler be allowed by the C++ standard to reorder these declarations so that ptr is initialized to some junk value?
No, it initializes ptr with the char* that buf decays into. If a compiler would be allowed to initialize them in the other order, it would need to fail compiling, since it wouldn't have seen buf yet.
Compare with these:
OK:
char buf[7];
char *ptr = buf;
Error:
char *ptr = buf;
char buf[7];
|
69,215,014 | 69,215,325 | Global variable pointer vs local variable pointer | so I understand that global variables are evil, and programmers should avoid them. However, I have been doing some studying regarding potential vulnerabilities behind it, so that is the reason why I'm using it at the moment.
I have this toy example:
#define MAX_LENGTH 8
int counter = MAX_LENGTH;
int *size;
int main(int argc, char **argv)
{
int value = atoi(argv[1]);
size = &value;
int *test;
*test = value;
printf("Hello World %d %d\n", *size, *test);
}
So the core question is that why for a global variable pointer, do I have to get the address of a variable to store the value stored in that variable?
My understanding of storing a value to a pointer is how I used the int *test; variable. I simply dereference this variable *test = value to store the value. However, I am curious why for global variable pointer *size, I cannot simply do *size = value, but instead must do size = &value.
I tried searching this question through StackOverflow, but maybe I didn't phrase the question right or such, so I could not find the relevant link for it.
I would appreciate any kind of tips, thank you in advance,
Kind regards,
Edit: Thanks everyone for the responses!
| Think of a pointer as a place in memory meant to store an address so that int *test, a pointer to an int, stores an address containing an int. When you first declare it, int *test, test has garbage as its value since you didn't initialize it. You were lucky that the garbage happened to be the value of "some address". When you set the value of that "garbage address" to value, *test = value;, you stored value (the int) in the "garbage address". If the random value in test happened to be an invalid address, like 0, your program would've crashed.
You should always initialize your pointers with a valid address, in this case an int address, before you store a value into that address. You may initialize you pointer with three kinds of addresses: nullptr, an address of an already existing integer, or an address dynamically obtained through new, for instance:
int *p = nullptr; // valid value for a pointer, but
// don't use it since it isn't pointing to a valid address yet
int value = 0; // an integer stored in an address in the stack
int *q = &value; // initialized with the address of value; it is said to point to value
p = &value; // p now also points to value
int *r = new int(0); // initialized with a dynamic address from the heap returned by new
// new also initialized the integer in the address with the value of 0
...
delete r; // don't forget to destroy and free the dynamic memory when you're done using it
// or you'll have a memory leak...
EDIT: As @Ben Voight commented. There is a difference in initialization between global and local pointers. Global pointers with no explicit initialization are implicitly zero-initialized, i.e. nullptr. On the other hand, local pointers that are not explicitly initialized are not, and they contain an indeterminate value.
|
69,215,139 | 69,215,627 | How do I incorporate the getline function so my program will read data from the file correctly? | I have this code as my default constructor. I am trying to read all the values correctly from my file (census2020_data.txt). The file contains letters and numbers, made up of states and a value representing population. One of the values in the data file has spaces (it is multiple words) and it makes my program not read from the file correctly.
How do I incorporate the getline() function to help read from my file correctly? I'll attach the fill contents below as an example.
Constructor:
state_class::state_class()
{
//intially count, capacity, and pop_DB are initialized with the following values:
count = 0;
capacity = 5;
ifstream in;
pop_DB = new population_record[capacity];
in.open("census2020_data.txt");
//check if file can be opened
while (!in.eof())
{
if (Is_Full())
{
double_size();
}
else
{
in >> pop_DB[count].state_name >> pop_DB[count].population;
count++;
}
}
in.close();
}
census2020_data.txt:
Alaska 710231
Arizona 6392017
District of Columbia 601723
Arkansas 2915918
California 37253956
Connecticut 3574097
Delaware 897934
Florida 18801310
Indiana 6483802
Maine 1328361
Oregon 3831074
Pennsylvania 12702379
Rhode Island 1052567
South Carolina 4625364
Maryland 5773552
Massachusetts 6547629
Michigan 9883640
Colorado 5029196
Minnesota 5303925
Mississippi 2967297
Iowa 3046355
Kansas 2853118
Kentucky 4339367
Louisiana 4533372
Missouri 5988927
Montana 989415
South Dakota 814180
Tennessee 6346105
Texas 25145561
Utah 2763885
Vermont 625741
Nebraska 1826341
Nevada 2700551
New Hampshire 1316470
New Jersey 8791894
Georgia 9687653
Hawaii 1360301
Idaho 1567582
Illinois 12830632
New Mexico 2059179
New York 19378102
North Carolina 9535483
North Dakota 672591
Ohio 11536504
Oklahoma 3751351
Virginia 8001024
Washington 6724540
West Virginia 1852994
Wisconsin 5686986
Wyoming 563626
Puerto Rico 3725789
Alabama 4779736
| operator>> stops reading on whitespace, which is not what you need in this case.
I would suggest using std::getline() to read an entire line, then use std::string::rfind() to find the last space character before the numbers, and then use std::string::substr() to split the text from the numbers. For example:
state_class::state_class()
{
//intially count, capacity, and pop_DB are initialized with the following values:
count = 0;
capacity = 5;
pop_DB = new population_record[capacity];
//check if file can be opened
std::ifstream in("census2020_data.txt");
std::string line;
while (std::getline(in, line))
{
if (Is_Full())
double_size();
auto pos = line.rfind(' ');
pop_DB[count].state_name = line.substr(0, pos);
pop_DB[count].population = std::stoi(line.substr(pos+1));
++count;
}
}
That being said, rather than maintaining your own population_record[] array manually, consider using std::vector<population_record> instead. Let the standard library handle the memory management for you:
private:
std::vector<population_record> pop_DB;
state_class::state_class()
{
//check if file can be opened
std::ifstream in("census2020_data.txt");
std::string line;
while (std::getline(in, line))
{
auto pos = line.rfind(' ');
population_record rec;
rec.state_name = line.substr(0, pos);
rec.population = std::stoi(line.substr(pos+1));
pop_DB.push_back(rec);
}
}
// use pop_DB.size() and pop_DB[index] as needed...
I would even go as far as suggesting to implement operator>> for reading population_record entries directly from the ifstream:
std::istream& operator>>(std::istream& in, population_record &rec)
{
std::string line;
if (std::getline(in, line))
{
auto pos = line.rfind(' ');
rec.state_name = line.substr(0, pos);
rec.population = std::stoi(line.substr(pos+1));
}
return in;
}
...
private:
std::vector<population_record> pop_DB;
state_class::state_class()
{
//check if file can be opened
std::ifstream in("census2020_data.txt");
population_record rec;
while (in >> rec) {
pop_DB.push_back(rec);
}
}
// use pop_DB.size() and pop_DB[index] as needed...
|
69,215,214 | 69,215,441 | Loop and object intialization question (C++) | I'm trying to use a loop to infinitely create objects from a class unless a specific input is entered. I think I have everything done except the loop. I know how to initialize one object in my main function, but I'm stuck as to how to use a loop to do this infinitely. My code is below.
Driver File:
#include <iostream>
#include "square.h"
using namespace std;
int main()
{
square square1;
square1.setSide();
square1.calcArea();
square1.calcPerimeter();
square1.showData();
}
Header file:
#pragma once
#include <string>
class square
{
public:
square();
void setSide();
double getSide() const;
void calcPerimeter();
void calcArea();
void showData();
private:
double squareSide;
double squarePerimeter;
double squareArea;
};
Implementation file:
#include <iostream>
#include <iomanip>
#include "square.h"
square::square()
{
squareSide = 0;
squarePerimeter = 0;
squareArea = 0;
}
void square::setSide()
{
std::cout << "Enter a side length: ";
std::cin >> squareSide;
std::cout << "\n";
if (squareSide == -1)
{
std::cout << "Exiting program.\n";
exit(-1);
}
while (std::cin.fail() || squareSide < 0)
{
std::cout << "\nYou must enter a positive number. Please try again.\n\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter a side length: ";
std::cin >> squareSide;
}
}
double square::getSide() const
{
return squareSide;
}
void square::calcPerimeter()
{
squarePerimeter = 4 * getSide();
}
void square::calcArea()
{
squareArea = getSide() * getSide();
}
void square::showData()
{
std::cout << "The side length of the square is: " << getSide() << "\n";
std::cout << "The perimeter of the square is: " << getSide() * 4 << "\n";
std::cout << "The area of the square is: " << getSide() * getSide() << "\n";
}
| You could add a do ... while loop around your code in main and store the squares in a vector<square>.
Example:
#include <limits> // you use numeric_limits from this header
#include <utility> // move
#include <vector> // vector
int main() {
std::vector<square> squares;
std::string answer;
do {
square square1;
square1.setSide();
square1.calcArea();
square1.calcPerimeter();
// move the square into the vector
squares.push_back(std::move(square1));
// ask the user if he/she wants to enter another
std::cout << "Go again? ";
} while(std::cin >> answer && answer == "yes");
// display what you stored
std::cout << "You stored " << squares.size() << " square(s)\n";
for(square& sq : squares) {
sq.showData();
std::cout << '\n';
}
}
|
69,215,239 | 69,216,015 | Explicitly using the namespace of the class attributes in methods to make code more readable? | This question is about writing good code in terms of readability/best practices.
Especially when working with a larger class and methods, I would prefer to be verbose when using attributes of the class. A simple example would be changing the value of an attribute through a method. In python, this would be done like "self.some_attribute", where the "self." makes it verbose and readable imo.
In C++, there is different ways of doing it.
Without the namespace:
class Example{
public:
int size = 10;
void setSize(int new_size){
size = new_size;
}
};
With the namespace:
class Example{
public:
int size = 10;
void setSize(int new_size){
Example::size = new_size;
}
};
Is there a standard way to do it that's considered the better practice? I prefer the second, more verbose way but it can look ugly if the class name is big. Is there a different approach to go about this?
Another example for why I prefer the more verbose way is that if an input to the function has the same name as an atrribute, it won't throw an error but the attribute will not be modified:
class Example{
public:
int size = 10;
void setSize(int size){
size = size;
}
};
| In Python, self. is critical because Python is a dynamic language. Imagine that self. wouldn’t be required:
class A:
def f():
x = 42 # whoops, is that a local or a member variable?
del x # what is deleted here?
return x # totally OK if there was another x in scope?
(the same problem effectively kills with in JS). But there is no such problem in C++! Each variable name is resolved at the time the method is compiled, and can’t change meaning afterwards.
So basically, while you definitely can access members via this->, there is little point in doing that.¹ All real IDEs are capable of highlighting members differently (some even distinguish own and inherited members). But from dark IDEless times, we still have common conventions of prefixing members with m_ or suffixing them with _ or likewise, as pointed out in the comments. That almost doesn’t hurt (esp. in comparison to lpdwsmthHere).
¹ Unless you’re writing a curiously recurring template or likewise where you can’t refer to an inherited member by bare name, because before instantiation, it is unknown whether there is an inherited member with such name. Much like in Python, but still during compilation.
|
69,215,464 | 69,233,247 | Pybind11: How to assign default value for a struct member variable? | I am trying to create python bindings for the below
struct example {
int a = 1;
int b = 2;
};
This is what I have so far
PYBIND11_MODULE(example_python, m) {
py::class_<example>(m, "example")
.def_readwrite("a", &example::a)
.def_readwrite("b", &example::b);
}
when I checked in python, both a and b are empty, so I tried something like
PYBIND11_MODULE(example_python, m) {
py::class_<example>(m, "example")
.def_readwrite("a", &example::a, py::arg("a") = 1)
.def_readwrite("b", &example::b, py::arg("b") = 2);
}
but this results in a compilation error. I went through the documentation multiple times but couldn't a way to do it. Can someone let me know how to assign the default values in pybind11?
| Your code doesn't compile, at least on my machine, because you didn't bind any constructor. However, if you do so then the default values become populated (because that's part of what a constructor does!). In other words, just use this:
PYBIND11_MODULE(example_python, m) {
py::class_<example>(m, "example")
.def(py::init<>()) // <-- bind the default constructor
.def_readwrite("a", &example::a)
.def_readwrite("b", &example::b);
}
|
69,215,509 | 69,215,562 | Why we need std::partition_point whereas we can use std::find_if_not algorithm? | Here is my possible implementation of the algorithm std::partition_point is :
template <typename In_It, typename FUNC>
In_It partitionPoint(In_It b, In_It e, FUNC pred){
int len = e - b;
while (len > 0){
int half = len >> 1;
In_It middle = b + half;
if( pred(*middle) ){
b = middle;
++b;
len = len - half - 1;
}
else
len = half;
}
return b;
}
My code looks like the STL one apart from using std::distance, traits... So it examines the input sequence and returns an iterator to the past-last element in the sequence for which the predicate succeeds. In other words the returned iterator denotes an element that doesn't satisfy the predicate.
int main(){
std::vector<int> v{1, 3, 5, 7, 9, 1, 3, 6, 8, 10, 12};
auto it = partitionPoint(v.begin(), v.end(), [](int x){return x % 2; });
if( it != v.cend() )
std::cout << *it << " " << it - v.cbegin() << '\n';
}
The output:
6 at index: 7
It is OK. however why I don't use directly std::find_if_not which returns an iterator to the first element for which the predicate is false?
auto it2 = findIfNot(v.cbegin(), v.cend(), [](int x){return x % 2; });
if(it2 != v.cend())
std::cout << *it2 << " at index: " << it2 - v.cbegin() << '\n';
The output:
6 at index: 7
| std::find_if_not has O(N) complexity as it does a linear traversal. std::partition_point on the other hand has O(logN) complexity as it takes advantage the fact that the set is partitioned and does a binary search to find the element. Depending on the situation, this could be a big performance win.
|
69,215,568 | 69,390,107 | How can i count percentage CPU for each process by PID | I am trying to code task manager and i stuck with %CPU for each process dy PID.
I wrote something like, that:
static float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;
unsigned long long totalTicksSinceLastTime = totalTicks - _previousTotalTicks;
unsigned long long idleTicksSinceLastTime = idleTicks - _previousIdleTicks;
float ret = 1.0f - ((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime) / totalTicksSinceLastTime : 0);
_previousTotalTicks = totalTicks;
_previousIdleTicks = idleTicks;
return ret;
}
static unsigned long long FileTimeToInt64(const FILETIME& ft) { return (((unsigned long long)(ft.dwHighDateTime)) << 32) | ((unsigned long long)ft.dwLowDateTime); }
And was using it like:
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
printError("Failed to create Process Snap");
return FALSE;
}
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hProcessSnap, &pe))
{
printError("Failed to move along process snap");
CloseHandle(hProcessSnap);
return FALSE;
}
do
{
printf("\n\n=====================================================");
_tprintf(TEXT("\n PROCESS NAME: %s"), pe.szExeFile);
printf("\n-----------------------------------------------------");
dwPriorityClass = 0;
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
if (hProcess == NULL)
{
printError("Failed to open process");
}
else
{
for (int i = 0; i < 2; i++)
{
GetProcessTimes(hProcess, &exist, &exit, &lastKernel, &lastUser);
GetSystemTimes(&lastIdle, 0, 0);
GetCPULoad(lastIdle, lastKernel, lastUser);
Sleep(2500);
}
std::cout << GetCPULoad(lastIdle, lastKernel, lastUser) << "\n";
CloseHandle(hProcess);
}
} while (Process32Next(hProcessSnap, &pe));
CloseHandle(hProcessSnap);
return (TRUE);
}
I know that using sleep() here isnt a good idea,but i havent think up anything better for now.
Pls help me with some code examples,if you can.
Also i want to know am i right that:
CPU% for process= (1- (IdleSystemTimeDelta/TotalProcessTimeDelta))*100%
| This is how i get_CPU in percent.
I use hash_map in order to have PID-time connection static to update it.
First time usage get_cpu_usage(int pid) returns zero every time,but with each next usage it will be more and more accurate(I use it with 0.5 sec period).
static int get_processor_number()
{
SYSTEM_INFO info;
GetSystemInfo(&info);
return (int)info.dwNumberOfProcessors;
}
static __int64 file_time_2_utc(const FILETIME* ftime)
{
LARGE_INTEGER li;
li.LowPart = ftime->dwLowDateTime;
li.HighPart = ftime->dwHighDateTime;
return li.QuadPart;
}
static int get_cpu_usage(int pid)
{
static int processor_count_ = -1;
static std::unordered_map<int, __int64> last_time_;
static std::unordered_map<int, __int64> last_system_time_;
FILETIME now;
FILETIME creation_time;
FILETIME exit_time;
FILETIME kernel_time;
FILETIME user_time;
__int64 system_time;
__int64 time;
__int64 system_time_delta;
__int64 time_delta;
int cpu = -1;
if (processor_count_ == -1)
{
processor_count_ = get_processor_number();
}
GetSystemTimeAsFileTime(&now);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
{
std::cout << "Unable to getProcessTime\n";
return -1;
}
system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time)) / processor_count_;
time = file_time_2_utc(&now);
if ((last_system_time_[pid] == 0) || (last_time_[pid] == 0))
{
last_system_time_[pid] = system_time;
last_time_[pid] = time;
return 0;
}
system_time_delta = system_time - last_system_time_[pid];
time_delta = time - last_time_[pid];
if (time_delta == 0)
{
std::cout << "timedelta=0";
return -1;
}
cpu = int((system_time_delta * 100 + time_delta / 2) / time_delta);
last_system_time_[pid] = system_time;
last_time_[pid] = time;
return cpu;
}
|
69,215,862 | 69,216,007 | How can solve vs2019 C++ template function trait problem? | I found a solution on Understanding how the function traits template works. In particular, what is the deal with the pointer to member function to get type of function parameters types by using templates. But following code gets "error C2760: syntax error: unexpected token '<', expected 'declaration'" on VS2019. It works on GCC ? When I use c++17 or c++20 gets same error. This seems vs2019 bug ?
Any suggestions ?
#include <functional>
#include <tuple>
#include <type_traits>
class CChTest
{
public:
CChTest()
{
}
bool ChDeneme(int a, int b)
{
return false;
}
};
template<typename> struct function_traits;
template <typename Function>
struct function_traits : public function_traits<
decltype(&std::remove_reference<Function>::type::operator())>
{
};
template <
typename ClassType,
typename ReturnType,
typename... Arguments>
struct function_traits<
ReturnType(ClassType::*)(Arguments...) const>
: function_traits<ReturnType(*)(Arguments...)>
{
};
template <
typename ClassType,
typename ReturnType,
typename... Arguments>
struct function_traits<
ReturnType(ClassType::*)(Arguments...)>
: function_traits<ReturnType(*)(Arguments...)>
{
};
template <
typename ReturnType,
typename... Arguments>
struct function_traits<
ReturnType(*)(Arguments...)>
{
typedef ReturnType result_type;
template <std::size_t Index>
using argument = typename std::tuple_element<
Index,
std::tuple<Arguments...>>::type;
static const std::size_t arity = sizeof...(Arguments);
};
template <
typename _ChClass,
typename _ChFunction>
void ChTemplate(
_ChClass cl,
_ChFunction fn)
{
typename function_traits<_ChFunction>::argument<0> a;
}
int main()
{
CChTest ChTest;
ChTemplate(&ChTest, &CChTest::ChDeneme);
return 0;
}
| You need to add the template keyword to make argument a dependent template name:
template <
typename _ChClass,
typename _ChFunction>
void ChTemplate(
_ChClass cl,
_ChFunction fn)
{
typename function_traits<_ChFunction>::template argument<0> a;
// ^^^^^^^^
}
Demo
|
69,215,985 | 69,230,368 | Why is `std::is_constant_evaluated()` false for this constant-initialized variable? | Note 2 to [expr.const]/2 implies that if we have a variable o such that:
the full-expression of its initialization is a constant expression when interpreted as a constant-expression, except that if o is an object, that full-expression may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types
then:
Within this evaluation, std::is_constant_evaluated() [...] returns true.
Consider:
#include <type_traits>
int main() {
int x = std::is_constant_evaluated();
return x;
}
This program returns 0 when executed.
However, I don't see how the full-expression of the initialization of x is not a constant expression. I do not see anything in [expr.const] that bans it. Therefore, my understanding of the note (which is probably wrong) implies that the program should return 1.
Now, if we look at the normative definition of std::is_constant_evaluated, it is only true in a context that is "manifestly constant-evaluated", and the normative definition of the latter, [expr.const]/14, is more clear that the program above should return 0. Specifically, the only item that we really need to look at is the fifth one:
the initializer of a variable that is usable in constant expressions or has constant initialization ...
x is not usable in constant expressions, and it doesn't have constant initialization because no automatic variable does.
So there are two possibilities here. The more likely one is that I haven't understood the note, and I need someone to explain to me why the note does not imply that the program should return 1. The less likely one is that the note contradicts the normative wording.
| The full quote here is
A variable or temporary object o is constant-initialized if
(2.1) either it has an initializer or its default-initialization results in some initialization being performed, and
(2.2) the full-expression of its initialization is a constant expression when interpreted as a constant-expression, except that if
o is an object, that full-expression may also invoke constexpr
constructors for o and its subobjects even if those objects are of
non-literal class types. [Note 2: Such a class can have a
non-trivial destructor. Within this evaluation,
std::is_constant_evaluated() ([meta.const.eval]) returns true.
— end note]
The tricky bit here is that the term "is constant-initialized" (note: not "has constant initialization") doesn't mean anything by itself (it probably should renamed to something else). It's used in exactly three other places, two of which I'll quote below, and the last one ([dcl.constexpr]/6) isn't really relevant.
[expr.const]/4:
A constant-initialized potentially-constant variable V is usable in constant expressions at a point P if V's initializing declaration D is reachable from P and [...].
[basic.start.static]/2:
Constant initialization is performed if a variable or temporary object with static or thread storage duration is constant-initialized ([expr.const]).
Let's replace "constant-initialized" with something less confusing, like "green".
So
A green potentially-constant variable is usable in constant expressions if [some conditions are met]
Constant initialization is performed if a variable or temporary object with static or thread storage duration is green.
Outside of these two cases, the greenness of a variable doesn't matter. You can still compute whether it is green, but that property has no effect. It's an academic exercise.
Now go back to the definition of greenness, which says that a variable or temporary object is green if (among other things) "the full-expression of its initialization is a constant expression when interpreted as a constant-expression" with some exceptions. And the note says that during this hypothetical evaluation to determine the green-ness of the variable, is_constant_evaluated() returns true - which is entirely correct.
So going back to your example:
int main() {
int x = std::is_constant_evaluated();
return x;
}
Is x green? Sure, it is. But it doesn't matter. Nothing cares about its greenness, since x is neither static nor thread local nor potentially-constant. And the hypothetical computation done to determine whether x is green has nothing to do with how it is actually initialized, which is governed by other things in the standard.
|
69,215,991 | 69,216,120 | Where is my memory leaking in my program and how would I fix it? | so i'm working on an assignment for my c++ class and I am attempting to do different functions using my class with arrays. It works mostly until the overload operator where the memory leak seems to happen.
#include <iostream>
#include <algorithm> // for std::copy_n
using namespace std;
class MyArray{
private:
double* a{};
int n{};
public:
MyArray(){
a = nullptr;
n = 0;
} // default constructor
/////////////////////////////////////////////////
explicit MyArray(int size){
n = size;
a = new double[size]{};
} //constructor specifying size
/////////////////////////////////////////////////
MyArray(int size, double def_val) {
n = size;
a = new double[size];
for (int i = 0; i < size; ++i) {
//def_val=i;
a[i] = def_val;
}
} //constructor set to default values and specifying size
/////////////////////////////////////////////////
double GetA(int i){
return a[i];
} //setter
/////////////////////////////////////////////////
int GetN() const{
return n;
} //getter
/////////////////////////////////////////////////
void SetN(int x) {
n = x;
} //setter
/////////////////////////////////////////////////
void SetA(int i, double x) {
a[i] = x;
} //getter
/////////////////////////////////////////////////
MyArray(const MyArray & a2, int n) {
a = new double[n]{};
n = a2.n;
for (int i=0; i< n; i++){
a[i]=a2.a[i];
}
} //constructor by copy
/////////////////////////////////////////////////
~MyArray(){
delete []a;
} // destructor
/////////////////////////////////////////////////
MyArray operator=(const MyArray& a2) {
int new_n = a2.n;
auto *new_data = new double[new_n];
std::copy_n(a2.a, new_n, new_data);
delete[] a;
n = new_n;
a = new_data;
return *this;
} //assignment
int get_Size() const{
return n;
} //accessor
/////////////////////////////////////////////////
void push_begin(double first) {
auto* temp = new double [n+1];
n++;
for (int i = 0; i < n-1; i++){
temp[i+1] = a[i];
}
temp[0] = first;
this-> a = temp;
}
/////////////////////////////////////////////////
void push_end(double last) {
a[n] = last;
n++;
}
/////////////////////////////////////////////////
void remove_begin() {
for (int i = 0; i < n - 1; i++) {
a[i] = a[i + 1];
}
n--;
} //done
/////////////////////////////////////////////////
void remove_End() {
n--;
}
/////////////////////////////////////////////////
void reverse() {
double temp;
for(int i=0; i<n/2; i++){
temp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = temp;
}
}
/////////////////////////////////////////////////
void display(){
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
friend MyArray operator + (MyArray &arr1, MyArray &arr2){
int n1 = arr1.get_Size();
int m = arr2.get_Size();
int size = m + n1;
MyArray ans(arr2, size);
for(int i=0; i<size; i++){
ans.push_end(arr2.a[i]);
}
return ans;
}
};
main:
int main(){
MyArray a(9);
MyArray b(10, 5);
b.push_begin(45);
b.push_end(64);
b.push_end(31);
b.push_begin(908);
b.display();
b.display();
b.display();
b.reverse();
b.display();
MyArray c (a+b);
c.display(); //////The leak seems to happen here but I can't find a memory
/////leak finder that works for me
}
I have tried to use valgrind but it doesn't want to run on my laptop.
908 45 8 8 8 8 8 8 64 31
908 45 8 8 8 8 8 8 64 31
908 45 8 8 8 8 8 8 64 31
31 64 8 8 8 8 8 8 45 908
The Max value of the concatenated array is: 908
31 64 8 8 8 8 8 8 45 908 6.93003e-310 6.93003e-310 0 0 0
This is what is output and I have no possible clue where 6.93003e-310 comes from when it should most definitely be 0.
| The problem is that your class has no copy constructor. MyArray(const MyArray & a2, int n) is not a copy constructor because it requires an additional argument, n. Which you don’t actually need as you have a2.n.
Also, you leak a in push_begin, and forget to resize it at all in push_end (as well as in setN but you don’t seem to use it at all).
Finally, your operator+ is indeed flawed in several ways. It could be written in one of several ways:
Create an empty new array, then push_back elements from arr1, then push_back elements from arr2.
Create a copy of arr1, then push_back elements from arr2.
Create an array of size arr1.n + arr2.n and fill it directly, without push_back.
What is in the code is a weird mix of these 3 approaches.
And a stylistic note: operator= should return a reference (as pointed out in comments), and operator+ should accept const references.
Still, this is better than most homeworks I’ve seen here on SO.
|
69,216,077 | 69,216,306 | Initializing multi-dimensional std::vector without knowing dimensions in advance | Context: I have a class, E (think of it as an organism) and a struct, H (a single cell within the organism). The goal is to estimate some characterizing parameters of E. H has some properties that are stored in multi-dimensional matrices. But, the dimensions depend on the parameters of E.
E reads a set of parameters from an input file, declares some objects of type H, solves each of their problems and fills the matrices, computes a likelihood function, exports it, and moves on to next set of parameters.
What I used to do: I used to declare pointers to pointers to pointers in H's header, and postpone memory allocation to H's constructor. This way, E could pass parameters to constructor, and memory allocation could be done afterwards. I de-allocated memory in the destructor.
Problem: Yesterday, I realized this is bad practice! So, I decided to try vectors. I have read several tutorials. At the moment, the only thing that I can think of is using push_back() as used in the question here. But, I have a feeling that this might not be the best practice (as mentioned by many, e.g., here, under method 3).
There are tens of questions that are tangent to this, but none answers this question directly: What is the best practice if dimensions are not known in advance?
Any suggestion helps: Do I have any other solution? Should I stick to arrays?
| Using push_back() should be fine, as long as the vector has reserved the appropriate capacity.
If your only hesitancy to using push_back() is the copy overhead when a reallocation is performed, there is a straightforward way to resolve that issue. You use the reserve() method to inform the vector how many elements the vector will eventually have. So long as
reserve() is called before the vector is used, there will just be a single allocation for the needed amount. Then, push_back() will not incur any reallocations as the vector is being filled.
From the example in your cited source:
std::vector<std::vector<int>> matrix;
matrix.reserve(M);
for (int i = 0; i < M; i++)
{
// construct a vector of ints with the given default value
std::vector<int> v;
v.reserve(N);
for (int j = 0; j < N; j++) {
v.push_back(default_value);
}
// push back above one-dimensional vector
matrix.push_back(v);
}
This particular example is contrived. As @kei2e noted in a comment, the inner v variable could be initialized once on the outside of the loop, and then reused for each row.
However, as noted by @Jarod42 in a comment, the whole thing can actually be accomplished with the appropriate construction of matrix:
std::vector<std::vector<int>> matrix(M, std::vector<int>(N, default_value));
If this initialization task was populating matrix with values from some external source, then the other suggestion by @Jarod42 could be used, to move the element into place to avoid a copy.
std::vector<std::vector<int>> matrix;
matrix.reserve(M);
for (int i = 0; i < M; i++)
{
std::vector<int> v;
v.reserve(N);
for (int j = 0; j < N; j++) {
v.push_back(source_of_value());
}
matrix.push_back(std::move(v));
}
|
69,216,803 | 69,219,384 | SDL_Log doesn't seem to support %g and %e specifiers | I'm using SDL 2.0.12 with Visual Studio 2013, and I'm seeing this:
SDL_Log("%f", 1.0); // fine
SDL_Log("%g", 1.0); // no luck; prints blank line
Do I need to switch to a newer/older version of SDL or something?
| SDL_Log delegates to SDL_vsnprintf. There are three possibilities:
#if defined(HAVE_LIBC) && defined(__WATCOMC__)
This seems to check for the Watcom C compiler. Not for you.
#elif defined(HAVE_VSNPRINTF)
This case delegates to your compiler's implementation of vsnprintf if that symbol was defined at compilation time. VS2015 appears to have the %g specifier, I assume VS2013 as well. You can check this yourself trivially.
#else
I think you are in this situation.
This uses a custom implementation in SDL. This indeed lacks support for the %g modifier, but you could add it yourself (and submit a pull request).
|
69,216,934 | 69,217,518 | Unable to use std::apply on user-defined types | While implementing a compressed_tuple class for some project I'm working on, I ran into the following issue: I can't seem to pass instances of this type to std::apply, even though this should be possible according to: https://en.cppreference.com/w/cpp/utility/apply.
I managed to reproduce the issue quite easily, using the following fragment (godbolt):
#include <tuple>
struct Foo {
public:
explicit Foo(int a) : a{ a } {}
auto &get_a() const { return a; }
auto &get_a() { return a; }
private:
int a;
};
namespace std {
template<>
struct tuple_size<Foo> {
constexpr static auto value = 1;
};
template<>
struct tuple_element<0, Foo> {
using type = int;
};
template<size_t I>
constexpr auto get(Foo &t) -> int & {
return t.get_a();
}
template<size_t I>
constexpr auto get(const Foo &t) -> const int & {
return t.get_a();
}
template<size_t I>
constexpr auto get(Foo &&t) -> int && {
return std::move(t.get_a());
}
template<size_t I>
constexpr auto get(const Foo &&t) -> const int && {
return move(t.get_a());
}
} // namespace std
auto foo = Foo{ 1 };
auto f = [](int) { return 2; };
auto result = std::apply(f, foo);
When I try to compile this piece of code, it seems that it cannot find the std::get overloads that I have defined, even though they should perfectly match. Instead, it tries to match all of the other overloads (std::get(pair<T, U>), std::get(array<...>), etc.), while not even mentioning my overloads. I get consistent errors in all three major compilers (MSVC, Clang, GCC).
So my question is whether this is expected behavior and it's simply not possible to use std::apply with user-defined types? And is there a work-around?
|
So my question is whether this is expected behavior and it's simply
not possible to use std::apply with user-defined types?
No, there is currently no way.
In libstdc++, libc++, and MSVC-STL implementations, std::apply uses std::get internally instead of unqualified get, since users are prohibited from defining get under namespace std, it is impossible to apply std::apply to user-defined types.
You may ask, in [tuple.creation], the standard describes tuple_cat as follows:
[Note 1: An implementation can support additional types in the
template parameter pack Tuples that support the tuple-like protocol,
such as pair and array. — end note]
Does this indicate that other tuple utility functions such as std::apply should support user-defined tuple-like types?
Note that in particular, the term "tuple-like" has no concrete definition at
this point of time. This was intentionally left C++ committee to make this gap
being filled by a future proposal. There exists a proposal that is
going to start improving this matter, see P2165R3.
And is there a work-around?
Before P2165 is adopted, unfortunately, you may have to implement your own apply and use non-qualified get.
|
69,217,027 | 69,217,104 | How to overload the = in c++ in order to use it when creating an object? | I have created a class that is meant to be initialized also with an initializer list:
#include <iostream>
#include<vector>
using namespace std;
class A{
public:
A() = default;
A(vector<int> values){
a1 = values;
}
A& operator=( vector<int> values){
a1 = values;
return *this;
}
private:
vector<int>a1;
};
When I do the first type of variable definition it won't give me errors:
int main() {
A obj;
obj={2,3,1,5,56,6,2};
return 0;
}
However when I try the following I get this error:
int main() {
A obj={2,3,1,5,56,6,2};
return 0;
}
error: could not convert '{2, 3, 1, 5, 56, 6, 2}' from 'brace-enclosed initializer list' to 'A'
| You should probably use initializer lists instead of vector in args. The following seems to work:
#include <iostream>
#include<vector>
using namespace std;
class A{
public:
A() = default;
A(initializer_list<int> values){ // <<<<<<<<<<<
a1 = values;
}
A& operator=(initializer_list<int> values){ // <<<<<<<<<
a1 = values;
return *this;
}
private:
vector<int>a1;
};
int main() {
A obj1 {2,3,1,5,56,6,2};
A obj2;
obj2={2,3,1,5,56,6,2};
return 0;
}
You need c++11 or later.
|
69,217,219 | 69,217,346 | c++ stringstream read doesn't seem to read the whole buffer | I have the following code: https://godbolt.org/z/9aqqe5eYh
#include<string>
#include<sstream>
#include<iomanip>
#include<iostream>
int main() {
std::string line = "fa0834dd";
for(int i = 0; i < line.length(); i += 2) {
std::stringstream ss;
std::uint8_t byte;
ss << std::hex << line.substr(i, 2);
std::cout << ss.str() << " ";
ss >> byte;
std::cout << std::hex << std::setw(2) << byte << std::endl;
}
}
Ideally, this takes in a string of hex numbers, splits them into bytes (pair of hex digits) and stores it into bytes (for illustrative purposes, I use only one std::uint8_t above).
The above code outputs this:
Program returned: 0
Program stdout
fa f
08 0
34 3
dd d
Which seems kinda odd. An std::uint8_t should be enough to store 2 hex character's worth of data. But it seems like ss >> byte only stores the front hex character. My guess is that:
ss << std::hex << line.substr(i, 2);
actually stores each hex character as 1 byte?
How would I fix the above code to generate an single-byte value equal to 2 hex characters in the string?
| stringstream is not eligible for parsing the character representation into a value in byte.
You may use something lik strtol to actually parse the string into value.
#include<string>
#include<sstream>
#include<iomanip>
#include<iostream>
int main() {
std::string line = "fa0834dd";
for(int i = 0; i < line.length(); i += 2) {
std::string ss = line.substr(i,2);
std::cout << ss << " ";
std::uint8_t byte = static_cast<std::uint8_t>(strtol(ss.c_str(), NULL, 16));
std::cout << std::hex << static_cast(byte) << std::endl;
}
}
Ref post
|
69,217,539 | 69,231,382 | Problem with GLFW linking, as it used in SharedLib (DLL) | Environment : Visual Studio 2019.
I'm developing an Engine as a SharedLib (DLL) and I made an example that uses this DLL so I can launch the Engine. at this stage I have to add GLFW library to the engine, so I added GLFW as a submodule (git) to my project and built this library as a StaticLib (.lib) with static runtime sets to "On". and added GLFW as a reference in the engine as in the second picture below. the build of GLFW goes very well and I get GLFW.lib. so I added some functions of GLFW to the engine code like glfwMakeContextCurrent() at this point when I build the Engine I get weird linking errors for many functions except glfwInit().
here is a picture of an example of one of my linking errors:
the project view:
Note: opengl32.lib already added to the engine in the Input in the Linker.
Please if you have any thoughts, I would appreciate it if you can share them
EDIT
Here is the full linker commandline:
| Thank you Everyone for your help. I got relatively a solution and I want to share it with you in case someone fall in the same situation.
Short Answer:
I converted the GLFW from static library to shared library while the building, and the linking errors just gone.
Long Answer
I wrote a Premake script to generate the GLFW project with configuration set to Shared Library and staticruntime to Off [meaning (Multi-threaded DLL (/MD)) for Runtime Library in Visual Studio configuration]. beside some includes and defines (take a look at the script) and I linked the GLFW library to the engine and I copied the .dll to the location of Sandbox/example application based on the engine and everything works pretty fine.
here is the script in case:
project "GLFW"
kind "SharedLib"
language "C"
targetname ("glfw3")
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-intermediate/" .. outputdir .. "/%{prj.name}")
files
{
"include/GLFW/glfw3.h",
"include/GLFW/glfw3native.h",
"src/internal.h",
"src/glfw_config.h",
"src/mappings.h",
"src/egl_context.h",
"src/osmesa_context.h",
"src/wgl_context.h",
"src/context.h",
"src/init.c",
"src/input.c",
"src/monitor.c",
"src/vulkan.c",
"src/window.c",
"src/context.c"
}
includedirs {
"%{prj.name}/src",
"%{prj.name}/include"
}
filter "system:windows"
buildoptions { "-std=c11", "-lgdi32" }
systemversion "latest"
staticruntime "Off"
files
{
"src/win32_platform.h",
"src/win32_joystick.h",
"src/win32_init.c",
"src/win32_joystick.c",
"src/win32_monitor.c",
"src/win32_time.c",
"src/win32_thread.c",
"src/win32_window.c",
"src/wgl_context.c",
"src/egl_context.c",
"src/osmesa_context.c"
}
defines
{
"_GLFW_WIN32",
"_CRT_SECURE_NO_WARNINGS",
"WIN32",
"_WINDOWS",
"UNICODE",
"_UNICODE",
"_GLFW_BUILD_DLL"
}
links{
"kernel32.lib",
"user32.lib",
"gdi32.lib",
"winspool.lib",
"shell32.lib",
"ole32.lib",
"oleaut32.lib",
"uuid.lib",
"comdlg32.lib",
"advapi32.lib"
}
postbuildcommands{
("{COPY} %{cfg.buildtarget.relpath} ../../../bin/" .. outputdir .. "/Sandbox")
}
filter { "system:windows", "configurations:Debug"}
buildoptions "/MDd"
filter { "system:windows", "configurations:Release"}
buildoptions "/MD"
|
69,217,597 | 69,218,017 | How to create an array from an input txt file | I am new to c++ and fstream (infile) and wanted to know how data is read from a txt file and how can I put that data in an array. Basically I am trying to make this korean game called omok. where the number of times a player gets their move 4 times simultaneously either vertically, horizontally or diagonally.
Input from the txt file
4 4 2 4
2 0 B
0 1 W
3 2 B
1 3 W
Data from the first line means that its is a 4x4 array / table. 2 means that there have been 2 moves from each player and 4 moves in total.
the second line onwards where the number coresponds to the location of the move for eg 2 0 means row 2 col 0.
Output should be:
0 1 2 3
0 . W . .
1 . . . W
2 B . . .
3 . . B .
Can white player win? No
Can black player win? No
This is what I've got so far, what am I supposed to do? I am logically stuck.
Could you first explain how the data is read an how I can display it like this?
void PrintBoard(char** board, int num_rows, int num_cols) {
cout << "Print board:" << endl << endl;
for (int i = 0; i < num_cols; i++) {
cout<<" "<<i;
}
cout << endl;
for (int i = 0; i < num_rows; i++) {
cout << " " << i << endl;
}
cout << endl;
/////////////////////////////////////////////////////////////////
// Print
// * " W" to print a white stone, and
// * " B" to print a black stone, and
// * " ." to print an empty cell.
/////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////
// Add your own functions if you need
bool CheckWhitePlayerWin(int num_rows, int num_cols, char** board, int N) {
return true;
}
bool CheckBlackPlayerWin(int num_rows, int num_cols, char** board, int N) {
return true;
}
void PrintPlayerWinCondition(int num_rows, int num_cols, char** board, int N) {
}
/////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[]) {
if (argc <= 1) {
cout << "Need the input file containing board size, N, and stones." << endl;
return 0;
}
int num_rows;
int num_cols;
int N;
char** board = ReadBoard(argv[1], num_rows, num_cols, N);
PrintBoard(board, num_rows, num_cols);
if(CheckWhitePlayerWin(num_rows, num_cols, board, N))
cout << "Can white player win? Yes" << endl;
else
cout << "Can white player win? No" << endl;
if (CheckBlackPlayerWin(num_rows, num_cols, board, N))
cout << "Can black player win?" << endl;
else
cout << "Can black player win?" << endl;
cout << endl;
cout << "List of winning conditions sorted by the index of top-left stone location:" << endl;
PrintPlayerWinCondition(num_rows, num_cols, board, N);
Thanks in advance!
| In any software project one of the key aspect you have to think about are your data structures: what do you need to store, what is the best format to store it, etc. Very often the data structures will define a lot of the resulting performance and clarity of your software.
In your case you decided to use char**, which I think is not a good choice. This basically reflects a piece of paper, but as a programmer your main task is abstraction. You have to re-think problems in terms of best fit for math, numerical solutions, data flow, performance and efficiency. The bad news is: there is no general best solution, it fundamentally depends on the underlying problem to solve. Since I don't know this in your case, I just provide here a way to process the char** data. And this is probably OK for you here, but in your next, larger, projects keep this in mind.
char** ReadBoard(std::string const& filename, int& num_rows, int& num_cols, int& N) {
int n_player = 0;
std::ifstream file(filename);
file >> num_rows >> num_cols >> n_player >> N;
// create data storage
char** data = new char*[num_rows];
for (int i_row=0; i_row<num_rows; ++i_row) {
data[i_row] = new char [num_cols];
// initialize data
for (int i_col=0; i_col<num_cols; ++i_col) {
data[i_row][i_col] = '.';
}
}
// read data
int x, y;
char player;
while (file >> y >> x >> player) {
if (x>=num_rows || y>=num_cols) {
std::cout << "data out of range" << std::endl;
continue;
}
data[y][x] = player;
}
file.close();
return data;
}
void PrintBoard(char** board, int num_rows, int num_cols)
{
for (int i_row=0; i_row<num_rows; ++i_row) {
for (int i_col=0; i_col<num_cols; ++i_col) {
std::cout << board[i_row][i_col];
}
std::cout<<"\n";
}
}
|
69,218,343 | 69,236,342 | Pybind11: How to create bindings for a function that takes in a struct as an argument? | Please see below C++ code that I am trying to create python bindings for
struct Config {
int a;
int b;
};
void myfunction(const Config &config);
Here is what I have so far,
PYBIND11_MODULE(example, m) {
py::class_<Config>(m, "Config")
.def_readwrite("a", &Config::a)
.def_readwrite("b", &Config::b);
m.def("myfunction", &myfunction);
}
This compiles, but when I attempt to call the python bindings in python,
import example
config = example.Config;
config.a = 1;
config.b = 2;
example.myfunction(config)
I got the below error
TypeError: myfunction(): incompatible function arguments. The following argument types are supported:
1. (arg0: example.Config) -> None
Invoked with: <class 'example.Config'>
Can someone let me know what is the right way to create python bindings for a function that takes in a struct as an argument?
| As hinted by @eyllanesc, the problem will be solved by adding a default constructor:
PYBIND11_MODULE(example, m) {
py::class_<Config>(m, "Config")
.def(py::init<>())
.def_readwrite("a", &Config::a)
.def_readwrite("b", &Config::b);
m.def("myfunction", &myfunction);
}
import example
config = example.Config();
config.a = 1;
config.b = 2;
example.myfunction(config)
|
69,218,470 | 69,218,775 | How to find a list that only contains a certain field and no other fields? | How to find a list that only contains a certain field and no other fields?
eg:
[a, b, c, d]
[a, b, c]
[a, b]
find the list containing only a and b: [a, b]
| Here I have implemented what you need. The input is 2d vector, which contains the input that you have mentioned as three lists. The check vector contains the list which you want to check if exists in the input.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
vector<vector<char>> input = {
{'a', 'b', 'c', 'd'},
{'a', 'b', 'c'},
{'a', 'b'}
};
bool broke = false;
vector<char> check = {'a', 'b'};
sort(check.begin(), check.end());
for(int j=0; j<input.size(); ++j){
auto x = input[j];
if(x.size()!=check.size())continue;
sort(x.begin(), x.end());
for(int i=0; i<min(x.size(),check.size()); ++i){
if(check[i]!=x[i]){
broke = true;
break;
}
}
if(!broke){
cout<<j+1<<" number list is equal to required list\n";
}
broke = false;
}
return 0;
}
This code accepts dynamic input so you can play around with input and check values to understand code. I have implemented ways suggested by Cwift in previous answer.
|
69,218,661 | 69,219,047 | " undefined reference to `toppers::recordTop' " error? | My problem was:
Write a program that has a class Student to store the details of students in a class. Derive another class Toppers from the Student that stores records of only top 3 students of the class
Here, In the inherited class toppers , I have take taken a data member(recordTop[3]) of derived class(Toppers) and initialised it in top3(toppers a[], int n) function but yet it giving me an error of undefined reference to `toppers::recordTop' .
#include<iostream>
#include<string>
using namespace std;
class students
{
protected:
string name;
int total;
public:
void input_students()
{
cout << "Enter your Name : ";
cin >> name;
cout << "Enter your total marks : ";
cin >> total;
}
void output_students()
{
cout << "Name : " << name << endl;
cout << "Total Marks : " << total << endl;
}
};
class toppers : public students
{
protected:
static toppers recordTop[3];
public :
friend void sort(toppers a[], int n)
{
for (int i = 0 ; i < n ; i++)
{
for (int j = i ; j < n ;j++ )
{
if(a[j].total > a[i].total)
{
toppers temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
}
void top3(toppers a[], int n)
{
recordTop[0] = a[0];
recordTop[1] = a[1];
recordTop[2] = a[2];
}
void output_toppers()
{
for (int i = 0; i<3 ; i++)
{
cout << "Details of RANK " << i + 1 << " are : " << endl;
recordTop[i].output_students();
}
}
};
int main()
{
int n;
cout << "Enter number of students : ";
cin >> n;
toppers st[n];
for (int i = 0; i < n ; i++)
{
st[i].input_students();
}
sort(st,n);
st[0].top3(st, n);
st[0].output_toppers();
return 0;
}
If possible , please point my mistake?
| I just changed your static topper recordTop[3] to students recordTop[3]. The code works as you might expect. Instantiation of a class member inside the class somehow creates infinite recursion like conditions. I have added a couple of \ns to see all statements clearly.
#include<iostream>
#include<string>
using namespace std;
class students
{
protected:
string name;
int total;
public:
void input_students()
{
cout << "\nEnter your Name : ";
cin >> name;
cout << "\nEnter your total marks : ";
cin >> total;
}
void output_students()
{
cout << "Name : " << name << endl;
cout << "Total Marks : " << total << endl;
}
};
class toppers : public students
{
protected:
students recordTop[3];
public :
friend void sort(toppers a[], int n)
{
for (int i = 0 ; i < n ; i++)
{
for (int j = i ; j < n ;j++ )
{
if(a[j].total > a[i].total)
{
toppers temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
}
void top3(toppers a[])
{
recordTop[0] = a[0];
recordTop[1] = a[1];
recordTop[2] = a[2];
}
void output_toppers()
{
for (int i = 0; i<3 ; i++)
{
cout << "\nDetails of RANK " << i + 1 << " are : " << endl;
recordTop[i].output_students();
}
}
};
int main()
{
int n;
cout << "Enter number of students : ";
cin >> n;
toppers st[n];
for (int i = 0; i < n ; i++)
{
st[i].input_students();
}
sort(st,n);
st[0].top3(st);
st[0].output_toppers();
return 0;
}
|
69,218,804 | 69,218,922 | Difference between Reference to a const Callable and Reference to a Callable in C++ | I want to know what happens if we have a function parameter that is a reference to a const function as shown below.
Version 1
int anotherFunc()
{
std::cout<<"inside anotherFunc"<<std::endl;
return 5;
}
void func(decltype(anotherFunc) const &someFunction)//note the const here
{
std::cout<<"inside func"<<std::endl;
std::cout<<someFunction()<<std::endl;
}
int main()
{
std::cout << "Hello World" << std::endl;
func(anotherFunc);
return 0;
}
Version 2
int anotherFunc()
{
std::cout<<"inside anotherFunc"<<std::endl;
return 5;
}
void func(decltype(anotherFunc) &someFunction)//note the missing const here
{
std::cout<<"inside func"<<std::endl;
std::cout<<someFunction()<<std::endl;
}
int main()
{
std::cout << "Hello World" << std::endl;
func(anotherFunc);
return 0;
}
My questions are:
Are version 1 and version 2 completely equivalent in terms of the function parameter someFunction of the function func? That is adding const for the function paramter someFunction does nothing(i.e. simply ignored).
If const is ignored in these examples then at what point(document) does the C++ standard specify that const will be ignored for this case.
PS: Looking at the generated assembly it does seem that const is ignored for reference to function parameter.
| Yes, the const qualifier is ignored when added to an alias for a function type.
From the standard, [dcl.fct]/7:
The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored.
[Note 4: A function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. — end note]
[Example 4:
typedef void F();
struct S {
const F f; // OK: equivalent to: void f();
};
— end example]
|
69,219,832 | 69,220,159 | Unresolved overloaded function type in std::transfrom | I am trying to write an overload function for both double and vector<double>.
I just did the following:
constexpr double degrees(double val) { return v * M_1_PI * 180.0; }
std::vector<double> degrees(const std::vector<double>& val)
{
std::vector<double> out;
out.reserve(val.size());
std::transform(val.begin(), val.end(), std::back_inserter(out), degrees);
return out;
}
I expect this to be rather straightforward, but it does not compile, and I cannot figure it out. The compiler cannot resolve the overloaded degrees function, and keeps complaining
couldn't deduce template parameter '_UnaryOperation'
Edit: fix the part with reserve, it is an obvious mistake.
| I don't want to believe that the asker didn't know they are defining two functions with the same name degrees, so I'll give another shade to my answer.
How is it possible, in this call
std::transform(val.begin(), val.end(), std::back_inserter(out), degrees);
that degrees is not known? I mean, std::transform should try to apply degrees to each element in val, and since each of those elements is a double, isn't it obvious that transform should make use of the first overload, the one which takes a double?
As convincing as this motivation might be, though, it would require the compiler to delay/defer the decision of what degrees should be called to the moment it's actually called, i.e. not at the call site of std::transform, but inside std::transform (specifically, when evaluating the expression unary_op(*first1++) in this possible implementation on the cppreference doc page).
This is simply not possible, as the rules are that the compiler must know at the call site of a function what its arguments are. With reference to the example, at the call site of std::transform the compiler has no idea which of the overloads of degree is needed.
One way around is to wrap degrees in a function object with overloaded operator(), as suggested by 463035818_is_not_a_number; doing so, the object degrees would be known at std::transform call site, and only inside std::transform, at the call site of the object's operator() would the compiler have to choose between the overloads of operator().
|
69,220,040 | 69,220,283 | Lambda to compose lambdas | I tried to write a function in C++ which can compose a variable amount of lambdas. My first attempt kind of works (even though I suspect it isn't perfect)
template <typename F, typename G> auto compose(F f, G g) {
return
[f, g](auto &&...xs) { return g(f(std::forward<decltype(xs)>(xs)...)); };
}
template <typename F, typename G, typename... Fs>
auto pipe(F f, G g, Fs... fs) {
if constexpr (sizeof...(fs) > 0) {
auto fg = compose(f, g);
return pipe(fg, fs...);
} else {
return compose(f, g);
}
}
int main() {
auto add_x = [](const auto &x) {
return [x](auto y) {
std::cout << "+" << x << std::endl;
return y + x;
};
};
auto to_str = [](const auto &s) {
std::cout << "to_str" << std::endl;
return std::string("String:") + std::to_string(s);
};
auto add_1 = add_x(1);
auto add_2 = add_x(2);
auto add_3 = add_x(3);
auto piped = pipe(add_1, add_2, add_3, to_str);
auto x = piped(3);
std::cout << x << std::endl;
}
However, I'd like to have the pipe function itself to be a lambda function. This is kind of hard however, since, as I understood it, lambdas can't capture themselves. This makes simply "lambdafying" my template function problematic. Does anyone have an alternative approach or an idea how to get similar results with a lambda function?
| You can use the y combinator to make a recursive lambda.
template<class Fun>
class y_combinator_result {
Fun fun_;
public:
template<class T>
explicit y_combinator_result(T &&fun): fun_(std::forward<T>(fun)) {}
template<class ...Args>
decltype(auto) operator()(Args &&...args) {
return fun_(std::ref(*this), std::forward<Args>(args)...);
}
};
template<class Fun>
decltype(auto) y_combinator(Fun &&fun) {
return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}
template <typename F, typename G> auto compose(F f, G g) {
return
[f, g](auto &&...xs) { return g(f(std::forward<decltype(xs)>(xs)...)); };
}
auto pipe = y_combinator([](auto self, auto f, auto g, auto... fs){
if constexpr (sizeof...(fs) > 0) {
auto fg = compose(f, g);
return self(fg, fs...);
} else {
return compose(f, g);
}
});
See it live
|
69,220,047 | 69,220,796 | Is there a way in C++ to make scoped global variables? | Let's say I have a program which uses n big modules:
A) Network/Communication
B) I/O files
C) I/O database
D) GUI
E) ...
Of course, a list of modules could be bigger.
Let's say I want to have some global variable, but with a scope limited to a single module.
As an example, let's say that I/O database module will consist of 10 classes, each representing each table in a database, but it needs some global const state like Name of table A, Columns of table A etc. (as it is a relational database, in table D I may need to use table A).
It is also obvious, that I do not need to access these table names through Network/Communication module. Is there a way to make a variable "globally" accessible only for some part of classes?
Just for clarification - I know that "Global for some part" is a contradiction, but my idea is that I want to keep the accessibility(no need of pointer passing to each object), while limiting the place from where it can be called (for example, limit from global to module scope)
| You don't need globals for that, I strongly advise you to learn about dependency injection. Basically you have one "factory" module. And each module has an interface on you can inject an interface that has getters to access the centralized data. (e.g. members of a n instance of a class). This also allows you to test the independent modules using mocks and stubs (e.g. a test class that returns other values). –
|
69,220,608 | 69,221,378 | How to debug C++-Program which triggers internal bug in gdb? | In one of my C++-projects I found an issue related to a linked library which results in a segfault directly after starting the compiled executable. I tried to dive into the issue using gdb, but it fails with the output:
../../gdb/dwarf2/read.c:1857: internal-error: bool dwarf2_per_objfile::symtab_set_p(const dwarf2_per_cu_data*) const: Assertion `per_cu->index < this->m_symtabs.size ()' failed.
After it is an internal error I am not able to do much (except reporting it), but I still would like to be able to debug the program itself. Which options do I have for that?
Use of a different debugger than gdb?
Manual update to a newer version of gdb (currently on 10.1)?
Somehow catch the segfault before it is damaging the debugger?
?
| Most likely this is already fixed gdb bug: https://sourceware.org/bugzilla/show_bug.cgi?id=28160. It has Target Milestone 11.1, so update to a latest version of gdb which is 11.1 now. It should be fixed in that version.
|
69,221,161 | 69,254,554 | Why is the concept of vacuous initialization necessary? | The concept of vacuous initialization is introduced and used at [basic.life/1], and it does not seem to be used anywhere else in the C++ standard:
The lifetime of an object or reference is a runtime property of the object or reference. A variable is said to have vacuous initialization if it is default-initialized and, if it is of class type or a (possibly multi-dimensional) array thereof, that class type has a trivial default constructor. The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
its initialization (if any) is complete (including vacuous initialization) ([dcl.init]),
Since vacuous initialization is a subset of default initialization, it is initialization for class and array types, and no initialization for scalar types (cf. [dcl.init.general/7]), and therefore both cases are covered by the phrase ‘initialization (if any)’.
So why is the concept of vacuous initialization necessary?
The quote seems equivalent to this amended version:
The lifetime of an object or reference is a runtime property of the object or reference. The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
its initialization (if any) is complete ([dcl.init]),
| The current draft standard, quoted by the OP, has reached its state via CWG issue 2256 (2256. Lifetime of trivially-destructible objects) and P1787R6 (P1787R6: Declarations and where to find them), after which, if any, the term (rather than "the concept") can be used to collective refer to cases where "initialization" will not suffice.
At the very least, it is referred to from [stmt.dcl]/3:
Upon each transfer of control (including sequential execution of statements) within a function from point P to point Q, all variables that are active at P and not at Q are destroyed in the reverse order of their construction. Then, all variables that are active at Q but not at P are initialized in declaration order; unless all such variables have vacuous initialization ([basic.life]), the transfer of control shall not be a jump. [...]
Simply "initialization" does naturally not suffice here, as variable could have non-vacuous initialization such that a jump between point P to point Q would violate the restriction of [stmt.dcl]/3.
If we were to amend [basic.life/1] as proposed, the term would no longer be defined, and e.g. [stmt.dcl]/3 would need to explicitly write out the full initialization contexts for where a jump (under the P->Q restrictions) is allowed.
|
69,221,487 | 69,227,482 | MSVC - Using namespace directive in caller of generic lambda leaks into the lambda's body | Consider the following toy code:
#include <boost/hana/transform.hpp>
#include <range/v3/view/transform.hpp>
auto constexpr f = [](auto) {
using namespace ranges::views;
auto xxx = transform;
};
void caller() {
using boost::hana::transform;
f(1);
}
It compiles fine with GCC and MS' compiler, which means that using boost::hana::transform; is not affecting the names available in f's body, so it's unambiguous that xxx is ranges::views::transform.
On the other hand, if I change using boost::hana::transform; to using namespace boost::hana;, then Visual Studio claims that transform in f's body is an ambiguous name.
Is this a bug in GCC or Visual Studio? Is it a known bug? What is it due to?
Here's a small example (run it):
#include <boost/hana/transform.hpp>
#include <range/v3/view/transform.hpp>
auto constexpr f = [](auto) {
using namespace ranges::views;
auto xxx = transform;
};
void caller() {
#if 1
using namespace boost::hana;
#else
using boost::hana::transform;
#endif
f(1);
}
| It is an MSVC bug that has to do with generic lambdas. A minimal example is
void foo() {}
namespace B {
void foo() {}
}
auto moo = [](auto) {
foo();
};
int main() {
using namespace B;
moo(1);
}
It reproduces with c++17 and c++20 settings.
MSVC is known to have non-conforming handling of template instantiation and two-phase name lookup. Many of these bugs are fixed in the latest versions of the compiler, but apparently not all. Here, after moo is instantiated, the name foo is apparently looked up in the instantiation context. This should not happen because it is not a dependent name.
A related example:
#include <iostream>
namespace A{
template <typename K>
int foo(K) { return 1; }
}
using namespace A;
namespace B {
struct BB {};
}
auto moo = [](auto i) {
return foo(i);
};
void test1() {
std::cout << moo(B::BB{}); // Comment this and see how the output changes
}
namespace B {
int foo(BB) { return 2; }
}
void test2() {
std::cout << moo(B::BB{});
}
int main() {
test1();
test2();
}
(See it here in action.)
|
69,221,539 | 69,229,855 | Does GetKeyState() detect if the key is being released? | Is there a way to detect if the key is being released using GetKeyState()? I read about it, and it only has 2 states, Toggled 0x8000 and Pressed 0x01.
I want something like this:
short Input(int Key, int Mode)
{
if (Mode == KEY_RELEASE)
if (GetKeyState(Key) & KEY_PRESS)
//Wait for the key to be released
else
return GetKeyState(Key) & KEY_PRESS;
}
| GetKeyState returns information about the key state of the current input queue (your thread and attached threads). You can get similar information for all the keys with GetKeyboardState.
Those two functions should only be used in response to some event, you should not be polling over and over to detect changes.
The best way to detect keyboard changes in windows you control is to handle WM_KEYDOWN/UP and WM_CHAR messages.
Worst case scenario, use SetWindowsHookEx to catch keyboard events or window messages.
|
69,221,619 | 69,230,429 | Transform functor struct to take a different argument | I got the following (unconstrained quadratic objective) defined borrowing matrices and vectors from the Eigen-library:
#ifndef QP_UNCON_HPP
#define QP_UNCON_HPP
#include "EigenDataTypes.hpp"
template <int Nx>
struct objective
{
private:
const spMat Q;
const Vec<Nx> c;
public:
objective(spMat Q_, Vec<Nx> c_) : Q(Q_), c(c_) {}
inline scalar operator()(const Vec<Nx> &x)
{
return (.5 * x.transpose() * Q * x + c.transpose() * x);
}
inline Vec<Nx> Eval_grad(const Vec<Nx> &x)
{
return Q.transpose() * x;
}
inline Mat<Nx, Nx> Eval_hessian(const Vec<Nx> &x)
{
return Q;
}
};
This makes it possible to evaluate the objective at different states x:
objective<2> f(Q, c);
Vec<2> x {0,1};
#Objective-value
f(x);
#gradient:
f.Eval_grad(x);
#hessian:
f.Eval_hessian(x);
I want to create a new struct Phi (for line search) where a scalar is used as input arguments instead, something like this:
p_objective<2> Phi(f, x0, p);
double alpha = 0.9;
#Objective-value
Phi(alpha);
#gradient:
Phi.Eval_grad(alpha);
#hessian:
Phi.Eval_hessian(alpha);
Which corresponds to this:
#Objective-value
f(x + alpha*p);
#gradient:
f.Eval_grad(x + alpha*p);
#hessian:
f.Eval_hessian(x + alpha*p);
This would be simple for a single function using lambda functions, but are there smooth ways of 'lambdifying' a functor struct?
EigenDataTypes.hpp
#ifndef EIGENDATATYPES_H
#define EIGENDATATYPES_H
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#ifdef CSOLVER_USE_SINGLE
typedef float real_t;
#else
typedef double real_t;
#endif
using scalar = Eigen::Matrix<double, 1, 1>;
template <int Rows>
using Vec = Eigen::Matrix<double, Rows, 1>;
template <int Rows, int Cols>
using Mat = Eigen::Matrix<double, Rows, Cols>;
using spVec = Eigen::SparseVector<double>;
using spMat = Eigen::SparseMatrix<double>;
using Triplet = Eigen::Triplet<double>;
#endif
1D-example without Eigen-library:
struct objective_1D
{
private:
const double Q;
const double c;
public:
objective_1D(double Q_, double c_) : Q(Q_), c(c_) {}
double operator()(const double &x)
{
return (.5 * x * Q * x + c* x);
}
double Eval_grad(const double &x)
{
return Q * x;
}
double Eval_hessian(const double &x)
{
return Q;
}
};
TLDR;
I want to create a functor struct p_objective
that works as a lambda for struct objective:
p_objective = [&x, &p] (double alpha) (return objective-methods at (x + alpha*p))
|
I want to create a functor struct p_objective that works as a lambda
for struct objective.
If you have already written the objective, you can also similarly make a p_objective. Following is an example.
Here is the (demo)
template <int Nx> class p_objective
{
objective<Nx> f;
const spMat x;
const Vec<Nx> p;
public:
explicit p_objective(const objective<Nx>& ob, spMat const& Q_, const Vec<Nx>& c_)
: f{ ob }
, x{ Q_ }
, p{ c_ }
{}
scalar operator()(const double alpha)
{
return f(x + (alpha*p));
}
Vec<Nx> Eval_grad(const double alpha)
{
return f.Eval_grad(x + alpha * p);
}
Mat<Nx, Nx> Eval_hessian(const double alpha)
{
return f.Eval_hessian(x + alpha * p);
}
};
Since both the objective and the p_objective have member functions, (i.e. Eval_grad, and Eval_hessian), it will be more readable, when they are normal classes, than a lambda function.
|
69,221,638 | 69,221,677 | Find max value in std::vector of structure of specified variable | I have vector of structure described below:
struct Point {
double x,y;
};
And now I have vector<Point> which contains about 2000 elements. I want to find element which contains maximum value of variable y in Point.
I know there is std::max_element but I don't know if it works with variables stored in structures inside vector.
|
I don't know if it works with variables stored in structures inside vector.
Yes it does. Use a custom comparator:
auto it = std::max_element(v.begin(),
v.end(),
[](const auto& a,const auto& b) {
return a.y < b.y;
});
|
69,221,887 | 69,221,946 | How does sorting algorithms sort containers and ranges of floats? | Since comparing floats is evil then if I have a container of floats and I sort it using some standard library sorting algorithm like std::sort then how does the algorithm sort them?
std::vector<float> vf{2.4f, 1.05f, 1.05f, 2.39f};
std::sort( vf.begin(), vf.end() );
So does the algorithm compare 1.05f and 1.05f?
Does it internally uses something like: std::fabs( 1.05f - 1.05f ) < 0.1;?
Does this apply too to containers of doubles? Thank you!
|
So does the algorithm compare 1.05f and 1.05f?
Yes
Does it internally uses something like: std::fabs( 1.05f - 1.05f ) < 0.1;?
No, it uses operator <, e.g. 1.05f < 1.05f. It doesn't ever need to compare for equality, so the comparison using epsilon value is not needed.
Does this apply too to containers of doubles?
Yes, it applies to containers of any type (unless you provide your own comparison function to std::sort)
|
69,221,924 | 69,222,165 | How to make restrictions about the derived class? | Consider the curiously recurring template pattern, can you prevent the following unsafe code to compile?
template <class Derived>
class Base {
public:
void foo()
{
// do something assuming "this" is of type Derived:
static_cast<Derived*>(this)->bar();
}
};
// This is OK
class A: public Base<A>
{
public:
void bar()
{
// ...
}
};
// Crash and burn, should be prevented by the compiler
class B: public Base<A>
{
//...
};
void f()
{
// undefined behavior: B object was static_cast to A
B{}.foo();
}
Is there a way to add some kind of restriction to class Base to prevent the definition of class B to be valid?
| You can make Base<D> constructor (or destructor) private and friend D.
You'll need to add
A()=default;
B()=default;
publicly, but when you do, B can't be created. Which is good.
|
69,222,373 | 69,223,055 | Fastest way for wrapping a value in an interval | I am curious about the ways to wrap a floating-point value x in a semi-closed interval [0; a[.
For instance, I could have an arbitrary real number, say x = 354638.515, that I wish to fold into [0; 2π[ because I have a good sin approximation for that range.
The fmod standard C functions show up quite high in my benchmarks, and by checking the source code of various libc implementations, I can understand why: the thing is fairly branch-ey, likely in order to handle a lot of IEEE754-specific issues:
glibc: https://github.com/bminor/glibc/blob/master/sysdeps/ieee754/flt-32/e_fmodf.c
Apple: https://opensource.apple.com/source/Libm/Libm-315/Source/ARM/fmod.c.auto.html
musl: https://git.musl-libc.org/cgit/musl/tree/src/math/fmod.c
Running with -ffast-math causes GCC to generate code that goes through the x87 FPU on x86/x86_64 which comes with its own set of problems (such as 80-bit doubles, FP state, and other fun things). I would like the implementation to vectorize at least semi-correctly, and if possible to not go through the x87 FPU but through vector registers at least as the rest of my code ends up vectorized, even if not necessarily an optimal way, by the compiler.
This one looks much simpler: https://github.com/KnightOS/libc/blob/master/src/fmod.c
In my case, I am only concerned about usual real values, not NaNs, not infinity. My range is also known at compile-time and sane (a common occurence being π/2), thus the checks for "special cases" such as range == 0 are unnecessary.
Thus, what would be good implementations of fmod for that specific use case ?
| Assuming that the range is constant and positive you can compute its reciprocal to avoid costly division.
void fast_fmod(float * restrict dst, const float * restrict src, size_t n, float divisor) {
float reciprocal = 1.0f / divisor;
for (size_t i = 0; i < n; ++i)
dst[i] = src[i] - divisor * (int)(src[i] * reciprocal);
}
The final code with a simple demo is:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void fast_fmod(float * restrict dst, const float * restrict src, size_t n, float divisor) {
float reciprocal = 1.0f / divisor;
for (size_t i = 0; i < n; ++i)
dst[i] = src[i] - divisor * (int)(src[i] * reciprocal);
}
int main() {
float src[9] = {-4, -3, -2, -1, 0, 1, 2, 3, 4};
float dst[9];
float div = 3;
fast_fmod(dst, src, 9, div);
for (int i = 0; i < 9; ++i) {
printf("fmod(%g, %g) = %g vs %g\n", src[i], div, dst[i], fmod(src[i], div));
}
}
produces an expected output:
fmod(-4, 3) = -1 vs -1
fmod(-3, 3) = 0 vs -0
fmod(-2, 3) = -2 vs -2
fmod(-1, 3) = -1 vs -1
fmod(0, 3) = 0 vs 0
fmod(1, 3) = 1 vs 1
fmod(2, 3) = 2 vs 2
fmod(3, 3) = 0 vs 0
fmod(4, 3) = 1 vs 1
Compilation with GCC with command:
$ gcc prog.c -o prog -O3 -march=haswell -lm -fopt-info-vec
prog.c:8:4: optimized: loop vectorized using 32 byte vectors
prog.c:8:4: optimized: loop vectorized using 32 byte vectors
prog.c:8:30: optimized: basic block part vectorized using 32 byte vectors
Thus the code was nicely vectorized.
EDIT
It looks that CLANG does even a better job vectorizing this code:
401170: c5 fc 10 24 8e vmovups (%rsi,%rcx,4),%ymm4
401175: c5 fc 10 6c 8e 20 vmovups 0x20(%rsi,%rcx,4),%ymm5
40117b: c5 fc 10 74 8e 40 vmovups 0x40(%rsi,%rcx,4),%ymm6
401181: c5 fc 10 7c 8e 60 vmovups 0x60(%rsi,%rcx,4),%ymm7
401187: c5 6c 59 c4 vmulps %ymm4,%ymm2,%ymm8
40118b: c5 6c 59 cd vmulps %ymm5,%ymm2,%ymm9
40118f: c5 6c 59 d6 vmulps %ymm6,%ymm2,%ymm10
401193: c5 6c 59 df vmulps %ymm7,%ymm2,%ymm11
401197: c4 41 7e 5b c0 vcvttps2dq %ymm8,%ymm8
40119c: c4 41 7e 5b c9 vcvttps2dq %ymm9,%ymm9
4011a1: c4 41 7e 5b d2 vcvttps2dq %ymm10,%ymm10
4011a6: c4 41 7e 5b db vcvttps2dq %ymm11,%ymm11
4011ab: c4 41 7c 5b c0 vcvtdq2ps %ymm8,%ymm8
4011b0: c4 41 7c 5b c9 vcvtdq2ps %ymm9,%ymm9
4011b5: c4 41 7c 5b d2 vcvtdq2ps %ymm10,%ymm10
4011ba: c4 41 7c 5b db vcvtdq2ps %ymm11,%ymm11
4011bf: c5 3c 59 c3 vmulps %ymm3,%ymm8,%ymm8
4011c3: c5 34 59 cb vmulps %ymm3,%ymm9,%ymm9
4011c7: c5 2c 59 d3 vmulps %ymm3,%ymm10,%ymm10
4011cb: c5 24 59 db vmulps %ymm3,%ymm11,%ymm11
4011cf: c4 c1 5c 5c e0 vsubps %ymm8,%ymm4,%ymm4
4011d4: c4 c1 54 5c e9 vsubps %ymm9,%ymm5,%ymm5
4011d9: c4 c1 4c 5c f2 vsubps %ymm10,%ymm6,%ymm6
4011de: c4 c1 44 5c fb vsubps %ymm11,%ymm7,%ymm7
4011e3: c5 fc 11 24 8f vmovups %ymm4,(%rdi,%rcx,4)
4011e8: c5 fc 11 6c 8f 20 vmovups %ymm5,0x20(%rdi,%rcx,4)
4011ee: c5 fc 11 74 8f 40 vmovups %ymm6,0x40(%rdi,%rcx,4)
4011f4: c5 fc 11 7c 8f 60 vmovups %ymm7,0x60(%rdi,%rcx,4)
4011fa: 48 83 c1 20 add $0x20,%rcx
4011fe: 48 39 c8 cmp %rcx,%rax
401201: 0f 85 69 ff ff ff jne 401170 <fast_fmod+0x40>
|
69,222,391 | 69,224,317 | multiple optional members in class template without overhead | If I want a class with an optional member, I'm using template specialization:
template<class T>
struct X {
T t;
void print() { cout << "t is " << t << '\n'; }
};
template<>
struct X<void> {
void print() { cout << "without T\n"; }
};
This is nice as there is no runtime overhead and little code duplication.
However, if I have 3 instead of 1 optional class member, I have to write 2^3=8 classes, that is, the "little duplication" quickly becomes unreasonable.
A possible solution may be to use std::conditional like so:
template<class T1, class T2, class T3>
struct X {
conditional_t<is_void_v<T1>, char, T1> t1;
conditional_t<is_void_v<T2>, char, T2> t2;
conditional_t<is_void_v<T3>, char, T3> t3;
void print() {
if constexpr (!is_void_v<T1>) cout << "t1 is " << t1 << '\n';
if constexpr (!is_void_v<T2>) cout << "t2 is " << t2 << '\n';
if constexpr (!is_void_v<T3>) cout << "t3 is " << t3 << '\n';
}
};
but now, objects of my class waste memory. I'm looking for some way to avoid most of the code duplication (down to at most linear in the number of optional members code overhead) while avoiding to spend more runtime and memory than necessary.
Note that this question exists (with answers) for single optional class members (see Optional class members without runtime overhead, Most efficient way to implement template-based optional class members in C++?) but, to the best of my knowledge, it has not been answered for multiple optional members.
| With an optional_member class,
template <class T>
struct OptionalMember
{
T t;
static constexpr bool has_member = true;
};
template<> struct X<void>
{
static constexpr bool has_member = false;
};
you might use inheritance (as long as their types differ) and EBO to avoid extra memory.
template<class T1, class T2, class T3>
struct X : OptionalMember<T1>, OptionalMember<T2>, OptionalMember<T3>
{
void print() {
if constexpr (!OptionalMember<T1>::has_member)
cout << "t1 is " << OptionalMember<T1>::t << '\n';
if constexpr (!OptionalMember<T2>::has_member)
cout << "t2 is " << OptionalMember<T2>::t << '\n';
if constexpr (!OptionalMember<T1>::has_member)
cout << "t3 is " << OptionalMember<T3>::t << '\n';
}
};
or, since C++20, attribute [[no_unique_address]] (no extra memory as long as their types differ).
template<class T1, class T2, class T3>
struct X {
[[no_unique_address]] OptionalMember<T1> t1;
[[no_unique_address]] OptionalMember<T2> t2;
[[no_unique_address]] OptionalMember<T3> t3;
void print() {
if constexpr (!t1.has_member) cout << "t1 is " << t1.t << '\n';
if constexpr (!t2.has_member) cout << "t2 is " << t2.t << '\n';
if constexpr (!t3.has_member) cout << "t3 is " << t3.t << '\n';
}
};
If type might be identical, you might modify OptionalMember to take extra tag (or any kind of identifier as std::size_t):
template <class T, class Tag>
struct OptionalMember
{
T t;
static constexpr bool has_member = true;
};
template<class Tag> struct X<void, Tag>
{
static constexpr bool has_member = false;
};
and then
struct tag1;
struct tag2;
struct tag3;
and use OptionalMember<TX, tagX> instead of OptionalMember<TX> from above solution.
|
69,222,631 | 69,266,317 | 46: regex error 17 for `(dryad-bibo/v)[0-9].[0-9]', (match failed) | I'm trying to determine the mime-type for several types of files using libmagic and the following bit of code:
auto handle = ::magic_open(MAGIC_MIME_TYPE);
::magic_load(handle, NULL);
// Both of these fail with the same error
// file_path being a const char* with the path to the file.
auto type2 = ::magic_file(handle, file_path);
// svg_content being an std::vector<char> with the contents of the file.
//auto type2 = ::magic_buffer(handle, svg_content.data(), svg_content.size());
if(!type2)
{
std::cout << magic_error(handle) << std::endl;
}
::magic_close(handle);
But for any file or buffer I try I receive regex error, either being or similar to:
46: regex error 17 for `(dryad-bibo/v)[0-9].[0-9]', (match failed)
For example with this .svg file:
<svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-no" viewBox="0 0 640 480">
<path fill="#ed2939" d="M0 0h640v480H0z"/>
<path fill="#fff" d="M180 0h120v480H180z"/>
<path fill="#fff" d="M0 180h640v120H0z"/>
<path fill="#002664" d="M210 0h60v480h-60z"/>
<path fill="#002664" d="M0 210h640v60H0z"/>
</svg>
What I've tried so far:
libmagic 5.35
libmagic 5.39
libmagic 5.40
libmagic from opensource.apple
setting LC_TYPE and LANG to "C"
I'm linking against a version of libmagic that was built locally, could there be anything I have missed while building? Are any of the calls incorrect or is there something I'm missing?
I get similar errors when trying to run the related file binary that was compiled locally. Whereas when I use the file command that is available by default I do get image/svg+xml as output.
Edit
To build libmagic (for macOS and Ubuntu), I followed these steps:
Downloaded relevant release from Github
autoreconf --install
./configure
make
make install
Update
It looks like the regex at the bottom of this file is causing issues (at least for the svg):
https://github.com/file/file/blob/b56b58d499dbe58f2bed28e6b3c297fe7add992e/magic/Magdir/dataone
Update 2
Something strange going on; On the system where I've got it working, magic_version() reports 540, as expected. But on the systems where it fails with this error, magic_version() reports 538.
This makes little sense to me as I can't find that version on the system itself anywhere and when I run ./file --version in the build library, it reports file-5.40.
| Very dissatisfying answer, but it was linking against GoogleTest causing this error somehow, not even running any tests, just linking against it.
I switched to using Catch2 instead and the issue was resolved.
|
69,222,691 | 69,298,714 | C++: Get the last week day of any month | i am working on a code to parse cron format
After going through the different syntax i got stuck on the 'L' operator, specifically on the '3L' which will give me the last Wednesday of the month (e.g the last Wednesday of September 2021 is going to be 29th )
the number 3 is the number of day :
0 = Sunday
1 = Monday
.
.
6 = Saturday
i looked through the internet and i cant find anything that can help me (i dont want use any libraries)
i found this code which calculates the last Friday of every month, i want to change it so i can get the last week day of my choice of any month i want.
EDITED
#include <iostream>
using namespace std;
class lastFriday
{
int lastDay[12]; //to store last day of all month//хранить последний день всего месяца
int year; //for given year//за данный год
string m[12]; // to store names of all 12 months//хранить имя всех 12 месяцев
bool isleap; // to check given year is leap year or not//проверить, является ли год високосным или нет
private:
//function to find leap year//функция поиска високосного года
void isleapyear()
{
if ((year % 4))
{
if (year % 100)
isleap = true;
else if ((year % 400))
isleap = true;
}
}
// to display last friday of each month
void display()
{
for (int x = 0; x < 12; x++)
cout << m[x] << lastDay[x] << endl;
}
//function to find last friday for a given month
int getWeekDay(int m, int d)
{
int y = year;
int f = y + d + 3 * m - 1;
m++;
if (m < 3)
y--;
else
f -= int(.4 * m + 2.3);
f += int(y / 4) - int((y / 100 + 7) * 0.75);
f %= 7;
return f;
}
public:
//set name of 12 months
lastFriday()
{
m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: ";
m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";
m[8] = "SEPTEMBER: "; m[9] = "OCTOBER: "; m[10] = "NOVEMBER: "; m[11] = "DECEMBER: ";
}
//function to find last fridays
void findLastFriday(int y)
{
year = y;
//to check given year is leap year or not
isleapyear();
//if given year is leap year then feb has 28 else 29
int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // to set number of days for each month
int d;
//for all 12 months we have to find last friday
for (int i = 0; i < 12; i++)
{
d = days[i];
while (true)
{
if (!getWeekDay(i, d))
break;
d--;
}
lastDay[i] = d;
}
//function call to print display dates of last friday for each month
display();
}
};
int main()
{
int year; //to store year given by user
lastFriday LF;
cout << "Enter the year in the range 1970 to 2037 : ";
cin >> year;
//validation for year between 1970 to 2037
if (year>2037|year<1970)
{
cout << "Not available for this year";
}
else
{
LF.findLastFriday(year);
}
return 0;
}
can anyone help me understand interpreting this code.
thanks!
| I found a solution for my problem and I want to share it with you, maybe someone can find it helpful.
I mentioned in my question that i want to get the day of month of the last weekday of any month.
First, in the cron format, if you want to specify that you could write it like this: "0 14 10 ? SEP 3L ?" this means, execute every last Wednesday of September on 10:14:00.
For that to work in my code, I need to get which day of month is on Wednesday,
This code is a portion of my project, but I will try explaining everything,
else if (contains(str[5],'L'))
{
if (str[5] == "L") bdaysOfWeekDesc[6]=6;
else
{
int diff;
auto parts = split(str[5],'L');
auto LDoM = LastDay(stoi(monthReplaced),currentYear);
tm time_in = { 0, 0, 0, LDoM, stoi(monthReplaced)-1, currentYear - 1900};
time_t time_temp = mktime(&time_in);
const tm * time_out = localtime(&time_temp);
if (stoi(parts[0].data()) == time_out->tm_wday)
{
bdaysOfMonthsDesc[time_out->tm_mday] = time_out->tm_mday;
}
else if ((stoi(parts[0].data()) > time_out->tm_wday) || time_out->tm_wday ==0 )
{
diff = time_out->tm_wday - stoi(parts[0].data());
for(size_t j=0;j<=sizeof(bdaysOfMonthsDesc) / sizeof(bdaysOfMonthsDesc[0]);j++)
{
bdaysOfMonthsDesc[j]=0;
bdaysOfMonthsDesc[time_out->tm_mday + abs(diff) - 7] = time_out->tm_mday + abs(diff) - 7;
}
}
else if (stoi(parts[0].data()) < time_out->tm_wday)
{
diff = time_out->tm_wday - stoi(parts[0].data());
for(size_t j=0; j <= sizeof(bdaysOfMonthsDesc) / sizeof(bdaysOfMonthsDesc[0]); j++)
{
bdaysOfMonthsDesc[j] = 0;
bdaysOfMonthsDesc[time_out->tm_mday - abs(diff)] = time_out->tm_mday - abs(diff);
}
}
}
}
the split function is for splitting the field according to the separator given
e.g: auto parts = split("3L", 'L');
parts[0] equals to "3"
the contains function checks if a character exists in a string or not
e.g: contains("3L", 'L');
the split and contains functions are from the croncpp
The LastDay function returns the last day (30 or 31 or 28 or 29) of the month given. This function is from @saqlain response on an other thread
At first, I need to get the date for last day of the month
so:
tm time_in = {seconds, minutes, hours, dayOfMonth, Month, year-1900}
seconds: 0-based,
minutes: 0-based,
hours: 0-based,
DOM: 1-based day,
Month: 0-based month ( the -1 in the code is because my month's field is 1-based)
year: year since 1900
with the mktime() and localtime() functions I can get which weekday is on the 30th or 31st of the month
After that, I tested if the week day I am requesting in the cron format is the same as the weekday of the last day of month,
or if it's superior or inferior.
With this code, my problem was solved, and maybe it can help someone else.
|
69,223,831 | 69,223,897 | Problems with Glm functions | Why does this code compile
[[nodiscard]] glm::mat4 rotationX(double theta)
{
return glm::rotate(glm::mat4(1.0), static_cast<float>(theta), glm::vec3(1.0, 0.0, 0.0));
}
and this one not
[[nodiscard]] glm::mat4 rotationX(double theta)
{
return glm::rotate(glm::mat4(1.0), theta, glm::vec3(1.0, 0.0, 0.0));
}
it results in error C2672 no matching overloaded function found and
Error C2782: Template parameter T is ambigous.
what type should theta be?
Also this code
[[nodiscard]] glm::mat4 shearing(double xy, double xz, double yx, double yz, double zx, double zy)
{
auto sh = glm::mat4(1.0);
sh[1][0] = xy;
sh[2][0] = xz;
sh[2][1] = yz;
sh[0][1] = yx;
sh[0][2] = zx;
sh[1][2] = zy;
return sh;
}
produces the following warning:
warning C4244: 'argument' : conversion from 'double' to 'T', possible loss of data
I can't understand what exactly the error is, because everything else seems to work.
PS, I include
#include <glm/fwd.hpp>
in .hpp and
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
in .cpp.
| When using glm::rotate with vec3 and mat4, the type of theta must be float, because the element type of mat4 and vec3 is float:
typedef mat<4, 4, f32, defaultp> mat4;
typedef vec<3, float, defaultp> vec3;
The corresponding double precision data types are damt4 and dvec3:
typedef mat<4, 4, f64, defaultp> dmat4;
typedef vec<3, f64, defaultp> dvec3;
The names of the types are the same as for the corresponding GLSL data types (Data Type (GLSL)). In glsl, the matrix and vector data types can be constructed from any basic data type.
|
69,224,065 | 69,263,374 | "undefined reference" and includes not found when using OpenCV in C++ | I'm very newbie with c++ and I need some help with libraries
Here's the case,
This simple code:
#include <opencv2/objdetect.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <iostream>
int main() {
cv::CascadeClassifier eye_detection;
return 1;
}
compiling with
g++ main.cpp -I/usr/include/opencv4
returns me
/usr/bin/ld: /tmp/ccOsUApG.o: na função "main":
main.cpp:(.text+0x20): referência não definida para "cv::CascadeClassifier::CascadeClassifier()"
/usr/bin/ld: main.cpp:(.text+0x31): referência não definida para "cv::CascadeClassifier::~CascadeClassifier()"
collect2: error: ld returned 1 exit status
Which translates to "undefined reference"
I also tried to change the way I wrote the "includes"
#include <opencv4/opencv2/objdetect.hpp>
#include <opencv4/opencv2/highgui.hpp>
#include <opencv4/opencv2/imgproc.hpp>
#include <opencv4/opencv2/videoio.hpp>
#include <iostream>
int main() {
cv::CascadeClassifier eye_detection;
return 1;
}
and compile with:
g++ main.cpp
and I had:
In file included from main.cpp:1:
/usr/include/opencv4/opencv2/objdetect.hpp:47:10: fatal error: opencv2/core.hpp: Arquivo ou diretório inexistente
47 | #include "opencv2/core.hpp"
| ^~~~~~~~~~~~~~~~~~
compilation terminated.
which translates to file not found
I checked other similar questions like this one, but I am doing it already without success
I thought about throwing the "opencv2" folder into the "include" folder directly, but that doesn't seem right, how can I compile this code the right way?
| Finally I figured it out, I created the CMakeList file as the library website says and still didn't worked, so I decided to uninstall my package from my system's package manager and installed it manually downloading the code and compiling it with cmake, and it did work now, even though I changed nothing (it might just changed the folder and I wasn't able to point it right before)
In short, cpp is way more complicated than I thought, going to check more about make and cmakes files from now on
|
69,224,093 | 69,224,292 | Structs without ifdefs in C or C++ | There are some C projects with structs full of ifdefs (for ex. WolfSSL https://github.com/wolfSSL/wolfssl/blob/bb70fee1ecff8945af8179f48e90d78ea7007c66/wolfssl/internal.h#L2792)
struct {
int filed_1;
int field_2;
#ifdef SETTING_A
int filed_b;
#endif
#ifdef SETTING_B
int field_b;
#endif
}
The reason is to reduce struct size for unused options.
There are a lot of ifdefs! Everywhere!
Is there a C++ way to get rid of those ifdefs, retaining the ability for compiler to optimize out unused fields?
Maybe with templates, usings or CRTP inheritance?
| You can do it in C++20 with [[no_unique_address]] and some chicanary. This isn't guaranteed result in smaller types however, so I still suggest you use the #defines
template<typename>
struct Empty {};
template<typename T, bool enable, typename uniquer>
using MaybeEmpty = std::conditional_t<enable, T, Empty<uniquer>>;
struct foo {
int filed_1;
int field_2;
[[no_unique_address]] MaybeEmpty<int, settingA, struct filed_b_uniquer> filed_b;
[[no_unique_address]] MaybeEmpty<int, settingB, struct field_b_uniquer> field_b;
};
Prior to C++20, that would have to be done with base classes
struct with_filed_b {
int filed_b;
};
struct with_field_b {
int field_b;
};
struct foo : MaybeEmpty<with_filed_b, settingA, struct filed_b_uniquer>, MaybeEmpty<with_field_b , settingB, struct field_b_uniquer> {
int filed_1;
int field_2;
};
|
69,224,905 | 69,226,384 | Inheritance and accessing attributes | I am learning OOP in C++, and I have written this piece of code to learn more about inheritance.
#include<bits/stdc++.h>
using namespace std;
class Employee {
public:
string name;
int age;
int weight;
Employee(string N, int a, int w) {
name = N;
age = a;
weight = w;
}
};
// this means the class developer inherits from employee
class Developer:Employee {
public:
string favproglang; //this is only with respect to developer employee
// now we will have to declare the constructor
Developer(string name, int age, int weight, string fpl)
// this will make sure that there is no need to reassign the name, age and weight and it will be assigned by the parent class
:Employee(name, age, weight) {
favproglang = fpl;
}
void print_name() {
cout << name << " is the name" << endl;
}
};
int main() {
Developer d = Developer("Hirak", 45, 56, "C++");
cout << d.favproglang << endl;
d.print_name();
cout << d.name << endl; //this line gives error
return 0;
}
Here the developer class is inheriting from the employee class, but when I am trying to print the name of the developer from the main function cout << d.name << endl; I am getting this error 'std::string Employee::name' is inaccessible within this context.
I am not getting why I am getting this error? I have declared all the attributes as public in the parent class. This error is not their when I am trying to access the name from the developer class itself as you can see in the function print_help(). Moreover I can also print d.favproglang from the main function, but then why not d.name? Any help will be highly appreciated. Thank you.
| There are 2 solutions(straightforward) to this.
Solution 1
Replace the class keywords for both the Employee and Developer class with the keyword struct. Note even if you replace class keyword for Developer with struct and leave the class keyword as it is for Employee then also this will work.
Solution 2
Add the keyword public in the derivation list as shown in the next line:
class Developer:public Employee
|
69,225,287 | 69,226,908 | Pointer issues when upgrading to openSSL 1.1.1 | I was using openSSL 1.0.2 and decided to upgrade to version 1.1.1k. However, I have some problems with some pointers:
X509_STORE_CTX *vrfy_ctx = X509_STORE_CTX_new();
X509_STORE_CTX_init(vrfy_ctx, store, cert_x509, NULL);
if(X509_verify_cert(vrfy_ctx) != 1)
{
if(ignore_date)
{
//X509_V_FLAG_NO_CHECK_TIME is not available here so check
// if the error is related to datetime, if it is, just ignore it
switch(vrfy_ctx->error) //error here
{
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_CERT_HAS_EXPIRED:
X509_STORE_CTX_free(vrfy_ctx);
X509_STORE_free(store);
return true;
}
}
error_message = X509_verify_cert_error_string(vrfy_ctx->error); //error here
X509 *error_cert = X509_STORE_CTX_get_current_cert(vrfy_ctx);
X509_NAME *certsubject = X509_get_subject_name(error_cert);
error_message += X509_NAME_oneline(certsubject, 0, 0);
X509_free(error_cert);
X509_STORE_CTX_free(vrfy_ctx);
X509_STORE_free(store);
return false;
}
And here too:
std::string ssl_tools::public_key_type(X509 *x509)
{
EVP_PKEY *pkey=X509_get_pubkey(x509);
int key_type = EVP_PKEY_type(pkey->type); //error here
EVP_PKEY_free(pkey);
if (key_type==EVP_PKEY_RSA) return "RSA";
if (key_type==EVP_PKEY_DSA) return "DSA";
if (key_type==EVP_PKEY_DH) return "DH";
if (key_type==EVP_PKEY_EC) return "ECC";
return "";
}
int ssl_tools::public_key_size(X509 *x509)
{
EVP_PKEY *pkey=X509_get_pubkey(x509);
int key_type = EVP_PKEY_type(pkey->type); //error here
int keysize = -1; //or in bytes, RSA_size() DSA_size(), DH_size(), ECDSA_size();
keysize = key_type==EVP_PKEY_RSA && pkey->pkey.rsa->n ? BN_num_bits(pkey->pkey.rsa->n) : keysize; //error here
keysize = key_type==EVP_PKEY_DSA && pkey->pkey.dsa->p ? BN_num_bits(pkey->pkey.dsa->p) : keysize; //error here
keysize = key_type==EVP_PKEY_DH && pkey->pkey.dh->p ? BN_num_bits(pkey->pkey.dh->p) : keysize; //error here
keysize = key_type==EVP_PKEY_EC ? EC_GROUP_get_degree(EC_KEY_get0_group(pkey->pkey.ec)) : keysize; //error here
EVP_PKEY_free(pkey);
return keysize;
}
The above errors are: "the pointer to the incomplete class type "evp_pkey_st" is not allowed" and "the pointer to incomplete class type "x509_store_ctx_st" is not allowed"
Couldn't understand how I can resolve these mistakes, any thoughts?
| Many structures are opaque in OpenSSL 1.1.1, which means you are not allowed to dive into the structure internals to access values. Instead you need to use accessor functions:
Replace any instances of vrfy_ctx->error with X509_STORE_CTX_get_error(vrfy_ctx)
Replace any instances of pkey->type with EVP_PKEY_id(pkey).
Replace any instances of pkey->pkey.rsa->n with RSA_get0_n(EVP_PKEY_get0_RSA(pkey))
Replace any instances of pkey->pkey.dsa->p with DSA_get0_p(EVP_PKEY_get0_DSA(pkey))
Replace any instances of pkey->pkey.dh->p with DH_get0_p(EVP_PKEY_get0_DH(pkey))
Replace any instances of pkey->pkey.ec with EVP_PKEY_get0_EC_KEY(pkey).
|
69,225,503 | 69,225,804 | how to generate the same random number in two different environments? | I compiled exactly the same code that generate random numbers in two different environments ( Linux and visual studio ). But I noticed that the outputs are different. I searched online and understand that the two implementations generate different random numbers. But I need the Linux to generate the same random numbers of that generated by visual studio.
So, how to let the two different environments ( Linux and visual studio ) generate the same random numbers. Any ideas.
My code:
void mix_dataset(array<array<int, 20>, 5430>& array_X_dataset, array<int, 5430>& array_Y_dataset) {
// size_t len = array_X_dataset.size();
// for (size_t i = 0; i < len; ++i) {
// size_t swap_index = rand() % len;
mt19937 engine;
engine.seed(3);
for (size_t i = 0; i < 5430; ++i) {
size_t swap_index = engine() % 5430;
if (i == swap_index)
continue;
array<int, 20> data_point{ };
data_point = array_X_dataset[i];
array_X_dataset[i] = array_X_dataset[swap_index];
array_X_dataset[swap_index] = data_point;
int Y = array_Y_dataset[i];
array_Y_dataset[i] = array_Y_dataset[swap_index];
array_Y_dataset[swap_index] = Y;
}
}
int main(){
srand(3);
mix_dataset(array_X_dataset, array_Y_dataset);
}
| You can use a the mersenne twister it has reproducable output (it is standardized).
Use the same seed on 2 machines and you're good to go.
#include <random>
#include <iostream>
int main()
{
std::mt19937 engine;
engine.seed(1);
for (std::size_t n = 0; n < 10; ++n)
{
std::cout << engine() << std::endl;
}
}
You can verify it here, https://godbolt.org/z/j5r6ToGY7, just select different compilers and check the output
|
69,225,658 | 69,226,143 | Why am I getting the last sum as largest sum of subarray? | #include <bits/stdc++.h>
using namespace std;
void printpair(int ar[], int n)
{
int largestsum = INT_MIN, currentsum = 0;
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
currentsum = 0;
largestsum = INT_MIN;
for (int k = i; k <= j; k++)
{
cout << ar[k] << ",";
currentsum += ar[k];
}
cout << "\n";
}
largestsum = max(largestsum, currentsum);
cout << "the largest sum is " << largestsum << endl;
}
}
int main()
{
int n;
cin >> n;
int ar[n];
for (int i = 0; i < n; i++)
cin >> ar[i];
printpair(ar, n);
}
When I input:
5
-5 5 6 -7 1
I'm getting output from the first iteration of the outer loop as
-5,
-5,5,
-5,5,6,
-5,5,6,-7,
-5,5,6,-7,1,
the largest sum is 0
...
But it should be 6 as -5 + 5 + 6 = 6 so the largest sum of subarray must be 6, but here it is 0, why!?
| You are not saving the max sum value, you need to do it within the loop:
void printpair(int ar[], int n)
{
int largestsum = INT_MIN, currentsum = 0;
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
currentsum = 0;
largestsum = INT_MIN;
for (int k = i; k <= j; k++)
{
std::cout << ar[k] << ",";
currentsum += ar[k];
largestsum = std::max(largestsum, currentsum);
}
std::cout << "\n";
}
std::cout << "the largest sum is " << largestsum << std::endl;
}
}
Note that variable length arrays are not C++ standard, you should not use them, I would also advise you not to use using namespace std; and #include <bits/stdc++.h>;, here are some threads with more on these matters:
Why aren't variable-length arrays part of the C++ standard?
Why is "using namespace std;" considered bad practice?
Why should I not #include <bits/stdc++.h>?
|
69,226,084 | 69,261,298 | Why might I get heap corruption using Armadillo matrices with pybind11? | I've worked on this for a couple weeks and can't make a reproducible example outside my codebase. That's why I need help! I'm not sure if this is a problem with pybind11 or Armadillo. It's not a problem with Carma since it happens in situations with no conversion going on.
EDIT: This actually does appear to be a bug in Carma and my MRE is working.
I've been trying to boil it down to an MRE and have been unsuccessful. I will explain what I know here, but since this isn't enough to reproduce the bug, what I need most are some ideas as to where to look. This is basically a very hard-to-reproduce memory corruption error (heap corruption, Windows fatal exception: code 0xc0000374). It seems to happen when I have a matrix A, not initialized, and assign a matrix to it large enough that Armadillo acquires memory. The crash happens when that memory is released.
I'm on Windows 10, using Armadillo 10.6.2 and pybind11 v2.7.1, compiling using Clang 11.
// mat_container.cpp
#include "mat_container.h"
MatrixContainer::MatrixContainer(size_t d) {
A = arma::Mat<double>(d, d, arma::fill::eye);
std::cerr << "filled arma matrix\n";
}
Binding code
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <armadillo>
#include <carma>
#include "mat_container.h"
PYBIND11_MODULE(example, m) {
py::class_<MatrixContainer>(m, "MC").def(py::init<size_t, bool>())
.def_readwrite("A", &MatrixContainer::A);
}
All I need to do to trigger the crash is from Python call example.MC(11) and it crashes upon releasing memory in the matrix destructor of the member variable (not the temporary one assigned to it). Armadillo debug messages right before crash:
@ __cdecl arma::Mat<double>::~Mat(void) [eT = double] [this = 000001569470DBA0]
Mat::destructor: releasing memory
In my attempted MRE, I tried to reproduce the same structure, with binding code using this MatrixContainer class compiled in a separate library. I don't know what could be missing so my MRE doesn't reproduce the bug.
Weird things
Only happens when calling from pybind11, not pure C++
Only happens when the constructor for the class containing the matrix is in a separately compiled source file. It doesn't happen when the constructor is in the header file.
Only happens when assigning a non-identity (e.g., np.ones but not np.eye) matrix to an object's matrix member variable. But this only happens on a class in my source code, not on the smaller test class I created!
Only happens when A is large enough for Armadillo to acquire memory instead of use local memory
Setting the size of A with set_size() before assigning to it doesn't solve the issue
This appears to be Armadillo-specific, when Armadillo releases memory (confirmed using ARMA_EXTRA_DEBUG), because I don't get a similar error when I use another class with dynamically allocated memory like a vector
When A is using acquired memory and is replaced by a matrix using local memory, the crash occurs
mc = MC(11)
mc.A = np.eye(3)
Arma debug messages right before crash, as mc.A is being assigned:
@ void __cdecl arma::Mat<double>::init_warm(arma::uword, arma::uword) [eT = double] [in_n_rows = 3, in_n_cols = 3]
Mat::init(): releasing memory
but not when it's the other way around; this runs successfully. It does not crash as the acquired memory is released as A is destroyed:
mc = MC(3)
mc.A = np.eye(11)
And when an 11x11 A is replaced by another 11x11 matrix from numpy, the crash is again Mat::destructor: releasing memory as in the very first example without assignment from Python. What I deduce from these examples is that the crash is averted when an acquired memory matrix prepared by Carma (not Armadillo directly) is assigned to a local memory A.
UPDATE:
Still working on this, but it looks like the code fails because arma_extra_code is on (where it wasn't in the MRE). The culprit seems to be ARMA_ALIEN_MEM functions, set here
| Credit to the carma developer, @RUrlus, for the answer:
The problem is due to the bindings module, linked to carma, being linked to a library that hasn't been linked to carma. The external library (mc in the MRE) was allocating memory using the standard malloc while pybind11 was using Carma's free on destruction. The mismatch was causing the crash on Windows.
Perhaps in the future there could be a more elegant solution, but for now the workaround is to link external libraries to carma at compile-time, e.g., target_link_libraries(mc PUBLIC armadillo carma) even if that external library doesn't include or use Carma in any obvious way.
|
69,226,390 | 69,226,621 | Is a for(auto ...) of list where we append new elements within the loop guaranteed to work against all the elements? | I have a class with an f_next field that looks like so:
class process
{
public:
typedef std::shared_ptr<process> pointer_t;
typedef std::list<pointer_t> list_t;
void add_next_process(pointer_t p);
void wait();
private:
list_t f_next = list_t();
};
The add_next_process() simply appends p to f_next:
f_next.push_back(p);
As a result, the wait() has to gather all the processes and wait for all of them. I'd like to avoid recursion and instead generate a list of all the f_next like so:
list_t n(f_next);
for(auto & it : n)
{
n.insert(n.end(), it->f_next.begin(), it->f_next.end());
}
Is n guaranteed to include all the items once the for() loop exits?
I know that std::list::insert() does not change the iterator:
No iterators or references are invalidated.
but I'm wondering whether the for(auto ...) will continue through all the items that I appended along the way.
| For-range is just a syntactic sugar for a classic for loop operating on iterators.
As long as your container implements begin and end (or you have free overloads), and don't invalidate the iterator in the process, this should technically be fine.
Other thing is whether this is a good and maintainable idea.
Before C++17:
auto && __range = range-expression ;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
range-declaration = *__begin;
loop-statement
}
From C++17:
auto && __range = range-expression ;
auto __begin = begin_expr ;
auto __end = end_expr ;
for ( ; __begin != __end; ++__begin) {
range-declaration = *__begin;
loop-statement
}
|
69,226,393 | 69,226,807 | How to properly use the for-range statements syntax in C++? | iteration-statement:
while ( condition ) statement
do statement while ( expression ) ;
for ( init-statement conditionopt ; expressionopt ) statement
for ( init-statementopt for-range-declaration : for-range-initializer ) statement
for-range-declaration:
attribute-specifier-seqopt decl-specifier-seq declarator
attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ]
for-range-initializer:
expr-or-braced-init-list
The syntax above is given by C++ISO. I have seen a ton of examples using the classic approach for a for-range statement:
#include <iostream>
using namespace std;
int main() {
int a[5] = { 1,2,3,4,5 };
for (int i : a) { cout << i << endl; }
}
But I'm not finding how to use for-range-declaration as attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ]. How does it work in this case? Could you provide an example?
| This part of the grammar
attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ]
is to allow for structured bindings in a loop. e.g. you could do something like this:
struct S { int i,j; };
std::vector<S> v;
for (auto [a, b] : v)
// ... a and b simply refer to i and j
Note that the identifier-list indicates that the names a and b just refer to the members of the struct.
|
69,226,565 | 69,226,965 | Reinterpret_cast sent data | The code below is just an example.
Function1 is a dllexport, how do I properly convert/read the value of data inside of Foo2?
When I print the value, it returns 000001DFA1C501F3.
Function1(PVOID InPassThruBuffer, ULONG InPassThruSize);
void Foo(std::wstring* data) {
Function1(&data, sizeof(wchar_t))
}
// ==============================================
typedef struct _REMOTE_ENTRY_INFO_
{
UCHAR* UserData;
ULONG UserDataSize;
}REMOTE_ENTRY_INFO;
void __stdcall Foo2(REMOTE_ENTRY_INFO* inRemoteInfo)
{
std::wstring wdata;
if (inRemoteInfo->UserDataSize == sizeof(wchar_t))
wdata = reinterpret_cast<wchar_t *>(inRemoteInfo->UserData);
}
| Try something more like this instead:
void Foo(std::wstring* data)
{
Function1(const_cast<wchar_t*>(data->c_str()), data->size() * sizeof(wchar_t));
// or, in C++17 and later:
// Function1(data->data(), data->size() * sizeof(wchar_t));
}
void __stdcall Foo2(REMOTE_ENTRY_INFO* inRemoteInfo)
{
wchar_t *wdata = reinterpret_cast<wchar_t*>(inRemoteInfo->UserData);
int wdatalen = inRemoteInfo->UserDataSize / sizeof(wchar_t);
}
Or, if Foo2() in called in the context of Function1() before Foo() exits, then you can just pass the std::wstring* pointer itself instead:
void Foo(std::wstring* data)
{
Function1(&data, sizeof(data));
// or, if Function1() does not *copy* the data,
// merely passes around the provided pointer as-is:
//
// Function1(data, sizeof(*data));
}
void __stdcall Foo2(REMOTE_ENTRY_INFO* inRemoteInfo)
{
std::wstring *wdata = *reinterpret_cast<std::wstring**>(inRemoteInfo->UserData);
// or:
// std::wstring *wdata = reinterpret_cast<std::wstring*>(inRemoteInfo->UserData);
}
|
69,226,612 | 69,226,645 | Which of the following is the correct behavior (g++ vs clang++-12)? | The following is the code:
#include <iostream>
const int& temp_func() {
return 3;
}
int main() {
std::cout << temp_func() << std::endl;
}
When compiled with g++ (Ubuntu 9.3.0-17ubuntu1~20.04), the result:
[1] 402809 segmentation fault ...
On the other hand, when compiled with clang++-12, the result:
3
| Both are correct. Your code has undefined behavior. When you do return 3 a temporary int object is created, and the reference the function returns is bound to that temporary object. After the return statement finishes, that temporary is destroyed leaving the reference dangling. Any access though that reference has undefined behavior.
|
69,227,220 | 69,228,049 | Expanding QChartView | A little at lost as to why QChartView will expand when put inside of a QTabWidget.
Here's a picture of the application when QChartView is not expanding (because it's hidden).
The black portion of the app is QOpenGLWidget.
When I click on the chart view, it will gradually increase in size until QOpenGLWidget is hidden.
When QChartView is just in a QVBoxLayout with QOpenGLWidget, then this effect does not occur. It's only when I add QChartView inside of the QTabWidget that this happens. I'm trying to figure out how to have QChartView not expand, and resize the same way other widgets do (such as the QTextEdit widget in this example).
Here's the code, which was written as a minimal example to reproduce the effect.
#include <QApplication>
#include <QChart>
#include <QChartView>
#include <QMainWindow>
#include <QOpenGLWidget>
#include <QTabWidget>
#include <QTextEdit>
#include <QVBoxLayout>
int
main(int argc, char** argv)
{
QApplication app(argc, argv);
// Main Window
QMainWindow main_window;
main_window.resize(1280, 720);
main_window.show();
// Central Widget
QWidget central_widget(&main_window);
main_window.setCentralWidget(¢ral_widget);
QVBoxLayout layout(¢ral_widget);
central_widget.setLayout(&layout);
// OpenGL Widget
QOpenGLWidget gl_widget(¢ral_widget);
gl_widget.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
layout.addWidget(&gl_widget);
// Tab Widget
QTabWidget tab_widget(¢ral_widget);
layout.addWidget(&tab_widget);
// Log
QTextEdit text_edit(&tab_widget);
text_edit.setReadOnly(true);
tab_widget.addTab(&text_edit, "Log");
// Chart View
QtCharts::QChartView chart_view(&tab_widget);
tab_widget.addTab(&chart_view, "Chart");
return app.exec();
}
| The problem is caused because the QChartView has the expansion sizePolicy as opposed to the QOpenGLWidget, so when it becomes visible it expands, hiding the other widget. The solution is to set a stretch factor associated with each widget in the layout:
layout.addWidget(&gl_widget, 1);
layout.addWidget(&tab_widget, 1);
|
69,227,273 | 69,227,438 | Are the data members in Stack or Heap memory in C++ | Just want to know where the data members are in the memory, heap or stack.
Here's my code:
#include <iostream>
#define p(s) std::cout << s << std::endl
class Fook
{
public:
char c = 'c'; //
Fook() {
p(c);
}
};
class IDK
{
public:
int* arr = new int[1]; //
IDK() {
Fook fook3; //
arr[0] = 90;
Fook* fook4 = new Fook(); //
p(arr[0]);
}
};
int main(int argc, char const *argv[])
{
Fook fook1;
Fook* fook2 = new Fook();
IDK idk1;
IDK* idk2 = new IDK();
return 0;
}
compiles and gives the expected output
c
c
c
c
90
c
c
90
in the above code sample the obj *fook2 and *idk2 are allocated on heap mem and fook1 and idk1 are allocated on stack mem.
is fook2->c on the stack mem (the obj is on the heap mem)
is *arr in idk1 on the heap mem (the obj is on the stack mem)
is *arr in idk2 on the heap mem
is *fook4 in ctor of idk1 on the heap mem
is fook3 in ctor of idk2 on the heap mem
is *fook4 in ctor of idk2 on the heap mem
To summarize everything,
Where are the data members of each object created in int main(int argc, char const *argv[]) in the memory(stack or heap)
| First of all: stacks and heaps are not C++ language concepts, but are implementation concepts. The C++ standard talks about automatic and dynamic storage instead. But for simplicity lets just talk about stacks and heaps.
Typically the new operator will put your object on the heap (unless new operator is overloaded). Otherwise your object goes to the stack.
is fook2->c on the stack mem (the obj is on the heap mem)
The c part of a Fook object will be in the same place where the object is. In the fook2 case it is the heap. Note the subtlety. You said fook2->c which is the arrow operator: it actually loads c (unless overloaded). So the result lands to wherever the left side of fook2->c is.
is *arr in idk1 on the heap mem (the obj is on the stack mem)
Again: arr field on an IDK object lives wherever the object lives. In the case of idk1 we have that arr pointer lives on stack. However the thing it is pointing to, i.e. *arr lives on the heap (since new was used). There's a subtlety here as well: * operator actually loads data to wherever the left side is (again: unless overloaded).
is *arr in idk2 on the heap mem
idk2 lives on the heap, and thus arr pointer lives on the heap. Additionally *arr lives on the heap since that's how it was declared via new operator.
is *fook4 in ctor of idk1 on the heap mem
fook4 pointer lives on the stack. The data it is pointing to lives on the heap.
is fook3 in ctor of idk2 on the heap mem
fook3 object lives on the stack. Always. It doesn't matter that the constructor was called during new initialization of the heap object idk2. Constructor is just a function, a bit special, but not really different from other functions. The constructor doesn't even know whether it is called on a heap or stack object, and it doesn't care.
is *fook4 in ctor of idk2 on the heap mem
Similarly to (3) and (4) fook4 pointer lives on the stack, while the data it is pointing to (i.e. *fook4) lives on the heap.
|
69,228,373 | 69,229,404 | Efficiently take N lowest bits of GMP mpz_t | There is mpz_class C++ wrapper of GMP type mpz_t. Having mpz_class number what is the most efficient way to take its N lowest bits to create another mpz_class number?
Of course I can do following masking operation
size_t N = 273; // how many lo bits to take
mpz_class x = ... ; // fill with something...
mpz_class mask = (mpz_class(1) << N) - 1; // mask having N 1-bits
mpz_class result = x & mask; // final result, N lowest bits taken
But this masking needs lots of unnecessary bit-and operations and slows down code. Maybe there is some shortcut for that like result = x.take_lo(N);?
Also it is possible that mpz_class is lacking such shortcut, but at least maybe C API has this function? Because any mpz_class can be easily converted without overhead to C type mpz_t through mpz_t c_num = x.get_mpz_t();. So it is fine for me to have .take_lo(N) shortcut within C API only.
| Although there's no C++ operator overload or function for mpz_class, you can indeed use: mpz_tdiv_r_2exp provided by the C API. e.g.,
mpz_tdiv_r_2exp(result.get_mpz_t(), x.get_mpz_t(), N);
note: cdiv and fdiv variants are available too.
Using mp_bitcnt_t as the type for (N), or static_cast<mp_bitcnt_t>(N) as the argument, would be more robust - as mp_bitcnt_t seems to be unconditionally defined as unsigned long, which may not match size_t.
|
69,228,813 | 69,228,838 | How to make std::map::find function case sensitive? | I had interviewed with a MNC company. He gave me the following code and asked me to make find() function as case-sensitive. I tried, but failed to understand how to make inbuilt find function as case-sensitive. Is there any way to make it case-sensitive to find only a particular key value?
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> mp;
mp["Test"] = 1;
mp["test"] = 2;
mp["TEST"] = 3;
mp["tesT"] = 4;
for (auto it = mp.find("TEST"); it != mp.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}
Output :
TEST 3
Test 1
tesT 4
test 2
But I expect output is:
TEST 3
| The problem is the for loop. You do not need to iterate through the map to print it. Rather you need to do
auto it = mp.find("TEST");
if (it != mp.end())
std::cout << it->first << " " << it->second << std::endl;
The std::map::find will find an iterator pointing to the key-value pair which has key exactly "TEST", if not found just the end iterator.
|
69,228,861 | 69,229,804 | CPP Question - Primes array, how the sqrt while loop finds the prime numbers? | I would like your help to understand how the below code is producing the prime numbers.
The code is correct, but I am not sure how the loop ensures that isprime = trial % primes[3] > 0; is not a prime number.
P.s. I know that 9 is not a prime number, but I would like to understand how the below code understands that 9 is not a prime number... probably it's connected to the sqrt and limit?
// Calculating primes using dynamic memory allocation
#include <iostream>
#include <iomanip>
#include <cmath> // For square root function
int main()
{
size_t max {}; // Number of primes required
std::cout << "How many primes would you like? ";
std::cin >> max; // Read number required
if (max == 0) return 0; // Zero primes: do nothing
auto* primes {new unsigned[max]}; // Allocate memory for max primes
size_t count {1}; // Count of primes found
primes[0] = 2; // Insert first seed prime
unsigned trial {3}; // Initial candidate prime
while (count < max)
{
bool isprime {true}; // Indicates when a prime is found
const auto limit = static_cast<unsigned>(std::sqrt(trial));
for (size_t i {}; primes[i] <= limit && isprime; ++i)
{
isprime = trial % primes[i] > 0; // False for exact division
}
if (isprime) // We got one...
primes[count++] = trial; // ...so save it in primes array
trial += 2; // Next value for checking
}
// Output primes 10 to a line
for (size_t i{}; i < max; ++i)
{
std::cout << std::setw(10) << primes[i];
if ((i + 1) % 10 == 0) // After every 10th prime...
std::cout << std::endl; // ...start a new line
}
std::cout << std::endl;
delete[] primes; // Free up memory...
primes = nullptr; // ... and reset the pointer
}
| Okay, think about prime numbers. A number is prime if there are no prime numbers that divide into it evenly.
maybe_prime % lower_prime == 0
If that's true for any of the prime numbers lower than your number, then your maybe_prime number isn't prime -- because something else divides easily.
That's a start of understanding. Now, let's talk about the square root.
const auto limit = static_cast<unsigned>(std::sqrt(trial));
This part is tricky to understand. Let's say our number is NOT prime. That means there exists a prime number < limit for which:
trial / a_number = b_number
and b_number is an integer. That is:
trial % a_number = 0
In other words:
a_number * b_number = trial.
Right?
Let's start with a number with lots of divisors -- like 105.
105 / 3 = 35
105 / 5 = 21
105 / 7 = 15
And then:
3 * 5 * 7 = 105
With me?
Consider the pattern:
3 * 35
5 * 21
7 * 15
Now, the square root of 105 is 10.246. But the code above turns this into an integer -- just 10.
You'll notice the pattern above -- it's converging on the square root of 105 -- converging on 10. The first number gets bigger, the second smaller.
It turns out... A number is prime if there are no prime numbers <= its square root that divide evenly.
In other words, all limit is doing is preventing a whole ton of math. If you make it to limit and don't find any primes that divide evenly into trial, then you won't find any if you keep going.
When dealing with primes in computing, this is important to remember. You only have to check values up to the square root of your number. If you don't find any by then, you won't find any.
|
69,228,881 | 69,229,045 | How to get function template taking invokables to match the types? | I have the following code intended to take a generic function object that takes two arguments and return a function object that does the same with the arguments in the other order.
#include <type_traits>
#include <functional>
template<typename Function, typename FirstIn
, typename SecondIn, typename std::enable_if<std::is_invocable<Function, FirstIn, SecondIn>::value>::type>
std::function<typename std::invoke_result<Function, FirstIn, SecondIn>::type(SecondIn, FirstIn)>
swapInput(Function f)
{
return[=](SecondIn b, FirstIn a) { return std::invoke(f, a, b); };
}
int main()
{
std::function<bool(std::string, int)> isLength = [](std::string s, int len) {return (s.size() == len); };
std::function<bool(int, std::string)> lengthIs =
swapInput<std::function<bool(std::string, int)>, std::string, int>(isLength);
}
This gives the following compiler errors at the line assigning lengthIs:
Error C2783 'std::function<std::invoke_result<Function,FirstIn,SecondIn>::type(SecondIn,FirstIn)> swapInput(Function)'
: could not deduce template argument for '__formal'
Error C2672 'swapInput': no matching overloaded function found
I am using Visual Studio 19 set to C++17.
| Your usage of std::enable_if is wrong. You need
template<typename Function, typename FirstIn, typename SecondIn
, typename = std::enable_if_t<
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
std::is_invocable_v<Function, FirstIn, SecondIn>
>
>
std::function<std::invoke_result_t<Function, FirstIn, SecondIn>(SecondIn, FirstIn)>
swapInput(Function f)
{
return [=](SecondIn b, FirstIn a) { return std::invoke(f, a, b); };
}
(See a Demo)
Suggestions:
Since you are using c++17, I would suggest a auto return for swapInput.
One step further, if you rearrange the function template parameters, you do not need the verbose explicit std::function<bool(std::string, int)> at the function call.
Using if constexpr, more easily readable code:
With the above suggestions:
template<typename FirstIn, typename SecondIn, typename Function>
auto swapInput(Function f)
{
if constexpr (std::is_invocable_v<Function, FirstIn, SecondIn >)
return [=](SecondIn b, FirstIn a) { return std::invoke(f, a, b); };
}
now the function call would be
std::function<bool(int, std::string)> lengthIs
= swapInput<std::string, int>(isLength);
(See a Demo)
|
69,228,910 | 69,340,711 | How can be shown the placeholder sync icon in a renamed folder using Win32 Cloud Filter API? | I'm using the Microsoft Cloud Filter API to manage placeholders in my local directory, and when I rename a folder its state icon isn't visually updated after I apply the CfSetInSyncState function to this folder. This folder contains a file that was previously copied from another placeholder from this cloned directory. I've applied several functions besides CfSetInSyncState as CfUpdatePlaceholder, CfSetPinState, CfRevertPlaceholder and CfConvertToPlaceholder to the folder but the sync icon isn't shown properly and I checked that the placeholder has the CF_PLACEHOLDER_STATE_IN_SYNC state. Is there some way to set the sync icon properly in this case?
Sync state icon correctly shown before rename a folder.
Sync state icon isn't visually updated after sync a renamed folder.
| I could show the placeholder sync icon correctly in this case renaming the folder twice using MoveFileW and CfUpdatePlaceholder functions. Here I show you the method that renames the folder twice.
bool FolderRenameTrick(const std::wstring& folderPath)
{
// Gets a nonexistent folder path
std::wstring folderPathAux = GenerateAuxPath(folderPath);
if (folderPathAux != L"")
{
bool renamed = false;
// Renames the folder with MoveFileW method (auxiliary folder)
if (MoveFile(folderPath.c_str(), folderPathAux.c_str()))
{
// UpdatePlaceholder calls internally to CfUpdatePlaceholder (auxiliary folder)
if (UpdatePlaceholder(folderPathAux))
{
renamed = true;
}
}
if (renamed)
{
// Renames the folder with MoveFileW method (correct folder)
if (MoveFile(folderPathAux.c_str(), folderPath.c_str()))
{
// UpdatePlaceholder calls internally to CfUpdatePlaceholder (correct folder)
if (UpdatePlaceholder(folderPath))
{
return true;
}
}
}
}
return false;
}
|
69,229,696 | 69,230,032 | Need help about iteratively guessing game | I'm new at coding, i made a small game. But program turns it self off after you answer true or false. But i want to make this program iteratively. I mean after you guess it, program should restart.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int secretnum;
int guess;
int guesscount = 0;
int guesslimit = 3;
bool outofguesses = false;
bool success = false;
bool success2 = true;
do {
cout << "Enter a number: ";
cin >> secretnum;
system("cls");
do {
if (guesscount < guesslimit) {
cout << "Enter your guess: ";
cin >> guess;
guesscount++;
}
else {
outofguesses = true;
}
} while (secretnum != guess && !outofguesses);
if (outofguesses) {
cout << "You lose." << endl;
success = true;
}
else {
cout << "You win." << endl;
success = true;
}
} while (success == success2);
if (success == true) {
guesscount = 0;
guesslimit = 3;
outofguesses = false;
success = false;
success2 = true;
}
else if (success == false)
guesscount = 0;
guesslimit = 3;
outofguesses = false;
success = false;
success2 = true;
system("pause>0");
}
Here is my code. I added "bool success", "bool success2" (success is false, success2 is true). When you guess it, program set success true and as you can see i added a code "while (success == success2);"
But after that -I mean you end game correct or wrong- this last part of code doesn't refresh/reset the "guesslimit". How can i fix that??
| Your code is getting very convoluted because you are using many unneeded variables. The variables success, success2 and outofguesses are all unnecessary.
If you use infinite loops and use an explicit break to break out of an infinite loop when necessary, the code is much cleaner and it is easy to restart the game:
#include <iostream>
#include <cmath>
using namespace std;
constexpr int GUESS_LIMIT = 3;
int main()
{
//one loop iteration represents a whole game
for (;;) //infinite loop, equivalent to while(1)
{
int secret_num;
int guess_count = 0;
cout << "Enter a number: ";
cin >> secret_num;
system("cls");
//one loop iteration represents a single guess
for (;;)
{
int guess;
cout << "Enter your guess: ";
cin >> guess;
guess_count++;
if ( guess == secret_num )
{
cout << "You win." << endl;
break; //break out of infinite loop
}
if ( guess_count == GUESS_LIMIT )
{
cout << "You lose." << endl;
break; //break out of infinite loop
}
}
cout << "\n\nRestarting game...\n\n";
}
}
Also, it is worth mentioning that you have no code for handling bad input. If the user provides bad input such as "g" instead of a number, then your program will start misbehaving. Therefore, it is safer to check for input failure, and to handle it properly.
The easiest form of handling bad input is to simply exit the program. In order to do so, you can change the code
cout << "Enter a number: ";
cin >> secret_num;
to:
cout << "Enter a number: ";
cin >> secret_num;
if ( cin.fail() )
{
cout << "Input error!\n";
return 0;
}
You can do the same with the lines:
cout << "Enter your guess: ";
cin >> guess;
If you don't won't the program to exit on bad input, then you could make a loop which continues running until the user enters valid input, for example like this:
for (;;)
{
cout << "Enter a number: ";
cin >> secret_num;
if ( !cin.fail() )
break;
cout << "Input error, try again!\n";
//discard remainder of line
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
//clear stream flags
cin.clear();
}
|
69,230,222 | 69,237,275 | Maximize this equation E[a1]-E[a2]+E[a3]-E[a4] | Can anyone please help me how todo this problem
We have to maximize the value of:
E[a1]- E[a2]+ E[a3]- E[a4]
where E is an array
constraints:
1<=E<=100 (size)
N>=4
a1>a2>a3>a4 (index)
Input format
N (no. of integers in array)
N value separated by spaces
Output
single integer(max value)
Test case:
I/P
6
3 9 10 1 30 40
O/P
46 (40-1+10-3)(index: 5>3>2>0)
| #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int> v(n);
for(int i=0; i<n; i++)
cin>>v[i];
vector<int> a1(n);
vector<int> a2(n);
vector<int> a3(n);
vector<int> a4(n);
int max4 = (-1)*v[0];
for(int i=0; i<n; i++)
{
max4 = max(max4, (-1)*v[i]);
a4[i] = max4;
}
int max3 = v[1]-v[0];
for(int i=1; i<n; i++)
{
max3 = max(max3, v[i]+a4[i-1]);
a3[i] = max3;
}
int max2 = (-1)*v[2]+v[1]-v[0];
for(int i=2; i<n; i++)
{
max2 = max(max2, (-1)*v[i]+a3[i-1]);
a2[i] = max2;
}
int max1 = v[3]-v[2]+v[1]-v[0];
for(int i=3; i<n; i++)
{
max1 = max(max1, v[i]+a2[i-1]);
a1[i] = max1;
}
cout<<a1[n-1]<<endl;
return 0;
}
Since nobody cared to answer so I did on my own using dp
|
69,230,577 | 69,230,670 | What is nth_element and what does it do exactly? and how to implement it | I've almost understood many STL algorithms until I've reached the algorithm std::nth_element. I 'm stuck on it; I don't know how it works and it does do exactly.
For education and understanding sake can someone explain to me how the algorithm std::nth_element works?
std::vector<int> v{ 9, 3, 6, 2, 1, 7, 8, 5, 4, 0 };
std::nth_element(v.begin(), v.begin() + 2, v.end());
for (auto i : v)
std::cout << i << " ";
std::cout << '\n';
The output:
1 0 2 3 6 7 8 5 4 9
So where is nth element here?
How and what the algorithm does?
Does it do some sort of partial sorting?
Here is some explanation from cppreference.com:
nth_element is a partial sorting algorithm that rearranges elements in [first, last) such that:
The element pointed at by nth is changed to whatever element would occur in that position if [first, last) was sorted.
All of the elements before this new nth element are less than or equal to the elements after the new nth element.
More formally, nth_element partially sorts the range [first, last) in ascending order so that the condition !(*j < *i) (for the first version, or comp(*j, *i) == false for the second version) is met for any i in the range [first, nth) and for any j in the range [nth, last). The element placed in the nth position is exactly the element that would occur in this position if the range was fully sorted.
nth may be the end iterator, in this case the function has no effect.
I am still confused about it. What is nth element and how to implement a possible algorithm like that?. For education sake I've mimicked many STL algorithms. Thank you so much!
|
So where is nth element here?
The n-th element is the 2 at index 2 because thats what you asked for when you passed begin()+2.
The element pointed at by nth is changed to whatever element would occur in that position if [first, last) was sorted.
This means that, if the vector was sorted, the order of elements would be
0 1 2 3 4 5 6 7 8 9
^--- begin() + 2
You asked to have 3rd largest element at index 2 (3rd position), and thats what the algorithm does.
In addition it puts all elements smaller in the front and all elements larger in the back:
!(*j < *i) (for the first version, or comp(*j, *i) == false for the second version) is met for any i in the range [first, nth) and for any j in the range [nth, last).
Let's use indices rather than iterators, then for any i < 2 and any j > 2 it holds that v[i] < v[j]. In other words, 1 and 0 are both smaller than any element in 2 3 6 7 8 5 4 9.
|
69,230,597 | 69,230,806 | How to access user-context data set on epoll when calling epoll_wait | Below I add sockets to epoll and set an application-context index within epoll_event.data.u32.
When receiving packets, recv() requires the socket file descriptor. In all the examples events[i].data.fd is used.
However, events[i].data.fd and events[i].data.u32 are in a union, so how do I also access my user-context index events[i].data.u32? It looks like it is overwritten with the socket file descriptor?
// Initially
int epollFd = epoll_create1(0);
// Adding each socket, along with a user-context index for callbacks
struct epoll_event event;
event.events = EPOLLIN;
event.data.u32 = callbackIndex; // Here is the user-defined index
int sock = createSocket(port, address);
assert(epoll_ctl(epollFd, EPOLL_CTL_ADD, sock, &event));
// Later when receiving packets
struct epoll_event events[MAX_EVENTS];
while (true)
{
int event_count = epoll_wait(epollFd, events, MAX_EVENTS, 30000);
for (i = 0; i < event_count; i++)
{
int n = recv(events[i].data.fd, &buffer[0], sizeof(buffer), flags);
// How do I access the user-context index I set when adding the socket to epoll?
}
}
| You tell epoll_ctl() which socket descriptor you want to listen for events for, and provide an epoll_event struct to associate with that listen operation.
Whenever epoll_wait() detects a registered event on a socket, it gives you back only the epoll_event struct that you had provided for that event, exactly as you had provided it. It does not tell you which socket triggered the event.
So, if you want to discover the socket, you have to either:
store the socket descriptor itself in the epoll_event, but then you can't use any other user-defined data.
store the socket descriptor somewhere else (ie, in an array, an object pool, etc) and then put identifying information needed to get back to the socket descriptor as user-defined data in the epoll_event (ie, array index, object pointer, etc).
Whatever you put in the epoll_event when calling epoll_ctl() is what you will get back from epoll_wait(). No more, no less.
|
69,230,824 | 69,230,898 | comparing a string at index i to a value in C++ | So im working on a class assignment where I need to take a base 2 binary number and convert it to its base 10 equivalent. I wanted to store the binary as a string, then scan the string and skip the 0s, and at 1s add 2^i. Im not able to compare the string at index i to '0, and im not sure why if(binaryNumber.at(i) == '0') isnt working. It results in an "out of range memory error". Can someone help me understand why this doesnt work?
#include <iostream>
using namespace std;
void main() {
string binaryNumber;
int adder;
int total = 0;
cout << "Enter a binary number to convert to decimal \n";
cin >> binaryNumber;
reverse(binaryNumber.begin(),binaryNumber.end());
for (int i = 1; i <= binaryNumber.length(); i++) {
if(binaryNumber.at(i) == '0') { //THIS IS THE PROBLEM
//do nothing and skip to next number
}
else {
adder = pow(2, i);
total = adder + total;
}
}
cout << "The binary number " << binaryNumber << " is " << total << " in decimal form.\n";
system("pause");
}
| Array indices for C++ and many other languages use zero based index. That means for array of size 5, index ranges from 0 to 4. In your code your are iterating from 1 to array_length. Use:
for (int i = 0; i < binaryNumber.length(); i++)
|
69,230,844 | 69,235,395 | `io_context.stop()` vs `socket.close()` | To close a Tcp client, which one should be used, io_context.stop() or socket.close()? What aspects should be considered when making such a choice?
As far as I know, io_context is thread-safe whereas socket is not.
So, I can invoke io_context.stop() in any thread which may be different from the one that has called io_context.run().
But for socket.close(), I need to call io_context.post([=](){socket.stop()}) if socket object is called in a different thread(e.g. the said thread calls aiso::async_read(socket, ...)).
|
To close a Tcp client, which one should be used, io_context.stop() or socket.close()?
Obviously socket.cancel() and or socket.shutdown() :)
Stopping the entire iexecution context might seem equivalent in the case of only a single IO object (your socket). But as soon as you have multiple sockets open or use timers and signal_sets, it becomes obvious why that is shooting a fly with a canon.
Also note that io_context::stop has the side effect of clearing any outstanding work (at least, inability to resume without reset() first) which makes it even more of a blunt weapon.
Instead, use socket::cancel() to cancel any IO operation on it. They will complete with error::operation_aborted so you can detect the situation. This is enough if you control all the async initiations on the object. If you want to prevent "other" parties from starting new IO operations successfully you can shutdown the socket instead. You can shutdown the writing side, reading side or both of a socket.
The reason why shutdown is often superior to close() can be quite subtle. On the one hand, shutting down one side makes it so that you can still handle/notify the other side for graceful shutdown. On the other hand there's a prevention of a pretty common race condition when the native socket handle is (also) being stored somewhere: Closing the socket makes the native handle eligible for re-use, and a client that is unaware of the change could at a later type continue to use that handle, unaware that it now belongs to someone else. I have seen bugs in production code where under high load RPC calls would suddenly be written to the database server due to this kind of thing.
In short, best to tie the socket handle to the life time of the socket instance, and prefer to use cancel() or shutdown().
I need to call io_context.post(={socket.stop()}) if socket object is called in a different thread(e.g. the said thread calls aiso::async_read(socket, ...)).
Yes, thread-safety is your responsibiliity. And no, post(io_context, ...) is not even enough when multiple threads are running the execution context. In that case you need more synchronization, like post(strand_, ...). See Why do I need strand per connection when using boost::asio?
|
69,230,926 | 69,231,037 | How to make base class template function visible for derived class instances without casting or duplicating signature? | Is there any way to avoid cast when calling a base class template function from a derived class instance? Suppose the following:
class Foo
{
public:
virtual void quux() = 0;
template <class T> void quux() { ... }
};
class Bar : public Foo
{
public:
void quux() override {}
};
Then later on usage of class Bar:
Bar bar;
bar.quux<int>(); // error: type 'int' unexpected
static_cast<Foo&>(bar).quux<int>(); // OK
Any way to make this less obnoxious and make function quux callable on instances of Bar without having to duplicate the function signatures directly in Bar implementation? I'm aware of dependent name lookup, looking for a maintainable way to solve this for all derived classes.
| Just add using Foo::quux;:
class Bar : public Foo
{
public:
using Foo::quux;
void quux() override {}
};
|
69,231,136 | 69,231,159 | how to make 69.99*100 print 6999 instead of 6998? | I want to have the right 6999 but the code prints 6998, is there any way to implement it in C/C++?
#include <iostream>
using namespace std;
int main() {
double x = 69.99;
int xi = x*100;
cout << xi << endl;
return 0;
}
| Your compiler is probably using the IEEE 754 double precision floating point format for representing the C++ data type double. This format cannot represent the number 69.99 exactly. It is stored as 69.989999999999994884. When you multiply this value with 100, the result is slightly smaller than 6999.
When implicitly converting floating-point numbers to integers, the number is always rounded towards zero (positive numbers get rounded down, negative ones get rounded up).
If you don't want to always round the result towards zero, you can change the line
int xi = x*100;
to
long xi = lround( x*100 );
which will not always round the number towards zero, but will instead always round it to the nearest integer.
Note that you must #include <cmath> to be able to use std::lround.
|
69,231,219 | 69,231,266 | C++ Simple Login Project | I tried making a simple login authentication program in C++. I wanted help on how to make a dictionary of username and passwords so as to authenticate login info. For the simple project I just assigned a login string with a string and password too and checked the input of user.
#include <iostream>
#include <string>
using namespace std;
int main(){
string username = "cool";
string password = "lol";
string user;
string pass;
cout << "Hello, Welcome to the App Login!" << std::endl;
cout << "Enter Your username: ";
cin >> user;
if (user == username){
cout << "Enter password: " << endl;
cin >> pass;
if (pass == password){
cout << "Successful Login!" << endl;
}
else {
cout << "Incorrect Password!" << endl;
}
}
else {
cout << "Incorrect Username!" << endl;
}
}
| You can use map to create your dictionary and use map's find method to check if the key is present in map or not.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// create your dictonary
map<string, string>dict = { {"john", "123"} };
string username, password;
cout<<"Enter username: "<<endl;
cin>>username;
cout<<"Enter password: "<<endl;
cin>>password;
// Check if provided username and password matches with the one is dictonary
if(dict.find(username) != dict.end() && dict[username] == password) {
cout<<"Login Successfully!";
} else {
cout<<"Invalid Credentials";
}
return 0;
}
Live Demo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.