question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,042,839 | 72,042,950 | nested list struct c++ | I have a nested list:
struct CHANNEL {
char channel_id[200];
char name_Channel[200];
};
struct Line {
CHANNEL* chan;
PROGRAM* prog;
HOST* host;
DATE_TIME* date;
struct Line* next;
};
but when I create a Line variable and try to work with it
char number[200];
Line* p;
p = (struct Line*)malloc(sizeof(*p));
strcpy_s(p->chan->channel_id, number);
Visual studio says: "Dereferencing NULL pointer 'p'" and "Access violation reading location 0xFFFFFFFFFFFFFFFF." in string.h
How can it be fixed?
| This line:
p = (struct Line*)malloc(sizeof(*p));
Allocates memory for an object of struct Line.
It does not initialize the object.
One of the uninitialized data members of this object is CHANNEL* chan.
Therefore when you try to access p->chan->channel_id, p->chan is uninitialized and you cannot use it to access the CHANNEL struct members.
You can solve this specific issue by "manually" initializing the members of p after the allocation.
But if you are using c++ (as suggested by the tags you put on your question), it's better to use new which calls the object's constructor after performing the memory allocation. For this to work, you will need to add a constructor to struct Line that will initialize all the members (and specifically initialize the pointers like CHANNEL* chan to point to some valid CHANNEL object). Also in c++ it's usually prefered to use smart pointers over raw ones.
|
72,043,955 | 72,044,938 | Address of a constexpr in a template parameter | Can someone solve the mystery of why do I get linking errors if I take the address of a variable that should go in a template parameter only if I make the variable const, constexpr or static, but not oherwise?
The piece(s) of code below are part of a larger project, but I extracted the exact same structure:
CMakeLists.txt
project(fun)
add_library(fun SHARED fun.cpp)
add_executable(main main.cpp)
target_link_libraries(main fun)
fun.cpp
#include "fun.h"
BlaaUser testBlaa(int)
{
return BlaaUser();
}
fun.h
#pragma once
#include "types.h"
extern BlaaUser testBlaa(int);
main.cpp
#include "fun.h"
int main()
{
auto b = testBlaa(2);
}
types.h
#pragma once
struct P
{
char n;
};
template<const P* S>
struct Blaa
{
Blaa() {}
char blaa{S->n};
};
//constexpr
//static
//const
P p{}; // <-- Here, right now it works. If I uncomment any of the specifiers, I get errors, see below
using BlaaUser = Blaa<&p>;
If I add any kind of specifier I get the following errors:
Scanning dependencies of target fun
[ 25%] Building CXX object CMakeFiles/fun.dir/fun.cpp.o
[ 50%] Linking CXX shared library libfun.so
[ 50%] Built target fun
Scanning dependencies of target main
[ 75%] Building CXX object CMakeFiles/main.dir/main.cpp.o
In file included from /home/fld/work/tmpl_test/main.cpp:1:
/home/fld/work/tmpl_test/fun.h:5:17: warning: ‘BlaaUser testBlaa(int)’ used but never defined
5 | extern BlaaUser testBlaa(int);
| ^~~~~~~~
[100%] Linking CXX executable main
/usr/bin/ld: CMakeFiles/main.dir/main.cpp.o: in function `main':
main.cpp:(.text+0x12): undefined reference to `testBlaa(int)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/main.dir/build.make:104: main] Error 1
make[1]: *** [CMakeFiles/Makefile2:97: CMakeFiles/main.dir/all] Error 2
make: *** [Makefile:103: all] Error 2
I sort of have the feeling that it has to do with the address of an object (as per the standard: For pointers to objects, the template arguments have to designate the address of a complete object with static storage duration and a linkage (either internal or external) ) but I'm just a bit confused because if everything goes in one file all is ok, the problem comes when it's split up in libraries ...
Does anyone have any explanations?
| The additional specifiers (e.g const, constexpr) makes the template parameter have internal linkage, which subsequently makes testBlaa(int) have internal linkage. It works if you do
extern const P p{}
right? Maybe Why does the following method get internal linkage? is similar?
|
72,043,966 | 72,044,153 | Why can an anonymous temporary exception be bound to a reference at a catch site? | Consider
#include <iostream>
struct Foo{};
int main(){
try {
throw Foo();
} catch (Foo& e){
std::cout << "Caught";
}
}
The output is Caught, but why? I would have thought that the catch should have been const Foo&. What am I forgetting?
|
I would have thought that the catch should have been const Foo&.
It doesn't need to be.
I suspect that you are expecting that there would be a problem with binding of an lvalue reference to non-const.
[except.handle]
The variable declared by the exception-declaration, of type cv T or cv T&, is initialized from the exception object, of type E, as follows:
if T is a base class of E ...
otherwise, the variable is copy-initialized ([dcl.init]) from an lvalue of type E designating the exception object.
The lifetime of the variable ends when the handler exits, after the destruction of any objects with automatic storage duration initialized within the handler.
Note the highlighted "lvalue". There's no problem binding a non-const lvalue reference to an lvalue.
Sidenotes:
A handler is a match for an exception object of type E if
The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or
Top level cv qualifiers are ignored and don't need to match between thrown object and handler type.
... When the handler declares a reference to an object, any changes to the referenced object are changes to the exception object and will have effect should that object be rethrown.
Catching a reference allows modifying the exception object.
|
72,044,055 | 72,044,295 | 2d array average and total c++ | it has to appear like this:
#include <iostream>
using namespace std;
int main()
{
float allsales[3] [2] = {{1200.33, 2350.75}, {3677.80, 2456.05}, {750.67, 1345.99}};
float totalsales = 0, ave = 0, sum = 0;
for (int row = 0; row < 3; row++)
{
cout << "Ave sale for store "<< row + 1 << ": ";
for (int col=0; col < 2; col++)
{
totalsales += allsales [row] [col];
sum = 0; // I cant figure out how to code the formula for the sum
ave = sum / 2;
cout << ave <<endl;
}
}
cout << "Total sales : $" << totalsales << endl;
return 0;
}
Also, Im a first year prog student so I cant use some advanced codes/commands etc.,. I can only stick on nested for loops, if else, while
| How would you do it by hand?
I would start sum with an initial value of zero for each row, add to it each element in that row, and then compute the average at the end of the row.
(Don't forget that you can declare variables in other places than first thing in a function.)
And I would also probably first sum the row, and then add the "row sum" to the total.
Like this:
for (int row = 0; row < 3; row++)
{
float sum = 0;
for (int col = 0; col < 2; col++)
{
sum += allsales[row][col];
}
cout << "Ave sale for store "<< row + 1 << ": " << sum / 2 << endl;
totalsales += sum;
}
|
72,044,415 | 72,045,748 | How can I read a specific value c++ using a text file to store in data structure | How do i seperate my text file values to store in a vector
I have a file.txt with values such as
DOB,NAME,Arrival,Depature
12/04/2021,Dennis,12:30:20,14:30:40
10/03/2001,Sam,14:20:30,-
I want to store these values in a vector I have figured out how to store all of them in the vector but now i am creating another vector where i want to store all the values without a depature time so in this case Sam '-' which has this value. and another vector which will store Dennis which already has a depature time
What i have done so far
name *v = new name;
ifstream myFileStream("FILE.txt");
if(!myFileStream.is_open()){
cout<<"File Failed to open"<<endl;
}
string date,name,arrival,depature;
std::string delimiter = "/";
std::string delimiters = ":";
string line;
string b;
string c;
string d;
string e;
std::getline(myFileStream,line);
while(getline(myFileStream,line)){
stringstream ss(line);
getline(ss,date,',');
//veh.at(i).dt = v->dt;
size_t pos = 0;
std::string token;
while ((pos = date.find(delimiter)) != std::string::npos) {
c=token;
token = date.substr(0, pos);
b=token;
date.erase(0, pos + delimiter.length());
}
v->dt.year = stoi(date);
v->dt.month = stoi(b);
v->dt.day = stoi(c);
veh.at(i).dt.month = v->dt.month;
veh.at(i).dt.year = v->dt.year;
veh.at(i).dt.day = v->dt.day;
getline(ss,v->name,',');
veh.at(i).pltno = v->name;
getline(ss,arrival,',');
size_t pose = 0;
std::string tokens;
while ((pose = arrival.find(delimiters)) != std::string::npos) {
e=tokens;
tokens = arrival.substr(0, pose);
std::cout << tokens << std::endl;
d=tokens;
arrival.erase(0, pose + delimiters.length());
}
v->arrive.hh = stoi(e);
veh.at(i).arrive.hh = v->arrive.hh;
v->arrive.mm = stoi(d);
veh.at(i).arrive.mm = v->arrive.mm;
((stoi(arrival) <= 9) ? 0 : "");
v->arrive.ss = stoi(arrival);
veh.at(i).arrive.ss = v->arrive.ss;
//veh.at(i).arrive = arrival;
getline(ss,depature,',');
//cout<<veh.at(i).arrive<<endl;
i++;
}
myFileStream.close();
Please guys i really need help with this I am stuck at the moment and really would appreciate someone helping me with the code so far the code above stores the Name arrival DOB into the vector but I am going to create a new vector for people who left and people who have not how can i seperate values which have '-' & which have time and store it in a similar format?
Thank YOU
| #include<vector>
#include<string>
#include<fstream>
using namespace std;
void split(const string& s, vector<string>& tokens, char delim = ' ') {
tokens.clear();
auto string_find_first_not = [s, delim](size_t pos = 0) -> size_t {
for (size_t i = pos; i < s.size(); i++) {
if (s[i] != delim) return i;
}
return string::npos;
};
size_t lastPos = string_find_first_not(0);
size_t pos = s.find(delim, lastPos);
while (lastPos != string::npos) {
tokens.emplace_back(s.substr(lastPos, pos - lastPos));
lastPos = string_find_first_not(pos);
pos = s.find(delim, lastPos);
}
}
struct DOB
{
string year;
string month;
string day;
// DOB(const string &y,const string &m,const string &d):year(y),month(m),day(d){}
DOB(const string &dob)
{
vector<string> strs;
split(dob,strs,'/');
year = strs[2];
month = strs[0];
day = strs[1];
}
};
struct Time
{
bool left;
string hour;
string minute;
string second;
// Time(const string &h,const string &m,const string &s):hour(h),minute(m),second(s){}
Time(const string &time)
{
vector<string> strs;
split(time,strs,':');
hour = strs[0];
minute = strs[1];
second = strs[2];
left = true;
}
Time()
{
left = false;
}
};
struct UserInfo
{
DOB dob;
string name;
Time arrival;
Time depature;
UserInfo(const DOB &d,const string &n,const Time &a,const Time &de):dob(d),name(n),arrival(a),depature(de){}
};
int main()
{
// read and open file
ifstream file;
file.open("./file.txt", ios::in);
if (!file.is_open())
{
// error
return 1;
}
vector<UserInfo> leftUsers;
vector<UserInfo> notleftUsers;
string buf;
getline(file,buf);
// handle file
while (getline(file,buf))
{
if(buf.find("-") == string::npos)
{
// left
vector<string> strs;
split(buf,strs,',');
// DOB
DOB dob(strs[0]);
// Arrival
Time arrival(strs[2]);
Time depature(strs[3]);
leftUsers.push_back(UserInfo(dob,strs[1],arrival,depature));
}
else
{
// not left
vector<string> strs;
split(buf,strs,',');
// DOB
DOB dob(strs[0]);
// Arrival
Time arrival(strs[2]);
Time depature;
notleftUsers.push_back(UserInfo(dob,strs[1],arrival,depature));
}
}
return 0;
}
|
72,044,765 | 72,044,927 | wanna know the difference of these two almost same answers | I'm doing a leetcode problem which you can check it here:https://leetcode.com/problems/binary-tree-preorder-traversal
here's my first time answer which is a wrong answer:
class Solution {
public:
TreeNode* preorderTraversal(TreeNode* root, vector<int> &res){
if(root) res.push_back(root->val); else return nullptr;
if(root->left) return preorderTraversal(root->left,res);
if(root->right) return preorderTraversal(root->right,res);
return root;
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorderTraversal(root,res);
return res;
}
};
And here's my second time answer which passed the test:
class Solution {
public:
void preorderTraversal(TreeNode* root, vector<int> &res){
if(root) res.push_back(root->val); else return;
preorderTraversal(root->left,res);
preorderTraversal(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorderTraversal(root,res);
return res;
}
};
if you had a leetcode account you can simply click the link above and copy my two answers in the code area and run each of both, you can then find out that inputs like "[1,2,3]", which represent trees that only have left branches in every tree node, can only pass the second code while in the first one, the left most node's value(in this example, 3) is not included in the vector that the problem ask for. I wonder what's wrong with my first answer that caused the difference in result.
I know the first code seem weird and tedious, I just wonder why it can't work correcetly.
I'll be really thankful to you guys who help me out.
| Preorder traversal requires to visit all the nodes in the tree.
In your 1st version you have these lines:
if(root->left) return preorderTraversal(root->left,res);
if(root->right) return preorderTraversal(root->right,res);
If root->left is not null the return statement will be executed, and will cause the function's execution to end after the recursive call to preorderTraversal will return.
This means that if root->left is not null the whole right sub tree will not be visited.
The second if is also wrong for consistency reasons (no reason the return the right subtree if you should never return the left one).
Your 2nd version performs recursion both to the left and to the right (in that order) which ensures all the nodes are visited according to the preorder criterion.
|
72,044,851 | 72,044,930 | What is this curly brace cpp syntax? | Alas, it's hard to google for symbols like braces.
I came across this code:
#include <functional>
#include <iostream>
template <typename A, typename B, typename C = std::less<>>
bool fun(A a, B b, C cmp = C{})
{
return cmp(a, b);
}
int main()
{
std::cout
<< std::boolalpha
<< fun(1, 2) << ' ' // true
<< fun(1.0, 1) << ' ' // false
<< fun(1, 2.0) << ' ' // true
<< std::less<int>{}(5, 5.6) << ' ' // false: 5 < 5 (warn: implicit conversion)
<< std::less<double>{}(5, 5.6) << ' ' // true: 5.0 < 5.6
<< std::less<int>{}(5.6, 5.7) << ' ' // false: 5 < 5 (warn: implicit conversion)
<< std::less{}(5, 5.6) << ' ' // true: less<void>: 5.0 < 5.6
<< '\n';
}
in https://en.cppreference.com/w/cpp/utility/functional/less.
What do braces in the statements C{}, std::less<int>{}(5, 5.6) mean?
| it create an instance of std::less<int>
then pass 5,5.6 as the parameter to it's bool operator()(const int&, const int&)
it's roughly the same as
auto temp = std::less<int>{};
std::cout << temp(5, 5.6);
|
72,044,972 | 72,045,828 | How to override a method of a base class which is an input of a function? | I am trying to override a method in a code I am using to learn about this but I didn't succeed, what am I missing?
Here some code to reproduce my issue:
my_class.h
#ifndef MY_CLASS_H
#define MY_CLASS_H
class Base {
public:
Base();
virtual ~Base();
virtual double evaluate(double x);
};
double call_evaluate(Base funct, double x);
#endif
my_class.cpp
Base::Base () {}
Base::~Base () {}
double Base::evaluate(double x){
std::cout << "evaluate base\n";
return 0.0;
};
double call_evaluate(Base funct, double x){
return funct.evaluate(x);
}
main.cpp
#include "my_class.h"
#include "iostream"
class Derived: public Base{
private:
double value;
public:
Derived(double value){
this->value = value;
}
double evaluate(double x) override{
std::cout << "evaluate derived\n";
return this->value*x;
}
};
int main(){
Derived problem(6);
double a=problem.evaluate(2);
double b=call_evaluate(problem, 2);
std::cout << "a = " << a << ", expected = 12\n";
std::cout << "b = " << b << ", expected = 12\n";
return 0;
}
Output
evaluate derived
evaluate base
a = 12, expected = 12
b = 0, expected = 12
| In short, you need to change call_evaluate to receive the first argument by reference.
double call_evaluate(Base& funct, double x);
For the reason why your program behaves like it does, see below.
Your coding style suggests you come from a Java-like background. You must make yourself aware of a very important point about C++. In the function declared below, both arguments are passed by value, not by reference.
double call_evaluate(Base funct, double x);
"by value" in current C++ parlance means the source object is going to be copied, that is, an unnamed copy of the original object is going to be created then passed to the function. "by reference" means the source object is merely going to be referenced or aliased, that is, the function receives a reference or alias to the same object.
From a Java-like programmers perspective, this should look like the pseudo-code below.
auto tmp0 = funct.clone();
auto tmp1 = x.clone();
call_evaluate(tmp0, tmp1);
In C++, you may achieve the effect of "by reference" by explicitly marking the parameter type as a reference type with the & declarator.
double call_evaluate(Base& funct, double x);
Doing "by reference" with reference types require no special notation on the callers side.
call_evaluate(func, x);
Additionally, in C and C++, you may achieve the effect of "by reference" by passing object addresses as parameters. You do this by explicitly marking the parameter type as a pointer type with the * declarator.
double call_evaluate(Base* funct, double x);
Calling "by reference" with a pointer type requires the caller to use the unary & operator to obtain the object's address.
call_evaluate(&func, x);
Now, what is the problem with your program? You are "slicing" a polimorphic object.
Since call_evaluate receives the first parameter "by value", C++ will generate a "copy" expression to create a new, temporary, unnamed object from the source object.
The target type for this "copy" expression will be the type of the parameter, Base. In other words, C++ will generate an expression for the purpose of creating a new, temporary, unnamed object of the Base type from the source object.
Since this temporary, unnamed object has type Base, you will readily see how it polimorphically behaves just like any Base type should.
This is called "slicing" since it "slices" the object, that is, it creates a new object from just the Base part of the source object.
You may benefit from doing these experiments:
Declare call_evaluate as a pure virtual function. If there is no definition in the base class, what will this program do? For more information, see https://en.cppreference.com/w/cpp/language/abstract_class
Forbid Base copy constructor and copy assignment operator with the = delete special syntax. If copying Base is not allowed, what will the compiler do? For more information, see https://en.cppreference.com/w/cpp/language/function#Deleted_functions
|
72,045,055 | 72,045,239 | why the const in c++ conversion operator is meaningless? | In "C++ Primer", exercise 14.47, there is a question:
Explain the difference between these two conversion
operators:
struct Integral {
operator const int();
operator int() const;
}
I don't know why the the answer I found on GitHub says that the first const is meaningless, because for one conversion operator should not define return type, this const here is unspecified, it will be ignored by the compiler. But I also found some guys say that it means the function will return a const value.
So, I wonder which one is correct, and why?
|
it will be ignored by compiler.
This is because of expr#6 which states:
If a prvalue initially has the type cv T, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.
This means that in your particular example, const int will be adjusted to int before further analysis since int is a built in type and not a class type.
which one is right?
Even though the return type of the first conversion function is const int, it will be adjusted to int prior to any further analysis.
While the const on the second conversion function means that the this pointer inside that function is of type const Integral*. This means that it(the conversion function) can be used with const as well as non-const Integral object. This is from class.this
If the member function is declared const, the type of this is const X*, ...
|
72,045,119 | 72,045,187 | If two digits are the same 0s then make 0 condition in C++ and Root | In my code, legends are running within a loop, and I am trying to show a graph with
0-10%
10-20%
and so on. The problem is when I write this code
legend->AddEntry(gr[i], Form("%d0-%d0 %%",i+0,i+1), "lep");
It shows
00-10%
10-20% etc
So how to not show 00, but 0 in the first line?
| A small adaptation of the shown statement should be enough; use:
legend->AddEntry(gr[i], Form("%d-%d %%", i*10 , (i+1)*10), "lep");
Explanation:
Form("%d0-%d0 %%",i+0,i+1) seems to be some kind of string formatting, and i your loop variable which runs from 0 to 9, right? The shown Form statement just appends "0" hard-coded to the single digit in i; instead, you can multiply i by 10, resulting in the actual numbers you want printed; and since 10*0 is still 0, this will be a single digit still; so, replace the previous Form(...) call with Form("%d-%d %%", i*10, (i+1)*10) and you should have the result you want!
In case you're worrying that printing i*10 is "less efficient" than printing i with "0" suffix - don't. The formatting and output of the string is most probably orders of magnitude slower than the multiplication anyway, so any overhead of doing multiple multiplications is negligible.
|
72,045,325 | 72,045,668 | libcurl to put stream of data instead of file | We are using libcurl C API in order to send a file over SFTP. This works fine using a code like this :
....
fd = fopen(local_file_full_path.c_str(), "rb");
if (!fd)
{
cout << "Error opening local file: " << local_file_full_path << endl;
return -1;
}
curl_easy_setopt(curl_easy_handle, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl_easy_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl_easy_handle, CURLOPT_READDATA, fd);
curl_easy_setopt(curl_easy_handle, CURLOPT_HTTPHEADER, headerList);
However, that means that even though we have our data available - we have to write them into a file, and then pass the file over.
I was wondering if libcurl provides an option in which, we could pass a stream of data, eg a pointer into a struct of our data. If that's the case, is there any example I could use? And does that mean changes are needed on the "receiver" end - as we don't own it.
| You already have 1/2 of the solution - CURLOPT_READDATA . You just need to pair it with a custom callback in CURLOPT_READFUNCTION, then you can pass a pointer to your existing data in CURLOPT_READDATA and have your callback copy that data into libcurl's buffer when it needs the data.
This callback function gets called by libcurl as soon as it needs to read data in order to send it to the peer - like if you ask it to upload or post data to the server. The data area pointed at by the pointer buffer should be filled up with at most size multiplied with nitems number of bytes by your function.
Set the userdata argument with the CURLOPT_READDATA option.
|
72,046,562 | 72,047,359 | Alternatives for storing a class member as a raw pointer | In the code example shown below - in Container class, it owns (and is responsible fore destroying) two objects c, d, which are subclasses of an abstract class B. Container object can create new ObjectDisplay that takes a kind of B in its constructor. I can pass the abstract type B as a pointer into ObjectDisplay and store it as a RAW pointer. But it's not ideal to store & use a raw pointer and always check if it's a null pointer. If B wasn't an abstract class, I could pass it in ObjectDisplay as a reference (ie. ObjectDisplay (B& b)). But since I can't change B, I wonder what's the aternative of storing B* object as a raw pointer in ObjectDisplay?
// B is abstract
class B
{
public:
virtual int getDefault() = 0;
};
class C : public B
{
public:
int getDefault() override { return 1; }
};
class D : public B
{
public:
int getDefault() override { return 5; }
};
class ObjectDisplay
{
public:
ObjectDisplay (B* b) : object (b) {}
void someFunction()
{
const auto result = b->getDefault();
// do something
}
private:
B* object;
};
class Container
{
public:
void addDisplay()
{
displays.push_back (ObjectDisplay (&c));
displays.push_back (ObjectDisplay (&d));
}
private:
C c;
D d;
std::vector<ObjectDisplay> displays;
};
|
If B wasn't an abstract class, I could pass it in ObjectDisplay as a reference
No, if B is an abstract class, you can still pass it by reference. B& object can be bound to an instance of B's subclass. It behaves almost the same as pointers.
As quoted in cppref:
That is to say, if a derived class is handled using pointer or reference to the base class, a call to an overridden virtual function would invoke the behavior defined in the derived class.
Declare a member of B& in ObjectDisplay and construct it through a reference.
class ObjectDisplay
{
public:
ObjectDisplay (B& b) : object (b) {}
private:
B& object;
};
class Container
{
public:
void addDisplay()
{
displays.push_back (ObjectDisplay (c));
displays.push_back (ObjectDisplay (d));
}
};
See online demo
Aside:
Since you are passing a temporary ObjectDisplay object directly constructed in push_back, I recommend you to use emplace_back.
void addDisplay()
{
displays.emplace_back (c);
displays.emplace_back (d);
}
|
72,047,016 | 72,047,767 | How to set enum val of fixed size to its max possible value? | This is probably simple but I'm not getting it right. I have a "bitmask" enum which has a value all that indicates that all bits are set. However, I can't get it to flip all bits using ~0. The following error appears:
<source>:11:16: error: enumerator value '-1' is outside the range of underlying type 'uint_fast8_t' {aka 'unsigned char'}
11 | all = ~0x0,
|
Which is strange because it should actually fit into uint8_t no? Here is my code (godbolt):
#include <iostream>
int main()
{
enum mask_t : uint_fast8_t {
first = 0x1,
second = 0x2,
all = ~0x0,
} mask;
mask = all;
}
| By default, 0x0 is of type int. So if you try to flip all the bits you'll get -1 which can't be assigned to the type your enumeration was defined to.
Even if you use a suffix for that literal value, like u for example. To indicate that the literal value is of unsigned type. As in ~0x0u. You'd get the maximum of the unsigned int type. Which exceeds the range of the 8-bit integer type you're using. So this doesn't work either.
So you need to tell the language that you want the literal value to be of the type you need first. That can be achieved with a static_cast as demonstrated in other answers:
static_cast<uint_fast8_t>( ~0x0 )
But using hardcoded types and values can get in the way sometimes if you decide to change the type of the enum later. So if you have c++14 available. You can use the std::underlying_type type-trait and make a generic utility like:
template < class T > constexpr std::underlying_type_t< T > enum_max_v = ~static_cast< std::underlying_type_t< T > >(0);
// If you have c++17 available with the inline keyword
// template < class T > inline constexpr std::underlying_type_t< T > enum_max_v = ~static_cast< std::underlying_type_t< T > >(0);
And then used like:
enum mask_t : uint_fast8_t {
first = 0x1,
second = 0x2,
all = enum_max_v< mask_t >,
} mask;
Now you don't have to care about the underlying type of the enumeration.
You can even use std::numeric_limits if you want the right values instead of relying on flipping bits:
template < class T > constexpr std::underlying_type_t< T > enum_max_v = std::numeric_limits< std::underlying_type_t< T > >::max();
Sky is the limit.
|
72,047,595 | 72,047,812 | Make dynamically allocated object type string | I need to make dynamically allocated object type of string to store sentences and after that sentences should be sorted in alphabetical order using std::sort.
This would be correct solution using char array:
#include <cstring>
#include <iostream>
#include <new>
#include <string>
#include <algorithm>
int main() {
std::cout << "How many senteces: ";
int n;
std::cin >> n;
std::cin.ignore(1000, '\n');
char ** sentence = nullptr;
std::cout << "Enter senteces:" << std::endl;
try {
sentence = new char * [n];
for (int i = 0; i < n; i++)
sentence[i] = nullptr;
for (int i = 0; i < n; i++) {
char temp[1000];
std::cin.getline(temp, 1000);
sentence[i] = new char[strlen(temp) + 1];
strcpy(sentence[i], temp);
}
std::sort(sentence, sentence + n, [](const char * a,
const char * b) {
return std::strcmp(a, b) < 0;
});
std::cout << "Sorted sentences:" << std::endl;
for (int i = 0; i < n; i++)
std::cout << sentence[i] << std::endl;
for (int i = 0; i < n; i++)
delete[] sentence[i];
delete[] sentence;
} catch (...) {
std::cout << "Problems with memory!";
return 0;
}
return 0;
}
When I try to convert this to dynamically allocated array type of string, like this:
#include <cstring>
#include <iostream>
#include <new>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::cout << "How many senteces: ";
int n;
std::cin >> n;
std::cin.ignore(1000, '\n');
std::string ** sentence = nullptr;
std::cout << "Enter senteces:" << std::endl;
try {
sentence = new std::string * [n];
for (int i = 0; i < n; i++)
sentence[i] = nullptr;
for (int i = 0; i < n; i++) {
std::string temp;
std::getline(std::cin, temp);
sentence[i] = new std::string[temp.length() + 1];
temp = sentence[i];
}
std::sort(sentence, sentence + n, [](std::string a,
std::string b) {
for (char & c: a) c = std::toupper(c);
for (char & c: b) c = std::toupper(c);
return a < b;
});
std::cout << "Sorted sentences:" << std::endl;
for (int i = 0; i < n; i++)
std::cout << sentence[i] << std::endl;
for (int i = 0; i < n; i++)
delete[] sentence[i];
delete[] sentence;
} catch (...) {
std::cout << "Problems with memory!";
return 0;
}
return 0;
}
I get a bunch of errors. Could you explain me how to convert this program of dynamically allocation of char array to dynamically allocated string array on a correct way?
| It looks like you think std::string "corresponds to" char, but it corresponds to char*.
You want std::string* sentence = nullptr;.
(A lot of the point of this exercise is to notice how much easier it gets when you don't need to allocate the strings yourself.)
int main() {
try {
std::cout << "How many sentences: ";
int n;
std::cin >> n;
std::cin.ignore(1000, '\n');
std::cout << "Enter sentences:" << std::endl;
std::string* sentence = new std::string [n];
for (int i = 0; i < n; i++) {
std::getline(std::cin, sentence[i]);
}
std::sort(sentence, sentence + n, [](std::string a,
std::string b) {
for (char & c: a) c = std::toupper(c);
for (char & c: b) c = std::toupper(c);
return a < b;
});
std::cout << "Sorted sentences:" << std::endl;
for (int i = 0; i < n; i++)
std::cout << sentence[i] << std::endl;
delete[] sentence;
} catch (...) {
std::cout << "Problems with memory!";
}
}
|
72,047,718 | 72,047,818 | Assigning to std::array element in std::vector of arrays fails | Today, I'm working on understanding some new-to-me features, particularly std::array and std::vector. Individually, these seem to behave as expected, but I'm very puzzled by the behavior illustrated below:
This version works:
printf("Using pointer:\n");
std::vector<std::array<int, 1>*> vap;
vap.push_back(new std::array<int, 1>());
printf("size of vector is %ld\n", vap.size());
printf("before setting value:\n");
printf("value is %d\n", vap.front()->at(0));
std::array<int, 1>* pvals = vap.front();
pvals->at(0) = -1;
printf("after setting value:\n");
printf("value is %d\n", vap.front()->at(0));
This version doesn't update the array:
printf("Without pointer:\n");
std::vector<std::array<int, 1>> va;
std::array<int, 1> arr = {99};
va.push_back(arr);
Inserting the array like this fails too: va.push_back(std::array<int, 1>());
printf("size of vector is %ld\n", va.size());
printf("before setting value:\n");
printf("value is %d\n", va.front().at(0));
std::array<int, 1> vals = va.front();
vals[0] = -1;
printf("after setting value:\n");
printf("value is %d\n", va.front().at(0));
It's likely obvious what I'm trying to do but, in case it helps, I'll write it in prose:
Loosely, I'm creating a vector of arrays of ints. In the first half of the example, I create a vector of pointers to those arrays, and am able to insert a new array, via a pointer, and then modify the element contained in that array. In the second half, I tried to avoid using pointers. That code seems to insert the array successfully but then does not allow me to alter the element within it.
I'm somewhat surprised that there are zero warnings or errors, either at compile or runtime, and I'm guessing that I'm missing something fundamental. What can I try next?
| You are working on a copy of the array, you need a reference to the array in the vector
int main() {
vector<array<int, 1>> v;
array<int, 1> a = { 99 };
v.push_back(a);
cout << v[0][0];
auto& ar = v[0];
ar[0] = 42;
cout << v[0][0];
}
gives
99 42
|
72,048,000 | 72,048,086 | Class "name" has no member class "name of the member" | I`m new to OOP.
Here is the code:
#include <cstdint>
#include <string>
#include <iostream>
namespace name
{
class Class
{
private:
struct u
{
std::string l{};
struct u* next{};
};
public:
Class(std::string s)
:
u::l(s)
{ }
~Class() = default;
};
};
When I compile this I`m getting an errors like this:
Error (active) E1018 class "name::Class::u" has no member class "l"
Error C2614 'name::Class': illegal member initialization: 'l' is not a base or member name
Can you help me. I will glad you.
| this
struct u
{
std::string l{};
struct u* next{};
};
does not do what you seem to think it does, it is just defining the type 'u', it does not say that 'Class' contains an instance of 'u'.
Plus you have to have a constructor in order to use that initialization syntax
namespace name
{
class Class
{
private:
struct u
{
std::string l{};
struct u* next{};
u(string s) :l(s) {} <<<=== here is Class::u constructor
};
u _u; <<<==== I want Class to contain a Class::u
public:
Class(std::string s)
:
_u(s) <<< ====use constructor
{
}
~Class() = default;
};
};
|
72,048,009 | 72,048,219 | size and alignment of int bitfields | A struct with bitfields, even when "packed", seems to treat a bitfield's size (and alignment, too?) based on the specified int type. Could someone point to a C++ rule that defines that behavior? I tried with a dozen of compilers and architectures (thank you, Compiler Explorer!) and the result was consistent across all.
Here's the code to play with:
https://godbolt.org/z/31zMcnboY
#include <cstdint>
#pragma pack(push, 1)
struct S1{ uint8_t v: 1; }; // sizeof == 1
struct S2{ uint16_t v: 1; }; // sizeof == 2
struct S3{ uint32_t v: 1; }; // sizeof == 4
struct S4{ unsigned v: 1; }; // sizeof == 4
#pragma pack(pop)
auto f(auto s){ return sizeof(s); }
int main(){
f(S1{});
f(S2{});
f(S3{});
f(S4{});
}
The resulting ASM clearly shows the sizes returned by f() as 1, 2, 4 for S1, S2, S3 respectively:
|
Could someone point to a C++ rule that defines that behavior?
Nothing about #pragma pack(push, 1) is specified by the standard (other than #pragma being specified as a pre-processor directive with implementation defined meaning). It is a language extension.
This is what the standard specifies regarding bit fields:
[class.bit]
... A bit-field shall have integral or (possibly cv-qualified) enumeration type; the bit-field semantic property is not part of the type of the class member. ... Allocation of bit-fields within a class object is implementation-defined.
Alignment of bit-fields is implementation-defined.
Bit-fields are packed into some addressable allocation unit.
It's essentially entirely implementation defined or unspecified.
|
72,048,397 | 72,048,480 | c++ function template restrict parameter type | Given the class
class foo {
public:
void func(std::string s){};
void func(int i){};
void func2(std::string s){};
void func2(int i){};
};
I'd like to get rid of the multiple function overloads by just using template functions. However, the functions should ONLY accept an int or a std::string.
I see how this can be accomplished using concepts in c++20. However, I do not have access to a compiler with concepts support.
What would be a way to accomplish such a goal in c++17? Id like to be able to accomplish in the template specification using some form of std::enable_if or similiar, as opposed to using static_assert.
The answer below shows this can be done. Would there be a way to only have to define the 'template' definition once?
class foo {
template <typename arg_t,
std::enable_if_t<std::is_same_v<std::decay_t<arg_t>, int> || std::is_same_v<std::decay_t<arg_t>, std::string>, boo> = true>
void func(arg_t arg){}
template <typename arg_t,
std::enable_if_t<std::is_same_v<std::decay_t<arg_t>, int> || std::is_same_v<std::decay_t<arg_t>, std::string>, boo> = true>
void func2(arg_t arg){}
};
```
| Using enable_if you could write the function like
template <typename arg_t, std::enable_if_t<std::is_same_v<std::decay_t<arg_t>, int> ||
std::is_same_v<std::decay_t<arg_t>, std::string>,
bool> = true>
void func(arg_t arg){}
|
72,048,553 | 72,048,689 | What is the purpose of ccall and cwarp functions in Emscripten? | I'm following the instructions from the Emscripten documentation here, and I want to practice with minimal examples. My final goal is to create a C++ library, compile it to a single wasm binary file and then use these compiled methods in pure-frontend web application.
I do not understand what is the purpose of calling C++ methods with "ccall" when you can just instatiate them directly from "Module". For example, I can use Module._doubleNumber(9);, which is shorter than Module.ccall('doubleNumber','number', ['number'], [9]);.
Whats the difference between calling one or another?
Here is the complete code:
extern "C" {
int doubleNumber( int x ) {
int res = 2*x;
return res;
}
}
Compiled with
emcc main.cpp -o main.js -sEXPORTED_FUNCTIONS=_doubleNumber -sEXPORTED_RUNTIME_METHODS=ccall
I'm using a simple html document to test results:
<html>
<head>
<meta charset="utf-8">
<title>WASM Demo</title>
</head>
<body>
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
Module.ccall('doubleNumber','number', ['number'], [9]); // 18
Module._doubleNumber(9); // 18
</script>
</body>
</html>
| There is no difference in such the tiny example. There might be issues in big projects.
Less important. Module.ccall can perform async call with the parameter async=true, whereas call to the exported function Module._doubleNumber is always sync.
More important. At higher optimisation levels (-O2 and above), the closure compiler runs and minifies (changes) function names. A minified name for _doubleNumber will be changed to another name, usually unpredictable one, and Module._doubleNumber will be undefined.
-sEXPORTED_FUNCTIONS=_doubleNumber prevents name minifying and can be used for small C libraries. A big C library would require a ton of items listed in EXPORTED_FUNCTIONS, and you shall take into account the limited command line length.
|
72,048,908 | 72,049,033 | Use vcxproj instead of Cmake for internal vcpkg port | We have some libraries written in Visual Studio that we would like to share with other projects in different solutions in different repos.
I liked the idea of using an internal vcpkg registry to distribute those libraries to those other solutions/projects.
My concern here is that the libraries we'd like to share are vcxproj projects, and I believe vcpkg requires "ports" (packages) to be Cmake projects.
Is my understanding correct? If we want to expose those libraries via an internal vcpkg registry we'd have to convert those projects to Cmake projects?
| Vcpkg has built-in support for wrapping MSBuild (ie. sln/vcxproj) projects. See the function vcpkg_install_msbuild
Many projects still use the deprecated vcpkg_build_msbuild, though.
Using git grep I can find a few portfiles that will work as examples:
gsoap: https://github.com/microsoft/vcpkg/tree/master/ports/gsoap
winpcap: https://github.com/microsoft/vcpkg/tree/master/ports/winpcap
unrar: https://github.com/microsoft/vcpkg/tree/master/ports/unrar
libfabric: https://github.com/microsoft/vcpkg/tree/master/ports/libfabric (this one uses the new helper)
|
72,049,284 | 72,049,946 | why does omp_get_schedule() return a monotonic schedule when OMP_SCHEDULE=static? | I am compiling my code with g++8.5 on redhat8 and I notice that when I set OMP_SCHEDULE=static, then inside my application omp_get_schedule() returns a "monotonic" schedule instead of a "static" schedule. Why could this be happening? If I set OMP_SCHEDULE to something else such as "dynamic" then my application recognizes it as "dynamic". Here is the code in question. Any ideas? Thanks
omp_sched_t kind;
int chunk_size;
omp_get_schedule(&kind, &chunk_size);
switch(kind)
{
case omp_sched_static:
{
schedule_msg = schedule_msg + "schedule=static, chunk_size="+std::to_string(chunk_size);
break;
}
case omp_sched_dynamic:
{
schedule_msg = schedule_msg + "schedule=dynamic, chunk_size="+std::to_string(chunk_size);
break;
}
case omp_sched_guided:
{
schedule_msg = schedule_msg + "schedule=guided, chunk_size="+std::to_string(chunk_size);
break;
}
case omp_sched_auto:
{
schedule_msg = schedule_msg + "schedule=auto, chunk_size="+std::to_string(chunk_size);
break;
}
default:
{
schedule_msg = schedule_msg + "schedule=monotonic, chunk_size="+std::to_string(chunk_size);
break;
}
}
| omp_sched_t is defined as:
typedef enum omp_sched_t {
omp_sched_static = 1,
omp_sched_dynamic = 2,
omp_sched_guided = 3,
omp_sched_auto = 4,
omp_sched_monotonic = 0x80000000
} omp_sched_t;
Note that omp_sched_monotonic is a modifier not a type, so monotonic:static is expressed as omp_sched_monotonic | omp_sched_static (and its value is 0x80000001).
According to OpenMP standard:
If the static schedule kind is specified or if the ordered
clause is specified, and if no monotonic modifier is specified,
the effect will be as if the monotonic modifier was specified.
Therefore, if OMP_SCHEDULE is set to static the return value of omp_get_schedule() is 0x80000001, but your code is not handling properly the monotonic modifier.
|
72,049,367 | 72,052,358 | Determine the object type of a HDF5 path | I have a path name (a string) and an open HDF5 file. I have used H5Lexists to ensure an object with that name exists. How do I determine what the object type is? e.g. dataset, group, etc.
// open the file
hid_t fapl = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG);
hid_t hid = H5Fopen(filename.c_str(), H5F_ACC_RDONLY, fapl);
// ensure the object exists
const string path = "/some/path/to/an/object";
if (H5Lexists(m_hid, path.c_str(), H5P_DEFAULT) < 0) throw runtime_error();
// determine the object type
// TODO
if (dataset) {
hid_t dataset = H5Dopen(hid, path.c_str(), H5P_DEFAULT);
// do something
}
else if (group) {
hid_t group = H5Gopen(hid, path.c_str(), H5P_DEFAULT);
// do something
}
H5Fclose(hid);
I am trying not to use the C++ class based interface because this is being added to legacy code. I tried just opening the dataset to see if dataset < 0 to determine if it is a dataset, however, the HDF5 library throws a ton of warnings to stderr, so I'd like to do it the correct way.
| Use H5Oopen if you don't know the type in advance and use H5Iget_type to determine it.
hid_t object = H5Oopen(hid, path.c_str(), H5P_DEFAULT);
H5I_type_t h5type = H5Iget_type(object);
if (h5type == H5I_BADID) {
... // error handling stuff
} else if (h5type == H5I_DATASET) {
... // dataset stuff
} else if (h5type == H5I_GROUP) {
... // group stuff
} else { // other stuff maybe
}
H5Oclose(hid);
|
72,049,956 | 72,050,316 | Identify laptop display vs external monitor programmatically in C++ | I'm IT for my company and multiple of our user know very little of computers. We have multiple drop-in stations with docks and external monitors. So users experience display issues when moving to a different station. Monitors resize, duplicate or change frequencies.
I made this easy to use one click tool to resize their monitors in a console C++ exe. The issue I run into is identifying whether the display is a laptop display or an external monitor. This is important because all of our external monitors are 1920 x 1080 but some of our laptops are 1920 x 1200.
main.cpp:
#include <Windows.h>
#include <string>
#include <iostream>
int main()
{
DEVMODE devmode;
SetDisplayConfig(0, NULL, 0, NULL, SDC_TOPOLOGY_EXTEND | SDC_APPLY);
//long result = ChangeDisplaySettings(&devmode, 0);
DISPLAY_DEVICE displayDevice;
displayDevice.cb = sizeof(displayDevice);
int deviceIndex = 0;
while (EnumDisplayDevices(0, deviceIndex, &displayDevice, 0))
{
std::wstring deviceName = displayDevice.DeviceName;
int monitorIndex = 0;
while (EnumDisplayDevices(deviceName.c_str(), monitorIndex, &displayDevice, 0))
{
devmode.dmPelsWidth = 1920;
devmode.dmPelsHeight = 1080;
devmode.dmDisplayFrequency = 60;
devmode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
devmode.dmSize = sizeof(DEVMODE);
long result = ChangeDisplaySettingsEx(deviceName.c_str(), &devmode, NULL, NULL, 0);
++monitorIndex;
}
++deviceIndex;
}
return 0;
}
| Perhaps you are looking for the DISPLAY_DEVICE_REMOVABLE flag in the displayDevice.StateFlags field?
Value
Meaning
DISPLAY_DEVICE_REMOVABLE
The device is removable; it cannot be the primary display.
https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-display_devicea
|
72,050,034 | 72,050,067 | Nothing prints on console in SFML | I am trying SFML, but got some strange issue,
#include <SFML/Graphics.hpp>
#include <iostream>
int main() {
sf::RenderWindow window;
window.create(sf::VideoMode(1100, 600), "SFML - learning");
while (window.isOpen()) {
std::cout << "Inside the game loop.\n"; // issue is here
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
exit(EXIT_SUCCESS);
}
}
window.clear();
window.display();
}
return 0;
}
'''
when I do compile/Link and go for output, nothing prints on my console.It runs successfully but on console should also print "Inside the game loop.", but it does nothing. Here is what I am doing (I am using mingw compiler)
g++ -IC:\SFML-2.5.1\include -c main.cpp -o out.o
g++ -LC:\SFML-2.5.1\lib .\out.o -o app.exe -lmingw32 -lsfml-graphics -lsfml-window -lsfml-system -lsfml-main -mwindows
| -mwindows means "don't open a console for my application". You might want to remove it in debug builds.
|
72,050,274 | 72,050,430 | Can't figure out the function for filling array with random numbers c++ | So I am trying to make a function randBetween that is going to generate random numbers and after fill the array with those numbers
Problem that I missing out on something when I try to move a statement into function
#include <iostream>
#include <ctime>
using namespace std;
void fillArray(int arr[], int size, int min, int max);
int randBetween(int max, int min);
void printArray(int arr[], int size);
const int size = 10;
int main()
{
int arr[size];
int min = -100;
int max = 100;
srand(time(NULL));
fillArray(arr, size, min, max);
printArray(arr, size);
}
int randBetween(int max, int min)
{
int num = (rand() % (max - min + 1)) + min;
return num;
}
void fillArray(int arr[], int size, int min, int max)
{
for (int i = 0; i < size; i++)
{
int num = 0;
randBetween(min, max);
//num = ( rand () % (max - min + 1)) + min;
arr[i] = num;
}
}
void printArray(int arr[], int size)
{
for (int count = 0; count < size; count++)
{
cout << arr[count] << "\n";
}
}
if I don't comment out //num = ( rand () % (max - min + 1)) + min; it works perfect without function
however I must use it in the functions and I cant figure out what I do wrong;
I tried to change parameters, change location but nothing helps
| Replacing num = ( rand () % (max - min + 1)) + min; with randBetween(min, max); is missing something crucial: You aren't setting the num variable in the second case. Although you do set num inside the randBetween function, this is actually not the same variable; it's defined inside randBetween, so it's not reachable outside of it, and doesn't effect the num inside fillArray. You can fix this by setting the outer num using this line:
num = randBetween(min, max);
instead of just randBetween(min, max);.
|
72,050,404 | 72,050,580 | What does standalone operator * do at beginning of an equation in C++? | I'm going through some code and came across a line like:
x = * y
What is the asterisk (*) in this case? I have some programming knowledge, but I'm new to C++. I think I grasp the concept of pointer variables, but the order and spaces make me think it's different than the *= operator or *y pointer.
| In x = * y, y is most likely a pointer to something, in which case * is used to dereference the pointer, giving you a reference to the object to which y points and x = *y; copy assigns that value to x.
Example:
int val = 10;
int* y = &val; // y is now pointing at val
int x;
x = *y; // the space after `*` doesn't matter
After this, x has the value 10.
Another option is that y is an instance of a type for which operator* is overloaded. Example:
struct foo {
int operator*() const { return 123; }
};
int main() {
foo y;
int x;
x = *y;
}
Here, *y calls the operator*() member function on the foo instance y which returns 123, which is what gets assigned to x.
the order and spaces make me think it's different than the *= operator or *y pointer.
The spaces don't matter. * y and *y are the same thing, but it is indeed different from *=, which is the multiply and assign operator. Example:
int x = 2;
int y = 3;
x *= y; // logically the same as `x = x * y;`
After this, x would be 6.
Combining dereferencing and the mutiply and assign operator while using a non-idiomatic placement of spaces can certainly produce some confusing looking code:
int val = 10;
int* y = &val;
int x = 2;
x *=* y; // `x = x * (*y)` => `x = 2 * 10`
|
72,050,664 | 72,050,776 | Why don't standard libraries in g++ violate the One Definition Rule when included multiple times? | I poorly understand the linkage process, and I'm struggling with multi-file compilation with template classes. I wanted to keep definitions in one file, declarations in another. But after a day of suffering, I found out that I should keep definitions and declarations in the same transition unit (see here). But my code still doesn't compile, and if I do not figure it out, I'll post another question.
But that's not the question. The question is: once I was reading about "keeping definitions and declarations in the same header" and it was considered as bad practice. One of the comments says:
The include guards protect against including the same header file multiple times in the same source file. It doesn't protect against inclusion over multiple source files
Makes sense, until I wanted to try this out with standard libraries in g++. I tried to do it with <vector>, so I have two files:
main.cpp:
#include "class.h"
#include <vector>
template class std::vector<int>;
int main()
{
std::vector<int> arr;
}
class.h:
#include <vector>
std::vector<int> a(4);
I compiled with g++ main.cpp class.h and it compiled successfully. But why? Didn't I included <vector> twice, and therefore I have double definitions?
I checked header files on my machine, and they have definitions and declarations in the same file.
| You need to differentiate between two categories of entities: Those that may have only one definition in the whole program and those that may have a single definition in each translation unit, although these definitions must be identical (i.e. same sequence of tokens plus some more requirements). In any case a single translation unit may contain only one definition of an entity.
See https://en.cppreference.com/w/cpp/language/definition for the details.
Most entities belong to the first category, but classes, templates of all kinds and inline functions belong to the second one. Not only can these entities be defined in every translation unit, but they typically need to be defined in every translation unit using them. That's why their definitions typically belong in header files, while definitions of entities of the first category never belong in a header file.
std::vector is a class template, so it and its member functions can be defined in each translation unit once.
It is not clear what you intention with the compiler invocation g++ main.cpp class.h is, but it actually compiles only one translation unit (main.cpp) and does something else for class.h because of its file ending (see comments under your question).
In the compilation unit for main.cpp you are not including two definitions of std::vector or its members, although you have two #include<vector> directives, because the standard library is required to prevent this from happening. It could e.g. use header guards as user code would to achieve the same guarantee.
If class.h would also be compiled as a translation unit, then there still wouldn't be an issue, since std::vector and its members are templated entities and so they can be defined again in this translation unit.
Note that technically the standard library is not bound by the language rules. It may not be written in C++ at all. In that case it just has to work correctly for the user, no matter how it is included, as long as the user program is in accordance with the language rules.
Also note that the explicit instantiation definition
template class std::vector<int>;
is pointless in the way you are using it. It is only required if the members of the class template are, against the typical usage mentioned above, not defined in the header but a single translation unit (but that is never the case for the standard library) or to speed up compilation time, in which case there should be an explicit instantiation declaration in the other translation units to prevent implicit instantiation.
|
72,050,699 | 72,051,045 | Is there any way to declare a array, not just its elements, as const? | Using std::array I can declare both the array itself and it's objects as const.
const std::array<const int,2> a {1,2};
However, if I read the standard correctly, a declaration such as this only declares the array elements const. See this
const int a[2] {1,2};
The reason this matters is that if the complete object, in these cases a, is const then it's UB to alter any subobjects. If only the subobjects, like a[0] are const then they can be modified by "transparent replacement" and it's not UB. This is a new change in basic.life as of c++20. See this. It's also clear from the definition of arrays that array elements are subobjects. See this
For instance this would be legal if the complete object (total array) wasn't const.
std::construct_at(&a[0], 5);
So is there any way other than using the std::array wrapper to declare the complete array const?
| The type of the variable declared in
const int a[2] {1,2};
is "array of 2 const int" per the rule you linked, but that itself is a const-qualified type by the resolution of CWG 1059, which can be found in [basic.type.qualifier]/3 of the post-C++20 draft:
An array type whose elements are cv-qualified is also considered to have the same cv-qualifications as its elements.
I don't think there are any const-qualified array types to non-const-qualified elements, nor non-const-qualified array types to const-qualified elements, although I guess the object replacement rules allow placing elements of different cv-qualification into an array under some circumstances.
So a is already a const complete object and modifying it in the suggested way would be UB.
|
72,051,206 | 72,053,733 | Atomic function pointer call compiles in gcc, but not in clang and msvc | When calling function from an atomic function pointer, like:
#include <atomic>
#include <type_traits>
int func0(){ return 0; }
using func_type = std::add_pointer<int()>::type;
std::atomic<func_type> f = { func0 };
int main(){
f();
}
gcc doesn't complain at all, while clang and msvc have problem with call f():
[clang]: error: call to object of type 'std::atomic<func_type>' (aka 'atomic<int (*)()>') is ambiguous
[msvc]: there is more than one way an object of type "std::atomic<func_type>" can be called for the argument list
Clang additionally specifies possible call candidates to be:
operator __pointer_type() const noexcept
operator __pointer_type() const volatile noexcept
It seems like this difference in volatility is confusing for clang and msvc, but not gcc.
When call is changed from f() to f.load()(), the code works in all abovementioned compilers. Which is all the more confusing, since both load() and operator T() are said to have const and const volatile overloads - if implicit conversion doesn't work, I'd expect load() not to work as well. Are the rules somehow different within implicit conversions (versus member calls)?
So, is gcc wrong to accept that code? Are clang and msvc wrong to error out? Any other combination of being wrong or right?
This is mostly a theoretical question, but if there is some better way to have an atomic function pointer, I'd like to know.
| Clang and MSVC are correct.
For each conversion function to a function pointer of the class, a so-called surrogate call function is added to overload resolution, which if chosen would first convert the object via this operator overload to a function pointer and then call the function via the function pointer. This is explained in [over.call.object]/2.
However, the surrogate call function does not translate the cv-qualifiers of the conversion operator in any way. So, since std::atomic has a conversion operator which is volatile and one which is not, there will be two indistinguishable surrogate call functions. These are also the only candidates since std::atomic doesn't have any actual operator() and so overload resolution must always be ambiguous.
There is even a footnote in the standard mentioning that this can happen, see [over.call.object]/footnote.120.
With a direct call to .load() the volatile-qualifier will be a tie-breaker in overload resolution, so this issue doesn't appear.
With (*f)() overload resolution on the (built-in) operator* with the function pointer type as parameter is performed. There are two implicit conversion sequences via the two conversion functions. The standard isn't very clear on it, but I think the intention is that this doesn't result in an ambiguous conversion sequence (which would also imply ambiguous overload resolution when it is chosen). Instead I think it is intended that the rules for initialization by conversion function are applied to select only one of the conversions, which would make it unambiguously the volatile-qualified one.
|
72,051,753 | 73,345,620 | How does ffmpeg extract audio data from mp3 files? | In the ffmpeg documentation, an example of mp2 decoding is given. I try to apply this to mp3:
#define SOURCE_FILE "ignore/audio01.mp3"
#define TARGET_FILE "ignore/target-audio01.pcm"
#define AUDIO_INBUF_SIZE 20480
#define AUDIO_REFILL_THRESH 4096
#define av_perr(errnum) \
char av_err_buff[AV_ERROR_MAX_STRING_SIZE]; \
av_strerror(errnum, (char *) &av_err_buff, AV_ERROR_MAX_STRING_SIZE); \
fprintf(stderr, "\033[91m%s\033[0m\n", av_err_buff);
static int decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame, FILE *outfile) {
int ret, i, j;
int data_size;
ret = avcodec_send_packet(dec_ctx, pkt);
if (ret < 0) {
av_perr(ret);
return EXIT_FAILURE;
}
while (ret >= 0) {
ret = avcodec_receive_frame(dec_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
break;
} else if (ret < 0) {
av_perr(ret);
return EXIT_FAILURE;
}
data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt);
if (data_size < 0) {
av_perr(data_size);
return EXIT_FAILURE;
}
for (i = 0; i < frame->nb_samples; i++) {
for (j = 0; j < dec_ctx->channels; j++) {
fwrite(frame->data[j] + data_size * i, 1, data_size, outfile);
}
}
}
return EXIT_SUCCESS;
}
#define IS_NULL_PTR(ptr, message) \
if (!ptr) { \
fprintf(stderr, "\033[91m%s\033[0m\n", message); \
goto FINALLY; \
}
#define av_perr(errnum) \
char av_err_buff[AV_ERROR_MAX_STRING_SIZE]; \
av_strerror(errnum, (char *) &av_err_buff, AV_ERROR_MAX_STRING_SIZE); \
fprintf(stderr, "\033[91m%s\033[0m\n", av_err_buff);
int main(int argc, char **argv) {
const AVCodec *codec;
AVCodecContext *c = nullptr;
AVCodecParserContext *parser = nullptr;
enum AVSampleFormat sfmt;
int ret = 0, len = 0, n_channels = 0;
FILE *source_file = nullptr, *target_file = nullptr;
const char *fmt = nullptr;
uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
uint8_t *data = nullptr;
size_t data_size = 0;
AVPacket *pkt = nullptr;
AVFrame *decode_frame = nullptr;
...
data = inbuf;
data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, source_file);
while (data_size > 0) {
ret = av_parser_parse2(parser, c, &pkt->data, &pkt->size, data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if (ret < 0) {
fprintf(stderr, "\033[91mError while parsing\033[0m\n");
goto FINALLY;
}
data += ret;
data_size -= ret;
if (pkt->size && decode(c, pkt, decode_frame, target_file)) goto FINALLY;
if (data_size < AUDIO_REFILL_THRESH) {
memmove(inbuf, data, data_size);
data = inbuf;
len = fread(data + data_size, 1, AUDIO_INBUF_SIZE - data_size, source_file);
if (len > 0) data_size += len;
}
}
...
}
I get these errors:
[mp3float @ 0x55c51ac63440] Header missing
Invalid data found when processing input
Here is the version of the ffmpeg library:
libavutil 57. 17.100 / 57. 17.100
libavcodec 59. 18.100 / 59. 18.100
libavformat 59. 16.100 / 59. 16.100
libavdevice 59. 4.100 / 59. 4.100
libavfilter 8. 24.100 / 8. 24.100
libswscale 6. 4.100 / 6. 4.100
libswresample 4. 3.100 / 4. 3.100
libpostproc 56. 3.100 / 56. 3.100
I guess this is due to the fundamental difference in the data format of the mp3 and mp2 frames, but I can't find a way to decode the mp3.
What is the essential difference between the audio formats of mp3 and mp2? Also, what can I do to properly handle mp3 audio?
| You may want to check if the input MP3 file starts with ID3 tag (pretty sure it does). FFMPEG does pretty awful job with skipping metadata that is not defined by particular codec standard. Thus, av_parser_parse2() would not skip ID3 tags and then avcodec_send_packet() would complain about data you fed it with (since it doesn't recognize ID3 metadata as a valid MP3 stream).
See https://id3.org/id3v2.3.0#ID3v2_header for more information about ID3 header - parse it properly and its size is all you need to skip the rest of ID3 tag. The simplest thing to do is to read first 10 bytes of the file and check for ID3 tag, if present - parse size of the rest of the tag and just seek this many bytes ahead in the input file. From that point you can read rest of the file and pass its content to FFMPEG functions normally, as in example.
|
72,051,855 | 72,051,879 | std::map<int, std::bitset<256 > > thread safety w/o mutex? | I have a
std::map<int, std::bitset<256 > > m;
After construction no new keys will be inserted and no keys will be removed. Can I safely assign the bitset in one thread while reading it in other threads without using a mutex?
// thread 1:
std::bitset<256> a = getBitset();
m[1] = a;
// thread 2:
std::bitset<256> b = m[1];
// or alternatively
std::bitset<256> c = m.at(1);
I think that the program will not crash but a data race could occur in the bitset. A data race would be acceptable if the read would deliver a combination of the old and the new bitset.
| No, it is not safe.
operator= of the bitset is a modifying operation, and as such is not guaranteed to be free of a data race if the bitset is simultaneously accessed in another thread. And in practice, it will almost surely cause a data race, since it needs to write to the object. This is not specific to std::bitset, but generally true for pretty much all non-empty non-atomic standard library types (and most other non-empty types, as well).
Any data race will result in undefined behavior. There are no partial updates. In that sense, it should never be acceptable.
If you want to be able to do this, either wrap the bitset in a struct with a mutex to protect access to the bitset, or use something like an atomic shared_ptr that allows atomically exchanging the old bitset with a new one and delaying destruction of the old one until all references are gone.
Although I think it is not guaranteed, std::bitset may also be trivially copyable. You could check that with a static_assert on std::is_trivially_copyable_v and if true, you could also use a std::atomic or std::atomic_ref which will allow accessing the bitset atomically (i.e. free of data race) and will probably use a lock only if the underlying architecture doesn't support atomic access to an object of the corresponding size.
Also note that std::bitset b = m[1]; and m[1] also cause undefined behavior, because operator[] of std::map is also a modifying operation, and is not specified to be free of a data race, even if it doesn't insert a new element into the map. You would need to use e.g. the find() member function instead.
|
72,052,108 | 72,052,186 | Meaning of 1[pointer] in C++? | Reading cppreference I found this example:
int a[4] = {1, 2, 3, 4};
int* p = &a[2];
std::cout << p[1] << p[-1] << 1[p] << (-1)[p] << '\n'; // 4242
I am confused about the meaning of 1[p] and (-1)[p]. Asking for help elsewhere I was told: "1[ptr] is equivalent to *(1 * sizeof(T) + ptr)". So I understand mechanically why it outputs 4242, but I find it hard to reason about. As it's nonsensical to put a pointer in square brackets usually, and is an error by itself:
[cling]$ 1[p]
(int) 4
[cling]$ [p]
input_line_15:2:3: error: 'p' cannot be captured because it does not have
automatic storage duration
[p]
^
Is this just a special case of the syntax I should just memorize, or am I misunderstanding some logic behind the statement?
| Assume p is a pointer or array, and n is an integer. When the compiler sees this:
p[n]
It logically interprets that expression as:
*(p+n)
So when it sees this:
n[p]
The compiler treats it as:
*(n+p)
Which is algebraically the same as *(p+n)
Hence: p[n] == n[p]
|
72,052,141 | 72,052,151 | Make user-defined types true/false in boolean context in c++ | I have a Line that represents the relevant information of a line on the cartesian plane. The type that has, among other members, a bool that indicates whether the slope is defined. I would like to be able to do the following:
if(my_line){
double new_slope = my_line.slope * 9;
}
where the instance my_line itself is implicitly converted to a true/false value in a boolean context. I am thinking of the behavior I see with smart pointers, where if it is pointing to nullptr or 0, the instance is considered false as-is.
How would I go about emulating this behavior?
| In your Line class, implement a bool conversion operator. You could also optionally overload the operator!, but that is not required in C++11 and later. See Contextual conversions.
For example:
class Line {
bool mSlopeDefined;
...
public:
...
explicit operator bool() const noexcept {
return mSlopeDefined;
}
// optional since C++11, but doesn't hurt...
bool operator!() const {
return !mSlopeDefined;
}
};
|
72,052,214 | 72,052,546 | Boost ASIO "Bad address" error when passing unique_ptr to completion handler | I'm trying to implement a simple TCP server using ASIO. The main difference here is that I'm using std::unique_ptr to hold the buffers instead of raw pointers and I'm moving them inside the completion handler in order to extend their lifetime.
Here is the code and it works just fine (I guess)
void do_read() {
auto data = std::make_unique<uint8_t[]>(1500);
auto undesired_var = boost::asio::buffer(data.get(), 1500);
socket_.async_read_some(
undesired_var,
[self = shared_from_this(), data = std::move(data)](auto ec, auto len) mutable {
if (!ec) {
std::cout << "Received " << len << " bytes :)" << std::endl;
} else {
std::cout << "Read error: " << ec.message() << std::endl;
}
}
);
}
Running the code above, I get the following output:
/tcp_echo/cmake-build-debug/bin/tcp_server 6666
Received 9 bytes :)
Note that I created a variable called undesired_var in order to hold the boost::asio::mutable_buffer data.
When I try to remove those variables by creating them directly in the socket_.async_read_some call:
void do_read() {
auto data = std::make_unique<uint8_t[]>(1500);
socket_.async_read_some(
boost::asio::buffer(data.get(), 1500),
[self = shared_from_this(), data = std::move(data)](auto ec, auto len) mutable {
if (!ec) {
std::cout << "Received " << len << " bytes :)" << std::endl;
} else {
std::cout << "Read error: " << ec.message() << std::endl;
}
}
);
}
I got the following output
tcp_echo/cmake-build-debug/bin/tcp_server 6666
Read error: Bad address
It seems that in the second case my std::unique_ptr is getting destroyed prematurely, but I can figure out why. Did I miss something?
| Yeah it's the order in which argument expressions are evaluated.
The std::move can happen before you do .get().
Another Bug:
Besides, there seems to be a large problem here:
auto data = std::make_unique<uint8_t>(1500);
That dynamically allocates an unsigned char (uint8_t) which is initialized from the integer value 1500. The allocation has size 1 (1 byte).
auto undesired_var = boost::asio::buffer(data.get(), 1500);
You're using it as if it is 1500 bytes. Oops. You probably meant:
auto data = std::make_unique<uint8_t[]>(1500);
The type of data is now std::unique_ptr<uint8_t[], std::default_delete<uint8_t[]>> which is an entirely different template specialization
|
72,052,572 | 72,052,673 | illegal instruction occur while using pointer and reference | when reading the source codes of realtime_tools::RealtimeBuffer, I got lots of questions about the pointer and reference. The related codes are shown below:
void writeFromNonRT(const T& data)
{
// get lock
lock();
// copy data into non-realtime buffer
*non_realtime_data_ = data;
new_data_available_ = true;
// release lock
mutex_.unlock();
}
To figure out, I tried to code the similar code like:
#include <iostream>
using namespace std;
void pt_ref(int& data)
{
int *ptr;
ptr = &data; // ptr points to "data"
cout << "data's addres: "<< ptr <<"\n"; // print address
}
int main()
{
int x = 3;
pt_ref(x);
cout << "x's address: " << &x;
}
\\ output:
\\ data's addres: 0x7ffe05c17c4c
\\ x's address: 0x7ffe05c17c4c
This code runs well, but it's still different to the source code.
// these 2 lines are different.
*non_realtime_data_ = data;
ptr = &data;
So I tried to change ptr = &data; to *ptr = data;, and ran again the code, the error("illegal instruction") occurred.
Hope someone can answer me, thanks a lot.
PS: I ran the code on the replit online compiler.
|
I tried to change ptr = &data; to *ptr = data;, and ran again the code, the error("illegal instruction") occurred.
The problem is that the the pointer ptr was uninitialized(and does not point to any int object) and so dereferencing that pointer(which you did when you wrote *ptr on the left hand side) leads to undefined behavior.
int *ptr; //pointer ptr does not point to any int object as of now
*ptr = data;
//-^^^^--------->undefined behavior since ptr doesn't point to any int object
To solve this make sure that before dereferencing ptr, the pointer ptr points to some int object.
void pt_ref(int& data)
{
int var = 10; //int object
//-------------vvvv-------->now ptr points to "var"
int *ptr = &var;
//--vvvv------------------->this is fine now
*ptr = data;
}
|
72,052,797 | 72,057,456 | Regex in c++ for maching some patters | I want regex of this.
add x2, x1, x0 is a valid instruction;
I want to implement this. But bit confused, how to, as I am newbie in using Regex. Can anyone share these Regex?
| If this is a longer project and will have more requirements later, then definitely a different approach would be better.
The standard approach to solve such a problem ist to define a grammar and then created a lexer and a parser. The tools lex/yacc or flex/bison can be used for that. Or, a simple shift/reduce parser can also be hand crafted.
The language that you sketched with the given grammar, may be indeed specified with a Chomsky class 3 grammar, and can hence be produced gy a regular grammar. And, with that, parsed with regular expressions.
The specification is a little bit unclear as to what a register is and if there are more keyowrds. Especially ecall is unclear.
But how to build such a regex?
You will define small tokens and concatenate them. And different paths can be implemented with the or operator |.
Let's give sume example.
a register may be matched with a\d+. So, an "a" followed by ome digits. If it is not only "a", but other letters as well, you could use [a-z]\d+
op codes with the same number of parameters can be listed up with a simple or |. like in add|sub
For spaces there are many solutions. you may use \s+ or [ ]+or whatever spaces you need.
To build one rule, you can concatenate what you learned so far
Having different parts needs an or | for the complete path
If you want to get back the matched groups, you must enclose the needed stuff in brackets
And with that, one of many many possible solutions can be:
^[ ]*((add|sub)[ ]+(a\d+)[ ]*,[ ]*(a\d+)[ ]*,[ ]*(a\d+)|(ecall))[ ]*$
See example in: regex101
|
72,052,949 | 72,053,252 | KeyPressedEvent not registering | I am new to Qt and trying to implement what should be a pretty straightforward "key pressed" event method, but it doesn't seem to be registering properly.
Here is the declaration in my header file:
#include <Qt>
#include <QKeyEvent>
class MainWindow : public QMainWindow
{
Q_OBJECT
protected:
void KeyPressEvent(QKeyEvent* event);
};
and here is the implementation:
void MainWindow::KeyPressEvent(QKeyEvent *event)
{
qDebug() << "Registered Key Press";
}
This is almost exactly what the examples I have seen online look like, so unless there is some connection somewhere I am missing, not sure what the issue would be.
| It is, as you say, almost exactly what the examples show. They should show
void keyPressEvent(QKeyEvent* event) override;
See QWidget::keyPressEvent. Note that C++ is case sensitive (K -> k).
Also, I've added the override keyword - then the compiler will tell you if you try to override a function which the compiler doesn't know!
Additional caveats are included in above linked documentation:
Make sure to call setFocusPolicy with an appropriate policy;
Note also that child widgets can "swallow" events. Meaning that if your main window has any children; and the key press happens inside a child, the child can say "I handle this event, no need to pass it on to my parent". Then your MainWindow::keyPressEvent also won't get called; see the corresponding notes in the QKeyEvent documentation; the gist: any child window of your MainWindow handling keyPressEvent has to ignore() the event in order for it to propagate to the parent class.
|
72,053,134 | 72,053,220 | I'm learning C++ lambda function. Why does it have this output? | This is my code
#include<iostream>
int* p = nullptr;
auto fun()
{
int a = 1;
p = &a;
std::cout << &a << std::endl;
auto z = [&a]() {std::cout << &a << " "; a++; std::cout << "lambda call " << a << std::endl; };
return z;
}
int main()
{
auto z = fun();
std::cout << *p << "\n";
z();
z();
fun()();
}
and the output is
0x7fffd10af15c
1
0x7fffd10af15c lambda call 21880
0x7fffd10af15c lambda call 21880
0x7fffd10af15c
0x7fffd10af15c lambda call 21880
The version of my compiler is gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
Why do i have this output? Is it an undefined behavior?
| Yes, the problem is that a is a local variable in the fun function and gets destroyed by the time fun finishes. That means, the returned lambda z is referencing an area on the stack where a used to be, but now when z is called this area is used for something else (this is why you see 21880).
In order to avoid this problem you need to prevent a being destroyed when leaving fun's scope. One way is to declare a as a global variable, just like p. The other one is to make it a static variable.
|
72,054,441 | 72,054,607 | Why is there no warning from -Wfloat-equal when comparing containers of doubles? | If I use the compiler option -Wfloat-equal with GCC or Clang, equality comparisons of float/double values cause a warning. However, when comparing containers (like std::vector or std::tuple) of float or double values, no such warning is raised.
Example code (also at https://godbolt.org/z/YP8v8hTs3):
#include <tuple>
#include <vector>
#include <assert.h>
int main() {
double d = 1.2;
std::tuple<double, double> t_d{1.2, 3.14};
std::tuple<double, double> t_d_2{1.2, 3.14};
std::vector<double> v_d{1.2, 3.14};
std::vector<double> v_d_2{1.2, 3.14};
// this causes a warning, like "warning: comparing floating-point with '==' or '!=' is unsafe [-Wfloat-equal]":
assert(d == 1.2);
// but why no warning from -Wfloat-equal here?
assert(t_d == t_d_2);
// no warning here either:
assert(v_d == v_d_2);
// all of these cause warnings as expected:
assert(std::get<0>(t_d) == 1.2);
assert(std::get<0>(t_d) == std::get<0>(t_d_2));
assert(v_d[0] == 1.2);
assert(v_d[0] == v_d_2[0]);
return 0;
}
Why are the warnings omitted for these container comparisons? And more importantly, what can I do to actually get these warnings as well?
| GCC doesn't report warnings for system headers by default. The desired behavior may be obtained by adding -Wsystem-header compiler flag.
Quotation from the documentation:
-Wsystem-headers
Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code...
Live demo: https://godbolt.org/z/s6rExszj6
Clang seemingly adopted the same approach, see https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-in-system-headers and https://clang.llvm.org/docs/UsersManual.html#options-to-control-error-and-warning-messages.
Live demo: https://godbolt.org/z/n9xY8rcM8
|
72,054,860 | 72,054,960 | How template deduce const pointer type? | I've tried following codes in cppinsights:
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
template<typename T>
void printType(T x) {
std::cout << typeid(x).name() << std::endl;
}
void test() {
const std::vector<int>::pointer a = new int[2];
const int* c = new int[2];
printType(a);//line15
printType(c);//line16
//delete
}
int main() {
test();
}
The output is like:
/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void printType<int *>(int * x)
{
std::operator<<(std::cout, typeid(x).name()).operator<<(std::endl);
}
#endif
/* First instantiated from: insights.cpp:16 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void printType<const int *>(const int * x)
{
std::operator<<(std::cout, typeid(x).name()).operator<<(std::endl);
}
#endif
Since std::vector<int>::pointer = int*, why const std::vector<int>::pointer a has been interpreted as int* instead of const int*?
BTW: If the pointer is replaced by value_type, they will be both deduced as int instead of const int.
How compiler deal with const in this type of cases?
|
Since std::vector<int>::pointer = int*, why const std::vector<int>::pointer a has been interpreted as int* instead of
const int*?
Because const std::vector<int>::pointer will be interpreted as int* const instead of const int*. Adding a const-qualifier to a pointer makes itself unmodifiable, not the value it points to.
If you need const int* then you should use std::vector<int>::const_pointer instead of const std::vector<int>::pointer.
|
72,055,063 | 72,056,635 | Append to registry without expanding variables | I'll just start off by saying that I'm by no means an expert in C++, so any pointers/tips are greatly appreciated.
I'm having some difficulties reading and writing from registry, while keeping variables, i.e. not expanding them.
I'm trying to append my executable path to the PATH environment variable (permanently), but I'm running into all sorts of problems.
I have a long PATH variable that makes it impossible to edit without using a program or regedit, so I opted to create an "OldPath" variable with my current PATH variable, and change my PATH variable to %OldPath%. This has worked great, but now when I try to write to it with C++, %OldPath% gets expanded into the old path variable and as a result, the variable gets truncated.
I tried first with normal strings, but I ended up with what looked like Chinese symbols in my PATH variable, so I changed it to wstring. Now I get normal strings, but the string gets truncated at 1172 characters.
My desired end result is that PATH is set to %OldPath;<current_path>
get_path_env()
inline std::wstring get_path_env()
{
wchar_t* buf = nullptr;
size_t sz = 0;
if (_wdupenv_s(&buf, &sz, L"PATH") == 0 && buf != nullptr)
{
std::wstring path_env = buf;
free(buf);
return path_env;
}
return L"";
}
set_permanent_environment_variable()
inline bool set_permanent_environment_variable()
{
const std::wstring path_env = get_path_env();
if (path_env == L"")
{
return false;
}
std::wstringstream wss;
wss << path_env;
if (path_env.back() != ';')
{
wss << L';';
}
wss << std::filesystem::current_path().wstring() << L'\0';
const std::wstring temp_data = wss.str();
HKEY h_key;
const auto key_path = TEXT(R"(System\CurrentControlSet\Control\Session Manager\Environment)");
if (const auto l_open_status = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key_path, 0, KEY_ALL_ACCESS, &h_key); l_open_status == ERROR_SUCCESS)
{
const auto data = temp_data.c_str();
const DWORD data_size = static_cast<DWORD>(lstrlenW(data) + 1);
// ReSharper disable once CppCStyleCast
const auto l_set_status = RegSetValueExW(h_key, L"PATH", 0, REG_EXPAND_SZ, (LPBYTE)data, data_size);
RegCloseKey(h_key);
if (l_set_status == ERROR_SUCCESS)
{
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, reinterpret_cast<LPARAM>("Environment"), SMTO_BLOCK, 100, nullptr);
return true;
}
}
return false;
}
In other words, I want to find the equivalent of the following in C#:
var assemblyPath = Directory.GetParent(Assembly.GetEntryAssembly()!.Location).FullName;
var pathVariable = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PATH", $"{pathVariable};{assemblyPath}", EnvironmentVariableTarget.Machine);
EDIT: I actually haven't tested if that code expands the value or not, but I want to do as the C# code states and if possible, not expand the variables in the path variable.
| You are trying to change the PATH setting in the registry. So one would expect that you would get the current PATH setting from the registry, change it, and set the new PATH setting in the registry.
But you are not getting the PATH setting from the registry. You are getting the PATH variable from the environment instead. Why is that? The environment is controlled by the setting in the registry, but it's not that setting. In particular, you noticed that the environment variables set in the registry get expanded before they actually go into the environment.
It's like changing the wallpaper by taking a screenshot of the desktop, changing the screenshot, then setting it as the wallpaper, then asking how to remove the icons from the wallpaper.
The solution is to simply get the current unexpanded PATH setting from the registry instead of the expanded one from the environment.
|
72,055,210 | 72,055,520 | OpenMP array initialization impact | I am working in parallel with OpenMP on an array (working part). If I initialize the array in parallel before, then my working part takes 18 ms. If I initialize the array serially without OpenMP, then my working part takes 58 ms. What causes the worse performance?
The system:
Intel(R) Xeon(R) CPU E5-2697 v3 (28 cores / 56 threads, 2 Sockets)
Example code:
unsigned long sum = 0;
long* array = (long*)malloc(sizeof(long) * 160000000);
// Initialisation
#pragma omp parallel for num_threads(56) schedule(static)
for(unsigned int i = 0; i < array_length; i++){
array[i]= i%10;
}
// Time start
// Work
#pragma omp parallel for num_threads(56) shared(array, 160000000) reduction(+: sum)
for (unsigned long i = 0; i < array_length; i++)
{
if (array[i] < 4)
{
sum += array[i];
}
}
// Time End
| There are two aspects at work here:
NUMA allocation
In a NUMA system, memory pages can be local to a CPU or remote. By default Linux allocates memory in a first-touch policy, meaning the first write access to a memory page determines on which node the page is physically allocated.
If your malloc is large enough that new memory is requested from the OS (instead of reusing existing heap memory), this first touch will happen in the initialization. Because you use static scheduling for OpenMP, the same thread will use the memory that initialized it. Therefore, unless the thread gets migrated to a different CPU, which is unlikely, the memory will be local.
If you don't parallelize the initialization, the memory will end up local to the main thread which will be worse for threads that are on different sockets.
Note that Windows doesn't use a first-touch policy (AFAIK). So this behavior is not portable.
Caching
The same as above also applies to caches. The initialization will put array elements into the cache of the CPU doing it. If the same CPU accesses the memory during the second phase, it will be cache-hot and ready to use.
|
72,055,546 | 72,055,895 | Is this pointer always a runtime construct | I am learning about the this pointer in C++. And i came across the following statement from the standard:
An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:
this, except in a constexpr function or a constexpr constructor that is being evaluated as part of e;
I do not understand the meaning of the above quoted statement. I thought that the this pointer is a runtime construct and so it cannot be used in compile-time contexts. But the above statement seems to suggest otherwise in the mentioned contexts. My first question is what does it mean. Can someone give some example so that i can understand the meaning of that statement.
I tried to create an example to better understand the meaning of the statement by myself but the program did not work as expected(meaning that it gave error while i thought that it should work according to the quoted statement):
struct Person
{
constexpr int size()
{
return 4;
}
void func()
{
int arr[this->size()]; //here size is a constexpr member function and so "this" should be a core constant expression and arr should not be VLA
}
};
Demo
In the above program, i thought that we're allowed to use the expression this->size() as the size of an array(which must be a compile time constant) because size is constexpr and so the quoted statement applies and so the program should compile. Also, since size is constexpr arr should not be VLA. But to my surprise, the arr seems to be VLA and the program also doesn't compile in msvc(because msvc don't have vla i think). So my second question is why doesn't the quoted statement applicable in the above example and why is arr VLA? I mean size is constexpr so arr shouldn't be VLA.
| The only way to use this in a core constant expression is to call a constructor (and use it in the constructor) or call a member function on an existing object.
this except in a constexpr function or a constexpr constructor that is being evaluated as part of e;
(emphasis added)
In your attempt, the constant expression should be this->size(), but Person::func (the function this appears in) is not being evaluated as a part of that expression.
An simple example of what this allows:
struct S {
int i = 0;
constexpr S(int x) {
this->i = x;
}
constexpr int get_i() const {
return this->i;
}
};
// `this` used in constructor
constexpr S s{7};
// `this` used in `S::get_i`
static_assert(s.get_i() == 7);
static_assert(S{4}.get_i() == 4);
Demo: https://godbolt.org/z/hea8cvcxW
|
72,056,424 | 72,057,076 | Why {} is better candidate to be int than string for C++ overload resolution? | Overload resolution favours to consider {} as being of some fundamental type as opposed to some container.
For example:
#include <iostream>
#include <string>
void foo(const std::string&) {std::cout << "string\n";}
void foo(int) {std::cout << "int\n";}
int main() { foo({}); }
That compiles without any diagnostics and outputs:
int
https://godbolt.org/z/zETfrs5as
If to comment out the int overload then it works fine with string.
The question is why? For programmer's standpoint it can be confusing
illusion.
| From over.ics.list#9.2:
if the initializer list has no elements, the implicit conversion sequence is the identity conversion. [ Example:
void f(int);
f( { } ); // OK: identity conversion
— end example ]
Thus, the conversion from {} to int is an identity conversion, while {} to const std::string& is a user-defined conversion. And since the identity conversion is a better match, the overload corresponding to int will be chosen.
|
72,058,944 | 72,059,062 | Why is signed and unsigned addition converted differently for 16 and 32 bit integers? | It seems the GCC and Clang interpret addition between a signed and unsigned integers differently, depending on their size. Why is this, and is the conversion consistent on all compilers and platforms?
Take this example:
#include <cstdint>
#include <iostream>
int main()
{
std::cout <<"16 bit uint 2 - int 3 = "<<uint16_t(2)+int16_t(-3)<<std::endl;
std::cout <<"32 bit uint 2 - int 3 = "<<uint32_t(2)+int32_t(-3)<<std::endl;
return 0;
}
Result:
$ ./out.exe
16 bit uint 2 - int 3 = -1
32 bit uint 2 - int 3 = 4294967295
In both cases we got -1, but one was interpreted as an unsigned integer and underflowed. I would have expected both to be converted in the same way.
So again, why do the compilers convert these so differently, and is this guaranteed to be consistent? I tested this with g++ 11.1.0, clang 12.0. and g++ 11.2.0 on Arch Linux and Debian, getting the same result.
| When you do uint16_t(2)+int16_t(-3), both operands are types that are smaller than int. Because of this, each operand is promoted to an int and signed + signed results in a signed integer and you get the result of -1 stored in that signed integer.
When you do uint32_t(2)+int32_t(-3), since both operands are the size of an int or larger, no promotion happens and now you are in a case where you have unsigned + signed which results in a conversion of the signed integer into an unsigned integer, and the unsigned value of -1 wraps to being the largest value representable.
|
72,059,107 | 72,062,630 | Order of static initialization with function call | I have a static global variable initialized with a function call. This causes the initialization order to be not respected, eve inside a translation unit. This is a reproducer (the order of the code makes little sense here but it resembles the original arrangement in my use case, and is important to trigger the issue, so please disregard it):
#include <array>
#include <iostream>
#include <limits>
template <typename T> constexpr T defaultValue = std::numeric_limits<T>::max();
namespace _Private {
template <typename T> std::array<T, 3> getDefaultArrayValue() {
std::cout << "Initialize array" << std::endl;
std::array<T, 3> result;
result[0] = defaultValue<T>;
result[1] = defaultValue<T>;
result[2] = defaultValue<T>;
return result;
}
} // namespace _Private
// This generates the wrong behavior
template <typename T> const std::array<T, 3> defaultValue<std::array<T, 3>> = _Private::getDefaultArrayValue<T>();
// This behaves right
//template <typename T> const std::array<T, 3> defaultValue<std::array<T, 3>> = {defaultValue<T>, defaultValue<T>, defaultValue<T>};
struct TestClass {
std::array<float, 3> arr;
TestClass();
};
TestClass tc;
int main() {
std::cout << tc.arr[0] << std::endl;
return 0;
}
TestClass::TestClass() : arr{defaultValue<std::array<float, 3>>} {std::cout << "Build TestClass" << std::endl;}
Here I have a TestClass class whose constructor initializes the arr member variable to its default value, as defined by the defaultValue<std::array<float,3>> specialization; the latter is a global variable whose value is set equal to the return value of getDefaultArrayValue(). A global instance of TestClass is created, and I would expect that its arr member is correctly initialized to the specified default, that is 3.40282e+38 (i.e. the maximum float value). However, running the program the value 0. is printed, because the initialization of defaultValue<std::array<float, 3>> is actually done after the creation of tc:
$ ./a.out
Build TestClass
Initialize array
0
so when tc is built defaultValue<std::array<float, 3>> still does not have its correct value. The problem is fixed if defaultValue<std::array<float, 3>> is initialized by directly assigning a value to it (see the commented line in the reproducer code) rather than calling a function, restoring the "from first to last" static variable initialization order rule that applies to a single translation unit.
To summarize, it seems that calling a function to initialize a global variable breaks the initialization order. Is this behavior mandated by the standard or is it an implementation detail (I'm using GCC 11.2.0)?
| It’s not that you used a function call: it’s that that function isn’t constexpr, and that it’s a (specialization of a) variable template being initialized. The former prevents constant initialization, and the latter removes all ordering constraints for dynamic initialization. Obviously in this case the fix can be trivial.
|
72,060,014 | 72,068,731 | How do i convert gmt time to other timezones in c++ | I have wrote a basic code to get the gmt time and i want to add specific hours to get another timezone how do i do that? (if there is any simpler way to do this that will work too)
#include <iostream>
#include <conio.h>
#include <ctime>
int main()
{
time_t tim = time(0);
tm* timenow = gmtime(&tim);
std::cout << "time in gmt is " << timenow->tm_hour << ":" << timenow->tm_min << ":" << timenow->tm_sec << std::endl;
return 0;
}
| clang/libc++/libstdc++ isn't yet fully supporting the C++20 <chrono> specification. However there exists a free, open-source preview of this part of C++20 that works with C++11/14/17. It exists in namespace date rather than namespace std::chrono, but otherwise is a pretty good approximation of the C++20 spec.
It consists of one source file, tz.cpp, that must be compiled with your source. On macOS and linux you can define this configuration macro: USE_OS_TZDB to use the time zone database provided by your OS. An easy way to do this is to put -DUSE_OS_TZDB=1 on the compile command line.
Here are complete setup instructions.
Here is example code that prints out the local time in several timezones (along with UTC):
#include "date/tz.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
auto timenow = system_clock::now();
auto fmt = "%F %T %Z\n";
cout << "UTC : " << format(fmt, timenow);
cout << "America/New_York : " << format(fmt, zoned_time{"America/New_York", timenow});
cout << "Europe/London : " << format(fmt, zoned_time{"Europe/London", timenow});
cout << "Asia/Tokyo : " << format(fmt, zoned_time{"Asia/Tokyo", timenow});
}
I compiled this on macOS using:
clang++ test.cpp -std=c++17 -I../date/include ../date/src/tz.cpp -DUSE_OS_TZDB=1
This just output for me:
UTC : 2022-04-30 12:54:43.963126 UTC
America/New_York : 2022-04-30 08:54:43.963126 EDT
Europe/London : 2022-04-30 13:54:43.963126 BST
Asia/Tokyo : 2022-04-30 21:54:43.963126 JST
The latest Visual Studio with the option /std:c++latest is shipping the C++20 version of chrono. The above example slightly changes:
#include <chrono>
#include <format>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
auto timenow = system_clock::now();
cout << "UTC : " << format("{:%F %T %Z}\n", timenow);
cout << "America/New_York : " << format("{:%F %T %Z}\n", zoned_time{"America/New_York", timenow});
cout << "Europe/London : " << format("{:%F %T %Z}\n", zoned_time{"Europe/London", timenow});
cout << "Asia/Tokyo : " << format("{:%F %T %Z}\n", zoned_time{"Asia/Tokyo", timenow});
}
Drop #include "date/tz.h"
Add #include <format>
Drop using namespace date;
Prefix the fmt string with {: and postfix it with }.
Inline the fmt string with each call to format.
I don't know why step 5 is needed. That looks like a bug in <format> to me, but I'm not positive.
Here is a way to programmatically list all of the time zone names your system provides:
for (auto& tz : get_tzdb().zones)
cout << tz.name() << '\n';
for (auto& tz : get_tzdb().links)
cout << tz.name() << '\n';
It is also possible to provide user-written time zones. Here is an example of a user-written POSIX time zone.
|
72,060,593 | 72,060,701 | Pointer obejct function call without instantiating it | I don't understand how does following code called f() function successfully. As object b is not instantiated using new keyword.
Please help and Thanks in advance for answers.
#include <iostream>
using namespace std;
class A{ public:
void f(){cout<<"f";}
};
int main()
{
A *b;
delete b;
b->f();
return 0;
}
|
I don't understand how does following code called f() function successfully.
The program has undefined behavior since b is not initialized and is also not pointing to memory allocated by new.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
For example, here the program doesn't crash but here it crashes.
To solve this make sure that the pointer b is initialized and is pointing to memory allocated by new.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
72,060,900 | 72,119,352 | how to change access time of a file using utime and mktime syscalls and c++? | I was trying to change the access time of a file, but i didn't get the result i wanted.
this is what i tried:
struct tm time;
time.tm_sec=56;
time.tm_min=48;
time.tm_hour=20;
time.tm_mday=12;
time.tm_mon=8;
time.tm_year=1905;
struct utimbuf utime_par;
utime_par.actime=mktime(&time);
if(utime("file_name",&utime_par)!=0)
{
perror("smash error: utime failed");
std::cout<<"entered";
return;
}
when I run on linux terminal
ls -l file_name
I get
-rwxrw-rw- 1 student student 3133 Jun 20 4461763 README.txt
Does anyone know what I did wrong?
| According to the documentation of the function utime, struct utimbuf (which you pass to the function utime) is defined in the following way:
struct utimbuf {
time_t actime; /* access time */
time_t modtime; /* modification time */
};
However, you are only setting the actime field of this struct, which means that the field modtime has an indeterminate value when you pass it to the function utime.
In your case, you probably want to set both fields to the same time value:
utime_par.actime = mktime( &time );
utime_par.modtime = mktime( &time );
Or, if you don't want to call the function mktime twice (which is a bit inefficient), you can also write:
utime_par.actime = mktime( &time );
utime_par.modtime = time_par.actime;
Also, as already pointed out in the comments section, the field tm_year in a struct tm should not be the absolute year, but rather the number of years since the year 1900. Therefore, it is probably wrong that you write 1905 into this field, as that corresponds to the year 3805.
Another issue is that you should set the field tm_isdst in the struct tm, to indicate whether daylight savings was in effect. You can simply set this field to a negative value, which will tell mktime that you are not providing this information, and that it should therefore determine this itself. By not setting this field, the value of this field will be indeterminate, which means that you may be providing mktime false information about whether daylight savings was in effect. This could lead to the timestamp on the file being wrong by one hour.
|
72,060,984 | 72,089,631 | Generating C# code for a given .proto file produces an error while opening a file | I'm working on Cpp-written dll, which will be used in my C# project. I use google::protobuf::compiler::csharp::Generator to generate .cs file.
First, I create google::protobuf::compiler::Importer. To do so, I need to get an instance of DiskSourceTree and implement MultiFileErrorCollector:
class ErrorCollector : public MultiFileErrorCollector
{
public:
void AddError(const std::string& filename, int line, int column, const std::string& message) override
{
std::fstream stream;
stream.open(filename);
stream << message;
stream.close();
}
void AddWarning(const std::string& filename, int line, int column, const std::string& message) override
{
std::fstream stream;
stream.open(filename);
stream << message;
stream.close();
}
};
After that, I implement GeneratorContext to pass it to Generator::Generate():
class Context : public GeneratorContext
{
public:
google::protobuf::io::ZeroCopyOutputStream* Open(const std::string& filename)
{
stream_ptr = std::make_unique<std::fstream>();
stream_ptr->open(filename);
proto_stream = std::make_unique<google::protobuf::io::OstreamOutputStream>(stream_ptr.get());
return proto_stream.get();
}
private:
std::unique_ptr<std::fstream> stream_ptr;
std::unique_ptr<google::protobuf::io::OstreamOutputStream> proto_stream;
};
The error occurs at the stage of importing .proto-file. The debugger says, const google::protobuf::FileDescriptor* desc = importer->Import(FILENAME); results to null.
It's probably something with the file path or even with my understanding of how it all works. I would appreciate any help.
Here's my main function:
int main()
{
// building an Importer
DiskSourceTree* tree = new DiskSourceTree;
ErrorCollector* collector = new ErrorCollector;
Importer* importer = new Importer(tree, collector);
const std::string FILENAME = "C:/my/path/my_file.proto";
const google::protobuf::FileDescriptor* desc = importer->Import(FILENAME); // the error is here
// generating the code
Generator generator;
Context* context = new Context();
std::string* error_str = new std::string;
error_str->reserve(256);
if (generator.Generate(desc, "", context, error_str)) // this line produces an exception since the descriptor is invalid
{
std::cout << "success!";
}
delete tree;
delete collector;
delete importer;
delete context;
delete error_str;
}
| Turns out, those were some extra code for a certain customization.
If all you do is generating a proto-class (in any supported language), you simply have to register the generator in google::protobuf::compiler::CommandLineInterface:
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/compiler/csharp/csharp_generator.h>
using namespace google::protobuf::compiler;
int main(int argc, char** argv)
{
CommandLineInterface cli;
csharp::Generator generator;
cli.RegisterGenerator("--cs_out", &generator, "Generate C# source.");
return cli.Run(argc, argv);
}
Command line arguments and some other details
|
72,061,157 | 72,061,343 | What is the time complexity of a recursive function that calls itself N times with one less? | What is the time complexity of a recursive function with this structure
void f(int n)
{
if (n == 0)
return;
for (int i = n; i >= 1; --i)
{
// something O(1)
f(n - i);
}
}
My thinking is that it follows
T(n) = T(0) + ... + T(n-2) + T(n-1) = (T(0) + ... + T(n-2)) + T(n-1) = T(n-1) + T(n-1) = 2T(n-1)
so we would say O(2^n-1)?
or is it
T(n) = T(0) * ... * T(n-1)
| Your analysis seems to be sound.
When in doubt you can measure it. If the complexity really is O(2^n) then you can count how often the inner loop is executed and for increasing n the count divided by 2^n should converge:
#include <iostream>
struct foo {
int counter = 0;
void f(int n) {
if (n == 0)
return;
for (int i = n; i >= 1; --i) {
++counter;
f(n - i);
}
}
};
int main() {
for (int i=0;i < 4;++i) {
long int n = 2<<i;
foo f;
f.f(n);
std::cout << n << " " << (2<<n) << " " << f.counter / static_cast<double>(2<<n) << "\n";
}
}
Output is:
2 8 0.375
4 32 0.46875
8 512 0.498047
16 131072 0.499992
Note that this measurement cannot prove your analysis to be correct. Though the count seems to converge to 0.5 and the measurement cannot falsify your analysis. The count seems to somewhere around 2^n-1, just that for complexity a constant factor of 2 does not matter and you can write it as O(2^n).
PS: Complexity is interesting when considering algorithms. When considering concrete implementations things are a little different. Note that the function as written can be optimized to an equivalent void f(int) {} which is obviously not O(2^n).
|
72,061,504 | 72,061,735 | Is there a way to stop GoogleTest after a specific test is run, whether it passes or fails? | I have a large number of unit tests run through GoogleTest. Currently one of them (call it fooTest) is failing when the full test suite is run, but passing when run alone. So one (or more then one) of the tests that run before fooTest is doing something that causes it to fail, which of course is a big nono for testing and I obviously want to find the culprit.
This is happening with default run conditions, so the test order is always the same. The fooTest is about half way through this run order and there are enough tests that the run time of the second half of the tests is significant, especially if running things multiple times.
So I want to set googletest to always stop the test run after fooTest is run - whether it passes or fails. I know I can do --gtest_break_on_failure, but if I do a test run that causes fooTest to pass I still want to stop right there and not go through everything else. I could run with debug and add a breakpoint after the test, but that also slows things down a little and feels less then ideal.
It seems like this could be an simple setting, but I've not been able to find anything yet. I'm hoping there is either a parameter on run I can use, or a trick to make this happen.
| You have several options:
Simply call exit function at the end of fooTest.
Create a test fixture. In SetUp check for a flag that is always false, but it sets to true if fooTest is executed. Something like this:
bool skip_testing = false;
// Class for test fixture
class MyTestFixture : public ::testing::Test {
protected:
void SetUp() override {
if (skip_testing) {
GTEST_SKIP();
}
}
};
TEST_F(MyTestFixture, test1) {
//
EXPECT_EQ(1, 1);
}
TEST_F(MyTestFixture, footest) {
EXPECT_EQ(1, 1);
skip_testing = true;
}
TEST_F(MyTestFixture, test2) {
//
EXPECT_EQ(1, 1);
}
TEST_F(MyTestFixture, test3) {
//
EXPECT_EQ(1, 1);
}
See a working a working example here: https://godbolt.org/z/8dzKGE6Eh
Similar to Option 2, but use explicit success and failure in SetUp instead of GTEST_SKIP. However using GTEST_SKIP is preferred, cause your output will show that the tests were skipped.
|
72,062,387 | 72,068,228 | Forward declared friend template class don't need to include header file | Let us have an abstract template class Stack which will inherit realisation from second class parameter in template.
// file Stack.h
template <class T, template<typename> class Implementation>
class Stack : private Implementation<T>
{
public:
Stack() {}
virtual ~Stack() {}
void push(const T& x) { Implementation<T>::push(x); }
void pop() { Implementation<T>::pop(); }
const T& top() { return Implementation<T>::top(); }
bool empty() const { return Implementation<T>::empty(); }
};
Then, we have a class that will provide implementation and then be used in instantiating a template.
// file ListStack.h
template <class Elem>
class ListStack
{
private:
size_t _size;
struct ListNode
{
Elem _elem;
ListNode * _next;
};
ListNode * _top;
~ListStack();
friend class Stack<Elem, ListStack>;
public:
ListStack();
bool empty() const;
const Elem& top() const;
void pop();
void push(const Elem & value);
size_t size() const;
};
I declared destructor private and made Stack class a friend class so it can be only used when instantiating Stack class.
// file main.cpp
#include "Stack.h"
#include "ListStack.h"
int main()
{
// ListStack<int> list; cannot instaniate
Stack<int, ListStack> s;
}
The question is why ListStack.h don't need to include Stack.h file?
| In order for template code to be compiled, it needs to be called somewhere. In your case, you have two header files both defining what a template should be. The call to the template is being made in a file that includes both Stack and ListStack. Since you are creating the Stack variable in main.cpp, you can get away with List and ListStack not knowing each other in the header files.
I suspect that the Stack class will be defined in your main.cpp by the compiler but I'm not sure if I'm right about it.
As for the ListStack class instantiation error, that's because your destructor is private. Check this LINK for more details.
EDIT: You also need to create definitions for your ListStack class. Without that, nothing will work. I assumed for simplicity that you have empty definitions everywhere.
|
72,062,606 | 72,062,727 | Can I initialize object of different types in an if statement? | I know I can write
if (int a = 1; /* whatever */) {}
and even
if (int a = 1, b{3}; /* whatever */) {}
but how can I declare, say, a of type int and b of type std::string?
Such a thing doesn't work:
if (auto a = 1, b{"ciaos"s}; /* whatever */) {}
I've not included a standard, because I'm interested in the answer in general, even though realistically I'd make use of the answer in the context of c++17.
And, if such a thing is not possible, is there any precise reason why (hence language-lawyer)?
| You are only allowed one variable declaration statement in a if statement and each variable declaration statement can only declare a single type. This is convered in [stmt.if]/3 where is shows the grammar for the if statement you are trying to use is
if constexpr(opt) ( init-statement condition ) statement
and init-statement can be a simple-declaration and that contains a init-declarator-list which only allows a single declarator. Normally this means just a single type, but pointers (*) and references (&) get applied to the variable name, not the type name so you can have T, T*, and/or T& variables declared in a single init-declarator-list i.e., int a = 42, *b = &a, &c = a;
As a workaround, you can leverage structured bindings and CTAD (to reduce verbosity) in conjunction with std::tuple to get a syntax like
int main()
{
using namespace std::string_literals;
if (auto [a, b] = std::tuple{42, "string"s}; a)
{
std::cout << b;
}
}
which outputs
string
|
72,062,610 | 72,064,243 | Loading a Bitmap Image into openGL program | I am trying to load a bitmap to my openGL 3d object, however I get this error:
loadbitmap - bitcount failed = 8;
what I am trying to do is that I have an object and 3 separate bitmap images (Body, Eye, Head) bitmap images, so I`ll try to draw the texture till vector 6498, which are the triangles for the body part.
This error message isnt from the compiler it is printed manually from this file:
#ifndef _Bitmap_
#define _Bitmap_
#include "glad/glad.h"
#include <stdio.h>
#include <windows.h>
#include <wingdi.h>
GLuint loadbitmap(const char* filename, unsigned char*& pixelBuffer, BITMAPINFOHEADER* infoHeader, BITMAPFILEHEADER* fileHeader)
{
FILE* bitmapFile;
errno_t err = fopen_s(&bitmapFile, filename, "rb");
if (err != 0 || bitmapFile == NULL)
{
printf("loadbitmap - open failed for %s\n", filename);
return NULL;
}
fread(fileHeader, sizeof(BITMAPFILEHEADER), 1, bitmapFile);
if (fileHeader->bfType != 0x4D42)
{
printf("loadbitmap - type failed \n");
return NULL;
}
fread(infoHeader, sizeof(BITMAPINFOHEADER), 1, bitmapFile);
if (infoHeader->biBitCount < 24)
{
printf("loadbitmap - bitcount failed = %d\n", infoHeader->biBitCount);
return NULL;
}
fseek(bitmapFile, fileHeader->bfOffBits, SEEK_SET);
int nBytes = infoHeader->biWidth * infoHeader->biHeight * 3;
pixelBuffer = new unsigned char[nBytes];
fread(pixelBuffer, sizeof(unsigned char), nBytes, bitmapFile);
fclose(bitmapFile);
for (int i = 0; i < nBytes; i += 3)
{
unsigned char tmp = pixelBuffer[i];
pixelBuffer[i] = pixelBuffer[i + 2];
pixelBuffer[i + 2] = tmp;
}
printf("loadbitmap - loaded %s w=%d h=%d bits=%d\n", filename, infoHeader->biWidth, infoHeader->biHeight, infoHeader->biBitCount);
}
#endif
and I use this texture as follows:
GLuint texture = setup_texture("OBJFiles/Body.bmp");
glBindTexture(GL_TEXTURE_2D, texture);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 6498);
glBindVertexArray(0);
| According to the posted code, the error message loadbitmap - bitcount failed = 8 indicates that the loaded image uses 8 bits per pixel, probably an 8-bit grayscale image.
The documentation of the biBitCount member of the BITMAPINFOHEADER structure (wingdi.h) says:
biBitCount
Specifies the number of bits per pixel (bpp). For uncompressed
formats, this value is the average number of bits per pixel. For
compressed formats, this value is the implied bit depth of the
uncompressed image, after the image has been decoded.
So, try to load an RGB bitmap file instead with a color depth of 24 bpp (8 bits per color channel).
In order to make it work with the original file, the grayscale image could be converted to the required format in an image editor (for example in Gimp). Alternatively, the bitmap loader code could be modified to accept grayscale images (related topic: How do I display a grayscale image with an OpenGL texture?).
|
72,062,898 | 72,064,028 | ImportError: No module named <module_name> with pybind11 on MacOS | I am trying to import C++ module created using pybind11 to python script.
The directory structure is:
pybind_test:
main.cpp
build
CMakeLists.txt
test.py
pybind11 (github repo clone)
It builds successfully and the file module_name.cpython-39-darwin.so is created. However when running test.py I get:
File "../test.py", line 2, in <module>
from build.module_name import *
ImportError: No module named build.module_name
My CMakeLists file:
cmake_minimum_required(VERSION 3.4...3.18)
set(CMAKE_CXX_STANDARD 17)
project(pybindtest)
add_subdirectory(pybind11)
pybind11_add_module(module_name main.cpp)
How would I import this module into python like a normal python module?
| As you noticed, the compiled library must be in a route (in terms of file path) reachable by the Python executable (which you achieved by moving test.py to the build directory, where your compiled library is).
You could also move the compiled library to your Python's site-packages folder, where other modules are stored.
|
72,063,191 | 72,063,402 | Can C++20 concepts be redeclared or not? | This one's rather straightforward: according to the cppreference article, concepts can be redeclared no problem:
So I figured alright, cool, I don't have to worry about redeclaring my concept for creating "printable enums"; I can declare the concept in both my logging header and my common types header, so I only have to include what's needed:
// common types header
#include <enum_traits.hpp>
template<typename E>
concept PrintableEnum = requires(E& e) { {enum_traits<E>::toString(e)} -> std::same_as<const char*>; };
template<PrintableEnum T>
std::ostream& operator<<(std::ostream& os, const T& o)
{
os << enum_traits<T>::toString(o);
return os;
}
// logging header
template<typename T>
concept PrintableEnum = requires(T& e) { {enum_traits<T>::toString(e)} -> std::same_as<const char*>; };
template<PrintableEnum T>
plog::Record& operator<<(plog::Record& rec, const T& o)
{
rec << enum_traits<T>::toString(o);
return rec;
}
(Ignore that the ostream overload could probably cover the plog record overload for the moment; that's probably how I'm gonna work around the problem, but I'm curious about this first.)
So when I try to compile this, MSVC throws a fit for every file both headers are included in (which one it points to as the error changes based on include order):
[build] commontypes.hpp(25): error C7571: 'PrintableEnum': variable template has already been initialized
[build] logging.hpp(162): note: see declaration of 'PrintableEnum'
Also note, doing what cppreference does in that screenshot and duplicating the PrintableEnum declaration right under the first one in one of the files is the same problem.
So, is cppreference wrong here? Does the standard not actually say anything about redeclarations? (I'm not actually sure where the official c++ standard is kept if not on cppreference...) Do I need to worry about redefinitions of concepts like anything else in C++?
Or is MSVC wrong here? (Not that I can do much about MSVC...) Searching the error message only got me stuff about other redeclarations, like classes and variables. Apparently "concept" is not very SEO-friendly.
|
This one's rather straightforward: according to the cppreference article, concepts can be redeclared no problem:
No, it doesn't say that. This snippet:
template<Incrementable T>
void f(T) requires Decrementable<T>;
template<Incrementable T>
void f(T) requires Decrementable<T>; // OK, redeclaration
Doesn't redeclare a concept. It doesn't even declare a concept. What it's showing is declaring the same function template, twice. That function template is constrained (with both Incrementable and Decrementable), but it is still a function template.
You cannot redeclare a concept.
One reason is that you can't just declare a concept, you always also define it. You can't just write:
template <class T> concept C;
in the same way that you can write:
template <class T> void f();
f here just a declaration of a function template, and I can add another declaration of it. But only one definition. This is ill-formed:
template <class T> void f() { }
template <class T> void f() { }
in the same way that this is ill-formed:
template <class T> concept C = true;
template <class T> concept C = true;
There can only be one definition.
|
72,063,357 | 72,063,757 | Taking the address of a returned temporary object | I have a piece of C++20 code that I believe is valid, but our static analyzer thinks it's unsafe.
struct Foo {
explicit Foo() { activeFoo = this; }
~Foo() { activeFoo = nullptr; }
Foo(const Foo&) = delete;
Foo(Foo&&) = delete;
inline static const Foo* activeFoo = nullptr;
};
Foo makeFoo()
{
// Is there a dangling reference here?
return Foo();
}
int main()
{
auto myFoo = makeFoo();
}
My static analyzer thinks makeFoo causes activeFoo to point to a temporary object and will become a dangling pointer. I believe this is wrong; the return Foo(); should get a guaranteed copy elision (as evidenced by the deleted copy & move constructors), so there is only ever one Foo instance constructed, myFoo.
Who is correct?
| makeFoo and copy elision (which as you noted is guaranteed in this specific example since C++17) don't even matter.
activeFoo can never be dangling. If it was pointing to an object after its lifetime ended, then the destructor of that object would have reset activeFoo to nullptr, meaning it cannot be pointing to the object, a contradiction. That is assuming the destructor is called for every created object of type Foo. Technically this might not always be the case if you placement-new objects explicitly, although it should.
I would however not generally expect a static analyzer to figure out this logic. Without some details on the static analyzer or what exactly it complains about, it will be hard to say more.
|
72,064,332 | 72,064,369 | create a base class object use a derived class constructor c++ | Is someone can tell why A a = B(); call constructor fisrt and then destructor immediately?
And why the output like this?
C A
C B
D B
D A
test1 A
D A
class A {
public:
A() {
cout<< "C A" <<endl;
}
~A() {
cout<< "D A" <<endl;
}
void test1() {
cout<< "test1 A" << endl;
}
};
class B:public A {
public:
B() {
cout<< "C B" <<endl;
}
~B() {
cout<< "D B" <<endl;
}
void test1() {
cout<< "test1 B" << endl;
}
};
int main(int argc, const char * argv[]) {
A a = B();
a.test1();
return 0;
}
| In this declaration
A a = B();
there is at first created a temporary object of the type B. So its base constructor A and the constructor of B are called.
C A
C B
The object a is created using the default copy constructor of the class A.
After the declaration the temporary object of the type B is destroyed calling destructors in the reverse order
D B
D A
At the end of the program the object a is also destroyed calling its destructor.
test1 A
D A
|
72,064,838 | 72,064,922 | What's the different between pointer new and default constructor in Qt? | I'm a newer for Qt and C++. And I feel about below:
//1
widget a;
a.show();
//2
widget *b=new widget();
b->show();
And I remember widget class (inherited from QWidget) have default constructor. But if I use it in a button like:
void MainWindow::on_pushButton_clicked()
{
//widget v;
//v.show();
widget *v=new widget();
v->show();
}
The first is shutdown in 10 miliseconds. What cause the difference between them?
Update:
I put this question is because the most popular way to create a windows in qt main is:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
It can work. The .exec() is a endless loop. So I want to know why it can't work in function...
| It is because in the first snippet, the object gets placed on the stack, so it will be destructed once it goes out of scope.
The new keyword places it on the heap. This means that it will live unil you delete it again, or exit the app. So you have to think about this, because if you don't make sure your object gets deleted, you have a memory leak.
These days there are plenty of smart pointers (also from Qt) out there that will delete your object for you.
Qt also will delete children of objects that get deleted, which can also help you manage your memory.
This is a very important bit of c++ to understand, so you shouldn't try to learn it all from a stackoverflow answer :)
Without knowing your app, i am going to guess that the best option for you here is, is just to add the widget as a member variable of the main window, and just call show() when you need it.
This means that it is constructed at the same time as MainWindow.
|
72,065,710 | 72,068,573 | Zakat of cows calculation | For every 30 cows, zakat is cow of one years old, and for every 40 cows zakat is female cow of two years old.
EXAMPLE:
30-39 cows -> zakat: 1 cow of one years old
40-49 cows -> zakat: 1 female cow of two years old
50-59 cows -> zakat: 1 female cow of two years old
60-69 cows -> zakat: 2 cows of one years old
120-129 cows -> zakat: 3 female cows of two years old OR 4 cows of one years old
EXPLANATION:
30-39 category: 30 combination: 30
30-49 category: 40 combination: 40
50-59 category: 50 combination: 40
60-69 category: 60 combination: 30 + 30
120-129 category: 120 combination: 40+40+40 OR 30+30+30+30
Category is clear. Combination could be made only using numbers 30 or 40. Based on combination zakat is calculated.
#include <iostream>
#include <cmath>
int main()
{
int cows=67;
int category=cows-cows%10;
if(30==category)
std::cout<<"1 cow of one years old";
if(40==category)
std::cout<<"1 female cow of two years old";
if(50==category)
std::cout<<"1 female cow of two years old";
if(30+30==category)
std::cout<<"2 cows of one years old";
if(30+30+30+30==category||40+40+40==category)
std::cout<<"4 cows of one years old OR 3 female cows of two years old";
return 0;
}
Do you have any idea how to make algorithm for making combinations that would work for huge numbers? Program should print zakat based on combinations.
| Consider a number of cows, N.
The maximum number of two-years female cows (V2 for short) is floor(N/40). So, your zakat may have a number of V2 ranging from 0 to floor(N/40), which leaves N-40*V2 cows untithed. These obviously require floor((N-40*V2)/30) V1 to complete zakat.
Pseudo-code:
N := number of cows
MV2 := floor(N/40)
out 'Possible zakat due:'
loop i from 0 to MV2:
V1 := floor((N-40*i)/30)
out i, ' female cows of 2 years, ', V1, ' cows of 1 year'
end
You can complicate the algorithm to ensure that when there are multiple combinations, only that with the minimum untithed cows is accepted.
For example if you have 60 cows, the basic algorithm will yield from 0 to 1 cows of two years:
V2=0, 60 cows remain, V1=2, untithed = 0
V2=1, 20 cows remain, V1=0, untithed = 20
In this case, the (1, 0) solution is a cheat and has to be discarded. With 112 cows:
V2=0, 112 cows remain, V1=3, untithed = 22
V2=1, 72 cows remain, V1=2, untithed = 12
V2=2, 32 cows remain, V1=1, untithed = 2
Here, the closest solution is 2 cows of 2 years, 1 cow of 1 year.
In C:
#include <math.h>
#include <stdio.h>
int main() {
int cows;
printf("Enter number of cows: ");
scanf("%d", &cows);
int category = cows - cows % 10;
int N, v2, mx, b1, b2, un, i;
for (N = 0; N <= cows; N += 10) {
v2 = floor(N / 40);
mx = 40;
b2 = 0;
b1 = 0;
for (i = 0; i <= v2; i++) {
int j = floor((N - 40 * i) / 30);
un = N - 40 * i - 30 * j;
if (un <= mx) {
b2 = i;
b1 = j;
mx = un;
}
}
un = N - 40 * b2 - 30 * b1;
if (N == category) {
printf("For %d cows, the zakat is:\n", cows);
if (cows < 30)
printf("0 cows");
if (b1)
printf("%d one years old cows\n", b1);
if (b2)
printf("%d two years old female cows\n", b2);
}
}
}
OUTPUT:
Enter number of cows: 140
For 140 cows, the zakat is:
2 one years old cows
2 two years old female cows
|
72,065,854 | 72,066,142 | How do I fix my current openGL error, my cmakelist may be my issue | I have included the library <GLUT/glut.h> and all my syntax is correct, yet I am receiving this error.
Undefined symbols for architecture arm64:
"_glBegin", referenced from:
triangle(float*, float*, float*) in main.cpp.o
"_glClear", referenced from:
displayTriangle() in main.cpp.o
"_glClearColor", referenced from:
_main in main.cpp.o
"_glColor3f", referenced from:
drawTetrahedron(int) in main.cpp.o
"_glEnable", referenced from:
_main in main.cpp.o
"_glEnd", referenced from:
triangle(float*, float*, float*) in main.cpp.o
"_glFlush", referenced from:
displayTriangle() in main.cpp.o
"_glLoadIdentity", referenced from:
displayTriangle() in main.cpp.o
"_glMatrixMode", referenced from:
reshapeWindow(int, int) in main.cpp.o
"_glOrtho", referenced from:
reshapeWindow(int, int) in main.cpp.o
"_glVertex3fv", referenced from:
triangle(float*, float*, float*) in main.cpp.o
"_glViewport", referenced from:
reshapeWindow(int, int) in main.cpp.o
"_glutCreateWindow", referenced from:
_main in main.cpp.o
"_glutDisplayFunc", referenced from:
_main in main.cpp.o
"_glutInit", referenced from:
_main in main.cpp.o
"_glutInitDisplayMode", referenced from:
_main in main.cpp.o
"_glutInitWindowSize", referenced from:
_main in main.cpp.o
"_glutMainLoop", referenced from:
_main in main.cpp.o
"_glutPostRedisplay", referenced from:
reshapeWindow(int, int) in main.cpp.o
"_glutReshapeFunc", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
My cmakefile I feel like is my issue, but I have no idea where to begin.
| Please provide more details like your relevant section of CMakeLists.txt for getting more info and getting quicker help from community.
Now, coming to the error logs, it seems you are cross-compiling the source files using a arm-based compilers.
The error message "ld: symbol(s) not found for architecture arm64" looks to me as a linker issue and you should be having the find_package() and linking calls in CMakeLists.txt for OpenGL.
So to start with , you should follow two steps initially and see if it solves your problem:
1. Make sure the CMake build system is pointing to correct compiler tool chain path (arm compilers in here).
Refer official website of CMake for same:
https://cmake.org/cmake/help/book/mastering-cmake/chapter/Cross%20Compiling%20With%20CMake.html
2. Make sure you are linking OpenGL
find_package(OpenGL REQUIRED)
target_include_directories(your_executable_name PUBLIC ${OPENGL_INCLUDE_DIR})
target_link_libraries(your_executable_name PUBLIC ${OPENGL_LIBRARIES})
|
72,066,464 | 72,067,394 | How can I implements erase( iterator erase(const_iterator first, const_iterator last)) of vector in c++ | https://www.cplusplus.com/reference/vector/vector/erase/
I want to make erase() method of vector in c++
iterator erase(const_iterator position)
{
theSize--;
int index = position - begin();
Object* newObj = new Object[theCapacity];
for (int i = 0, j = 0; j <= index; ++j)
{
if (j != index)
newObj[i++] = objects[j];
}
std::swap(objects, newObj);
delete[] newObj;
return &objects[index];
}
First, I tried to make erase() and try to reuse it to make iterator erase(const_iterator first, const_iterator last)
iterator erase(const_iterator first, const_iterator last)
{
int index = last - begin();
for (auto it = first; it != last; ++it)
{
erase(it);
}
return objects;
}
I don't know whether my approach was right or not.
Since returned value is garbage value. I think my index was wrong.
How can I improve my ** iterator erase(const_iterator position)**and
How can I reuse my iterator erase(const_iterator position) to make iterator erase(const_iterator first, const_iterator last)?
v.erase(v.begin(),v.begin()+3)
input
541234
output
-842150451-842150451
expected
1234
| You don't need to reallocate the array; use move semantics instead. Even if you use the current implementation, you benefit from moving the values from the old array instead of copying them.
Furthermore it's more efficient for erase(const_iterator, const_iterator) to receive its own implementation.
Your actual problem here is the fact that you're invalidating the iterators by calling erase as noted by @UlrichEckhardt and even if you didn't reallocate the array, you'd need to call erase with first instead of it, since erasing the element at the current position of it shifts the remaining elements left by one resuling in the next element to be erased to be placed at the current position of it, not at the next position.
Here's a simplified vector implementation that should work:
template<class T>
class Vector
{
public:
using iterator = T*;
using const_iterator = T const*;
Vector(std::initializer_list<T>&& list)
: size(list.size()),
objects(size == 0 ? nullptr : new T[size])
{
auto out = objects;
for (auto& e : list)
{
*out = std::move(e);
++out;
}
}
~Vector()
{
delete[] objects;
}
iterator begin() noexcept
{
return objects;
}
iterator end() noexcept
{
return objects + size;
}
const_iterator cbegin() const noexcept
{
return objects;
}
const_iterator cend() const noexcept
{
return objects + size;
}
iterator erase(const_iterator pos)
{
auto const result = objects + std::distance(cbegin(), pos);
auto const endIter = end();
for (auto p = result; p != endIter;)
{
auto& lhs = *p;
++p;
lhs = std::move(*p);
}
--size;
return result;
}
iterator erase(const_iterator first, const_iterator last)
{
auto const result = objects + std::distance(cbegin(), first);
if (first == last)
{
// empty delete sequence
return result;
}
// shift the elements after last
auto writeIter = result;
auto readIter = objects + std::distance(cbegin(), last);
for (auto const endIter = end(); readIter != endIter; ++writeIter, ++readIter)
{
*writeIter = std::move(*readIter);
}
// remove extra elements from the end
size = std::distance(objects, writeIter);
return result;
}
private:
size_t size;
T* objects;
};
int main()
{
{
Vector<int> a = { 1, 2, 3, 4, 5 };
auto iter = a.erase(a.cbegin() + 1, a.cend() - 1);
std::cout << "element pointed to by returned value: " << *iter << '\n';
for (auto i : a)
{
std::cout << i << '\n';
}
}
{
Vector<int> a = { 1, 2, 3, 4, 5 };
auto iter = a.erase(a.cbegin() + 1);
std::cout << "element pointed to by returned value: " << *iter << '\n';
for (auto i : a)
{
std::cout << i << '\n';
}
}
}
Note: The loops in the member functions can be replaced by the overload of std::move taking iterators.
|
72,066,657 | 72,066,741 | Merge two arrays of pointers into a third array of pointers in C++ | arr1,arr2 are two arrays of pointers, I have to merge these into arr3.
When the program gets arr3[1] (when k=1) the program is closes , I don't get why.
Please help.
class Node {
public:
Node* left;
T data;
Node* right;
int height;
};
void mergeArrays(Node<T>** arr1,Node<T>** arr2,int len1,int len2){
int p=0,q=0,k=0;
Node<T>** arr3 = new Node<T>*[len1+len2];
while ( p < len1 && q < len2) {
if ((arr1[p])->data< (arr2[q])->data) {
(arr3[k++])->data = (arr1[p++])->data;
} else {
(arr3[k++])->data = (arr2[q++])->data;
}
}
while ( p < len1) {
(arr3[k++])->data = (arr1[p++])->data;
}
while ( q < len2) {
(arr3[k++])->data = (arr2[q++])->data;
}
}
| You're not copying pointers. You're copying values from one data member of some object to another data member of some object. But the problem is, there is no "there" there to copy to . You allocate a bed of pointers for arr3, but there are no objects behind those pointers so this:
(arr3[k++])->data = (arr1[p++])->data;
Invokes undefined behavior.
I'm fairly certain this is what you were shooting for:
template<class T>
Node<T>** mergeArrays(Node<T> **arr1, Node<T> **arr2, int len1, int len2)
{
int p = 0, q = 0, k = 0;
Node<T> **arr3 = new Node<T> *[len1 + len2];
while (p < len1 && q < len2)
{
if ((arr1[p])->data < (arr2[q])->data)
{
arr3[k++] = arr1[p++];
}
else
{
arr3[k++] = arr2[q++];
}
}
while (p < len1)
{
arr3[k++] = arr1[p++];
}
while (q < len2)
{
arr3[k++] = arr2[q++];
}
return arr3;
}
|
72,067,768 | 72,068,040 | C++ vector of custom template class as member | I'm currently coding a program in c++ using a template class:
template<typename TYPE>
class TemplateClass {
private:
TYPE t;
};
I have another class which acts as manager of my TemplateClass which should store multiple instances of this class in a vector. Different instances should have different types e.g. int, std::string, etc.. Speaking in Java ways the solution would be to just use something like in the example below but it seems like this is not possible in C++.
class ManagerClass {
private:
// Here seems to be the problem.
std::vector<TemplateClass<?>> templates;
}
Is it possible to do something like that?
Thank you for all answers
| If you know all the types that will be stored in the std::vector at compile time I'd use an std::variant in such a case.
// This is used for the visitor pattern.
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
// The below line not needed in C++20...
template<class... Ts> overload(Ts...) -> overload<Ts...>;
template<typename T>
struct MyClass { T value; };
using types = std::variant<
MyClass<std::string>,
MyClass<int>,
MyClass<double>>;
int main()
{
std::vector<types> stuff{};
stuff.push_back(MyClass<std::string>{});
stuff.push_back(MyClass<int>{});
stuff.push_back(MyClass<double>{});
for(const auto& v : stuff)
{
if (std::holds_alternative<MyClass<std::string>>(v))
{
std::cout << "Im a string\n";
}
else if (auto* p{std::get_if<MyClass<int>>(&v)})
{
std::cout << "Im an int\n";
}
else
{
auto t = std::get<MyClass<double>>(v);
std::cout << "Im a double\n";
}
// Or you can use the visitor pattern.
std::visit(overload{
[](const MyClass<std::string>& ) { std::cout << "I'm a string\n"; },
[](const MyClass<int>& ) { std::cout << "I'm a int\n"; },
[](const MyClass<double>& ) { std::cout << "I'm a double\n"; },
}, v);
}
}
|
72,068,206 | 72,068,953 | libusb_open returns LIBUSB_ERROR_NOT_SUPPORTED on windows 10 | OS: Windows 10 64bit
Compiler: MSVC 19 std:c++20
static linking
I have below code which just initialize and print some information about the device
#include "libusb.h"
#include <iostream>
int main()
{
libusb_context* cntx{ nullptr };
int status{ libusb_init(&cntx) };
if (status != LIBUSB_SUCCESS)
{
std::cerr << libusb_strerror(status);
return -1;
}
libusb_device** devices;
ssize_t numberOfDevices{ libusb_get_device_list(cntx, &devices) };
if (numberOfDevices <= 0)
{
std::cerr << "Device does NOT found\n";
return -1;
}
std::cout << "Found " << numberOfDevices << " Devices\n";
int index{ 0 };
std::cout << std::hex;
std::cout << "Device Address: " << +libusb_get_device_address(devices[index]) << '\n'
<< "Port Number: " << +libusb_get_port_number(devices[index]) << '\n'
<< "Bus Number: " << +libusb_get_bus_number(devices[index]) << '\n'
<< "Device Speed: ";
switch (libusb_get_device_speed(devices[index])
{
case LIBUSB_SPEED_SUPER: std::cout << "5Gb\n"; break;
case LIBUSB_SPEED_SUPER_PLUS: std::cout << "10Gb\n"; break;
case LIBUSB_SPEED_FULL: std::cout << "12Mb\n"; break;
case LIBUSB_SPEED_LOW: std::cout << "1.5Mb\n"; break;
case LIBUSB_SPEED_HIGH: std::cout << "480Mb\n"; break;
default: std::cout << "UNKNOWN\n"; break;
}
so far so good, but when I want to open the (for example) devices[0], LIBUSB_ERROR_NOT_SUPPORTED will return:
constexpr std::uint16_t VID{ 0x8086 };
constexpr std::uint16_t PID{ 0x1D26 };
libusb_device_handle* device{ nullptr };
status = libusb_open(devices[index], &device);
if (status)
{
std::cerr << "Can NOT open the device: " << libusb_strerror(status) << '\n';
device = libusb_open_device_with_vid_pid(cntx, VID, PID);
if (!device)
{
std::cerr << "Can NOT open the device with VID & PID\n";
return -1;
}
}
std::cout << "Device opened\n";
return 0;
}
neither works.
btw, the device was programmed by a micro-programmer so I don't know about how he programmed it, my job is just to get data from the device.
| libusb can enumerate all USB devices. But it can only open devices that have the WinUSB driver (or libusbK or libusb0) installed. WinUSB is the generic driver to work directly with the USB device and its endpoints, without the need for implementing and providing your own device driver.
This is appropriate if the device does not implement any of the standard USB protocols (mass storage, camera, audio, serial port etc.), for which Windows provides and load standard drivers, and if the device does not come with its own driver that needs to be installed first.
On Linux and macOS, this is a non-issue as USB devices without a dedicated driver are available to applications without any driver hassles.
In order to install WinUSB, Zadig can be used. Make sure you select the correct device, which can be unplugged if a problem occurs. If the driver is replaced for a crucial device such a USB host controller, a keyboard etc., the PC might no longer boot.
To automate the WinUSB installation, the device can implement additional USB control requests. There are two options:
WCID
Microsoft OS 2.0 descriptor
|
72,068,313 | 72,074,755 | Whenever i use while(cin>>(var)) in my code, the istream gets stuck in error state | The code i am trying to run is given below. Here in line 9 I am trying to take multiple inputs using the while(cin>>n) method. The input I gave is like :
2 4 5 6 45 357 3 (ctrl+z)(ctrl+z)
to indicate EOF in windows.
Then, even thought the numbers get added into the vector v1, the istream is stuck into error state cause the output I get this :
error2 4 5 6 45 357 3.
And I can also confirm that istream is stuck in error state cause if I use another cin statement after this, it gets ignored by the compiler until I clear the stream by cin.clear() function.
Can anybody please tell me why does this happen and how can I prevent the stream getting into error state. or is it something normal and I must use cin.clear() after every while(cin>>(var)) statement?
#include <iostream>
#include <vector>
using std:: cin; using std:: cout; using std::endl;using std::vector;
int main(){
vector<int> v1;
int n;
cout<< "enter the list of numbers";
while(cin>>n){
v1.push_back(n);
}
if((cin>>n).fail()){cout<<"error";}
for (auto i: v1){
cout<< i<<" ";
}
https://godbolt.org/z/c54dGdWcq
| the statement cin>>n return the cin object itself, put it inside while does something like
while(true){
cin >> n;
if(cin){ // equals to if(!cin.fail())
// ... body of while
}
else break;
}
so yes, after you leave the loop, cin is in fail state, thus any subsequence operator >> would not success until you call clear.
relevant: https://en.cppreference.com/w/cpp/io/ios_base/iostate
|
72,068,339 | 72,068,544 | Creating a derived class as a subset of superclass | I have created (for purely eductional value, this is not production code, there are libraries out there, more efficient implementations exist) a templated matrix class.
I want to do 2D graphics, so I need a 2D vector. Because of homogenous coordinates this will have three items. Moreover, I want a new constructor, I want someone to have an x and y value and him to be able to construct a 2D point without having to understand what a templated Matrix is and why there are 3 elements in this vector. Therefore, I create a derived class, because that is the only way I know how to do that:
#include "matrix.hpp"
// 3 rows because of homogenous coordinate system.
class Point2D: public Matrix<3, 1>
{
public:
Point2D(float x, float y) : Matrix<3, 1>({x, y, 1}) {}
};
Note that the derived class is more of a subset of Matrix<N,M>, it does not add any functionality, instead it restricts the templated type to Matrix<3, 1>.
Now I want to operate on my newly created Point2D:
Point2D a(-1, 1);
Matrix<3, 3> translate = {(1, 0, 2,
0, 1, -2,
0, 0, 1);
Point2D out = translate*a;
And this is not allowed:
g++ -I2dgfx/inc/ -Imatrix/inc/ -Iinc/ -std=gnu++20 -DDEBUG -Og -ggdb -Wall -Wshadow=local -Werror -Wno-error=unused-variable -Wno-error=unused-but-set-variable -MMD -MP -c 2dgfx/test/point2d.cpp -o obj/test/2dgfx/point2d.cpp.o
2dgfx/test/point2d.cpp: In member function ‘virtual void PointMatrix2D_translation_Test::TestBody()’:
2dgfx/test/point2d.cpp:23:28: error: conversion from ‘Matrix<3, 1>’ to non-scalar type ‘Point2D’ requested
23 | Point2D out = translate*a;
| ~~~~~~~~~^~
make: *** [2dgfx/rules.mk:34: obj/test/2dgfx/point2d.cpp.o] Error 1
Which I get, a Matrix<3,1> is not the same as a Point2D. Except I want those two to be exactly equal, I just need that new constructor to hide the fact that this object representing a point in 2D space secretly has 3 elements of which the last is a 1 because of math. So a solution is to modify the Point2D class:
#include "matrix.hpp"
// 3 rows because of homogenous coordinate system.
class Point2D: public Matrix<3, 1>
{
public:
Point2D(float x, float y) : Matrix<3, 1>({x, y, 1}) {}
Point2D(const Matrix<3,1>& mat) : Matrix<3, 1>(mat) {}
};
Which works, but is this the best way? Is there a better way to achieve what I want?
|
Which works, but is this the best way? Is there a better way to achieve what
I want?
The best way depends on how you intend to use your Point2D.
If you really want Point2D and Matrix<3,1> to be the same, a possible approach is to make Point2D a type alias and write a make function to create it:
using Point2D = Matrix<3, 1>;
Point2D make_point_2d(float x, float y) { return Point2D{x, y, 1}; }
int main() {
auto const a = make_point_2d(-1, 1);
Matrix<3, 3> translate = {1, 0, 2, 0, 1, -2, 0, 0, 1};
Point2D out = translate * a;
}
To keep the design consistent, I'd introduce type aliases and make_* functions for other types too. E.g.:
using Matrix3x3 = Matrix<3,3>;
Matrix3x3 make_matrix_3x3(/* ... */) { /*...*/ }
This may work as long as the type aliases you need to introduce are not too many.
Edit: I'm not really sure having Point2D be (or publicly inherit from)
Matrix<3,1> is a good idea. As a user, I'd be quite surprised by the fact
this code would compile (and run without causing any assert to fail):
auto const a = make_point_2d(-1, 1);
a(2,0);
// 1. Why do I need the second index to access the elements of a Point2D?
// 2. Why can I access the element at index 2?
|
72,068,465 | 72,068,514 | cast from WNDPROC to LONG | static LRESULT CALLBACK wndProcNew(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int CALLBACK wWinMain(HINSTANCE hInst,HINSTANCE,PWSTR szcmdLine,int cmdShow){
using namespace std;
Pixel pix;
LONG tmp = SetWindowLong(pix.getWnd(), GWLP_WNDPROC, (LONG)wndProcNew);
return 0;
}
I want to change the window procedure. mingw throws an error:
error: cast from 'LRESULT ()(HWND, UINT, WPARAM, LPARAM)' {aka 'long
long int ()(HWND__*, unsigned int, long long unsigned int, long long
int)'} to 'LONG' {aka 'long int'} loses precision [-fpermissive] 21
| LONG tmp = SetWindowLongW(pix.getWnd(), GWLP_WNDPROC,
(LONG)wndProcNew);
what am I doing wrong?
| On 64-bit Microsoft Windows, pointers (including function pointers) have a size of 64 bits, whereas a variable of type long or LONG has a size of 32 bits. Therefore, a variable of that size is unable to represent the value of a pointer.
If you want to set 64-bit values, I recommend that you use SetWindowLongPtr instead of SetWindowLong.
|
72,068,948 | 72,069,971 | Is std::from_chars supposed to handle uppercase hexadecimal exponents? | On upgrading to Ubuntu 22.04 (amd64), I have noticed that the following code has started to give the result 1.4375 instead of the expected value 1472:
#include <charconv>
#include <iostream>
#include <string_view>
int main()
{
std::string_view src{"1.7P10"};
double value;
auto result = std::from_chars(src.data(), src.data() + src.size(), value, std::chars_format::hex);
std::cout << value << '\n';
}
I get the expected result if I change the P character in the source to lowercase p. Both uppercase and lowercase work with std::strtod.
Is std::from_chars supposed to fail with uppercase exponent characters, or is this a bug in g++/libstdc++?
Command line used to compile:
g++ -std=c++17 test.cpp
(optimisation level appears to have no effect)
Output of g++ --version:
g++ (Ubuntu 11.2.0-19ubuntu1) 11.2.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
Is std::from_chars supposed to fail with uppercase exponent
characters, or is this a bug in g++/libstdc++?
This is a bug of libstdc++, submitted 105441.
From [charconv.from.chars], emphasis mine
from_chars_result from_chars(const char* first, const char* last, double& value,
chars_format fmt = chars_format::general);
Preconditions: fmt has the value of one of the enumerators of chars_format.
Effects: The pattern is the expected form of the subject sequence in the "C" locale, as described for strtod, except that
the sign '+' may only appear in the exponent part;
if fmt has chars_format::scientific set but not chars_format::fixed, the otherwise optional exponent part shall
appear;
if fmt has chars_format::fixed set but not chars_format::scientific, the optional exponent part shall not
appear; and
if fmt is chars_format::hex, the prefix "0x" or "0X" is assumed.
So in your example, "1.7P10" should be a valid pattern, and the result of from_chars should be equivalent to strtod("0x1.7P10").
|
72,069,293 | 72,077,249 | Reverse string with one space | I need to reverse string but to keep only one space between words.
EXAMPLE:
" na vrh brda vrbaa mrdaa!!! "
"!!!aadrm aabrv adrb hrv an"
Code:
#include <iostream>
#include <string>
std::string ReverseOneSpace(std::string s) {
std::string str = s;
int j = 0;
for (int i = s.length() - 1; i >= 0; i--) {
// skip spaces
while (s[i] == ' ' && i >= 0)
i--;
while (s[i] != ' ' && i >= 0) {
str[j] = s[i];
j++;
i--;
}
// add only one space
if (s[i] == ' ') str[j] = ' ';
j++;
if (i == 0) break;
}
return str;
}
int main() {
std::string s = " na vrh brda vrbaa mrdaa!!! ";
std::string str = ReverseOneSpace(s);
std::cout << "\"" << str << "\"" << std::endl;
std::cout << "\"" << "!!!aadrm aabrv adrb hrv an" << "\"";
return 0;
}
OUTPUT:
"!!!aadrm aabrv adrb hrv an aa!!! " // my output
"!!!aadrm aabrv adrb hrv an" // correct
Why do I have some extra characters after the string was reversed?
| Another solution is to use what is available in the C++ library:
Usage of std::istringstream removes the need to check for spaces.
Usage of std::reverse will reverse the string automatically.
Putting these together results in the following program:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
std::string ReverseOneSpace(std::string s)
{
std::istringstream strm(s);
std::string word;
std::string ret;
// Loop for each word found
while (strm >> word)
{
// Reverse the word
std::reverse(word.begin(), word.end());
// Add reversed word to front of the result string
ret = word + " " + ret;
}
// Remove the excess space at the back
ret.pop_back();
return ret;
}
int main() {
std::string s = " na vrh brda vrbaa mrdaa!!! ";
std::string str = ReverseOneSpace(s);
std::cout << "\"" << s << "\"" << std::endl;
std::cout << "\"" << str << "\"" << std::endl;
return 0;
}
Output:
" na vrh brda vrbaa mrdaa!!! "
"!!!aadrm aabrv adrb hrv an"
Note that there is no checking for spaces. Manually checking for spaces is error-prone, at least most of the time on the first attempt of writing such code. So why waste time doing that if there is something (in this case std::istringstream) that does the space checking for you?
|
72,069,476 | 72,069,565 | Disabling possibility of instantiation of base struct | I have a usecase for two different structs (just storage of data) which share some common members, e.g.
struct Foo {
int i;
int j;
};
struct Bar {
int i;
float f;
};
The common data could be represented in a base struct but I'd like to disable the possibility of creating an object of the base struct.
| If you make the constructor protected, then only derived classes can access it:
struct Base {
int i;
protected:
Base() = default;
};
|
72,069,868 | 72,070,075 | C++ decltype evaluate wrong type | I have the function which type the same as minimal argument:
#include <iostream>
template<typename A, typename B>
auto Min(A a, B b) -> decltype(a < b ? a : b)
{
return a < b ? a : b;
}
int main()
{
auto b = Min(5, 2.0f); // float
auto a = Min(5, 6.0f); // also float ?!
std::cout << typeid(a).name() << std::endl;
std::cout << typeid(b).name() << std::endl;
std::cin.get();
}
But actuale I've got float for a and b. And my console print looks like:
float
float
Why the second function return type evaluating also as float ?
| The conditional operator (?:) can only yield a single type. In your case, int and float share the common type float, so that is the type the expression will yield.
If you don't want that, you'll need to move your code from being executed at run time and move it into being executed at compile time. Doing that allows you to return different types depending on the conditions at compile time. That would give you a min function like:
template<auto a, auto b> auto min()
{
if constexpr(a < b)
return a;
else
return b;
}
In the above code, if the if constexpr is false, the whole return a; is discarded and the entire body of the function become return b; and if it is true, the opposite happens and your left with just return a;. This allows the function to return the type and value of the minimum object.
making this change to your code will give you
#include <iostream>
template<auto a, auto b> auto min()
{
if constexpr(a < b)
return a;
else
return b;
}
int main()
{
auto b = min<5, 2.0f>(); // float
auto a = min<5, 6.0f>(); // int
std::cout << typeid(a).name() << std::endl;
std::cout << typeid(b).name() << std::endl;
std::cin.get();
}
which ouputs
i
f
as seen in this live example
|
72,069,924 | 72,069,980 | How do I get my linked list to display on one line and not create a new line each time? C++ | So I need help on making the program display the linked list in only one line with nothing in between them. I also need to the use _getch(), getch() or getchar() functions not cin or something similar, the current program uses the _getch() function.
I'll provide my code, output and desired output.
Thank you for the help in advance.
Code:
#include <iostream>
#include <conio.h>
#include <string>
#include <iomanip>
using namespace std;
struct Node {
std::string data{};
Node* next{ nullptr };
};
void addToList(Node*& head, Node*& tail) {
bool quit{ false };
std::string temp{};
Node* current{ nullptr };
while (!quit) {
temp = _getch();
if (temp == "quit") {
std::cout << "\tQuitting submenu.\n";
quit = true;
}
else {
// Allocate the new node here
current = new Node;
current->data = temp;
if (tail) {
tail->next = current;
tail = current;
}
else {
head = current;
tail = current;
}
std::stringstream ss;
for (current = head; current; current = current->next) {
ss << current->data;
}
std::cout << "+------------+" << std::endl;
std::cout << "|" << std::setw(12) << ss.str() << "|" << std::endl;
std::cout << "+------------+" << std::endl << std::endl;
}
}
}
int main() {
bool quit = false;
int choice = 0;
Node* head = nullptr;
Node* tail = nullptr;
while (!quit) {
std::cout << "1. add to list, 2. quit:\n";
std::cin >> choice;
switch (choice) {
case 1:
addToList(head, tail);
break;
case 2:
std::cout << "Quitting main menu.\n";
quit = true;
break;
default:
std::cout << "That is not a valid input, quitting program.\n";
quit = true;
}
}
for (auto tmp{ head }; tmp;) {
tmp = tmp->next;
delete head;
head = tmp;
}
}
Output:
+------------+
| 3|
+------------+
+------------+
| 334|
+------------+
+------------+
| 334345|
+------------+
+------------+
| 3343453456|
+------------+
Desired Output:
+------------+
| 3|
+------------+
+------------+
| 34|
+------------+
+------------+
| 345|
+------------+
+------------+
| 3456|
+------------+
| You could create the string you want to print first using a std::stringstream, then print it on a single line, like this:
std::stringstream ss;
for (current = head; current; current = current->next) {
ss << current->data;
}
std::cout << "+------------+" << std::endl;
std::cout << "|" << std::setw(12) << ss.str() << "|" << std::endl;
std::cout << "+------------+" << std::endl << std::endl;
instead of this, which prints one line per list entry
cout << "+------------+" << endl;
for (current = head; current; current = current->next) {
std::cout << "|" << std::setw(12) << current->data << (current->next ? "" : "") << "|" << endl;
}
cout << "+------------+" << "\n\n";
Remember to add #include <sstream> at the top too.
|
72,070,260 | 72,073,593 | What's the right way to partially initialize a struct? | For a user-defined allocator, the relation between the allocated-units must be constructed at the beginning, while the memory space for elements should be left uninitialized.
A simple demo:
template <typename T>
struct Node {
T _item;
Node* _prev;
Node* _next;
};
template <typename T, typename ParentAllocator>
class MyAllocator {
using Allocator = std::allocator_traits<ParentAllocator>::rebind_alloc<Node<T>>;
Allocator _allocator;
Node<T> _header;
/* ... */
public:
MyAllocator()
: _allocator()
{
_header._prev = &_header;
_header._next = &_header;
// leaving `_item` uninitialized
}
T* allocate(/*one*/) {
auto* newNode = _allocator.allocate(1);
newNode->_prev = &_header;
newNode->_next = _header._next;
// leaving `_item` uninitialized
/* ... */
return &(newNode->_item);
}
};
Node is not initialized, instead direct initialization for its members, though not for all.
My questions are:
Are _header and _next really partially initialized as expectations, even if the default constructor of T (both normal and explicit one) were deleted.
Have I implemented it properly?
If not, what's the right way?
| You need to modify Node to make it default constructible, and you don't want to default construct T even if it has a default constructor. So you can replace T _item with:
std::aligned_storage<sizeof(T), alignof(T)> _item;
Or in C++23 because std::aligned_storage is deprecated:
alignas(T) std::byte _item[sizeof(T)];
That will give you the storage space you need, with appropriate alignment, and then you'll use placement new to construct T in that storage. You will also need to explicitly invoke ~T() before or during destruction of each Node.
Demo showing the basics, certainly not complete or tested: https://godbolt.org/z/bGaKWb3de
|
72,071,206 | 72,075,784 | QTextDocument and selection painting | I am painting a block of text on a widget with QTextDocument::drawContents. My current goal is to intercept mouse events and emulate text selection. It's pretty clear how to handle the mouse, but displaying the result puzzles me a lot.
Just before we start: I can not use QLabel and let it handle selection on it's own (it has no idea how to draw unusual characters and messes up line height (https://git.macaw.me/blue/squawk/issues/59)), nor I can not use QTextBrowser there - it's just a message bubble, I'm not ready to sacrifice performance there.
There is a very rich framework around QTextDocument, but I can not find any way to make it color the background of some fragment of text that I would consider selected. Found a way to make a frame around a text, found a way to draw under-over-lined text, but it looks like there is simply just no way this framework can draw a background behind text.
I have tried doing this, to see if I can take selected fragment under some QTextFrame and set it's style:
QTextDocument* bodyRenderer = new QTextDocument();
bodyRenderer->setHtml("some text");
bodyRenderer->setTextWidth(50);
painter->setBackgroundMode(Qt::BGMode::OpaqueMode); //this at least makes it color background under all text
QTextFrameFormat format = bodyRenderer->rootFrame()->frameFormat();
format.setBackground(option.palette.brush(QPalette::Active, QPalette::Highlight));
bodyRenderer->rootFrame()->setFrameFormat(format);
bodyRenderer->drawContents(painter);
Nothing of this works too:
QTextBlock b = bodyRenderer->begin();
QTextBlockFormat format = b.blockFormat();
format.setBackground(option.palette.brush(QPalette::Active, QPalette::Highlight));
format.setProperty(QTextFormat::BackgroundBrush, option.palette.brush(QPalette::Active, QPalette::Highlight));
QTextCursor cursor(bodyRenderer);
cursor.setBlockFormat(format);
b = bodyRenderer->begin();
while (b.isValid() > 0) {
QTextLayout* lay = b.layout();
QTextLayout::FormatRange range;
range.format = b.charFormat();
range.start = 0;
range.length = 2;
lay->draw(painter, option.rect.topLeft(), {range});
b = b.next();
}
Is there any way I can make this framework do a simple thing - draw a selection background behind some text? If not - is there a way I can unproject cursor position into coordinate translation, like can I do reverse operation from QAbstractTextDocumentLayout::hitTest just to understand where to draw that selection rectangle myself?
| You can use QTextCursor to change the background of the selected text. You only need to select one character at a time to keep the formatting. Here is an example of highlighting in blue (the color of the text is highlighted in white for contrast):
void MainWindow::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.fillRect(contentsRect(), QBrush(QColor("white")));
QTextDocument document;
document.setHtml(QString("Hello <font size='20'>world</font> with Qt!"));
int selectionStart = 3;
int selectionEnd = selectionStart + 10;
QTextCursor cursor(&document);
cursor.setPosition(selectionStart);
while (cursor.position() < selectionEnd) {
cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); // select one symbol
QTextCharFormat selectFormat = cursor.charFormat();
selectFormat.setBackground(Qt::blue);
selectFormat.setForeground(Qt::white);
cursor.setCharFormat(selectFormat); // set format for selection
cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
}
document.drawContents(&painter, contentsRect());
QMainWindow::paintEvent(event);
}
|
72,071,391 | 72,071,485 | How to group data in tuples of tuples into a tuple of vectors | I want to group data of tuples in tuples into a tuple of vectors.
Given is a tuple of tuples containing data. There are multiple duplicate types, that's data should be grouped into a vector of each unique type.
So far boost::mp11 is the most elegant way I found, to build a type
std::tuple<std::vector<T1>, std::tuple<std::vector<T2>, ...>
based on an incoming parameter pack
std::tuple<std::tuple<some_data>, std::tuple<std::tuple<some_more_data>, ...
using mp_unique and mp_transform to get vectors for each unique type.
Happy if you know a std::ish alternative (optional).
I am stuck finding a way to fill tuple elements into matching vectors?
I'd be excited, finding a fold expression'ish way to do so.
This example should help to give a better idea of what I have in mind.
template <typename T> using vector_of = std::vector<T>;
static constexpr auto tuple_to_vector(auto&&... Vs) noexcept {
// merged_tuple = std::tuple<int, double, int, char, int, float, char, float, double>
auto merged_tuple = std::tuple_cat(std::forward<decltype(Vs)>(Vs)...);
// vector_t = std::tuple<std::vector<int>, std::vector<double>, std::vector<char>, std::vector<float>>
using vector_t = boost::mp11::mp_transform<vector_of, boost::mp11::mp_unique<decltype(merged_tuple)>>;
vector_t vec;
// how to add merged_tuple elements to vec
// resulting in
// std::tuple< std::vector<int>{1,3,2}, std::vector<double>{2.0,3.0}, std::vector<char>{'b','c'}, std::vector<float>{3.0f,2.0f}>
return std::move(vec);
};
int main() {
constexpr auto vec = tuple_to_vector(
std::make_tuple(1,2.0,3),
std::make_tuple('b',2,3.0f),
std::make_tuple('c',2.0f,3.0)
);
// expecting
// vec = std::tuple<
// std::vector<int>{1,3,2},
// std::vector<double>{2.0,3.0},
// std::vector<char>{'b','c'},
// std::vector<float>{3.0f,2.0f}
// >
return 42;
}
| You can use std::apply to expand the elements of merged_tuple, and use std::get to extract the corresponding vector in vector_t according to the type of the element, and fill into the vector through push_back
std::apply([&vec](auto... args) {
(std::get<std::vector<decltype(args)>>(vec).push_back(args), ...);
}, merged_tuple);
Demo
Note that vec cannot be constexpr even in C++20 since its allocation is non-transient. If you really want to construct a constexpr tuple, then you can use std::array since the size of the array can be obtained at compile time. Here is a demo that converts the resulting vec to the corresponding std::array type.
|
72,071,397 | 72,072,531 | I Want This Code To Prove If An Integer Is A Palindrome. How Do I do It? | I am sure this code isn't perfect, but I am new to programming and am trying to work out a challenge for checking if a number is a palindrome or not. I tried writing a bool-type function in the code to return 'true' if the number is a palindrome and 'false' otherwise.
Anyway, jumping to context, I want this code to print 'YES" every time the computer notices a sign of palindrome-ism. The code is compiling successfully, however, it does not output anything after 'What is the integer you wanna check palindromism for?:' even when inputting numbers like '12321', '111', '1234321' (palindromes).
Can anyone help me, and if possible, without changing much of the code tell me ways to achieve what I want to (to prove palindrome-ism)?
#include <cstring>
using namespace std;
bool isPalindrome(int x, string md) {
int y = md.length() + 1;
char abz[y];
for (int i=0; i < md.length()-1; ++i) {
if (abz[i] == (md.length()-1)-i){
cout << "YES";
}
}
return true;
}
int main(){
int x;
cout << "What is the integer you wanna check palindromism for?: ";
cin >> x;
string md = to_string(x);
isPalindrome(x, md);
return 0;
}
Thanks!
| I'm not sure what you're trying to do in isPalindrome.
One way to check if a string of size len is palindrome is to compare its i-th and (len-i-1)-th characters for i ranging in [0, len / 2).
If they differ at any point the string is not palindrome.
Here's how you may do it:
bool isPalindrome(std::string const& md) {
if (md.empty()) // Empty strings are not palindrome
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; ++i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
Can anyone help me, and if possible, without changing much of the code tell
me ways to achieve what I want to (to prove palindrome-ism)?
Please check the comments I've added in the code:
// Include the correct headers
#include <iostream>
#include <string>
// Don't do this
//using namespace std;
// This just checks if the string is palindrome.
// It does not print anything.
bool isPalindrome(std::string const& md) {
if (md.empty())
return false;
auto const len = md.size();
auto const halfLen = len / 2;
for (std::size_t i = 0; i != halfLen; ++i)
if (md[i] != md[len - i - 1])
return false;
return true;
}
int main() {
// No need to parse the number and convert it to string again.
//int x;
std::string md;
std::cout << "What is the integer you wanna check palindromism for?: ";
// NOTE: you may input any string here: not just integers.
std::cin >> md;
std::cout << (isPalindrome(md) ? "YES" : "") << '\n';
// ^ print "YES" or nothing
return 0;
}
You may also implement isPalindrome with algorithms and iterators like so:
// You'll need these two headers
#include <algorithm>
#include <iterator>
template <typename BidIt>
bool isPalindrome(BidIt first, BidIt last) {
if (first == last)
return false;
auto const halfLength = std::distance(first, last);
auto const mid = std::next(first, halfLength);
auto const rFirst = std::make_reverse_iterator(last);
return std::equal(first, mid, rFirst);
}
bool isPalindrome(std::string const& str) {
return isPalindrome(std::cbegin(str), std::cend(str));
}
This is basically the same algorithm as above but you can reuse
template <typename BidIt>
bool isPalindrome(BidIt, BidIt);
with more containers than just std::string.
|
72,071,571 | 72,085,313 | What is an alternative to the negative lookbehind (that's not implemented) in CTRE? | I'm trying to match a part of a string that surrounds a word inside of it.
For example: [This]. I would like to match [This], but only when the character before it is not a backslash, so for example, not this \[This].
for (auto match: ctre::range<R"((((?<!\\))\[[^\]]*\])">(input)) {
// you can use match.str() here
}
Usually the regex I would use is this:
(((?<!\\))\[[^\]]*\])
..but, according to this comment and the received ctre::problem_at_position<5>, it seems that it's not supported in CTRE as of today.
Is there a way to do what I want to do even though it's not implemented?
| The regex is the following:
(?:^|[^\\])(\[[^\]]*\])
where:
(?:^|[^\\]) is a non-capturing group that uses alternation (|) for choosing between ^ (the beginning of the string) or [^\\] (any character that is not a backslash).
(\[[^\]]*\]) captures the desired pattern.
|
72,071,734 | 72,072,100 | Best practice to link modules split into multiple files with gcc/g++ | I would like to have a file containing only the declarations in a module and one or more files containing the definitions.
According to How to split a module into multiple files (and this awseome cppcon talk: https://youtu.be/nP8QcvPpGeM at 12:04) I should split my files like this:
Log.cpp:
export module Log;
int i = 0;
export void Log();
Log_imp.cpp:
module Log;
void Log() {
std::cerr << "This is a log and i=" << i << "\n";
}
I can build both with g++-11 -std=c++20 -fmodules-ts -c Log.cpp and
g++-11 -std=c++20 -fmodules-ts -c Log_imp.cpp respectively.
My main simply imports the Log module and calls the Log() function.
Note that I have to link with both Log.o and Log_imp.o, otherwise I get linking errors.
Is it possible to have a single object file for a single module, without building a static library? If not, then should I link modules into a static library, or keep multiple .o files?
| Modules are basically orthogonal to the linking process. Each module file is its own translation unit and therefore will produce its own object file. You can combine them into a library (or a single object file), but otherwise, you're going to have to link to all such object file.
|
72,072,023 | 72,072,046 | A shortcut to compare data on the heap in C++ | Consider two arrays of data allocated on the heap:
int *A = new int[5];
int *B = new int[5];
// Some code which changes data pointed to by A and B
Now I want to compare these two arrays (not the pointers, but the data A and B point at). That is, I want to check out if the elements of the arrays are equal.
One might suggest elementwise comparison with a loop, but since there are functions such as memcpy which allow to avoid looping through data to copy it, it seems reasonable to assume there is a similar function which would allow to avoid looping through an array for elementwise comparison.
Does C++ have any shortcuts for this?
| Since you're mentioning memcpy, there's also memcmp.
This seems to be what you're after?
See also Compare fast two memory regions.
|
72,072,035 | 72,072,852 | Compiling a cpp file with vscode, in Ubuntu | I'm trying to follow this link on how to get started with c++ and vscode in ubuntu.
I have gcc already installed with the latest version.
Running sudo apt-get install build-essential gdb gives:
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version (12.8ubuntu1.1).
build-essential set to manually installed.
gdb is already the newest version (9.2-0ubuntu1~20.04.1).
gdb set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
However, when I get to the stage of creating the config file, I have no option for C/C++: g++ build active file. I only have
So, I choose /usr/bin/cpp.Then I build the file, and get the success message.
However, when run the newly created executable file, I get several error messages:
./helloworld: line 17: namespace: command not found
./helloworld: line 23: syntax error near unexpected token `('
./helloworld: line 23: ` typedef decltype(nullptr) nullptr_t;'
the strange thing is that the lines with code in the helloworld file end on line 16, so I think there's something wrong with the compiler...
| Its best to get GCC working in your commandline, then get it working using VS Code tasks.
I suggest that you create the most simplistic project structure you can. Use only a project directory, and a single file named main.cpp.
Something that looks like this:
PROJECT (dir) // path = ./
│
└──> main.cpp (file) // path = ./main.cpp
Once you have a directory with main.cpp do 1 of 2 things:
Use the following command to add a Hello World example to your main.cpp file.
$> echo -e "\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n cout << \"Hello World\!\" << endl;\n}" > main.cpp
Or copy and paste the code below into main.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
}
FYI: You should be doing this from the command-line not vscode (not until you create the vscode task which I will show bellow)
Another thing to note, is your commandline should be pointed to your project directory, the directory you created with main.cpp in it.
From inside your project directory execute the following command.
$> g++ ./main.cpp -o build
if your file compiled & built your executable correctly you should be able to use the ls command to see a new file named build in your project directory.
If all went well, the new build file is an executable. Execute it by entering...
$> ./build
and you should see "Hello World!"
At this point use the following command...
$> code .
VS Code should open to your projects directory.
Now using vscode create another directory, and name it ./.vscode
Then add a file to the ./.vscode directory named tasks.json
The files full pathname will be: ./.vscode/tasks.json
then you will want to add the following to your tasks file
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "GCC: My Compilation Task",
"command": "/usr/bin/g++",
"args": ["-g", "./main.cpp", "-o", "./build"],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
then you should be able to press F1 and type RUN TASK, when you see the option in the quick menu that says RUN TASK click it, and then select the tasks with the same name as the label key in your tasks.json file, which is "GCC: My Compilation Task"
|
72,072,236 | 72,073,572 | Is exists SFINAE technique to check several statement? | In C++17, I want to check some prerequisite before invoke some function using SFINAE, example:
class TestClass
{
public:
bool foo() const { return true; }
bool bar() { return false; }
};
template<typename T>
class Checker
{
public:
template<typename Fn, typename = std::enable_if_t<(std::is_same_v<invoke_result_t<Fn, const T&>, bool>
|| std::is_same_v<invoke_result_t<Fn>, bool>)>>
void checkBoolConstFn(Fn fn) {}
};
int main()
{
auto foo = [](const TestClass&) { return true; };
auto bar = []() { return true; };
Checker<TestClass> checker;
checker.checkBoolConstFn(foo);
checker.checkBoolConstFn(bar);
checker.checkBoolConstFn(&TestClass::foo);
checker.checkBoolConstFn(&TestClass::bar);
return 0;
}
i try to do check: is return type of Fn is bool if Fn is accept one argument OR zero argument?
This code doesn't compile because happens substitution failure in enabled_if_t in example, but i want to somehow invoke checkBoolConstFn if at least one of statement:
std::is_same_v<invoke_result_t<Fn, const T&>, bool>
or
std::is_same_v<invoke_result_t<Fn>, bool>
is compile. Is exists some technique how to do it?
| It seems like what you need is is_invocable_r_v, i.e., we can just determine whether Fn can be invoked with the zero argument or one argument of type const T& to yield a result that is convertible to bool
template<typename T>
class Checker
{
public:
template<typename Fn,
typename = std::enable_if_t<
(std::is_invocable_r_v<bool, Fn, const T&> ||
std::is_invocable_r_v<bool, Fn>)>>
void checkBoolConstFn(Fn fn) {}
};
Demo
|
72,072,310 | 72,097,071 | Apache Ignite: Manual Data Colocation | So I understand data can be colocated together by use of an affinity function.
My questions is, if it is possible to force data to be placed in a particular node? And then force rebalancing if I need that partition to be moved to another node.
This would be useful for a scenario where I have a client that will be using a server the most to access his data and there'd be an ignite node very close, network wise, to this server. I'd like the data for this client to be as close as possible to where it's used.
But now say this client moves to another server, I'd like to be able to move his data to a node that is closer to the new server.
Is this behavior possible in Ignite?
| You can use a node filter to limit which nodes store data, but you can't easily force data to a specific node.
But the good news is that's really a design anti-pattern. You should let Ignite figure it out for you.
Part of the reason for that is that you appear to assume that a client connects to a server. That's not the case. Ignite nodes are peers. Any node can connect directly to any other in the cluster. (Perhaps you have a "stretched cluster," one that's spread across multiple data centres? Because a cluster is peer-to-peer, this is generally not recommended.)
|
72,072,494 | 72,084,045 | When changing build target to release in Visual Studio, thousands of errors appear | I setup a simple Empty Project on Visual Studio 2022. I attached some GLFW / Glad sources to it so that I could do a basic rendering project.
I've been editing it for around two days with no issues. It runs fine.
I went to build it and noticed the debug version builds the debug console and everything into the EXE, which I didn't want.
I tried to do a release version instead, and when I switch to release, suddenly all of my includes in my code start pushing like 100 errors.
enter image description here
When I fix all the include errors (Using VS's recommended fix tool), the errors go away, but then when I try to build, thousands of more errors appear, and I have no clue what I'm doing wrong.
It's at a point right now where I can only use the debug version with the console popup, which is really irritating, considering I'm developing a desktop application. I cant have these debug tools popping up while I'm trying to use a piece of software.
My full code so far is right here: https://github.com/ArctanStudios/GLSL-Bay
I've done some searching on my own but I haven't found anything helpful.
When asking people on other sites I was told that I just "screwed something up" providing absolutely zero help or an explanation as to what I could do to fix this issue. Id appreciate any ideas.
| You can refer to the Document: Set debug and release configurations in Visual Studio.
Visual Studio projects have separate release and debug configurations for your program.
|
72,072,629 | 72,072,927 | lots of OpenGL glDebugOutput Shader Stats / Shader Compiler / Other / notification severity messages with mesa radeon | I have an opengl toy code that I am using to learn ogl and 3d graphics. I am using glDebugMessageCallback and glDebugMessageControl to check for OGL errors and on windows I did not have any messages. I am now testing my code on linux and I am getting a lot of these message:
Debug message (1): Shader Stats: SGPRS: 16 VGPRS: 12 Code Size: 88 LDS: 0 Scratch: 0 Max Waves: 8 Spilled SGPRs: 0 Spilled VGPRs: 0 PrivMem VGPRs: 0 DivergentLoop: 0, InlineUniforms: 0, ParamExports: 2, (VS, W64)
Source: Shader Compiler
Type: Other
Severity: notification
Here is some more info on my environment
[OpenGL] OpenGL version loaded: 4.6
[OpenGL] Vendor: AMD
[OpenGL] Renderer: AMD Radeon RX 570 Series (polaris10, LLVM 13.0.1, DRM 3.44, 5.17.3-302.fc36.x86_64)
[OpenGL] Version: 4.6 (Compatibility Profile) Mesa 22.0.1
[OpenGL] Version GLSL: 4.60
My question is why do i not get these message in windows and why do I keep getting them even if i change my callback from
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE , 0, nullptr, GL_TRUE);
to
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH_AMD , 0, nullptr, GL_TRUE);
? they seem informational to me and at this rate they are mostly noise
|
My question is why do i not get these message in windows
The debug messages are completely implementation-specific. In the worst case, you could not get any message at all. The verbosity of the different drivers can vary a lot, the mesa open source drivers on Linux are notably on the more verbose end of the spectrum. Nvidia Win/Linux is also quite good in that regard, but AMD and INtel on windows can be quite lacking.
and why do I keep getting them even if i change my callback from [...] to
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH_AMD , 0, nullptr, GL_TRUE);
Because glDebugMessageControl(..., GL_DEBUG_SEVERITY_HIGH_AMD, ..., GL_TRUE) just enables the SEVERITY_HIGH messages (which were enabled before anyways), it does not disable the SEVERITY_NOTIFICATION which are still enabled by default, as stated in the GL_KHR_debug extension specification (the other variants of the debug output exstensions like the AMD one are similar):
Messages can be either enabled or disabled. Messages that are disabled will not be generated. All messages are initially enabled unless their assigned severity is DEBUG_SEVERITY_LOW. The enabled state of messages can be changed using the command DebugMessageControl.
|
72,072,721 | 72,091,965 | AVX divide __m256i packed 32-bit integers by two (no AVX2) | I'm looking for the fastest way to divide an __m256i of packed 32-bit integers by two (aka shift right by one) using AVX. I don't have access to AVX2.
As far as I know, my options are:
Drop down to SSE2
Something like AVX __m256i integer division for signed 32-bit elements
In case I need to go down to SSE2 I'd appreciate the best SSE2 implementation.
In case it's 2), I'd like to know the intrinsics to use and also if there's a more optimized implementation for specifically dividing by 2.
Thanks!
| Assuming you know what you’re doing, here’s that function.
inline __m256i div2_epi32( __m256i vec )
{
// Split the 32-byte vector into 16-byte ones
__m128i low = _mm256_castsi256_si128( vec );
__m128i high = _mm256_extractf128_si256( vec, 1 );
// Shift the lanes within each piece; replace with _mm_srli_epi32 for unsigned version
low = _mm_srai_epi32( low, 1 );
high = _mm_srai_epi32( high, 1 );
// Combine back into 32-byte vector
vec = _mm256_castsi128_si256( low );
return _mm256_insertf128_si256( vec, high, 1 );
}
However, doing that is not necessarily faster than dealing with 16-byte vectors. On most CPUs, the performance of these insert/extract instructions ain’t great, except maybe AMD Zen 1 CPU.
|
72,072,804 | 72,075,659 | MessageBox has 2 different styles in C++? (Windows) | Not too long ago I found that there are 2 different styles/looks for the standard Windows Message Box. The interesting thing is, even having the exact same program/code for the message box, you might get either style 1 or style 2.
As you can clearly see, there are some differences in the style, but the code behind them is the exact same:
#include <Windows.h>
// inside DllMain
MessageBoxA(0, "MessageBoxA", "Message Box Style ...", MB_ICONINFORMATION);
I am sure you are wondering how I got two different results/styles with the same code? I made a very basic DLL which shows a message box right after being loaded/injected in a process. In most cases if you load the DLL in a console application, you will see style 1. On the other hand if you load the DLL in a GUI application (with a window), you probably will see style 2.
My question for you is why this happens, why are there 2 different styles? And is it possible to always force the message box to be in a specified style? I personally like style 2 a lot more because it looks more modern, so I would like to always have my message boxes in style 2, but how?
| They are different commctrl versions but, as of 2022, there is no point of not using the newer style, nobody would target an older system nowadays.
Put this to a cpp:
#if defined _WIN64
#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
and then you get the new styles.
|
72,072,834 | 72,083,892 | Is there a way to use the RtlSetProcessIsCritical function from the Windows API in Python? | I want to use the RtlSetProcessIsCritical function that sets a current process as critical but I really couldn't find a way to use it with Python.
Here is the example of it in C++:
#include <windows.h>
typedef VOID(_stdcall* RtlSetProcessIsCritical) (
IN BOOLEAN NewValue,
OUT PBOOLEAN OldValue,
IN BOOLEAN IsWinlogon);
BOOL ProcessIsCritical()
{
HANDLE hDLL;
RtlSetProcessIsCritical fSetCritical;
hDLL = LoadLibraryA("ntdll.dll");
if (hDLL != NULL)
{
(fSetCritical) = (RtlSetProcessIsCritical)GetProcAddress((HINSTANCE)hDLL, "RtlSetProcessIsCritical");
if (!fSetCritical) return 0;
fSetCritical(1, 0, 0);
return 1;
}
else
return 0;
}
Is there any way to make it work in Python?
Here is the link to an article that describes the RtlSetProcessIsCritical function pretty good: https://www.codeproject.com/Articles/43405/Protecting-Your-Process-with-RtlSetProcessIsCriti
| Try to load ntdll.dll in python. Requires Pywin32 library.
import win32process
import win32api
import ctypes
from ctypes import *
ntdll = WinDLL("ntdll.dll")
ntdll.RtlSetProcessIsCritical(1,0,0)
|
72,073,110 | 72,077,222 | Missing certain overloaded SFML methods, while others are fine | Im trying to build an application on SFML and decided to build it myself instead of using apt package manager. Im also using cmake but i don't think that matters much for my question:
In my file UserInterface.h i have #include <SFML/Graphics.hpp>
which worked fine before when i used SFML-dev from apt.
Compiler tells that a lot of SFML methods that take in (int x, int y) does not exist (while finding the version taking in sf::Vector2f). These overloaded methods worked fine before.
Now i looked into the source code of SFML and can't actually find the overloaded functions? even though they are in the Documentation:
void sf::Transformable::setOrigin(float x, float y)
I don't understand where i went wrong.
The rest of SFML seems to be fine. How does SFML even support these overloaded methods if they are not declared?
This is the output i get when building:
error: no matching function for call to ‘sf::RectangleShape::setOrigin(int, int)’
103 | background.setOrigin(0, 0);
| ^
In file included from /usr/local/include/SFML/Graphics/Shape.hpp:33,
from /usr/local/include/SFML/Graphics/CircleShape.hpp:32,
from /usr/local/include/SFML/Graphics.hpp:34,
from /home/bonkt/dev/digitus/src/UserInterface/UserInterface.h:1,
from /home/bonkt/dev/digitus/src/UserInterface/UserInterface.cpp:1:
/usr/local/include/SFML/Graphics/Transformable.hpp:115:10: note: candidate: ‘void sf::Transformable::setOrigin(const Vector2f&)’
115 | void setOrigin(const Vector2f& origin);
edit:
When casting the arguments (int) to float it won't work, so that's not the problem. It also occurs for many other similar methods:
window.setPosition()
window.setScale()
sf::FloatRect()
| Found my answer: The apt SFML package i used earlier must have been an older version of SFML.
I found these merged pull requests at their github just a couple of weeks ago. SFML decided that numerical pairs are not needed, as usage of sf::Vector2T is more consistent with the rest of the API. - So i'll just change my code to use SF::Vector2f
I just had really unlucky timing as the new pullrequests was merged just 5 days ago.
|
72,073,303 | 72,073,318 | cout printing garbage when string is concatenated with array value | Here is my very basic C++ code:
#include <iostream>
char values[] = {'y'};
int main() {
std::cout << "x" + values[0];
}
My expected output would just be xy, but instead I am just getting random text/symbols
| Perhaps you meant to do:
std::cout << "x" << values[0];
Otherwise, you are taking "x" (which decays into a pointer to the 1st element of a const array that holds the characters {'x', '\0'} in memory), and adding 'y' (which has the numeric value 121 when converted to an int) to that pointer.
Adding an integer to a pointer changes what it points to. You are reading memory that is 121 bytes beyond the 'x' character in memory, so you are going to be reading random bytes, or causing an Access Violation.
|
72,073,481 | 72,073,514 | How do I access individual numbers in a string? | Say I have a string that goes:
199 200 208 210 200 207 240 269 260 263
How do I make it so if that string is called s, then s[0] = 199 (rather than 1), s[1] = 200 (rather than 9), s[2] = 208 (rather than 9), etc. I am sorry to keep coming back here, but I really want to resolve this.
By the way, this is my code so far:
int main()
{
int increase_altitude = 0;
int previous = 10000;
std::string s;
while (std::getline(std::cin, s))
{
std::stringstream ss(s);
}
| You can simply use vector of string for this purpose,
std::vector <std::string> numvec;
numvec.push_back("199");
numvec.push_back("200");
// accessing the element
numvec[0] // equals to 199
You can take input for the vector as:
std::string str;
for (int i = 0 ; i < 10000 ; ++i){
std::cin >> str; // take input from the user
numvec.push_back(str); // add to the vector
}
However you would need to add vector header.
|
72,073,493 | 72,073,592 | Two notify_one() methods do not work on Cygwin | On Cygwin, when dealing with threads in two different functions using two different conditionals, the main thread does not notify one of the waiting threads on the notify_one() call. On visual studio, this method works fine. Does Cygwin not allow a main thread to handle two different unique_locks? For example:
mutex m_mutex;
mutex b_mutex;
condition_variable intersection;
condition_variable freeway;
void someFunction(){
unique_lock<mutex> mlock(m_mutex);
unique_lock<mutex> block(b_mutex);
intersection.notify_one();
freeway.notify_one();
}
Then wait on this main thread:
void someWaitingThreadFunc(){
unique_lock<mutex> mlock(m_mutex);
intersection.wait(mlock); //one thread waiting
someWaitingOtherThread(); //thread then moves to new function where it
//encounters second wait
}
void someWaitingOtherThread(){
unique_lock<mutex> block(b_mutex);
freeway.wait(block); //a different thread waiting for something else
}
Here is the main function that makes the threads run and wait before notify_one() is called:
int main(){
vector<thread> vts;
for (int i = 1; i <= 5; i++) {
vts.push_back(thread(someWaitingThreadFunc));
}
Sleep(1);
thread mainThread(someFunction);
mainThread.join();
for (int i = 0; i < 5; i++) {
vts[i].join();
}
}
| Your code does not assure that freeway.wait(block); happens before freeway.notify_one();. Therefore the thread may start waiting only after you tried to notify it and then wait forever.
In fact, the locks guarantee that freeway.notify_one(); happens before freeway.wait(block);, because someWaitingOtherThread will first have to wait until the lock in someFunction is released, which happens after the notify_one calls.
It technically also doesn't assure this for intersection.notify_one();, although waiting for one second is likely to work in practice in most cases (I wouldn't bet on it though if the system is under high load.)
Nonetheless, wait can always wake up sporadically, so both compilers are behaving correctly.
Also, since you are using notify_one instead of notify_all, four of the five threads may never make up at all.
|
72,073,866 | 72,073,945 | How do I copy a C-style array into a void pointer in C++? | So basically I've recently started coding in C++ instead of C so maybe that's not the C++ way of doing this, but I've got a program where the user passes an array as a function parameter (void foo(void* pass_array_here)) and I want to copy it in a private member of a class, also declared as void* array_private. I'm copying it like this:
void foo(void* pass_array_here) {
array_private = pass_array_here;
}
I must note that I'm working with OpenGL so I don't know if I can rely on the new keyword or the heap in general. So how do I do that?
(Note, on a sizeof call, a 9-element float array appeared as 8 bytes in the stack, so it definitely didn't work).
|
As already commented above, using void* is not very useful.
If you need an array object, it's recommended in C++ to use either std::array for a fixed size array, or std::vector for dynamic size array.
This line: array_private = pass_array_here is simply assigning the pointer, not copying the array content.
If you use std::array or std::vector as suggested in point 2 above, you can utilize the copy constructor of these classes to actually copy the array's content easily:
void foo(std::vector<SomeType> const & pass_array_here) {
array_private = pass_array_here;
}
If the caller of the function foo does not need to use the array after calling the function, you can save the copy of the data, and utilize C++ move semantics (available since C++ 11):
void foo(std::vector<SomeType> && pass_array_here) {
array_private = std::move(pass_array_here);
}
If the caller does not have a std::vector but an old C style array, it is possible to initialize the std::vector member from it (which will copy the data). See: std::vector::assign.
For 4, 5 and 6 above, your private data member will have to be defined as:
std::vector<SomeType> array_private;
If you need to access the data buffer managed by an std::vector, you can use std::vector::data: std::vector::data. You can cast this data pointer into a void* if you need to pass it to a C style function, e.g. in opengl (no need to copy the data).
More about move semantics and R value references here: Understanding rvalue references
|
72,074,190 | 72,074,572 | How to check the element is in the vector using std::lower_bound? | The book, "Effective STL," (by Scott Meyers), suggests that using sorted vectors instead of associative containers is efficient in some conditions. It shows the example of using std::lower_bound on std::vector. But I found some code in it that looks incorrect:
vector<Widget> vw; // alternative to set<Widget>
...... // Setup phase: lots of
// insertions, few lookups
sort(vw.begin(), vw.end()); // end of Setup phase.
Widget w; // object for value to look up
...... // start Lookup phase
vector<Widget>::iterator i =
lower_bound(vw.begin(), vw.end(), w); // lookup via lower_bound;
(1) Below is the weird part!
if (i != vw.end() && !(*i < w))... // see Item 45 for an explana-
// tion of the"!(*i < w)" test
... // end Lookup phase, start
When you see (1), it checks returned iterator from lower_bound so that it can tell if w is in the vector or not. But I think !(w < *i) is right because std::lower_bound would be using less(w, iterating element). The *i only has two choices: either it is equivalent with w (i.e. w is an element of vector) or it is greater than w. So, as far as I know, to tell these two cases the example code should have used !(w < *i).
Am I correct? Or is there any other reason for above example code?
| The !(*i < w) is clearly wrong (or, at the very least, redundant) because, if the std::lower_bound() search does not return vw.end(), then the result of that test must be true. From cppreference:
Returns an iterator pointing to the first element in the range [first,
last) that is not less than (i.e. greater or equal to) value, or last
if no such element is found.
Here's a trivial test that shows it does not correctly determine whether or not a given value is in your vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vec = { 1,2,3,5,6,7,8,9,10 };
std::vector<int>::iterator i1 = std::lower_bound(vec.begin(), vec.end(), 3); // Present
if (i1 != vec.end() && !(*i1 < 3)) {
std::cout << "3 is present\n";
}
else {
std::cout << "3 is missing\n";
}
std::vector<int>::iterator i2 = std::lower_bound(vec.begin(), vec.end(), 4); // Missing
if (i2 != vec.end() && !(*i2 < 4)) {
std::cout << "4 is present\n";
}
else {
std::cout << "4 is missing\n";
}
return 0;
}
Output (clearly wrong):
3 is present
4 is present
However, changing the second test from the above !(*i < w) form, to your !(w < *i) works, as shown in the following modified code:
int main()
{
std::vector<int> vec = { 1,2,3,5,6,7,8,9,10 };
std::vector<int>::iterator i1 = std::lower_bound(vec.begin(), vec.end(), 3); // Present
if (i1 != vec.end() && !(3 < *i1)) {
std::cout << "3 is present\n";
}
else {
std::cout << "3 is missing\n";
}
std::vector<int>::iterator i2 = std::lower_bound(vec.begin(), vec.end(), 4); // Missing
if (i2 != vec.end() && !(4 < *i2)) {
std::cout << "4 is present\n";
}
else {
std::cout << "4 is missing\n";
}
return 0;
}
Output (correct):
3 is present
4 is missing
So, unless you have somehow inadvertently misrepresented the code from the book you quote (which I am not accusing you of doing), then its author should be contacted to point out their error.
|
72,074,771 | 72,074,903 | Do static libraries behave like dynamic libraries in terms of ABI compatibility? | I have learned that you cannot use shared libraries compiled with different compilers together because their ABIs are usually incompatible. The exception is of course if you have a pure C interface, then it is possible. However, I did not find a clear statement about static libraries in this regard, hence this question.
My question is if static libraries have the same issue. If my shared library links against a static library from a different compiler, will it compile and work as expected at runtime? Or will it compile and behave badly? Or will it never compile?
| There are several kinds of mismatches which could occur, including:
Name mangling. This is a major reason why different compilers may be incompatible. However, many compilers are cross-compatible.
Calling conventions. How to pass function arguments, return values, etc. Tends to be tied to the CPU architecture and operating system.
Language types. For example int can have different widths on different operating systems.
Library types. Commonly std::string, std::map and other classes can be implemented differently by each library vendor, and since many people use the standard library provided by their compiler vendor, this issue may arise.
Some of these, like name mangling, are likely to result in build failures. Others may seem to build OK but behave unexpectedly at runtime. Whether you're using static or dynamic linking, the overall situation is the same.
|
72,075,289 | 72,075,318 | Copy constructor implicitly called? | I have the following class with both a normal constructor and copy constructor defined.
#include <iostream>
class Bla
{
public:
Bla()
{
std::cout << "Normal Constructor Called\n";
}
Bla(const Bla& other)
{
std::cout << "Copy Constructor Called\n";
}
};
int main()
{
Bla a = Bla(); // prints Normal Constructor
}
In the main function, it prints the normal constructor as I expected and only the normal constructor. However, if I make the copy constructor a private member of the class, the compiler gives me the error
error: ‘Bla::Bla(const Bla&)’ is private within this context
From the looks of it, it looks like the copy constructor was called, but I do not see anything being printed from it. Is the copy constructor being implicitly called? What's going on here?
| Before C++17, the copy operation might be elided but the copy constructor still needs to be present and accessible.
This is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:
Since C++17 there's no such issue because of mandatory copy elision.
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
|
72,075,467 | 72,092,294 | python ctypes module how to transfer uint64_t from c++func return to python int,not set restype=c_long_long | i use python ctypes module to cal crc from c++ function it return uint64_t type.
In python, i do not set restype(c_long_long), i get a python int value -870013293 , however set restype the value is 14705237936323208851.
can you tell me the relation about int_val and long_val.
| The default return type for ctypes is c_int which is a 32-bit signed value. If you don't set .restype = c_uint64 for a 64-bit value, the return value is converted incorrectly from C to Python. You can see that the value was truncated to 32 bits if you display it in hexadecimal:
>>> hex(-870013293 & 0xFFFFFFFF) # twos complement representation of a 32-bit negative value
'0xcc24a693'
>>> hex(14705237936323208851) # the actual return value
'0xcc137ffdcc24a693'
Note that the last 32 bits of the 64-bit value match the 32-bit signed value.
|
72,075,577 | 72,075,705 | "error: cannot convert 'int*' to 'int**'" | I try to implement a template avl tree while Node includes a pointer to the object :
template <class T>
class Node {
public:
Node* left;
T* data;
Node* right;
int height;
};
template <class T>
class AVLTree{
public:
Node<T*>* root;
Node<T*>* insert(Node<T*>* p, T* key){
Node<T*>* t;
if (p == NULL){
t = new Node<T*>;
t->data = key;
t->left = NULL;
t->right = NULL;
t->height = 1;
return t;
}
if (*(key) < *(p->data)){
p->left = insert(p->left, key);
} else if (*(key) > *(p->data)){
p->right = insert(p->right, key);
}
return p;
}
int main() {
AVLTree<int*>* tree1 = new AVLTree<int*>();
int a=5;
int* ap=&a;
tree1->root = tree1->insert(tree1->root,ap);
By executing this I got an error, I hope there are enough details about the problem.
please help . thanks !
| T = int* and you say that you want a T* (that is, an int**) in T* key so when you try to supply an int* instead, it fails.
I suggest changing the Node to contain a T instead of a T*:
template <class T>
class Node {
public:
Node* left;
T data; // not T*
Node* right;
int height;
};
template <class T>
class AVLTree {
public:
Node<T>* root;
Node<T>* insert(Node<T>* p, T* key) {
Node<T>* t;
if (p == nullptr) {
t = new Node<T>;
t->data = *key;
t->left = nullptr;
t->right = nullptr;
t->height = 1;
return t;
}
if (*key < p->data) {
p->left = insert(p->left, key);
} else if (*key > p->data) {
p->right = insert(p->right, key);
}
return p;
}
};
And then instantiate an AVLTree<int> instead of an AVLTree<int*>
Here's a suggestion making it possible to store pointers and comparing them using std::less and std::greater. Note that if you store pointers, it'll be the actual pointer values that you compare, not the values the pointers point at.
#include <functional>
template <class T>
class Node {
public:
Node* left;
T data;
Node* right;
int height;
};
template <class T>
class AVLTree {
public:
Node<T>* root;
Node<T>* insert(Node<T>* p, const T& key) { // key is an int*& in this example
Node<T>* t;
if (p == nullptr) {
t = new Node<T>;
t->data = key;
t->left = nullptr;
t->right = nullptr;
t->height = 1;
return t;
}
if (std::less<T>{}(key, p->data)) { // less
p->left = insert(p->left, key);
} else if (std::greater<T>{}(key, p->data)) { // greater
p->right = insert(p->right, key);
}
return p;
}
};
int main() {
AVLTree<int*> tree1;
int a = 5;
int* ap = &a;
tree1.root = tree1.insert(tree1.root, ap);
}
|
72,075,776 | 72,075,814 | ASSIMP : mNumMeshes is 0 | When I was following the LearnOpenGL, a problem come up:
I can't figure out why the scene->mRootNode->mNumMeshes is 0. However the scene has been imported rightly (I guess, 'cause scene->mNumMeshes is 7).
void Model::loadModel(std::string path)
{
Assimp::Importer import;
const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);
if (scene == nullptr || !scene->mRootNode || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE)
{
std::cout << "ERROR::ASSIMP::" << import.GetErrorString() << std::endl;
return;
}
directory = path.substr(0, path.find_last_of('/'));
processNode(scene->mRootNode, scene);
}
void Model::processNode(aiNode *node, const aiScene *scene)
{
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
meshes.push_back(processMesh(mesh, scene));
std::cout << "SUCCESS::ASSIMP::PROCESSED:" << i << std::endl;
}
for (unsigned int i = 0; i < node->mNumMeshes; i++)
processNode(node->mChildren[i], scene);
}
| Meshes are not necessarily attached to the root node. They can also be attached to any of the child nodes (or children's child nodes). Having a scene which contains 7 meshes with scene->mRootNode->mNumMeshes beeing 0 is perfectly valid.
But, the recursive loop in your code is wrong. You have to iterate over node->mNumChildren instead of node->mNumMeshes:
for (unsigned int i = 0; i < node->mNumChildren; i++)
processNode(node->mChildren[i], scene);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.