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
|
|---|---|---|---|---|
73,396,664
| 73,397,005
|
Data structure/algo for fast insertion and counting
|
I'm looking for a data structure/algorithm that allows both logarithmic insertion of elements into data structure, and logarithmic counting of elements in data structure that are smaller than a given value.
For instance, std::set<int> allows logarithmic insertion, and logarithmic iter = std::upper_bound(..., value) but then distance(iter, set.begin()) is linear...
Can it be done using C++ STL containers?
|
There is a way, unfortunately only for GNU C++. Called Policy based data structure.
I'll show basics of usage.
#include <ext/pb_ds/assoc_container.hpp>
#include <iostream>
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag,
tree_order_statistics_node_update>
indexed_set;
int main() {
indexed_set s;
s.insert(1);
s.insert(5);
s.insert(10);
s.insert(20);
s.insert(21);
cout << s.order_of_key(10) << '\n';
}
order_of_key returns the number of values in a set that are strictly smaller than the value passed.
Further information: https://codeforces.com/blog/entry/11080
|
73,396,880
| 73,399,081
|
C++ if, else if, else statement is not printing cout result
|
I'm struggling with this code. Been working at these if, else if, else statements for a few hours now.
void metric()
{
double mWeight;
double mHeight;
double mAge;
char mExercise;
bool mCorrectExercise = true;
int metricResult;
cout << "Please type in your age: ";
cin >> mAge;
cout << "Please type in your weight: ";
cin >> mWeight;
cout << "Please type in your height: ";
cin >> mHeight;
cout << "Finally, please select an exercise program that most closely matches yours.\n\n1) No exercise.\n\n2) 1-2 hours a week.\n\n3) 3-5hours a week.\n\n4) 6-10 hours a week\n\n5) 11-20 hours a week.\n\n6) 20+ hours a week.\n\n";
cin >> mExercise;
if (mExercise == 1)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult << "\n\n";
}
else if (mExercise == 2)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.1 << "\n\n";
}
else if (mExercise == 3)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.25 << "\n\n";
}
else if (mExercise == 4)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.35 << "\n\n";
}
else if (mExercise == 5)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.5 << "\n\n";
}
else if (mExercise == 6)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.7 << "\n\n";
}
else
{
cout << "Invalid input. Please try again.\n\n";
}
}
They aren't successfully printing the cout results. I had it somewhat working earlier when the math formulas inside the statements used to be different. I've tried to have all of them as if statements which I'm pretty sure isn't how it's supposed to be. I also had an issue where it would only print the result from option #1 despite typing in any other option.
TLDR, with the current code, simply won't print no matter which option I pick from 1 to 6.
|
You forgot to add single quotation marks (i.e. '') to your values. For instance, this '1' is a character literal but this 1 is not a character literal (it's an integer literal). You need to compare a value of char type with values of char type.
Also, you better use a switch statement instead of the if else if structure.
Like this:
#include <iostream>
void metric( )
{
// bool mCorrectExercise = true;
std::cout << "Please type in your age: ";
double mAge;
std::cin >> mAge;
std::cout << "Please type in your weight: ";
double mWeight;
std::cin >> mWeight;
std::cout << "Please type in your height: ";
double mHeight;
std::cin >> mHeight;
std::cout << "Finally, please select an exercise program that "
"most closely matches yours.\n\n1) No exercise.\n\n"
"2) 1-2 hours a week.\n\n3) 3-5hours a week.\n\n"
"4) 6-10 hours a week\n\n5) 11-20 hours a week.\n\n"
"6) 20+ hours a week.\n\n";
char mExercise;
std::cin >> mExercise;
const double metricResult { (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66 };
switch ( mExercise )
{
case '1':
std::cout << metricResult * 1.0 << "\n\n";
break;
case '2':
std::cout << metricResult * 1.1 << "\n\n";
break;
case '3':
std::cout << metricResult * 1.25 << "\n\n";
break;
case '4':
std::cout << metricResult * 1.35 << "\n\n";
break;
case '5':
std::cout << metricResult * 1.5 << "\n\n";
break;
case '6':
std::cout << metricResult * 1.7 << "\n\n";
break;
default:
std::cout << "Invalid input. Please try again.\n\n";
}
}
int main( )
{
metric( );
}
It's probably also worth mentioning that due to the changes I made, the assembly output of the program decreased from 207 lines down to 136 lines which means it's more efficient now.
|
73,396,946
| 73,399,292
|
OpenCV Mat data address shows weird value
|
I'm suffered by using OpenCV Mat due to unexpected results.
There is an example code:
cv::Mat local_mat = cv::Mat::eye(cv::Size(1000, 1000), CV_8UC1);
qDebug() << "1. local_mat.data: " << local_mat.data;
cv::Mat sobel_img_ = cv::Mat::eye(cv::Size(1000, 1000), CV_8UC1);
qDebug() << "2. sobel_img_.data: " << sobel_img_.data;
sobel_img_ = local_mat; // copy address but no clone()
qDebug() << "3. sobel_img_.data: " << sobel_img_.data;
sobel_img_ = cv::Mat::eye(cv::Size(1000, 1000), CV_8UC1); // renew
qDebug() << "4. sobel_img_.data: " << sobel_img_.data;
local_mat.data: 0x55aa19a53e40
sobel_img_.data: 0x55aa19b480c0
sobel_img_.data: 0x55aa19a53e40
sobel_img_.data: 0x55aa19a53e40
1 and 2 should be different because I create new Mat(), so it is fine.
However, 3 and 4 are same even though I create new Mat() after copying the local_mat into sobel_mat.
I meet many problems like this when I use OpenCV Mat.
Could you explain why it happens and how can I solve this?
|
Initializing of matrix is a form of matrix expression.
cv::Mat has overloads of operator=. One of them handles MatExpr as its argument:
Assigned matrix expression object. As opposite to the first form of
the assignment operation, the second form can reuse already allocated
matrix if it has the right size and type to fit the matrix expression
result. It is automatically handled by the real function that the
matrix expressions is expanded to. For example, C=A+B is expanded to
add(A, B, C), and add takes care of automatic C reallocation.
by bold font I emphasized what happens in your case. Already allocated memory is used to create identity matrix by cv::Eye.
You can turn MatExpr into cv::Mat just by casting:
sobel_img_ = (cv::Mat)cv::Mat::eye(cv::Size(1000, 1000), CV_8UC1); // renew
then sobel_img will refer to new allocated matrix.
|
73,397,226
| 73,397,594
|
C++ Can't print certain words from Char array
|
Not sure how to phrase the question, but I'm making a program for an assignment, which we're not allowed to use pre-existing libraries besides input/output. We also can only use primitive data-types. I have to read a text file with words, remove all punctuation from the word, and then store those words in a 2D array of characters.
This problem seems to be that when a word starts with a non-alphabetic character, the whole word doesn't output when using cout << stack[top] but when I output each individual character with cout << stack[top][i], it produces the expected output.
'stack' is a 2D array which contains characters to make up words.
'top' is a variable to represent the length of stack
Code:
#include <iostream>
#include <fstream>
using namespace std;
// Function Prototypes
void push(char word[]);
char formatCharacter(char letter);
bool isAlphabet(char letter);
char toLowercase(char letter);
// Global Variables
const int STACK_SIZE = 50000;
const int WORD_SIZE = 30;
char stack[STACK_SIZE][WORD_SIZE];
int top = 0;
int words = 0;
int wordCount[STACK_SIZE];
int main(){
// Local Variables
char filename[20];
ifstream fin;
char word[WORD_SIZE];
// Get file input
cerr << "Please enter the name of the input file: ";
cin >> filename;
// Open file
fin.open(filename);
// Print error if file doesn't open, then quit the program.
if (!fin) {
cerr << "Error opening file " << filename << ". Program will exit." << endl;
return 0;
}
// Read the file into the stack
while (fin >> word) {
push(word);
}
// Close file
fin.close();
}
void push(char word[]){
if (top == STACK_SIZE) return;
int i = 0;
int j = 0;
do {
if (isAlphabet(word[i])){
word[i] = formatCharacter(word[i]);
stack[top][i] = word[i];
cout << stack[top][i]; // Output fine
j++;
}
i++;
} while (word[i]);
wordCount[words] = j;
//cout << stack[top] << ": " << wordCount[words] << endl; // Output incorrect
cout << endl;
top++;
words++;
return;
}
bool isAlphabet(char letter){
if ((letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z')){
return false;
}
else{
return true;
}
}
char formatCharacter(char letter){
if ((letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z')){
letter = '\0';
}
else{
if (letter >= 'A' && letter <= 'Z'){
letter = toLowercase(letter);
}
}
return letter;
}
char toLowercase(char letter){
letter = letter + 32;
return letter;
}
isAlphabet() just checks if it's an alphabetic character
formatCharacter() removes any punctuation by replacing the character with '\0', and also changes uppercase to lowercase.
Input:
Jabberwocky
'Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
Output when using cout << stack[top][i]:
jabberwocky
twas
brillig
and
the
slithy
toves
did
gyre
and
gimble
in
the
wabe
all
mimsy
were
the
borogoves
and
the
mome
raths
outgrabe
Output when using cout << stack[top]:
jabberwocky: 11
: 4
brillig: 7
and: 3
the: 3
slithy: 6
toves: 5
did: 3
gyre: 4
and: 3
gimble: 6
in: 2
the: 3
wabe: 4
all: 3
mimsy: 5
were: 4
the: 3
borogoves: 9
and: 3
the: 3
mome: 4
raths: 5
outgrabe: 8
Notice the word 'twas' is missing. I'd rather not loop through each character of each word to get the output I need. I'd appreciate any advice, thanks!
|
The simplest fix is to change:
stack[top][i] = word[i];
To:
stack[top][j] = word[i];
^ j not i here
This will ensure that the 'Twas ends up as twas and not \0twas.
Also, formatCharacter() should call isAlphabet() rather than repeat the condition.
|
73,398,329
| 73,400,179
|
QT signal slot behavior with respect to const ref arguments
|
I am working on some code where I see the following:
In header file:
private slot:
void OnNotifySomeSlot(const QList<bool>& someList); // Note the argument is pass by const ref
In implementation file:
connect(&m_serviceObj,SIGNAL(NotifySomeSlot(QList<bool>)), this, SLOT(OnNotifySomeSlot(QList<bool>)); // Note that arguments are pass by value
Slot function definition:
void OnNotifySomeSlot(const QList<bool>& someList)
{
m_list = someList;
} // Note that argument is passed by const ref as in the header
Now my doubt is that:
1: Why is such a code getting compiled as there is difference in signature between connect statement and slot definition?
2: During runtime if the value is getting passed a const ref , will it still not cause problems in a multithreaded environment. Because the reference to the list (be it const) can still be modified by some other code referring the same list in a multithreaded environment.
3: Can we just "pass by value" everywhere to avoid any issue in a multi threaded environment. Will it make the application slower?
|
Answering your questions in order:
The Qt macro machinery canonicalizes signal and slot names so they "fit". If you use the modern connection approach you do not have to worry about this:
QObject::connect(m_serviceObj, &SomeServiceObjectClass::NotifySomeSlot, this, &ThisObjectClassOnNotifySomeSlot)
Yes, even though you pass the list as a const ref, some other thread that has a non-const ref can change it behind your back.
Yes, passing it by value makes this behave properly. It is also efficient, as QList is an "implicitly shared" datastructure. This means that a copy is only made when a mutation happens, by the thread doing the mutation.
|
73,401,155
| 73,401,181
|
Why do i can't add an string to an letter of another string?
|
Consider the following code:
#include <iostream>
#include <typeinfo>
int main(){
std::string word = "This is string";
std::string word1 = "a" + word[0];
std::cout << word1;
}
As you can see, i heve a string with the name word and i want to add first letter of it to another string and store them to string word1. when i run code, I expect that output is aT, but the output is ╨≥ ╨≥ ╨≥ ╨≥ P≥ ►≥ @≥ ╕♠≥ ! What does this mean? How do i fix it? (Also note that my IDE is Code::Blocks 20.03)
|
"a" is not a string (well, its a c-string, but not a std::string, and a c-string is just an array). Its a const char[2] and decays to a pointer when + is applied. There is an operator+ for std::string though:
std::string word1 = std::string("a") + word[0];
or
std::string word1 = "a"s + word[0];
|
73,401,495
| 73,402,028
|
Is there such a C++ feature: "const scope" in method definitions?
|
I was wondering if there is a safety feature to restrict a scope of a class method definition to allow disallow modifying access to *this. See this pseudo-code:
class C{
void method();
void const_method() const {
// do const stuff here
}
};
void C::method(){
const_method();
}
Now instead of calling const_method(); I would directly have a scope which only allows const access, i.e. which only allows code that would also be valid within the const_method definition like this:
void C::method(){
// { "const scope"
// instead of const_method();
// do const stuff directly here
// }
}
I know that I can just call a const method but when I like to modify outer local variables in the const scope I would have to make them be returned from the const function or use a reference or pointer parameter as a workaround. So I am wondering if there exists a language feature to have "const scopes"?
My goal is to have peace of mind in some sections of the code, the compiler shall verify that I do not modify the class instance in sections of code where I do not intend this.
EDIT
I have seen in the comments that I can use const C* const_this{this}; But of course this does not prevent me from modifying *this when I forget to use const_this. I have the feeling that it could be done with a lambda thich captures all locals and captures *this as const somehow. How could this be done?
|
You can use a immediately invoked lambda, though you still have to capture the local variables explicitly:
#include <iostream>
struct foo {
int member = 42;
void bar() {
int local_var = 42;
[const_obj=const_cast<const foo&>(*this),&local_var](){
//member = 2; // error: this is not captured
//const_obj.member = 2; // error: const_obj is read-only
const_obj.const_method();
std::cout << const_obj.member;
}();
}
void const_method() const {};
};
However, I somewhat agree with comments. Your approach of simply calling const_method is ok, while your argument against it (Needing to pass paramteters and return values) is a matter of design that can be solved in different less arcance ways. The reluctance to pass parameters and return values around can lead to the most absurde constructs, while simply passing parameters and return values around is typically the more clear, readable and simpler code.
PS: There is a way to get somewhat the opposite of what you ask for. I am not recommending it, hence I will only outline it: In the example above you could make bar call a private bar() const. Because bar() const is only called from non-const bar() you can safely cast away constness to get a mutable reference to the current object that can be restricted to a narrow scope. Though, if you aim for "peace of mind" then this approach is not the way to go.
|
73,401,506
| 73,401,851
|
Copy vector of object to vector of shared_ptrs
|
I have a simple struct and vector of its objects.
And I want to move all objects to the vector of shared_ptrs.
I don't need the initial vector anymore.
I presented you with my situation.
Is my approach correct? I want to do this the most effective way:
struct MyStruct
{
int i_;
std::string s_;
};
void copyVector(std::vector< MyStruct>&& vt)
{
std::vector<std::shared_ptr<MyStruct>> ptrsVt;
for (auto& v : vt)
ptrsVt.push_back(std::make_shared<MyStruct>(std::move(v)));
// ...
}
void processing()
{
std::vector<MyStruct> vt = getVectorFromSomewhere();
copyVector(std::move(vt));
}
|
Yes, that's correct. You might want to reserve the size of the destination beforehand though:
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>
template <class T>
auto transform_vector(std::vector<T>&& src) -> std::vector<std::shared_ptr<T>> {
std::vector<std::shared_ptr<T>> dst;
dst.reserve(src.size());
transform(begin(src), end(src), back_inserter(dst),
[](T& elm) { return std::make_shared<T>(std::move(elm)); });
return dst;
}
int main() {
std::vector<std::string> elms{"a", "b", "c"};
auto ptrs = transform_vector(std::move(elms));
for (auto const& elm : elms) {
std::printf("\"%s\", ", elm.c_str()); // moved strings, possibly empty
}
std::putchar('\n');
for (auto const& ptr : ptrs) {
std::printf("\"%s\", ", ptr->c_str()); // "a", "b", "c"
}
std::putchar('\n');
}
|
73,401,560
| 73,401,753
|
c++ bubble sort routine with template functions doesn't work with string literals
|
I have a bubble sort algorithm to order integers in a descending order. Next I am asked to implement a template specialization for type char* in which I replace the arithmetic operator between two integers (>) with (strcmp). The code seems to work, as I print out the number of successful swaps, but my output just shows the array of chars* in reverse order compared to what I have inputted. Any idea?
#include <iostream>
#include <cstring>
using namespace std;
const int n=10;
template <class T> void order (T&, T&);
template <class T> void sort(T[n]);
template <class T> void display(T[], int);
int main(){
int arr[n]={12, 3, 7, 120, 69, 420, 15, 666, 23, 10};
float _arr[n]={71.9,111.7,197.8,378.1,246.9,312.9,445.5,121,166.7,434.3};
const char* str[n]={"have","you","put","them","aside","your",
"crazy","thoughts","and","dreams"};
sort(arr);
display(arr, n);
sort(_arr);
display(_arr, n);
sort(str);
display(str, n);
return 0;
}
template <class T> void order(T& a, T& b){
T tmp;
tmp=a;
a=b;
b=tmp;
return;
}
template <> void order <char*>(char* &A, char* &B){
char* tmp;
tmp=A;
A=B;
B=tmp;
return;
}
template <class T> void sort(T A[n]){
int count=0;
for (int i=0; i<n-1; i++) {
for (int j=0; j<n-1-i; j++) {
if (A[j+1]>A[j]){
count++;
order(A[j], A[j+1]);
}
}
}
cout <<"Swaps: " <<count <<endl;
} //doesn't work for strings because comparing pointers isn't sensible to chars
template <> void sort<char*>(char* A[n]){
int count=0;
for (int i=0; i<n-1; i++) {
for (int j=0; j<n-1-i; j++) {
if (strcmp(A[j+1],A[j])>0){
count++;
order(A[j], A[j+1]);
}
}
}
cout <<"Swaps: " <<count <<endl;
}
template <class T> void display(T t[], int n){
for (int k=0; k<n; k++){
cout <<t[k] <<endl;
}
cout <<endl;
return;
}
Originally this was the template specialization for "sort":
template <> void sort<const char*>(const char* A[n])
...
but it would originate this error message:
error: specialization of ‘void sort(T*) [with T = const char*]’ after instantiation
50 | template <> void sort<const char*>(const char* A[n]){
|
You have const char *str[n], but your template specialisation takes char *, so as the compiler will not automatically cast away constness the compiler will select the default class T template.
You should also refactor the code so that for instance a baseSort() function takes a pointer to a comparison function so you don't need to repeat the for loops in both templates.
Note also that you don't need the order() specialisation as it is identical to the default one.
Finally, using namespace std; and defining sort() can cause all sorts of problems as the std::sort() is now in the same namespace.
Oh, and concerning your update, declaring templates but not defining them until after they are used is not a common pattern, and probably causes issues like the one you see for reasons I am not sure of...
|
73,402,616
| 73,402,746
|
Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted. I tried to find it but still can't find where i got out of bounds array
|
what was i trying to do is a recursion of first 40 fibonacci numbers, when tried to launch a program, it's stopped at return 0;.
#include <stdio.h>
#define SIZE 40
void sum(int arr[], int n1, int n2, int offset);
int main(void)
{
int arr[SIZE] = { 0, 1 };
printf("%d\n", arr[0]);
printf("%d\n", arr[1]);
sum(arr, 0, 1, 2);
return 0;
}
void sum(int arr[], int n1, int n2, int offset)
{
if (offset > SIZE)
return;
arr[offset] = arr[n1] + arr[n2];
printf("%d\n", arr[offset]);
sum(arr, n1 + 1, n2 + 1, offset + 1);
}
|
Look at this check:
if (offset > SIZE)
return;
That means if offset is equal to SIZE, it passes.
arr[offset] with offset being equal to SIZE refers to the 41 nth element.
This array only have 40 element, hence the corruption.
If you run your program in a debugger, it should stop at the crash and you would be able to look at the value of offset that caused the crash.
A solution for this would be to change the check to if (offset >= SIZE).
|
73,402,996
| 73,403,193
|
Should you use std::unique_ptr alongside std::function?
|
I'm having trouble figuring out the best way to deal with allocation and deallocation of std::function.
Of course the underlying function is never going to be deallocated, but the captured variables etc. need to be deallocated.
I presume that this is deallocated inside the destructor of std::function.
Does this mean the best way to manage functions that persist is through the use of std::unique_ptr<std::function<...>> and std::shared_ptr<std::function<...>>, or even just a raw pointer std::function<...>*?
Wouldn't this be an extra pointer of indirection? Is this the recommended way to go?
|
Remember that std::function is not a lambda. A std::function don't have captures. It's a polymorphic wrapper around a function like object like a lambda.
A (extremely rough and incomlete and incorrect) representation of std::function looks like this:
template<typename R, typename... Args>
struct function {
function(auto lambda) :
fptr{[](void* l, Args...){ static_cast<decltype(lambda)>(l)(std::forward<Args>(args)...); }}
function_object{new auto(lambda)} {}
auto operator()(Args...) const -> R {
return fptr(function_object, std::forward<Args>(args)...);
}
// other members...
private:
R(*fptr)(void*, Args...);
void* function_object;
};
As you can see, the function_object member is dynamically allocated. This is the lambda, and the lambda contains the captures. They will only be deleted when the std::function destructor is called.
Then, also remember that std::function respects value semantics. This means that if the std::function is copied, the lambda held inside is also copied. This means you can freely copy, move around, make some copies out of scope, call the function and it won't affect other copies.
This means this code works:
auto make_function_with_captures(double a, double b) -> std::function<double()> {
// captures 'a' and 'b' as values
auto lambda = [a, b] {
return a + b;
};
// Here, 'lambda' is copied in the std::function
return std::function<double()>{lambda};
} // 'lambda' goes out of scope here, with its captures
int main() {
auto function = make_function_with_captures(1.2, 4.5);
// Here, use a copy of the lambda that was created in the function
double a = function();
}
Wouldn't this be an extra pointer of indirection?
Yes. This would be two pointer indirection with a virtual call.
Is this the recommended way to go?
I would answer this question to "no" most of the time, like 98% of cases.
|
73,403,115
| 73,403,426
|
Linux perf not resolving some symbols with high addresses starting with 0xffffffff
|
g++ -std=c++17 -fno-omit-frame-pointer -O0 -g3 -o main main.cpp
perf stat ./main 5
perf report
20.98% main [unknown] [k] 0xffffffffb1077f22 ◆
19.11% main main [.] func ▒
17.96% main libc-2.31.so [.] __memset_avx2_erms ▒
13.07% main [unknown] [k] 0xffffffffb067a936 ▒
5.75% main [unknown] [k] 0xffffffffb10e68e5 ▒
3.30% main main [.] std::min<int> ▒
1.72% main [unknown] [k] 0xffffffffb1077f25 ▒
1.58% main [unknown] [k] 0xffffffffb086f485 ▒
1.01% main main [.] std::max<int>
func is a symbol in main.cpp, so symbols in my source file have been resolved. I call std::max and memset, they have beed resolved, too. But what about 0xffffffffb1077f22, it is an address. And with nm main, I'm sure that it is not a symbol in main source file. What is it? I don't think it is a library function because memset and std::max can be resolved.
I run perf in ubuntu virtual machine of macos.
|
I did not give attention to the warning message of perf report.
It says:
WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,
check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid.
So it seemed that I should set a proper value in /proc/sys/kernel/kptr_restrict.
sudo echo 0 > /proc/sys/kernel/kptr_restrict
Then the address can be resolved.
|
73,403,427
| 73,403,525
|
How to scan for a letter in c++ instead of a number?
|
My code prompts the user to input 0 or 1 as an integer in answer to one of the questions. I want the user to type Y or N. I tried to create a char variable, but I am not getting it right. It says y and n is not declared. I know it's a basic question, but I have just started learning c++.
Here is my code and below that the prompts, inputs, and output as well as a screenshot.
#include <iostream>
using namespace std;
int main() {
int a; // number of classes held
int b; // number of classed attended
int percent;
cout<<"Number of classes held "<<endl;
cin>>a;
cout<<"Number of classes attended "<<endl;
cin>>b;
percent = (b*100)/a;
if (percent>75 && percent<=100) {
cout<<"Congratulation you are allowed to sit in the examination your attendence is "<<percent<<"%";
} else if (percent<75) {
int m;
cout<<"Do you have any medical cause? (Respond in '1' for yes or '0' for no) "<<endl;
cin>>m;
if (m==1) {
cout<<"You are allwed due to a medical cause your percentage is "<<percent<<"%";
} else if (m==0) {
cout<<"You are not allowed to sit in the examination your percentage is "<<percent<<"%";
} else if (m!=1 && m!=0) {
cout<<"Invalid Responce";
}
} else {
cout<<"invalid attendence";
}
return 0;
}
cout<<"Number of classes held "<<endl;
cin>>a;
cout<<"Number of classes attended "<<endl;
cin>>b;
percent = (b*100)/a;
if (percent>75 && percent<=100) {
cout<<"Congratulation you are allowed to sit in the examination your attendence is "<<percent<<"%";
} else if (percent<75) {
int m;
cout<<"Do you have any medical cause? (Respond in '1' for yes or '0' for no) "<<endl;
cin>>m;
if (m==1) {
cout<<"You are allwed due to a medical cause your percentage is "<<percent<<"%";
} else if (m==0) {
cout<<"You are not allowed to sit in the examination your percentage is "<<percent<<"%";
} else if (m!=1 && m!=0) {
cout<<"Invalid Responce";
}
} else {
cout<<"invalid attendence";
}
return 0;
}
Here is the output of my code:
Number of classes held
100
Number of classes attended
53
Do you have any medical cause? (Respond in '1' for yes or '0' for no)
1
You are allwed due to medical cause your percentage is 53%
screenshot of code and output
|
Try using char:
char m;
std::cin >> m;
if (m == 'y')
// do something
else if (m == 'n')
// do something else
|
73,404,182
| 73,404,416
|
glBufferSubData() and glBindArray()
|
I have two methods:
opengl_init()
opengl_draw()
In the first one I initialize an empty GL_ARRAY_BUFFER because I want to update my point coordinates each frame.
Everything works if in opengl_draw() method I keep commented out //glBindBuffer(GL_ARRAY_BUFFER, 0)
Normally I use this function when I draw elements statically in the last line of the opengl_init() method.
Question:
Could you explain why commenting out glBindBuffer() function positions are updated every frame, and if I use glBindBuffer() function objects are draw statically (no change of y coordinate) even if I use glBufferSubData() in a while loop every frame?
I also do not understand why I need to write glBindVertexArray(0); in the last line of opengl_init() method. I used this line from learnopengl tutorials.
My working code:
void opengl_init()
{
//vertex array
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
//vertex buffer
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
//-> keep this function NULL to dynamically draw vertices glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertex), &vertices[0], GL_STATIC_DRAW); // target | size | data (poinnting to first element e.g. glm::value_ptr(vertices[0])) | usage
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertex), NULL, GL_STATIC_DRAW);
//set attributes that corresponds to layout id in the vertex shader
// set the vertex attribute pointers
// vertex Positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), (void*)0);
// vertex normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vertex), (void*)offsetof(vertex, color));
//bind buffers vao | vbo | ibo
glBindVertexArray(0);
//glBindBuffer(GL_ARRAY_BUFFER, 0);
}
// render the mesh
void opengl_draw(opengl_shaders::shader& shader)
{
for (auto& v : vertices)
v.position.y += 0.001;
glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(vertex), &vertices[0]);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(vao);
glDrawArrays(GL_POINTS, 0, vertices.size());
glBindVertexArray(0);
}
|
glBufferSubData requires that GL_ARRAY_BUFFER is bound to a buffer. glBindBuffer(GL_ARRAY_BUFFER, 0); binds it to nothing.
Assuming nothing else in this code touches GL_ARRAY_BUFFER, commenting that line leaves it bound to vbo, which means that the glBufferSubData call knows which buffer to update.
It is best to be explicit and bind the correct buffer before you touch it. In this case, inside opengl_draw.
If you find all of this confusing, know that modern OpenGL also has direct state access, which does not require a separate glBindBuffer:
// Note we pass vbo directly instead of GL_ARRAY_BUFFER
glNamedBufferSubData(vbo, 0, vertices.size() * sizeof(vertex), &vertices[0]);
|
73,404,774
| 73,404,822
|
sorting a list of tuple by second element but if the second element of mutiple tuple matches then sort using the first element
|
Given a list of tuples where first and second elements are integer. Sort them using the second element but if the second element matches sort them using first element. Basically, I am trying to convert c++ pair<int, int> type comparison to python code. This is the c++ version.
bool cmp(const pair<int,int>& a, const pair<int,int>& b)
{
if(a.second != b.second) return a.second < b.second;
return a.first < b.first;
}
int main() {
//some code here
sort(v.begin(), v.end(), cmp);
//some code here
return 0;
}
this code produces,
input: [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]
output: [(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]
I tried to convert that code in python
sil = [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]
sil.sort(key = lambda y : y[1])
But sadly this only produces output: [(2, 5), (1, 5), (3, 6), (6, 9), (8, 10)]. Clearly, (1, 5) should come before (2, 5) but it didn't happen.
My question is how to implement this in python so the output should be [(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]
|
You can specify both the elements in the key -
inp = [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]
sorted(inp, key=lambda x: (x[1], x[0]))
Output
[(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]
|
73,405,112
| 73,405,197
|
Optimizing bug in ARM Apple Clang on implicit casting double to byte
|
I found a nasty bug in our C++ iOS application, which I suspect to be caused by a compiler bug on ARM based Apple Clang.
I was able to reproduce the bug in a MRE on a Mac M1 machine.
#include <cstdio>
int main(int argc, const char** argv)
{
int total = 0;
for(double a=1000; a<10000; a*=1.1)
{
unsigned char d = a / 0.1;
total += d;
}
printf("Total: %d\n", total);
}
Compiled without optimization, the test program always produces the same output:
% ./a.out
Total: 3237
% ./a.out
Total: 3237
% ./a.out
Total: 3237
However, when compiling with optimization, the resulted number seems like random:
% clang -O3 test.cpp
% ./a.out
Total: 74841976
% ./a.out
Total: 71057272
% ./a.out
Total: 69828472
The Apple Clang version is 13.0:
% clang --version
Apple clang version 13.0.0 (clang-1300.0.29.30)
Target: arm64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
I believe the program does not have undefined behavior. So my questions:
Is that really a compiler bug?
Is the behavior also wrong on original (not Apple) Clang?
Should I fill in a bug report?
|
Your code does have undefined behavior. When you do
unsigned char d = a / 0.1;
you are doing floating point to integer conversion which means [conv.fpint]/1 applies and it states:
A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.
emphasis mine
so once a / 0.1 exceeds the max value of an unsigned char you have undefined behavior.
|
73,405,297
| 73,405,441
|
Semi-private enum values
|
Is it possible to have an enumeration where (some) members are accessible from user-code and others are reserved for the implementation?
Here is a minified example of the situation I'm trying to handle: I have a benchmarking framework where I instrument the functions given by a user. To check the sanity of execution the user should report whether execution happened correctly or not, hence a return_code enumeration is created:
enum return_code {
ok,
error,
execution_timeout,
waiting_time_exceeded
};
The last two enumerators should not be available to the user, i.e. I'm the one responsible to check if there's a timeout or the processing queue never got to executing the function on time.
My current handling of the situation is to split the enumerators in a private and public interface:
namespace detail {
enum return_code_internal {
ok,
error,
execution_timeout,
waiting_time_exceeded
};
}
enum return_code {
ok,
error
};
So return_code::ok maps to detail::return_code_internal::ok and same happens for error, while the "internal" enumerators are not visible to the user. This works but forces me to jump through hoops when converting between the two types since they are not symmetric (one has 2 members while the other has 4). Is there a better way?
P.S I know that in C++ enumerators have the same visibility. I'm looking for a technique that would simulate having two enum members as "public", while the other two are "private" (or for internal use).
|
You could use a class with static members as the enumeration. This lets you have public and private members. The only catch is you would need to grant friendship to all of the things that need access to those private variables. That could look like:
struct return_code
{
constexpr static int ok = 0;
constexpr static int error = 1;
private:
constexpr static int execution_timeout = 2;
constexpr static int waiting_time_exceeded = 3;
friend xxx;
friend yyy;
friend zzz;
};
|
73,405,440
| 73,406,604
|
Initialization by conversion function for direct reference binding
|
I found out the rules for determining the candidate conversion functions, for direct reference binding, are not described clearly by the standard at least for me.
The rules are found in [over.match.ref]
Under the conditions specified in [dcl.init.ref], a reference can be
bound directly to the result of applying a conversion function to an
initializer expression. Overload resolution is used to select the
conversion function to be invoked. Assuming that “reference to cv1 T”
is the type of the reference being initialized, the candidate
functions are selected as follows:
(1.1) Let R be a set of types including
(1.1.1) “lvalue reference to cv2 T2” (when initializing an lvalue reference or an rvalue reference to function) and
(1.1.2) “cv2 T2” and “rvalue reference to cv2 T2” (when initializing an rvalue reference or an lvalue reference to function) for any T2.
The permissible types for non-explicit conversion functions are the
members of R where “cv1 T” is reference-compatible ([dcl.init.ref])
with “cv2 T2”. For direct-initialization, the permissible types for
explicit conversion functions are the members of R where T2 can be
converted to type T with a (possibly trivial) qualification conversion
([conv.qual]); otherwise there are none.
As far as I understood, I can say that when initializing an "lvalue reference to cv1 T" the conversion function is a candidate if and only if it returns "lvalue reference to cv2 T2", where “cv1 T” is reference-compatible with “cv2 T2”.
And when initializing an "rvalue reference to cv1 T", the conversion function is a candidate if and only if it returns "rvalue reference to cv2 T2" or "cv T2", where “cv1 T” is reference-compatible with “cv2 T2”. Right?
Assuming my understanding is correct, here is a question. Why do we even need a conversion function to convert from cv2 T2 to cv1 T even though “cv1 T” is reference-compatible with “cv2 T2”?
Can you clearly explain the bullet (1.1) with some examples?
|
Why do we even need a conversion function to convert from cv2 T2 to cv1 T even though “cv1 T” is reference-compatible with “cv2 T2”?
Because only after the conversion is done(using the conversion function), the result is of type cv2 T2. In other words, the result of using/calling the conversion function is cv2 T2 and not whatever expression you have before using the conversion function. This is the whole point of using a conversion function so that we can something that is reference compatible with cv1 T.
Lets look at some examples:
Example 1
struct C {
operator int&();
};
const int& ref= C();
In the above example, the type cv1 T = const int is not reference-compatible with the class-type C. But due to the presence of the conversion function C::operator int&(), a given C can be converted to an lvalue of type cv2 T2 = int. And we know that const int is reference compatible with int. This means that the reference ref can be bound to the result of the conversion function according to your quoted clause.
Example 2
This example 2 does not uses a conversion function but i've added this just to clarify the explanation given at the beginning of my answer.
double val = 4.55;
const int &ref = val;
In the above example, the type cv1 T = const int is not reference-compatible with the type double. And at the end, the reference ref is bound to a materialized temporary(prvalue) of type cv2 T2 = int. This is possible because const int is reference compatible with the type of the materialized temporary int.
The important thing to note here is that a temporary is materialized because originally cv1 T = const int was not reference compatible with double. But after the materialization, cv1 T = const int is reference compatible with the result cv2 T2 = int.
|
73,405,684
| 73,406,157
|
How would one specify a custom deleter for a shared_ptr constructed with an aliasing constructor?
|
How would one specify a custom deleter for a shared_ptr constructed with an aliasing constructor?
struct Bar {
// some data that we want to point to
};
struct Foo {
Bar bar;
};
shared_ptr<Foo> f = make_shared<Foo>(some, args, here);
shared_ptr<Bar> specific_data(f, &f->bar);
// ref count of the object pointed to by f is 2
f.reset();
// the Foo still exists (ref cnt == 1)
// so our Bar pointer is still valid, and we can use it for stuff
some_func_that_takes_bar(specific_data);
How will this line shared_ptr<Bar> specific_data(f, &f->bar); be modified to add a custom deleter?
|
It doesn't really make sense to add a custom deleter in the construction of the aliasing shared_ptr.
The deleter is associated with the managed object, not the specific shared_ptr instance that will actually call it. The deleter is stored together with the object in the shared control block.
So once all aliasing and non-aliasing shared_ptr instances to the shared object are destroyed, the last instance (whether it is aliasing or not) will call the deleter which was associated with the object when it was first put under shared_ptr control.
So to add a custom deleter for the Foo object, replace std::make_shared:
auto f = std::shared_ptr<Foo>(new Foo(some, args, here), some_deleter_here);
some_deleter_here will then be called with the Foo pointer as argument, even if the aliasing shared_ptr is the last to be destroyed.
Note however that if you are using a custom deleter, then you probably are not creating the pointer with a simple call to new. The only correct way to delete an object created with new is to call delete on it, which is what the default deleter already does.
|
73,405,703
| 73,405,954
|
Confused by local scope and function Parameters
|
Hello im confused by function parameters.
I've had a guy try and help me but i struggle to understand. I've been following learncpp
And local scope confuses me when it comes to parameters.
It says on learncpp, That if you declare a function
int foo(int x, int y) // int x and y are local
So How then can i access those parameters if it is local using a function.
Here is my code with what im struggling with.
double increaseSpeedControl(int Speed, int max) // int speed and int max are local
{ // local scope
if (Speed <= 100)
{
int max{ 100 };
while (Speed < max)
{
std::cout << "Increasing : " << Speed++ << std::endl;
}
}
else
{
return 0;
}
return Speed;
} // end of scope
int main()
{ // local scope
std::cout << "Set Current Speed :";
int sp{};
std::cin >> sp;
std::cout << "Speed Increased :" << increaseSpeedControl(sp, 100) << std::endl;
std::cout << "Now : " << sp;
// How then am i able to access increaseSpeedControl(sp, 100)
if inside the function is a local scope?
} // end local scope
This is really hard for me to grasp and i would appreciate some help.
|
From main's perspective, the function is a black box. The box has two holes labeled Speed and max. main inserts two int's and lets the box do its thing. Then the box spits out an int at the end for main. At no point can main see into that box to access Speed or max (those are local only to the box). main can only feed two values in and wait for one to be spat back out.
This is what we mean when we say that variables are "local." They exist only in the black box where no one outside of the scope can see them.
|
73,406,458
| 73,413,966
|
Is there an idiomatic way to solve small isolated independent task with CUDA?
|
I wrote my first CUDA program which I am trying to speed up. I ask myself if this is possible since the problem is not really appropriate for SMID-Processing (Single instruction, multiple data). It is more a "single function, multiple data" problem. I have many similar tasks to be solved independently.
My current approach is:
__device__ bool solve_one_task_on_device(TaskData* current){
// Do something completely independent of other threads (no SMID possible).
// In my case each task contains an array of 100 elements,
// the function loops over this array and often backtracks
// depending on its current array value until a solution is found.
}
__global__ void solve_all_tasks_in_parallel(TaskData* p, int count){
int i = blockIdx.x * blockDim.x + threadIdx.x ;
if(i < count) {
solve_one_task_on_device(&p[i]);
}
}
main {
...
// tasks_data is an array of e.g 4096 tasks (or more) copied to device memory
solve_all_tasks_in_parallel<<<64, 64>>>(tasks_data, tasks_data_count);
...
}
What would be the idiomatic way to do it? If it should be done at all.
I already read some threads about the topic. I have 512 CUDA cores. What I am less sure is if each CUDA Core can really independently solve a task so that
instructions are not synchronized. How many task-parallel threads can I start and what would be the recommended way to do the parallelization?
It is an experiment, I want to see if CUDA is useful for such problems at all.
Currently running my function in parallel on the CPU is much faster. I guess I cannot get similar performance on my GPU unless I have a SMID problem, correct?
My hardware is:
CPU: Xeon E5-4650L (16 Cores)
GPU: NVIDIA Quadro P620
CUDA Driver Version / Runtime Version 9.1 / 9.1
CUDA Capability Major/Minor version number: 6.1
|
I have 512 CUDA cores.
Remember "CUDA cores" is just NVIDIA marketing speech. You don't have 512 cores. A Quadro P620 has 4 cores; and on each of them, multiple warps of 32 threads each can execute the same instruction (for all 32). So, 4 warps, each executing an instruction, on each of 4 cores, makes 512. In practice, you usually get less than 512 instructions executing per clock cycle.
What I am less sure is if each CUDA Core can really independently solve a task so that instructions are not synchronized.
So, no. But if you arrange your tasks so that the logic is the same for many of them and only the data is different, then there's a good chance you'll be able to execute these tasks in parallel, effectively. Of course there are many other considerations, like data layout, access patterns etc to keep in mind.
On different cores, and even on the same core with different warps, you can run very different tasks, completely independently past the point in the kernel where you choose your task and code paths diverge.
|
73,407,650
| 73,407,991
|
Unexpected page fault when writing return value from assembly procedure
|
I am experimenting mixing assembly(x86) and C++.
I wrote a procedure in assembly and then called it from C++.
However, when writing the returned value to a local variable I get a write permission violation error.
#include <iostream>
// will return 1 if all ok and 0 if b is 0
extern "C" int integerMulDiv(int a, int b, int* prod, int* quo, int* rem);
int main() {
int a = 13, b = 4;
int p, q, r;
int res = integerMulDiv(a, b, &p, &q, &r);
std::cout << p << '\t' << q << '\t' << r << std::endl;
std::cout << res << std::endl << std::endl;
res = integerMulDiv(31, 0, &p, &q, &r);
std::cout << p << '\t' << q << '\t' << r << std::endl;
std::cout << res << std::endl << std::endl;
return 0;
}
The assembly procedure returns a few values through pointers and an int through RAX.
; Returns : 0 Error (division by 0)
; : 1 All ok
; *prod = a * b
; *quo = a / b
; *rem = a % b
integerMulDiv proc
push ebp
mov ebp, esp
push ebx ; save ebp and ebx
xor eax, eax
mov ecx, [ebp + 8] ; get a
mov edx, [ebp + 12] ; get b (the divisor)
or edx, edx ; check divisor
jz invalidDivizor
imul edx, ecx
mov ebx, [ebp + 16] ; get address of prod
mov [ebx], edx ; write prod
mov eax, ecx
cdq ; extend to edx
idiv dword ptr[ebx + 12]
mov ebx, [ebp + 20] ; get address of quo
mov [ebp], eax ; write quo
mov ebx, [ebp + 24] ; get address of rem
mov [ebp], edx ; write rem
mov eax, 1 ; set success
jmp returnFromProc
invalidDivizor:
mov eax, 0 ; set failed
returnFromProc:
pop ebx
pop ebp
ret ; restore and return
integerMulDiv endp
I get the error after the first call of integerMulDiv, when it tries to write the result in the res variable.
The disassembly looks like this:
int res = integerMulDiv(a, b, &p, &q, &r);
002D24BD lea eax,[r]
002D24C0 push eax
002D24C1 lea ecx,[q]
002D24C4 push ecx
002D24C5 lea edx,[p]
002D24C8 push edx
002D24C9 mov eax,dword ptr [b]
002D24CC push eax
002D24CD mov ecx,dword ptr [a]
002D24D0 push ecx
002D24D1 call _integerMulDiv (02D133Eh)
002D24D6 add esp,14h
002D24D9 mov dword ptr [res],eax <- The #PF happens here
Does anyone know what is happening and why?
|
The following section of code stands out to me.
idiv dword ptr[ebx + 12]
mov ebx, [ebp + 20] ; get address of quo
mov [ebp], eax ; write quo
mov ebx, [ebp + 24] ; get address of rem
mov [ebp], edx ; write rem
I am not sure you are wanting to divide by the contents of memory 12 bytes after the address of the product. Perhaps you meant [ebp + 12].
After that, you are loading addresses into ebx and then writing values to ebp.
|
73,407,671
| 73,407,910
|
Cannot find boost shared library files in Android application
|
For Intellij (and Android Studio) I built a JNI shared library that links to boost libraries that I'd link to include in my Android app. I called System.loadLibrary on my .so file but it fails to find boost libraries when I run it. I get the following error:
java.lang.UnsatisfiedLinkError: dlopen failed: library "libboost_unit_test_framework-clang-mt-x32-1_77.so.1.77.0" not found: needed by /data/app/~~28p8gv9ihFbZAejYd9c9yw==/sensoft.applications.dt1demo-0IEJ8o6cHOk0kputNbnbNQ==/base.apk!/lib/x86/libssi_utils_java.so in namespace classloader-namespace
Even though the boost .so files are there in the libs/x86 directory (I built them in x86 with the android toolchain to run on my emulator) but it did manage to find the .so file that I built in the same directory.
I placed my .so file and all the required boost .so files in the libs/x86 directory and included the following as a jni source in my build.gradle file:
sourceSets {
main.jniLibs.srcDirs = ['libs']
}
But my application can't seem to find the boost shared libraries specifically.
|
Android's install process will not extract libraries that don't have the suffix .so. You have to remove the version suffix of the library (which serves no purpose on Android anyway, because libraries are not all installed to a single common path).
|
73,408,359
| 73,408,426
|
What message is sent when user is trying to close window?
|
What message do i need to listen into my window procedure to close the GUI
when right-clicking into her taskbar button and clicking on X Close window?
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case ???:
{
//...
}
break;
}
Note: Im not referring to the X into the caption/title bar.
|
It's the same message you get when the user presses the [X] button in the caption bar, or chooses Close from the system menu: WM_CLOSE.
The documentation contains useful information. In particular:
An application can prompt the user for confirmation, prior to destroying a window, by processing the WM_CLOSE message and calling the DestroyWindow function only if the user confirms the choice.
By default, the DefWindowProc function calls the DestroyWindow function to destroy the window.
|
73,408,490
| 73,409,109
|
CMake: Properly setting up a multi-directory project with a library and executable project
|
I'm struggling with properly setting up my CMake project. I've been trying to fix this error for the past 2 days. I'm currently learning CMake so please, pardon a "nooby" question.
I have a library, let's call it "InternalLibrary" and an executable project, called "App". InternalLibrary uses a static library, let's call it "ExternalLibrary". Since I want to actively test InternalLibrary while developing it, I setup a multi-directory project.
Here's how directory structure looks like:
Root
├───App
│ └───src/
└───InternalLibrary
├───include/
├───Libs/
│ └───ExternalLibrary/
│ ├───include/
│ └───lib/
└───src/
Here's root's CMakeLists.txt:
cmake_minimum_required(VERSION 3.12)
project(LibraryProject)
add_subdirectory(InternalLibrary)
add_subdirectory(App)
InternalLibrary's CMakeLists.txt:
cmake_minimum_required(VERSION 3.12)
project(InternalLibrary)
set(CMAKE_CXX_STANDARD 17)
add_library(InternalLibrary STATIC ${CMAKE_CURRENT_SOURCE_DIR}/src/internallibrary.cpp)
target_include_directories(InternalLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Libs/ExternalLibrary/include)
target_include_directories(InternalLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(InternalLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Libs/ExternalLibrary/lib/ExternalLibrary)
App's CMakeLists.txt:
cmake_minimum_required(VERSION 3.12)
project(App)
set(CMAKE_CXX_STANDARD 17)
add_executable(App ${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp)
target_link_libraries(App InternalLibrary)
And as you can see, because InternalLibrary uses ExternalLibrary, when compiling there's an error:
No rule to make target 'DIRECTORY/Root/InternalLibrary/Libs/ExternalLibrary/lib/ExternalLibrary', needed by 'App/App.exe'. Stop.
There's no error when compiling InternalLibrary alone, so there's probably some thing I need to add in my App's CMakeLists.txt to tell CMake to include that ExternalLibrary used by InternalLibrary.
|
The parameters passed to the target_link_library command as any parameter other than the first one can be:
A library target name
A full path to a library file
A plain library name
[other stuff for different use cases]
Given the parameter you're passing in
target_link_libraries(InternalLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Libs/ExternalLibrary/lib/ExternalLibrary)
you're closest to the "a full path to a library file" case, but ExternalLibrary is not the name of the library, at least not for any common library type I know of. Possible file names could be e.g. (depending on the lib type and OS)
libExternalLibrary.so
libExternalLibrary.a
ExternalLibrary.lib
You could use the appropriate file name here.
# may need to be adjusted depending on the exact lib file name
target_link_libraries(InternalLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Libs/ExternalLibrary/lib/libExternalLibrary.so)
Alternatively you could specify a link directory and use the "A plain library name" option:
# add directory to search for libs
target_link_directories(InternalLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Libs/ExternalLibrary/lib)
# would find e.g. libExtenalLibrary.so in .../Libs/ExternalLibrary/lib
target_link_libraries(InternalLibrary PUBLIC ExternalLibrary)
|
73,408,517
| 73,409,143
|
Function that takes array of strings and returns the longest one
|
Trying to get this to work, but CodeBlocks gives me this error:
error: no matching function for call to 'max(char[4][10], int)'
Tried getting rid of template <>, made function to receive char*, nothing works.
How do I make this function to receive an array of strings (char[]), and spit out the longest one?
EDIT: Yeah, I missed that thing with index, now corrected. The problem is not gone.
#include <iostream>
#include <cstring>
template<class number>
number max(number numbers[], int n)
{
number maximum = numbers[0];
for (int i = 1; i < n; i++)
{
if (numbers[i] > maximum)
maximum = numbers[i];
}
return maximum;
}
template<>
char* max (char** strings, int n)
{
int maxlen = strlen(strings[0]);
int maxind = 0;
for (int i = 1; i < n; i++)
{
if (strlen(strings[i]) > maxlen)
{
maxlen = strlen(strings[i]);
maxind = i;
}
}
return strings[maxind];
}
int main()
{
char strings[4][10] = {"Cat", "Dog", "CANNIBALS", "Witch"};
int test_int[4] = {1, 2, 3, 4};
double test_dble[5] = {1.2, 3.1, 5223e11, 23, -1000.0};
std::cout << "int max(): " << max(test_int, 4) << std::endl;
std::cout << "double max(): " << max(test_dble, 5) << std::endl;
std::cout << "char** max(): " << max(strings, 4) << std::endl;
return 0;
}
|
If we simplify your code a lot we can boil it down to this:
#include <cstring>
char* max(char** strings, int n) { return nullptr; }
int main() {
char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
max(strings, 4);
return 0;
}
As Avi Berger pointed out char[4][10] isn't convertible to char**. The following would compile:
#include <cstring>
char* max(char (&strings)[4][10], int n) { return nullptr; }
int main() {
char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
max(strings, 4);
return 0;
}
Obviously this is only useful for char[4][10], you could make it more generic like this:
#include <cstring>
template <int a, int b>
char* max(char (&strings)[a][b], int n) { return nullptr; }
int main() {
char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
max(strings, 4);
return 0;
}
Now that we have a and b there is no point in passing in n, it might as well reduce to this:
#include <cstring>
template <int a, int b>
char* max(char (&strings)[a][b]) { return nullptr; }
int main() {
char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
max(strings);
return 0;
}
|
73,408,931
| 73,411,150
|
SWIG Converting a vector of vectors to a list of lists for Python, 'x' was not declared in this scope
|
I have a short c++ function that populates a vector of vectors when given inputs a,b which are rows and columns, like this
vec_of_vec.cpp
#include <iostream>
#include "vec_of_vec.h"
#include <vector>
std::vector<std::vector<int>> f(int a, int b) {
std::vector<std::vector<int>> mat;
for (int i = 0; i < a; i++)
{
// construct a vector of int
std::vector<int> v;
for (int j = 0; j < b; j++) {
v.push_back(j+i);
}
// push back above one-dimensional vector
mat.push_back(v);
}
return mat;
}
its header file
vec_of_vec.h
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
#include <vector>
#include <functional>
std::vector<std::vector<int>> f(int a,int b);
#endif
From here I want to call this code from python so I try and wrap it with SWIG. This is the interface file I've been using. I've taken inspiration from this post.
vec_of_vec.i
%module vec_of_vec
#define SWIGPYTHON_BUILTIN
%{
#include "vec_of_vec.h"
#include <vector>
%}
%include <std_vector.i>
%template(VectorOfInt) std::vector<int>;
%template(VectorOfStructVector) std::vector<std::vector<int> >;
%typemap(out) std::vector<std::vector<int>> (PyObject* _inner,PyObject* _outer) %{
// Allocate a PyList object of the requested size.
_outer = PyList_New($1.size());
// Populate the PyList. PyLong_FromLong converts a C++ "long" to a
// Python PyLong object.
for(int x = 0; x < $1.size(); x++)
_inner = PyList_New($1[x].size());
for(int y = 0; y < $1[x].size(); y++)
PyList_SetItem(_inner,y,PyLong_FromLong($1[x][y]));
PyList_SetItem(_outer,x,_inner);
$result = SWIG_Python_AppendOutput($result,_outer);
%}
%include "vec_of_vec.h"
This is the makefile:
all:
rm -f *.so *.o *_wrap.* *.pyc *.gch vec_of_vec.py
swig -c++ -python vec_of_vec.i
g++ -fpic -c vec_of_vec_wrap.cxx vec_of_vec.h vec_of_vec.cpp -I/usr/include/python3.8
g++ -shared vec_of_vec_wrap.o vec_of_vec.o -o _vec_of_vec.so
When I call this I get an error:
vec_of_vec_wrap.cxx: In function ‘PyObject* _wrap_f(PyObject*, PyObject*)’:
vec_of_vec_wrap.cxx:9412:3: error: expected initializer before ‘for’
9412 | for(x = 0; x < (&result)->size(); x++)
| ^~~
vec_of_vec_wrap.cxx:9412:40: error: expected ‘;’ before ‘)’ token
9412 | for(x = 0; x < (&result)->size(); x++)
| ^
| ;
vec_of_vec_wrap.cxx:9414:7: error: ‘y’ was not declared in this scope
9414 | for(y = 0; y < result[x].size(); y++)
| ^
make: *** [makefile:4: all] Error 1
However when I try and populate it manually, in the interface file, without a for loop, something similar to this:
%typemap(out) std::vector<std::vector<int>> (PyObject* _inner,PyObject* _outer) %{
// Allocate a PyList object of the requested size.
_outer = PyList_New($1.size());
_inner = PyList_New($1[0].size());
PyList_SetItem(_inner,0,PyLong_FromLong($1[0][0]));
PyList_SetItem(_inner,1,PyLong_FromLong($1[0][1]));
PyList_SetItem(_outer,0,_inner);
...
$result = SWIG_Python_AppendOutput($result,_outer);
%}
it returns a list of lists.
Another thing is that if i change %typemap(out) to %typemap(argout), I get a tuple of tuples back, but it works without errors.
If it's not obvious, I'm not very proficient with c++ or swig but I'm trying to find my way around it but can't figure it out for the life of me.
|
You were close, although the error message doesn't agree with the code shown or the error in the title. Code shown is for(int x = 0...) but error message is for(x = 0...). In the code shown you are missing the marked curly braces below in the %typemap(out) implementation:
%typemap(out) std::vector<std::vector<int>> (PyObject* _inner,PyObject* _outer) %{
// Allocate a PyList object of the requested size.
_outer = PyList_New($1.size());
// Populate the PyList. PyLong_FromLong converts a C++ "long" to a
// Python PyLong object.
for(int x = 0; x < $1.size(); x++) { // <<<<<<< MISSING
_inner = PyList_New($1[x].size());
for(int y = 0; y < $1[x].size(); y++)
PyList_SetItem(_inner,y,PyLong_FromLong($1[x][y]));
PyList_SetItem(_outer,x,_inner);
} // <<<<<<< MISSING
$result = SWIG_Python_AppendOutput($result,_outer);
%}
Output after fix:
>>> import vec_of_vec as vv
>>> vv.f(3,5)
[[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]
Note that your code worked with %typemap(argout) because there is a default %typemap(out) for the vector<vector<int>> template you declared that generates a tuple of tuples, and %typemap(argout) simply wasn't used. If a tuple of tuples is OK for you, then you don't need the %typemap(out) that outputs a list of lists.
|
73,409,118
| 73,409,378
|
std::enable_if_t and std::array implementation
|
How can I use this function? (syntax)
template<typename T, typename = std::enable_if_t<std::is_array_v<T>>>
void foo(T&& a)
{
std::cout << a.size() << std::endl;
}
because this is error
std::array<std::string, 3> arr { "1", "2", "3" };
foo<std::array<std::string, 3>>(arr);
this error too
std::array<std::string, 3> arr { "1", "2", "3" };
foo<>(arr);
this error too
std::array<std::string, 3> arr { "1", "2", "3" };
foo<std::array<std::string, 3>, 3>(arr);
link: https://godbolt.org/z/ToMeGe5d5
PS:
How to use exactly this function? How exactly can it be used, at least with C-style arrays?
This example is taken from the book C++ Templates. David Vandevoord and more...
Where it says that the first way is:
template<typename T, size_t N>
void foo(const T(&a)[N])
And the second one, just this one:
template<typename T, typename = std::enable_if_t<std::is_array_v<T>>>
void foo(T&& a)
|
That function is (almost[1]) uncallable as written:
std::is_array_v is only true for built-in C-style arrays. That is std::is_array_v<int[10]> is true, but std::is_array_v<std::array<int, 10>> is false.
Built-in C-style arrays do not have a size member function.
That means that for any parameter type that will satisfy your type constraint, the body of the function will fail to compile.
You don't really need a type constraint though. You can just make your parameter a std::array:
template<typename T, size_t N>
void foo(const std::array<T, N>& a)
{
std::cout << a.size() << std::endl;
}
int main()
{
std::array<int, 4> arr = {1, 2, 3, 4};
foo(arr); // prints 4
}
Or if you're trying to get the size of a built-in C-style array:
template<typename T, size_t N>
void foo(const T(&a)[N])
{
std::cout << N << std::endl;
}
int main()
{
int arr[] = {1, 2, 3, 4};
foo(arr); // prints 4
}
Since you seem dead-set on using this overly-complex (and somewhat incorrect) enable_if_t-based type check, you could re-write the body to work with built-in C-style arrays by doing something like this:
template <typename T, typename = std::enable_if_t<std::is_array_t<T>>>
void foo(T&& a)
{
std::cout << std::size(a) << '\n';
}
int main()
{
int arr[] = {1, 2, 3, 4};
foo(std::move(arr));
}
Note the seemingly unnecessary std::move. Your type constraint has yet another problem in that std::is_array_t<int(&)[]> is false. This causes the function to become invalid when the forwarding reference parameter deduces T to be a reference type, as is the case when the function is passed an lvalue. To avoid that problem, you can change the type constraint to check std::is_array_t<std::remove_reference_t<T>>, but if you're changing the signature at all you would be better off using the simpler version that simply accepts a T(&)[N] and deduces N.
Note also that the T(&)[N] overload of std::size was introduced in C++17. If using an older version of the language, you can implement your own array size function template as
template <typename T, size_t N>
size_t size(T(&)[N])
{
return N;
}
[1]: Technically foo<std::array<std::string, 3>&, void>(arr) works, but that's just because you've implemented the type check in such a way that it can be worked around by supplying something in place of the default template argument.
|
73,409,581
| 73,409,650
|
TMP using using-directives
|
Today I played around and tried to achieve template-meta-programming using using-directives.
So far I managed to write simple function calls, but nothing more.
#include <iostream>
template< int value_ > struct int_type { static constexpr int value = value_; operator int() { return value; } };
template< class lhs, class rhs > using lt = int_type <
(lhs::value < rhs::value) ? 1 : 0
>;
template< class lhs, class rhs > using plus = int_type <
lhs::value + rhs::value
>;
template< class val > using mm = int_type <
val::value - 1
>;
template< class val, template<class> typename func > using apply = func< val >;
int main() {
using i5 = int_type< 5 >;
using i3 = int_type< 3 >;
using x = apply< plus< i5, i3 >, mm >;
std::cout << x{};
}
Is there any way to make recursion in this manner. The following does not work:
template< class lhs, class rhs > using times2 = int_type <
lhs::value * rhs::value
>;
template< class first, class ... rest > using times = times2< first, times< rest...> >;
|
[temp.alias]/4 forbids this sort of thing.
The defining-type-id in an alias template declaration shall not refer to the alias template being declared. The type produced by an alias template specialization shall not directly or indirectly make use of that specialization.
So no, alias templates alone can't be recursive. You'd need something else (like the usual class template and typename Operation<T1, T2>::result TMP mechanism) somewhere in the cycle.
|
73,409,797
| 73,409,876
|
Why do I get 0xC0000374 (STATUS_HEAP_CORRUPTION) error when using qsort() function of std in C++, and how do I fix it?
|
It's a simple C++ test code, it will just sort the student structs by their studentId which is an integer:
#include <iostream>
using namespace std;
struct student {
int grade;
int studentId;
string name;
};
int studentIdCompareFunc(const void * student1, const void * student2);
int main()
{
const int ARRAY_SIZE = 10;
student studentArray[ARRAY_SIZE] = {
{81, 10009, "Aretha"},
{70, 10008, "Candy"},
{68, 10010, "Veronica"},
{78, 10004, "Sasha"},
{75, 10007, "Leslie"},
{100, 10003, "Alistair"},
{98, 10006, "Belinda"},
{84, 10005, "Erin"},
{28, 10002, "Tom"},
{87, 10001, "Fred"},
};
qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);
for (int i = 0; i < ARRAY_SIZE; i++)
{
cout << studentArray[i].studentId << " ";
}
}
int studentIdCompareFunc(const void * voidA, const void * voidB)
{
student* st1 = (student *) (voidA);
student* st2 = (student *) (voidB);
return st1->studentId - st2->studentId;
}
It prints the studentId integers as expected, but doesn't return zero, it returns -1072740940 (0xC0000374).
I tested by changing ARRAY_SIZE to 15, or increasing ARRAY_SIZE argument, but I still get the same result.
What's the cause of this error? How do I fix it?
|
qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);
qsort is a C library function and it knows absolutely nothing, whatsoever, about C++ classes. Like that std::string object in the structure this code is trying to sort. Undefined behavior, and hillarity, ensues.
If the intent here is to write C++ code, then use the C++ equivalent, std::sort, which is a native C++ algorithm:
#include <algorithm>
// ...
std::sort(studentArray, studentArray+ARRAY_SIZE,
[]
(const auto &a, const auto &b)
{
return a.studentId < b.studentId;
});
|
73,410,284
| 73,410,376
|
Why do I get weird stray errrors with cxxopts.hpp and meson + ninja build?
|
I'm currently working on this project. I'm using cxxopts.hpp in order to parse cli options but since I added it I get some error that I now list how to reproduce:
Build the project
$ meson build
$ cd build
$ ninja
Everything good so far, it builds without any errors.
I can change anything other than test/vector.cpp and test/random.cpp (that are the places where I'm using cxxopts.hpp) and build with ninja without any problems.
Then when I edit test/vector.cpp or test/random.cpp and do ninja these error appears:
[1/4] Compiling C++ object test/random.p/random.cpp.o
FAILED: test/random.p/random.cpp.o
c++ -Itest/random.p -Itest -I../test -I../include -fdiagnostics-color=always -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -Wnon-virtual-dtor -Wextra -Wpedantic -O0 -g -MD -MQ test/random.p/random.cpp.o -MF test/random.p/random.cpp.o.d -o test/random.p/random.cpp.o -c ../test/random.cpp
In file included from ../include/cxxopts.hpp:43,
from ../test/random.cpp:6:
test/vector:1:1: error: stray ‘\177’ in program
1 | <U+007F>ELF<U+0002><U+0001><U+0001><U+0003><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0003><U+0000>><U+0000><U+0001><U+0000><U+0000><U+0000> F<U+0000><U+0000><U+0000><U+0000><U+0000><U+0000>@<U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><90><91><U+0015><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000>@<U+0000>8<U+0000><U+000D><U+0000>@<U+0000>(<U+0000>'<U+0000><U+0006><U+0000><U+0000><U+0000><U+0004><U+0000><U+0000><U+0000>@<U+0000><U+0000><U+0000><U+0000><U+0000><U+0000><U+0000>@<U+0000><U+0000><U+0000><U+0000>...
(a very lengthy error up to 400 MB in a file)
Any idea on how to fix this or why this happens in the first place?
|
As pointed out by @KamilCuk in their comment, this error emerged from a name collision between the standard library #include <vector> and the binary vector I was creating from vector.cpp.
Changing the name of my binary solves the issue.
EDIT:
The desired behavior can be also achieved by setting the option implicit_include_directories to false like this:
vector = executable('vector', 'vector.cpp', include_directories: incdir, implicit_include_directories: false)
|
73,410,421
| 73,410,515
|
Moving a vector of unique_ptrs bug
|
I've always used std::move to move a std::vector into an empty one in member initialization lists like this:
class Bar{};
class Foo
{
public:
Foo(std::vector<std::unique_ptr<Bar>>&& t_values)
: m_Values{ std::move(t_values) }
{
}
private:
std::vector<std::unique_ptr<Bar>> m_Values{};
};
I thought that the std::move in the constructor would clear the t_values vector, but recently I've discovered a bug that does not clear the t_values vector and causes unexpected behaviour e.g. destroying the vectors elements before they should be (std::swap would fix this issue). Is it not required by the standard for the moved vector to be empty?
|
A move results in a "valid but unspecified state":
Moved-from state of library types [lib.types.movedfrom]
Objects of types defined in the C++ standard library may be moved from.
Move operations may be explicitly specified or implicitly generated. Unless
otherwise specified, such moved-from objects shall be placed in a valid
but unspecified state.
A moved-from vector can certainly be empty, that would be "valid". But nothing in the C++ standard requires that. In the case of a moved-from vector of std::unique_ptrs, it would also be "valid" if the moved-from vector remains non-empty, but now has some indeterminate number of default-constructed std::unique_ptrs (the moved-from vector's size can remain the same, or may be different). The original std::unique_ptrs are now in the moved-to vector, and the moved-from vector has some default-constructed std::unique_ptrs. No rules are broken. The moved-from vector is in a "valid" state.
For various practical reasons, it's extremely unlikely for a moved-from vector in any typical C++ library implementation to behave this way, in this case. That's very unlikely. But it would be valid, if it were the case, provided that the overall state is still valid. It would not be valid for both the moved-from and the moved-to vector of std::unique_ptrs to end up with std::unique_ptrs to the same objects.
If you're observing spurious, or extra, object construction or destruction, it must be due to undefined behavior of some other source. There's nothing wrong with the shown code. If there's undefined behavior, it must be in code that's not shown.
|
73,410,428
| 73,484,006
|
Within qmake how can I get the full path to static library created by a subproject?
|
I am currently using qmake to build an application. The project is structured to have some sub libraries. So my project looks like this:
--root project (.pro file)
--app
|_ pro file and cpp/h files
--core
|_ pro file and cpp/h files
--gui
|_ pro file and cpp/h files
When the build runs, it outputs the static libraries from each of these sub projects to a default location as follows.
$$top_builddir/src/core/common/debug/
$$top_builddir/src/core/helpers/debug/
$$top_builddir/src/core/models/debug/
$$top_builddir/src/core/services/debug/
$$top_builddir/src/gui/forms/debug/
$$top_builddir/src/gui/widgets/debug/
So, when building my app and linking to the LIBS I do this:
unix|win32: LIBS += \
-L$$top_builddir/src/core/common/debug/ -lcommon \
-L$$top_builddir/src/core/helpers/debug/ -lhelpers \
-L$$top_builddir/src/core/models/debug/ -lmodels \
-L$$top_builddir/src/core/services/debug/ -lservices \
-L$$top_builddir/src/gui/forms/debug/ -lforms \
-L$$top_builddir/src/gui/widgets/debug/ -lwidgets
I can turn "debug" into a variable that is populated based off the config in order to dynamically build this path to be either debug or release. I could also set the destination directory for each project (DESTDIR) to something known based on my build config, store it in a variable, and then use that.
But I want to ask if this is the best way to handle this, or there a better way? I'm worried I am overlooking a simpler way to specify where my app should look for the static libraries it depends on.
|
In my projects I use the solution as you suggested:
I can turn "debug" into a variable that is populated based off the config in order to dynamically build this path to be either debug or release.
The .pro file code example:
CONFIG(debug, debug|release) : BUILD_TYPE = debug
CONFIG(release, debug|release) : BUILD_TYPE = release
LIBS += -L$${LIB_DIR}/mylib/$${BUILD_TYPE} -lmylib
I think it is a comprehensible and good way to handle this case.
|
73,411,110
| 73,670,742
|
MPI Matrix Multiplication - Task sharing when size(of procs) < rows of matrix
|
I am trying to perform matrix-matrix multiplication in MPI using c++.
I have coded for the cases where number_of_processes = number_of_rows_of_matrix_A (so that rows of matrix_A is sent across all processes and matrix_B is Broadcasted to all processes to perform subset calculation and they are sent back to root process for accumulation of all results into Matrix_C) and I have also coded for the case when number_of_processes > number_of_rows_of_Matrix_A
I have no idea how to approach for the case when number_of_processes < rows_of_matrix_A.
Lets say I have 4 processes and 8 * 8 matrix_A and matrix_B. I can easily allocate first 4 rows to respective ranks of processes, i.e 0,1,2,3. How should I allocate the remaining rows so that I wont mess up with synchronization of the results which I get from respective processes.
Side note of my implementation:
I have used only MPI_Recv, MPI_Send for all the coding part which I have done.
Thanks in advance.
|
From getting suggestion from people here, I came to the below solution.
floor(N * (j + 1)/P) - floor(N * j/P)
Where :
N : Number of rows in matrix
P : Total number of processes available
j : jth process. (i.e if P = 4, j = 0,1,2,3)
|
73,411,359
| 73,411,416
|
Why am I unable to use my increment operator overload? [C++]
|
I have the following struct:
struct sequence_t {
uint8_t val;
explicit sequence_t(uint8_t value) : val(value) {}
sequence_t() : sequence_t(0) {}
auto operator++() -> sequence_t& { // prefix
val = (val + 1) % 16;
return *this;
}
auto operator++(int) -> sequence_t { // postfix
sequence_t tmp{val};
++*this;
return tmp;
}
uint8_t value() const { return val; }
auto operator==(const sequence_t& other) const -> bool = default;
auto operator==(const uint8_t other) const -> bool { return val == other; }
};
And I use it inside a class declared like this:
class messenger {
private:
sequence_t sequence;
public:
messenger() = default;
~messenger() = default;
auto make_message(const uint8_t type) const -> std::shared_ptr<std::uint8_t[]>;
auto make_message(uint8_t const* data, const uint8_t size) const -> std::shared_ptr<std::uint8_t[]>;
auto parity(uint8_t const* buffer) const -> std::uint8_t;
};
I am calling the operator in the make_message() member of the messenger class because I want to update the value of the sequence (to the whole messenger object) when I create a message:
auto messenger::make_message(uint8_t const* data, const uint8_t data_size) const -> std::shared_ptr<std::uint8_t[]> {
auto buffer = std::make_shared<std::uint8_t[]>(sizeof(header) + data_size + sizeof(parity(nullptr)));
++sequence;
header h = {START, data_size, sequence.value(), TYPE_DATA}; // TODO: implementar sequência
std::copy(std::bit_cast<uint8_t*>(&h), std::bit_cast<uint8_t*>(&h) + sizeof(header), buffer.get());
std::copy(data, data + data_size, buffer.get() + sizeof(header));
buffer[sizeof(header) + data_size] = parity(buffer.get());
return buffer;
}
But when I try to use sequence++ or ++sequence inside the messenger class methods I get the following error:
error: passing ‘const sequence_t’ as ‘this’ argument discards qualifiers [-fpermissive]
[build] 17 | ++sequence;
[build] | ^~~~~~~~
Why is it const? How can I modify the content of my sequence?
|
auto messenger::make_message(uint8_t const* data, const uint8_t data_size) const
That const keyword at the end signifies that this is a const class method. A const class method:
Can only call other const class methods
Cannot modify any class members
If any class members are objects, only their const methods can be called
(ignoring explicitly mutable class members, to avoid confusion)
++sequence effectively calls a sequence's method. As per rule 3, it is not a const class method, hence the compilation error.
You have the following options:
change make_message() to not be a const class method.
given the sample usage here, it might be feasible to declare sequence as a mutable class member. You must fully understand the repercussions of doing so.
|
73,411,437
| 73,440,182
|
Accessing Function from a Nested Include in C++
|
Trying to understand more complex project structure in C++. This is for an nrf52840 (embedded 2.4Ghz radio device). But the question is about C++ but using it for an example.
Say I have 5 files I created:
1) main.cpp
2) mouse.cpp
3) mouse.h
4) radio_controls.cpp
5) radio_controls.h
There is also a .h I included:
1) esb.h
In esb.h there is a function called esb_set_rf_channel(int) which is used to set a frequency on the radio device to receive and transmit on. I included it in radio_controls.h since I use functions defined in esb.h in the radio_controls.h and radio_controls.cpp.
I included radio_controls.h in mouse.cpp since I need to control the radio device for the mouse to mostly transmit move commands.
Is this even proper? What is the recommended standard? I now can call esb_set_channel(int) directly in mouse.cpp but the intent was to have all the radio stuff in radio_controls and maybe have a helper member function call it for me from radio_controls. I also want to avoid including header files too many times where you might start to run into issues since esb.h is not my file as a project gets larger I could see this as an issue.
Edit: Code for more clarity. Main problem is I need a structure from esb.h in radio_controls.h. Maybe I could have a struct of my own for the settings I want to change and have the implantation file create the esb.h struct on the stack? This seems terrible too.
radio_controls.h
#ifndef RADIO_CONTROLS_H
#define RADIO_CONTROLS_H
#include <esb.h>
class RadioControls {
private:
esb_config config; // this structure is from esb.h (this is why I need the #include <esb.h> here
// config changes from default that need to be added by mouse
// and need to set RF
//config.retransmit_delay = 250; // lower retransmit delay from default of 600
//config.event_handler = event_handler; // add radio event handler
int clocks_start(void); // start HF clock (needed for ESB to work)
int esb_initialize(void); // initialize esb radio
// want a structure for esb initialize values to be passed in
// rx and tx payloads
static struct esb_payload rx_payload;
static struct esb_payload tx_payload;
public:
RadioControls(); // initialize radio on nrf device
int esb_set_rf_channel(uint32_t channel); // set rf channel to first element in array of unifying
// could be a helper function like set_rf(uint32 channel); and implementation file calls esb.h defined one
}; // namespace controls::radio
#endif // RADIO_CONTROLS_H
#ifndef MOUSE_H
#define MOUSE_H
/*
* Initialize mouse.
*
* And need to restore any settings from
flash.
*
*/
class mouse {
private:
// restore mouse settings from flash
public:
Mouse(); // create unifying mouse
// ~Mouse(); // reset to default and disable
// int move_mouse(); // x, y mouse move command
// initialize esb radio
// set radio to default settings for mouse
// this includes RF, address for pipes, etc.
};
#endif // MOUSE_H
|
@Steve4879, yes, There's a way to use structures from the esb.h. You can use forward declaration for it. Take a look:
#pragma once
#include <memory>
class ClassFromLibrary;
struct StructFromLibrary;
namespace controls::radio {
std::shared_ptr<ClassFromLibrary> makeClassFromLib(const StructFromLibrary &data);
// here will be error:
ClassFromLibrary makeClassFromLib(StructFromLibrary data);
// Because the forward declared classes can only be pointers or referencies
} // namespace controls::radio
|
73,411,698
| 73,412,242
|
OpenMP parallel iteration over STL unordered_map VS2022
|
I am trying to parallelize my sparse square matrix self multiplication. For instance, I want to compute:
R = A * A
where R and A are sparse matrices. These sparse matrices are represented using 2d unordered_map, where A[i][j] corresponds to the (i,j)-th element. Also i and j are the keys of the corresponding 2d unordered_map. Unfortunately, the OpenMP's #pragma omp parallel for doesn't seem to work in my code below... (this code is part of my smatrix class definition).
std::pair<int, int> shape;
std::unordered_map<int, std::unordered_map<int, mpreal>> nzel;
smatrix smul(void)
{
smatrix result(shape);
#pragma omp parallel for
for (int row = 0; row < shape.first; row++)
{
auto& c = result.nzel[row];
for (const auto& [k1, v1] : nzel[row])
for (const auto& [k2, v2] : nzel[k1])
c[k2] += v1 * v2;
}
return result;
}
What is my problem? I am still new to OpenMP, but I seriously need to make my code parallel. Your help is much appreciated.
|
You don't say how your code "doesn't work".
I'm guessing it doesn't compile: OpenMP needs a random-access iterator, and unordered map is not.
However, you're mapping int to a sparse row. Why not make that an array of sparse rows?
You have a race condition on your output array so the results will be incorrect. You need to rewrite this. Sparse matrix-matrix is not a simple operation.
|
73,412,127
| 73,412,337
|
How do I preserve inter-string null characters in std::format string
|
In an attempt to refactor this code:
static const auto opf_str = [&]() {
std::string result;
for(auto& e : extension_list) {
result.append(StringUtils::ToUpperCase(e.substr(1)) + " file (*"s + e + ")\0*"s + e + "\0"s);
}
result += "All Files (*.*)\0*.*\0\0"s;
return result;
}();
I replaced the std::string::operator+ joins with std::format:
static const auto opf_str = [&]() {
std::string result;
for(auto e : extension_list) {
result.append(std::format("{0} file (*{1})\0*{1}\0", StringUtils::ToUpperCase(e.substr(1)), e));
}
result += "All Files (*.*)\0*.*\0\0"s;
return result;
}();
But the internal null characters (which are required for how OPENFILENAME works) are being stripped in the std::format version.
Changing the format string to an actual std::string causes a compiler error because the string isn't a compile-time constant.
|
std::string as argument doesn't work, but at least std::string_view should be fine. There is no issue with having it even as the result of a constant expression if it is referencing only static objects:
std::format("{0} file (*{1})\0*{1}\0"sv, StringUtils::ToUpperCase(e.substr(1)), e)
Looking a the current draft specification of std::basic_format_string it is indeed impossible to use a std::string as format string to std::format, even if its construction is a constant expression. As an alternative it is of course always possible to use std::vformat instead, which doesn't perform the compile-time checks. (It is in the end not really surprising since the consteval construction of the std::basic_format_string would need to copy the string contents, but can't rely on storing the result in dynamic memory.)
|
73,412,140
| 73,412,514
|
Why can std::find_if potentially fail with std::bad_alloc exception?
|
As I stated in the title, I just can't understand why does this function throw std::bad_alloc. If we take a look at the cppreference all of the three possible implementations are just as someone would assume and it looks like there is no special need dynamic memory allocation.
|
The 3 possible implementations shown in cppreference are for the 3 overloads that do not take an execution policy. It is specifically the overloads that do take an execution policy that are specifically listed as possibly throwing std::bad_alloc.
Execution policy involves the possibility of parallelizing or vectorizing the operation. That would require extra memory to pull off rather than just relying on the scalar variables in the non parallelized/vectorized version.
Edit: That said, as @user17732522 said in comments:
The default is that a standard library function without noexcept
specification is allowed to throw implementation-defined exceptions
(see eel.is/c++draft/res.on.exception.handling#4) and find_if doesn't
have any "Throws:" clause constraining that
(eel.is/c++draft/alg.find).
So an implementation is allowed to provide a std::find that does throw for any of the overloads.
|
73,412,333
| 73,412,802
|
Throw and Catch in c++
|
(c++)So my throw code is like
throw "No paper"
And my catch code is
catch(const char *txt ){}
My question is why we are using a pointer to define the catch type and why char, can't we use something like
catch(string txt){}
I just learn exception handling and can't figure out why they used a pointer.
here is the code!
|
When you throw a C string literal like "No paper" you are actually throwing a pointer of type const char* and not an array of characters. This is how C++ works.
In other words, a string literal automatically decays into a const char*. It doesn't magically turn into a std::string or something like that when the catch parameter receives it.
And technically speaking, it's usually more efficient to throw an 8 byte pointer rather than to throw a 32 byte std::string. The bigger the size of an object is, the more costly it is to copy it around during the exception handling process.
|
73,412,515
| 73,434,692
|
How to get global mouse position in Qt6?
|
I'm trying to get global position of the mouse however the functions mentioned in older topics are either deprecated or not working as intended. I have tried QCursor::pos() as seen below but it didn't work as intended.
#include <QtCore/QCoreApplication>
#include <QCursor>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
while(1)
{
std::cout << QCursor::pos().x() << " " << QCursor::pos().y() << std::endl;
}
return a.exec();
}
Output: 2147483647 2147483647
|
It is very simple. QCursor is in the Gui module of Qt see here, so you have to change QCoreApplication to QGuiApplication and then it works (already tested it).
|
73,413,425
| 73,413,578
|
How to write a void function for different Structs/Containers with a template?
|
For instance I have a function
void func(my_cont &C){
C.membA = 1;
C.membB = 2;
dosomething_with(C);
}
Also what to do in the function, if I have a Struct that does not have a member B?
|
This is a way to statically check for the existence of a membB member inside the template function.
template<typename T>
void func(T& C)
{
C.membA = 1;
if constexpr (requires() { C.membB; })
{
C.membB = 2;
}
}
int main()
{
struct A
{
int membA;
};
struct B
{
int membA;
int membB;
};
A a;
func(a);
B b;
func(b);
}
Another way to get functionality that differs per type:
Using template specialization, as OP requested.
struct A
{
int membA;
};
struct B
{
int membA;
int membB;
};
template<typename T> void func(T&);
template<> void func<A>(A& a) {
a.membA = 1;
}
template<> void func<B>(B& b) {
b.membA = 1;
b.membB = 2;
}
int main()
{
A a;
func(a);
B b;
func(b);
}
|
73,413,518
| 73,432,109
|
Could golang implement this interview question of getting array summary without for/while if/else?
|
I'm looking into an interesting interview question, and try to implement it with go.
(1) Input an integer number, say i
(2) Calculate the summary of 1+2+...+i, output the summary
(3) Requirement: don't use multiply, don't use loop(for/while), and don't use if/else
Well, in c++ or java this is pretty easy. We can use static variable to initialize an object array, while the objects's constructor function calculate this summary. Like this:
#include <iostream>
struct s {
static int count;
static int sum;
s() {++count; sum += count;}
};
int s::count = 0;
int s::sum = 0;
int main(int argc, char *argv[]) {
s obj[10];
std::cout << s::sum << std::endl; // 55, ok
return 0;
}
(2) in c++ we could also use template type deduction to do this. Plenty samples on the internet.
But, can we achieve this with go language?
I know that golang has neither constructor function, nor it supports static variable. And it doesn't have any template syntax. Plus, using recursive function still requires if branches in the code.
So is this possible to do same thing in go? (no for loop, no if else). Thanks.
|
Here's a language-neutral solution that uses no multiplication, no for and no if.
It's kind of like a recursive solution, where the if is substituted with a function map, having functions for the true and false branches:
fs := map[bool]func(int) int{}
fs[false] = func(int) int { return 0 }
fs[true] = func(i int) int { return i + fs[i > 1](i-1) }
var i int
fmt.Scanln(&i)
fmt.Println("sum:", fs[i > 0](i))
Inputting 10, the output is (try it on the Go Playground):
sum: 55
|
73,414,499
| 73,415,853
|
Parallel programming with C++ and MPI -- same executable possible?
|
I would like to create a program that would work with both MPI and without at run time and I have reached a point where I think that is not possible.
For example, an MPI program might look like this:
#include <mpi.h>
int main(int argc, char* argv[])
{
MPI_Init(&argc, &argv);
...
MPI_Finalize ();
return 0;
}
But in order to allow users who don't have MPI installed to compile this, I would have to wrap it around #if's:
// Somewhere here, pull in a .h file which would set HAVE_MPI to 0 or 1
#if HAVE_MPI
#include <mpi.h>
#endif
int main(int argc, char* argv[])
{
#if HAVE_MPI
MPI_Init(&argc, &argv);
#endif
...
#if HAVE_MPI
MPI_Finalize ();
#endif
return 0;
}
Until now, I think I'm correct? If this program compiled to a.out with HAVE_MPI set to 1, it would be run as: mpirun -np 4 ./a.out or mpirun -np 1 ./a.out. It could never be run as ./a.out, because even if it isn't run within mpirun, it would call the MPI_* functions.
I guess to achieve what I would like -- an executable that could be run with and without mpirun is not possible. And the only option is to create two separate executables -- one with HAVE_MPI set to 0 and another set to 1. Is this correct or am I missing something about how C++ programs using MPI are implemented?
As a side-note, I don't think this is true with shared memory parallelization (i.e., with OpenMP). The same executable should work with a single or multiple threads.
Is my understanding correct?
|
A compiled MPI program needs MPI libraries at runtime in addition to the mpirun call (not required by all MPI implementations for 1 process nor in all cases). Thus, to run MPI function only in some cases at runtime without having a dependency to MPI, the potion of the code using MPI needs to be dynamically loaded. This can be done by putting MPI-related functions in shared library components and loading them at runtime regarding your needs.
The same thing is also true for OpenMP: an OpenMP code requires OpenMP compiler flags like -fopenmp creating a dependency to an OpenMP implementation required at runtime. That being said, the common GOMP (GCC) runtime or the IOMP runtime (ICC/Clang) are often installed on most Linux computing machines by default (especially the former since GCC is generally the default compiler and is bundled with GOMP).
Using shared library help you to easily switch between two parallel implementations: MPI and OpenMP. That being said, it means the initialization, finalization and communication collectives must be wrapped in an external library compiled separately of your program. The library functions can be loaded dynamically at startup time or manually at runtime using dlopen (see this related post).
As pointed out in the comments, using preprocessor directives are parsed at compile time and this is why you need to rebuild your program twice when using them. This is not required with shared libraries (though all diverging parts to be executed at runtime needs to be compiled separately).
|
73,415,591
| 73,416,484
|
How to Write more than one data on same cell when export to excell?
|
I'm us'ng Qxlsx for export data to excell. Day, month and year data are not coming as a whole, but separately. I can print them one by one while printing them in excel. How can I combine these 3 data and print it?
here is my code for export
for (i = 0; i < maxRowCount; ++i) // get maximum data row
{
//strList.clear();
for (j = 0; j < 7; ++j)
{
/*
j[0] = Temp Değeri
j[1] = Humadity
j[2] = Day
j[3] = moon
j[4] = Year
j[5] = Second
j[6] = Minute
j[7] = Hour
*/
if (i < dataColums[j].count()) {
format.setNumberFormatIndex(2); // for save as number format
if (j == 0)
{
xlsx.write(k, 3, dataColums[j][i], format);
}
else if(j==1)
{
xlsx.write(k, 4, dataColums[j][i], format);
}
else if(j==2 )
{
//here I need write day moon and year when j=2 But I cannot write 3 data on same time.
}
}
k = k + 1;
}
|
Sounds like you just want QString::arg:
xlsx.write(k, 5, QString("%1/%2/%3").arg(dataColums[4][i]).arg(dataColums[3][i]).arg(dataColums[2][i]));
As an aside, you can make your code a lot cleaner if you eliminate the for-switch pattern:
format.setNumberFormatIndex(2);
for (int j = 0; j < 8; j++) {
maxRowCount = min(maxRowCount, dataColums[j].count());
}
for (i = 0; i < maxRowCount; i++, k++) {
xlsx.write(k, 3, dataColums[0][i], format);
xlsx.write(k, 4, dataColums[1][i], format);
xlsx.write(k, 5, QString("%1/%2/%3").arg(dataColums[4][i]).arg(dataColums[3][i]).arg(dataColums[2][i]));
}
|
73,415,953
| 73,415,985
|
How to instantiate and rename a template class
|
Description
I declared a template class
template <typename T,size_t RootNum>
class Tree;
And I want to specialize another template class BinaryTree, whose RootNum is 2, but every members is identicial with class Tree.
An inelegant method is defining a class BinaryTree inherits class Tree as below
template <typename T>
class BinaryTree: public Tree<T,2>{};
But I vaguely remember that it exists a declaration simillar to this style to 'elegantly' specialize a template class:
template <typename T>
typedef Tree<T,2> BinaryTree;
Actually the above code is invalid. I wonder is there a keyword-like to concisely achive this operation.
Thank you for your kind suggession.
|
You are looking for an alias template:
template <typename T>
using BinaryTree = Tree<T,2>;
|
73,416,040
| 73,416,427
|
cmake disabling MSVC incremental linking
|
Background
I have some project which after a while (many builds when developing) consumes so many computer resources during linking process. So much that my machine becomes unresponsive (even mouse do not move).
My project has many static libraries (4) targets and many executable (2 are production excusable and 4 for testing purposes).
Quick googling indicated that problem is incremental linking. I've found this as solution for cmake. And applied fix from answer:
cmake -A x64 -Thost=x64 -DCMAKE_BUILD_TYPE=Debug -G "Visual Studio 16 2019" .. ^
-DCMAKE_EXE_LINKER_FLAGS_DEBUG="/DEBUG /INCREMENTAL:NO" ^
-DCMAKE_EXE_LINKER_FLAGS_RELEASE="/DEBUG /INCREMENTAL:NO" ^
-DCMAKE_STATIC_LINKER_FLAGS_DEBUG="/DEBUG /INCREMENTAL:NO" ^
-DCMAKE_STATIC_LINKER_FLAGS_RELEASE="/DEBUG /INCREMENTAL:NO" ^
-DCMAKE_SHARED_LINKER_FLAGS_DEBUG="/DEBUG /INCREMENTAL:NO" ^
-DCMAKE_SHARED_LINKER_FLAGS_RELEASE="/DEBUG /INCREMENTAL:NO" ^
-DCMAKE_MODULE_LINKER_FLAGS_DEBUG="/DEBUG /INCREMENTAL:NO" ^
-DCMAKE_MODULE_LINKER_FLAGS_RELEASE="/DEBUG /INCREMENTAL:NO"
Problem
So far my machine do not show any signs of hangs, but in build logs I see this:
Generating Code...
LINK : warning LNK4044: unrecognized option '/DEBUG'; ignored [F:\repos\Src\build64\Project\Project.vcxproj]
LINK : warning LNK4044: unrecognized option '/INCREMENTAL:NO'; ignored [F:\repos\Src\build64\Project\Project.vcxproj]
Based on MSVC linker documentation this should be fine!
Question
How it is possible I have this logs? Did I disabled incremental linking or not (just data do not grow enough to cause a problem)? If I didn't how I can fix this problem?
|
For the static linker flags you do not need to add those options. In case of MSVC lib.exe is used as static linker and that one does not understand these options.
For most projects of mine I use inside the CMakeLists.txt the add_link_options command to let CMake properly add the link options to the linker commands.
add_link_options(
/LARGEADDRESSAWARE
/DEBUG
$<$<NOT:$<CONFIG:DEBUG>>:/INCREMENTAL:NO> # Disable incremental linking.
$<$<NOT:$<CONFIG:DEBUG>>:/OPT:REF> # Remove unreferenced functions and data.
$<$<NOT:$<CONFIG:DEBUG>>:/OPT:ICF> # Identical COMDAT folding.
$<$<CONFIG:DEBUG>:/INCREMENTAL> # Do incremental linking.
$<$<CONFIG:DEBUG>:/OPT:NOREF> # No unreferenced data elimination.
$<$<CONFIG:DEBUG>:/OPT:NOICF> # No Identical COMDAT folding.
)
|
73,416,712
| 73,416,777
|
Why is lock_guard a template?
|
I just learned about std::lock_guard and I was wondering why it is a template.
Until now I have only seen std::lock_guard<std::mutex> with std::mutex inside the angle brackets.
|
Using std::lock_guard<std::mutex> is indeed quite common.
But you can use std::lock_guard with other mutex types:
Various standard mutex types, e.g.: std::recursive_mutex.
Your own mutex type. You can use any type, as long as it is a BasicLockable, i.e. it supports the required methods: lock(), unlock().
|
73,417,828
| 73,418,313
|
Explicit copy constructor of a parameter passed via std::async
|
In the following program foo function is executed asynchronously and its argument of type A is copied inside async by value:
#include <future>
struct A {
A() = default;
explicit A(const A &) = default;
};
void foo(const A &) {}
int main() {
auto f = std::async(std::launch::async, foo, A{});
}
Despite copy-constructor of A is explicit, the program is accepted in the latest MSVC and in libstdc++ from GCC 10. But starting from GCC 11 the program is rejected with the
error: could not convert '{std::forward<void (&)(const A&)>((* & __args#0)), std::forward<A>((* & __args#1))}' from '<brace-enclosed initializer list>' to 'std::tuple<void (*)(const A&), A>'
1693 | _M_fn{{std::forward<_Args>(__args)...}}
Online demo: https://gcc.godbolt.org/z/r3PsoaxT7
Is GCC 11 more correct here or it is a regression?
|
In the post-C++20 draft (https://timsong-cpp.github.io/cppwp/n4868/futures.async) there is a "Mandates:" clause which effectively only requires std::is_move_constructible_v<A> to be satisfied. This tests whether a declaration of the form
A a(std::declval<A&&>());
would be well-formed, which it is even with explicit on the constructor. Therefore the "Mandates:"-clause is satisfied. (If it was not, the program would be ill-formed.)
However there is also a "Precondition:" clause effectively requiring A to be Cpp17MoveConstructible. This library concept has the effective requirement that
A a = rv;
where rv is a rvalue of type A (see https://timsong-cpp.github.io/cppwp/n4868/library#tab:cpp17.moveconstructible), is well-formed. This is not the case here, since this is copy-initialization which doesn't consider explicit constructors. Theferore the "Precondition:" clause is not satisfied, which causes the program to have undefined behavior.
As a result both behaviors are conforming.
However, in the current draft the precondition has been removed with resolution of LWG issue 3476 (draft commit) and I don't see anything else that would forbid the type from being usable as an argument to std::async. The arguments are now specified to be constructed with auto(/*...*/) which does consider explicit constructors. The resolution of the mentioned issue explicitly says that no other copy/move should be allowed either.
|
73,418,366
| 73,420,706
|
searching for the maximum number between two indexes in an array of numbers
|
I want to calculate the maximum number between two indexes in an array in an efficient way. I will be given a very large number of queries in each query I will be given indexes l and r where I need to find the maximum number between these two indexes
when I tried to solve that problem my solution had a time complexity of o((l-r)*q) where q is the number of queries
#include <bits/stdc++.h>
using namespace std;
int main()
{
int number = 1e6;
vector <int> v(number);
// the user should enter the elements of the vector
for(auto &i : v) cin >> i;
int number_of_queries=1e6;
for(int i=0; i < number_of_queries; ++i)
{
int left_index,right_index,max_number = -1;
//the user should enter the left and the right index (base zero)
cin >> left_index >> right_index;
//searching between the indexes for the maximum number between them
for(int j=left_index ; j <= right_index; ++j) max_number=max(max_number,v[j]);
//printing the number
cout << max_number << "\n";
}
}
That's what I came up with
I want to know if there is a way to decrease the time complexity by maybe doing some operations on the array before starting
note that the array contains only positive numbers and it can contain the same number more than one time
Thank you in advance
|
when I tried to solve that problem my solution had a time complexity of O((l-r)*q) where q is the number of queries
The only real way to reduce this is if the queries overlap. Then we need some way to store some kind of intermediate result (the max element of some given sub-range) so we can reuse it.
The general approach to reusing intermediate results is called dynamic programming, and the specific technique is to memoize a naive function, caching its result for later reuse.
Note that pre-computing maxima for fixed-size partitions adds a fixed (and possibly very large) overhead, but offers no guarantee about the hit rate - most of that effort could be wasted if we get a billion queries for the same small range.
In order to memoize results in this case, we need to chunk them. Only whole chunks can be easily reused.
So, your solution is:
choose a partition size - say we notionally divide our million elements into 100-element chunks
a small power of 2 like 16, 32 or 64 is probably optimal in practice, but I'm using round numbers for the example
write the naive max_in_chunk function (which, as mentioned in comments, is really just calling std::max_element)
now that this is a fixed-size chunk, there's a chance the compiler can vectorize it, which is always nice, but it's a secondary consideration to the memoization below
memoize that function with a wrapper, say memo_max_in_chunk, like
// index must be a multiple of 100 or whatever chunk size we selected
unsigned memo_max_in_chunk(size_t index)
{
static std::unordered_map<size_t, unsigned> memo;
auto lookup = memo.insert({index, 0});
auto &value = lookup.first->second; // value stored in map
if (lookup.second)
{
// insertion succeeded => we don't have an existing result
value = max_in_chunk(index);
}
return value;
}
It's a little hairy, so read the documentation until you understand it.
For your top-level loop, you now need to split the range [left_index, right_index] into three sections:
the prefix, from left_index to the lowest multiple of 100 between left_index and right_index
the suffix, from the highest multiple of 100 between left_index and right_index, to right_index
a series of 100-element chunks in between them
Now you can calculate the prefix_max and suffix_max naively, and call memo_max_in_chunk for each of the chunks between. Note that any of the prefix, suffix and chunk sections may be empty.
Finally just take the max of the prefix_max, suffix_max and all the chunk maxima.
Note that there are various optimizations that may improve the actual speed of this (like the vectorization mentioned, or, with some effort, using async evaluation of chunk maxima), but none of them change the complexity.
Even memoization won't improve the complexity if the queries are all smaller than our selected chunk size or never overlap, and there's not a lot we can do about that.
|
73,418,382
| 73,418,505
|
how to only indent brackets after case labels using clang-format
|
I wanna a style that only indent brackets after case labels, while keeping case label not indented.
this is what I want:
switch(a)
{
case 1:
{
do_some_thing();
}
break;
}
I find an option IndentCaseLabels, but it will the whole things include the case label, neither true or false isn't what I want
true:
switch(a)
{
case 1:
{
do_some_thing();
}
break;
}
false:
switch(a)
{
case 1:
{
do_some_thing();
}
break;
}
Is this style possible in clang-format? If is, how could I Configure it?
|
It's just immediate above one you found in the manual.
IndentCaseBlocks: true
Indent case label blocks one level from the case label.
false: true:
switch (fool) { vs. switch (fool) {
case 1: { case 1:
bar(); {
} break; bar();
default: { }
plop(); break;
} default:
} {
plop();
}
|
73,418,423
| 73,438,321
|
MacPorts /opt/local/bin/python3 can't find _libiconv symbol unless run under shell
|
I just updated macOS to Monterey 12.5 and updated MacPorts as described here. I have MacPorts python38, python39 and python310 installed. Each exhibits the same new bad behavior.
I have a C++ program that writes a small Python script into a file and then runs a Python interpreter as a child process, specifying the full pathnames for both the desired Python interpreter and that script file. (This is for self-tests, and it has worked well for years. I'm interested in resolving the problem, not in alternative structures.)
If I run that same command under the shell, either by hand or via std::system(), the script runs as I expect, as it always used to.
But when I directly execute the command under my C++ program, bypassing the shell, the Python interpeter fails to load with:
dyld[54748]: Symbol not found: (_libiconv)
Referenced from: '/opt/local/lib/libintl.8.dylib'
Expected in: '/usr/lib/libiconv.2.dylib'
I must emphasize that this used to work until this week's macOS update. It's not the C++ library; I get the same behavior from two different library implementations.
You might reasonably think that the new MacPorts libintl.8.dylib contains a bad reference to /usr/lib/libiconv.2.dylib, which in fact no longer exists. But:
$ otool -L /opt/local/lib/libintl.8.dylib
/opt/local/lib/libintl.8.dylib:
/opt/local/lib/libintl.8.dylib (compatibility version 11.0.0, current version 11.0.0)
/opt/local/lib/libiconv.2.dylib (compatibility version 9.0.0, current version 9.1.0)
/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 1853.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1311.0.0)
So maybe the bad reference would be in /opt/local/lib/libiconv.2.dylib ?
$ otool -L /opt/local/lib/libiconv.2.dylib
/opt/local/lib/libiconv.2.dylib:
/opt/local/lib/libiconv.2.dylib (compatibility version 9.0.0, current version 9.1.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1311.0.0)
I don't even understand the mechanism of the error here, never mind how to resolve it. Help very much appreciated!
|
The only situation where macOS' loader would search /usr/lib/libiconv.2.dylib for a symbol that /opt/local/lib/libintl.8.dylib expects in /opt/local/lib/libiconv.2.dylib is when you have DYLD_LIBRARY_PATH set to include /usr/lib. This variable causes dyld (the macOS loader) to ignore the absolute path of /opt/local/lib/libiconv.2.dylib and instead search for files called libiconv.2.dylib in all paths specified in DYLD_LIBRARY_PATH.
Since libraries are referenced using absolute paths on macOS, setting DYLD_LIBRARY_PATH is usually not necessary. If it is necessary, you should try setting DYLD_FALLBACK_LIBRARY_PATH first, since it does not cause the issue you are seeing.
Ideally, you would avoid the need to set the environment variable by modifying whatever binary requires you to set it. To do that, change the binary to reference its libraries using absolute paths. Use install_name_tool's -change option to fix an existing binary, or relink the binary after fixing the offending library's ID load command (either using install_name_tool -id or by setting the -install_name linker option to an absolute path when linking the library).
The reason why this starts working when run through a Shell is probably macOS' System Integrity Protection. Apple ships all binaries in /usr/bin with a flag that causes the loader to ignore and strip all DYLD_* environment variables, so that they always run using the libraries Apple intended them to use. Your shell is likely either /bin/sh or /bin/zsh and also has this mode bit set, which means any DYLD_LIBRARY_PATH variable that was set when executing the shell was removed from the environment. Note that the same mechanism also prevents you from seeing DYLD_LIBRARY_PATH when you run env (because that's /usr/bin/env also has the bit). Use set | grep DYLD in a running shell instead.
Finally, the reason why /usr/lib/libiconv.2.dylib and /opt/local/lib/libiconv.2.dylib contain different symbols is because Apple sets a define that causes symbols to not have the lib prefix (i.e., the symbol is called _iconv in /usr/lib/libiconv.2.dylib) and MacPorts just uses the configuration that you'd get by default from upstream. A #define in a header file makes this different transparent to users. I'm not sure why the iconv developers have chosen to provide this mechanism. I can only speculate that this is some kind of mechanism that ensures the headers that were used to compile match the library that is being linked and loaded.
|
73,418,551
| 73,420,180
|
C++ inherit class as static
|
After reading through How to write a Java-enum-like class with multiple data fields in C++? I decided to give it a try and added some functionality to it. In order to abstract this functionality I've put it in a separate class EnumClass<T>. But since these abstracted features have to be static in the implementation but not in the original class I would need to do something like:
class Planet : public static EnumClass<Planet>
Which is not allowed. Is there some other way to do this? I got around it by adding a static instance of EnumClass<Planet> to Planet, but it is not really optimal:
template<class T, uint64_t S>
class EnumClass {
public:
const T elements[S];
const uint64_t length = S;
template<typename F>
const T find(F lambda) const {
for (int i = 0; i < S; i++) {
if (lambda(elements[i])) {
return elements[i];
}
}
return NULL;
}
};
template <class T, class... U>
EnumClass(T, U...) -> EnumClass<T, 1 + sizeof...(U)>;
class Planet {
public:
static const Planet MERCURY;
static const Planet VENUS;
static constexpr EnumClass ENUM = { &MERCURY, &VENUS };
private:
double massValue;
double radiusValue;
private:
Planet(double massValue, double radiusValue) {
this->massValue = massValue;
this->radiusValue = radiusValue;
}
public:
double mass() const {
return this->massValue;
}
double radius() const {
return this->radiusValue;
}
static const Planet* findByMass(double massValue) {
return ENUM.find([massValue](const Planet * element) { return element->mass() == massValue; });
}
static const Planet* findByRadius(double radiusValue) {
return ENUM.find([radiusValue](const Planet * element) { return element->radius() == radiusValue; });
}
};
// Enum value DEFINITIONS
const Planet Planet::MERCURY = Planet(3.303e+23, 2.4397e6);
const Planet Planet::VENUS = Planet(4.869e+24, 6.0518e6);
|
If you want members of EnumClass to be static then just make them static. static as in class Planet : public static EnumClass<Planet> does not make sense. You cannot turn non-static members into static members like that.
#include <array>
#include <iostream>
#include <cstddef>
template<class T,size_t S>
class EnumClass {
public:
static const std::array<const T*,S> elements;
static const size_t length = S;
template<typename F>
static const T* find(F lambda) {
for (int i = 0; i < S; i++) {
if (lambda(elements[i])) {
return elements[i];
}
}
return NULL;
}
};
class Planet : EnumClass<Planet,2> {
public:
static const Planet MERCURY;
static const Planet VENUS;
//static constexpr EnumClass ENUM = { &MERCURY, &VENUS };
private:
double massValue;
double radiusValue;
private:
Planet(double massValue, double radiusValue) {
this->massValue = massValue;
this->radiusValue = radiusValue;
}
public:
double mass() const {
return this->massValue;
}
double radius() const {
return this->radiusValue;
}
static const Planet* findByMass(double massValue) {
return find([massValue](const Planet * element) { return element->mass() == massValue; });
}
static const Planet* findByRadius(double radiusValue) {
return find([radiusValue](const Planet * element) { return element->radius() == radiusValue; });
}
};
// Enum value DEFINITIONS
const Planet Planet::MERCURY = Planet(3.303e+23, 2.4397e6);
const Planet Planet::VENUS = Planet(4.869e+24, 6.0518e6);
template <>
const std::array<const Planet*,2> EnumClass<Planet,2>::elements{{&Planet::MERCURY,&Planet::VENUS}};
|
73,418,590
| 73,423,517
|
Legality of using delete-expression on a pointer not obtained from usual new
|
I wonder if this code is legal:
delete new (operator new(1)) char;
This code does the same thing, but doesn't use delete expression on a pointer obtained from placement new:
void* p = operator new(1);
new (p) char;
delete static_cast<char*>(p);
The standard rules at [expr.delete#2]:
In a single-object delete expression, the value of the operand of delete may be a null pointer value, a pointer value that resulted from a previous non-array new-expression, or a pointer to a base class subobject of an object created by such a new-expression. If not, the behavior is undefined. In an array delete expression, the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression.68 If not, the behavior is undefined.
The standard does not say that new-expression does not include placement new. So I think according to the standard, the first piece of code should be legal, but the second should be illegal. Is my idea correct?
Why the standard says that? Calling operator new and constructing an object on it does almost the same thing as the new expression, but using the delete expression on the obtained pointer is not necessarily legal.
For allocating an array, the standard seems to allow this:
delete[] new (operator new[](2)) char[2];
But it should be illegal due to unspecified overhead.
Why does the standard allow that?
EDIT: According to [intro.object]/13:
Any implicit or explicit invocation of a function named operator new or operator new[] implicitly creates objects in the returned region of storage and returns a pointer to a suitable created object.
So I can even write the following code:
delete static_cast<char*>(operator new(1));
It destroys the implicitly created char object and deallocates the memory, doing the same thing as the examples above. But it's definitely illegal according to the standard because no new-expression is used.
Why doesn't the standard allow that?
|
delete new (operator new(1)) char; does appear to be legal. Like you said, the standard does not make any exceptions for placement new.
Your second example is also legal:
void* p = operator new(1);
new (p) char;
delete static_cast<char*>(p);
Let's walk through what happens step by step. The call to operator new implicitly creates a char object and returns a pointer to said object1. So p starts out already pointing to a char object. The placement new expression constructs a new char object over the old one, ending the lifetime of the old object; according to the rules of the abstract machine, this magically changes the value of p such that it points to this new object; see [basic.life]/8. Finally, static_cast<char*>(p) returns a pointer pointing to that same char object. That is, this pointer has the same value as the pointer that was returned by the placement new. So if the first example is valid, so is this one.
Note that [expr.delete]/2 does not suggest that in order for an operand to delete to be valid, there must be some sort of valid "chain of custody" from a new expression to the value that is now being deleted. It merely says "... a pointer value that resulted from a previous non-array new-expression..." The value of the pointer is all that matters. In your second example, p has the same value as the pointer returned from the placement new, thanks to [basic.life]/8.
Regarding your third example, delete[] new (operator new(2)) char[2];, I agree that it shouldn't be legal. I suggest filing a defect report.
1 See [intro.object]/13.
|
73,419,022
| 73,419,673
|
Android JNI GetMethodID for sharedPreferences.getString
|
I'm trying to get a string from sharedPreferences on Android from C++ code using JNI. I can successfully get the MethodID for getBoolean with this code:
jmethodID getBooleanMethodID = JEnv->GetMethodID(sharedPreferencesClass, "getBoolean", "(Ljava/lang/String;Z)Z");
The getBoolean function is defined in Java as getBoolean(String key, boolean defValue)
But I can't figure out how to correctly format the GetMethodID arguments for getString.
The getString function is defined in Java as getString(String key, String defValue)
I've tried:
jmethodID getStringMethodID = JEnv->GetMethodID(sharedPreferencesClass, "getString", "(Ljava/lang/String;Ljava/lang/String)");
Can someone provide the correct way to format the argument param for getString?
|
The correct format turned out to be:
jmethodID getStringMethodID = JEnv->GetMethodID(sharedPreferencesClass, "getString", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
There were a couple issues with my original attemps. First, the second String arg inside the brackets needed a semi-colon. Then I needed to add the return type, also a String, and be sure that it had a semi-colon at the end too.
|
73,419,663
| 73,434,976
|
QTabwidget click tab event C++
|
I am new in QT 4 C++ .I have QT 4 form with QTabwidget like in th picture below.
enter image description here
I want to disply on console the string "aa" by selecting tab on clicking it.
Here is my newForm.h
#ifndef _NEWFORM_H
#define _NEWFORM_H
#include "qwidget.h"
#include "ui_newForm.h"
class newForm : public QDialog {
Q_OBJECT
public:
newForm();
virtual ~newForm();
private:
Ui::newForm widget;
};
#endif /* _NEWFORM_H */
_________________________________________________________________________________________
Here is my main.cpp
#include <QApplication>
#include "newForm.h"
int main(int argc, char *argv[]) {
// initialize resources, if needed
// Q_INIT_RESOURCE(resfile);
QApplication app(argc, argv);
newForm *a = new newForm();
a->show();
// create and show your widgets here
return app.exec();
}
Here is my newForm.cpp
#include "newForm.h"
#include <iostream>
#include <QDebug>
newForm::newForm() {
connect(widget.tabWidget, SIGNAL(stateChanged()), this, SLOT(onTabChanged(int)));
widget.setupUi(this);
}
newForm::~newForm() {
}
void newForm::onTabChanged(int ){
qDebug()<<"aa"<<"\n";
}
On selecting new tab it is not displaying "aa"?How to qDebug() "aa" on console?
|
First of all, why are you using Qt 4 in 2022?
Next thing use currentIndexChanged(int) istead of stateChanged().
Did you also noticed that stateChanged() doesnt pass an interger which is needed for onTabChanged(int).
You also connected widget.tabWidget which isn't initilized yet.
This code might work:
newForm.h
#ifndef _NEWFORM_H
#define _NEWFORM_H
#include "qwidget.h"
namespace Ui { class newForm; };
class newForm : public QDialog {
Q_OBJECT
public:
newForm();
~newForm();
private:
Ui::newForm *widget;
};
#endif /* _NEWFORM_H */
newForm.cpp
#include "newForm.h"
#include "ui_newForm.h"
#include <QDebug>
newForm::newForm()
: widget(new Ui::newForm)
{
widget->setupUi(this);
connect(widget->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));
}
void newForm::onTabChanged(int ){
qDebug() << "aa";
}
newForm::~newForm() {
delete widget;
}
main.cpp
#include <QApplication>
#include "newForm.h"
int main(int argc, char *argv[]) {
// initialize resources, if needed
// Q_INIT_RESOURCE(resfile);
QApplication app(argc, argv);
newForm a;
a.show();
// create and show your widgets here
return app.exec();
}
|
73,419,669
| 73,549,652
|
How to get the mangled symbol of a function in C++?
|
Context
I'm using dlmopen to load multiple instance of a shared library which I can't modify (proprietary). I do this because this library is not thread-compatible, so I need an independent version of it to be loaded for each thread.
void *handle = dlmopen(LM_ID_NEWLM, "/myLib.so", RTLD_LAZY);
In order to get the function I need, I call dlsym :
void * test_load = dlsym(handle, <function_symbol>);
My question is :
How do i get <function_symbol> knowing that :
My library is in C++ (aka the function symbol is mangled)
I can't modify the library (aka no extern "C" to get a predicable symbol)
I know that dlopen/dlmopen is initialy meant to be used in C, not C++, but unless there is an other way to load many time the same shared library, I am stuck
|
How do i get <function_symbol> knowing that
Presumably you know which function you want to call. Let's say its name is somelib::Init(int, char**).
Find that function address:
nm -CD libsomelib.so | grep 'somelib::Init\(int, char\*\*\).
This should produce something like 12345fa T somelib::Init...
Find its mangled name of that symbol: nm -D libsomelib.so | grep '^12345fa '.
This should produce something like 12345fa T _ZN7somelib4InitEiPPc.
Use the mangled name in the dlsym call.
There is no way to map somelib::Init(int, char**) to its mangled name because that mapping is not a 1:1 and depends on the exact compiler used to build libsomelib.so.
|
73,419,997
| 73,420,127
|
Generate a random amount of numbers and sort them with bubble sort
|
I am new to programming and I am trying to generate an amount of numbers b and then sorting it with bubble sort without using the sort function of list (Because that would be too easy). Since arrays must have a constant value and I cannot put b as the value I'm trying to put the numbers into a list first and then converting the list into a dynamic array to later use bubble sort. How would I convert list1 into an array here?
#include "Log.h"
#include <array>
#include <list>
#include <ctime>
#include <memory>
using namespace std;
void Initlog();
void Log(const char* message);
int main();```
int main()
{
Initlog();
int a;
int b;
list<int> list1;
cout << "Give how many numbers to generate: "; // Gibt an wie viele Zahlen generiert werden
cin >> b;
cout << "Give the biggest possible outcome: "; // Gibt an wie gro? die größte Zahl sein kann
cin >> a;
srand(time(0)); // Damit die Zahlen auch halbwegs random sind
for (int i = 0; i < b; i++) // Der Loop der solange macht, bis b erreicht ist
{
int x = rand()%a; // a steht für die größtmögliche Zahl, x ist was rauskommt
cout << x << "\n"; // alle entstandenen Zahlen werden angezeigt
list1.push_back(x); // Zahlen werden in eine Liste links nach rechts gesteckt
}
cout << "The list after inserting all elements is : ";
for (list<int>::iterator i = list1.begin(); i != list1.end(); i++)
cout << *i << " "; // Inhalt der Liste wird ausgelesen
cout << endl;
std::cin.get();
}
|
Prefer to use std::vector<int>:
std::vector<int> data;
for (int index = 0; index < b; ++index)
{
int x = rand() % a;
std::cout << x << "\n";
data.push_back(x);
}
// The std::vector can be treated as an array.
To answer your question about converting std::list to an array:
std::list<int>::iterator iter = list1.begin();
std::list<int>::iterator end_iter = list1.end();
int * pointer_to_array = new int [list1.size()];
for (int *p = pointer_to_array;
iter != end_iter;
++iter)
{
*p++ = *iter;
}
The code above is one of many techniques to convert a std::list to an array. The array must use dynamic memory because the quantity of data is not known at compile time.
Note: prefer std::vector because it handles memory allocation and deallocation for you.
|
73,420,175
| 73,420,364
|
Fold expresion & CRTP
|
I'm writing this small application trying to test about fold expressions and i can't get it to compile, it complaints about ambiguous request on method Play, i don't understand why the signature of the function Play should be different on both calls..
#include <iostream>
#include <any>
using namespace std;
struct A
{
void play() const
{
std::cout << "A..." << std::endl;
}
};
struct B
{
void play() const
{
std::cout << "B..." << std::endl;
}
};
template<typename TKey>
struct BaseValue
{
void Play(const TKey& arg)
{
arg.play();
}
};
template<typename... Keys>
struct MyMap : public BaseValue<Keys>...
{
};
int main()
{
MyMap<A, B> oMyMap;
A a;
oMyMap.Play(a)
return 0;
}
|
Beside the constness mentioned in the comment, the fix is
template<typename... Keys>
struct MyMap : public BaseValue<Keys>...
{
using BaseValue<Keys>::Play ...;
};
The initial problem, has to do with name-lookup, which happens before overload resolution, see [this answer] https://stackoverflow.com/a/60775944/2412846) and the linked duplicates.
|
73,420,352
| 73,420,646
|
How to see intermediate files created during C++ compilation process
|
When building an application in C++, I want to see all my intermediary files generated during the process like .o file, .i file, .asm file etc. But when I jump into explorer in windows, it shows nothing even after I try to show "hidden files".
I tried to read one SO post but it is involving some CMake thing.
Can these files be seen without using the CMake ? If yes How?
|
Just use the -save-temps compiler option. From the man page:
-save-temps
Store the usual "temporary" intermediate files permanently; name
them as auxiliary output files, as specified described under
-dumpbase and -dumpdir.
There are a bunch of other options to influence which files and what name they will get. But for learning purposes that is usually more than enough.
|
73,420,763
| 73,421,142
|
deducing variadic inheritance type from constructor
|
I have a struct that can have a variadic number of members by inheriting from them:
struct A{ int a; };
struct B{ float b; };
struct C{ const char* c; };
template<typename ... Ts>
struct collection : Ts... {
};
int main() {
collection<A, B, C> n;
n.a = 5;
n.b = 0.5f;
n.c = "123";
}
now I want to use the initializer-list constructor:
auto n = collection<A, B, C>{ 5, 0.5f, "123" };
but I have to name the templates A, B, C. The compiler should figure this out.
I want to achieve this:
auto n = collection{ 5, 0.5f, "123" };
but this doesn't work
main.cpp(8,1): error C3770: 'int': is not a valid base class
main.cpp(12): message : see reference to class template instantiation 'collection<int,float,const char *>' being compiled
main.cpp(8,1): error C3770: 'float': is not a valid base class
main.cpp(8,1): error C3770: 'const char *': is not a valid base class
main.cpp(12,38): error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'collection<int,float,const char *>'
main.cpp(12,21): message : Invalid aggregate initialization
Visual Studio 2022 17.3.0, /std:c++latest, Debug x64
Is there a (clean) way to deduce the right type? It should be possible with the right constructor, since all underlying types are uniquely assignable.
|
You can do this using a user defined deduction guide and a couple "meta functions" to map the parameter type to the desired class type. First the meta functions get declared like
A type_map(int);
B type_map(float);
C type_map(const char*);
and then we can create a deduction guide in the form of
template<typename... Ts>
collection(Ts... ts) -> collection<decltype(type_map(ts))...>;
and now
auto n = collection{ 5, 0.5f, "123" };
will have n being a collection<A, B, C> as seen in this live exmaple
A "meta function" is the term I use for a function that doesn't actually do anything, it is just used to map one type into another. The are only ever called in an unevaluated context like in decltype in the above example.
|
73,420,945
| 74,254,696
|
Air control for mouse movement to change direction mid-air after jumping
|
I'm working on a custom character in Unreal Engine 5. I want the player to have his velocity direction based on mouse movement when he is in the air.
For example, when you jump forward and move your mouse right, he should follow the new direction, but if you jump backwards and move your mouse right, it will change direction towards where your back is looking.
|
I created a custom character movement component and overrode CalcVelocity() method:
// AirControl = 0;
// AirControlBoostMultiplier = 0;
// AirControlBoostVelocityThreshold = 0;
void UCustomCharacterMovementComponent::CalcVelocity(const float DeltaTime, const float Friction, const bool bFluid, const float BrakingDeceleration)
{
Super::CalcVelocity(DeltaTime, Friction, bFluid, BrakingDeceleration);
if (IsMovingOnGround() && Velocity.Size() > 0) {
const FVector NewDirection = UKismetMathLibrary::InverseTransformDirection(GetActorTransform(), Velocity);
LastYawOnGround = FMath::CeilToInt(FRotationMatrix::MakeFromX(NewDirection).Rotator().Yaw);
}
// Air control for mouse movement to change direction mid-air after jumping
if (!IsMovingOnGround()) {
FVector VelocityDirection;
const bool IsMovingForward = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, -22, 0) || UKismetMathLibrary::InRange_IntInt(LastYawOnGround, 0, 22);
const bool IsMovingForwardRight = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, 23, 67);
const bool IsMovingRight = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, 68, 112);
const bool IsMovingBackwardRight = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, 113, 157);
const bool IsMovingBackward = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, -180, -158) || UKismetMathLibrary::InRange_IntInt(LastYawOnGround, 158, 180);
const bool IsMovingBackwardLeft = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, -157, -113);
const bool IsMovingLeft = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, -112, -68);
const bool IsMovingForwardLeft = UKismetMathLibrary::InRange_IntInt(LastYawOnGround, -67, -23);
if (IsMovingForward) {
VelocityDirection = UpdatedComponent->GetForwardVector();
} else if (IsMovingBackward) {
VelocityDirection = -UpdatedComponent->GetForwardVector();
} else if (IsMovingRight) {
VelocityDirection = UpdatedComponent->GetRightVector();
} else if (IsMovingLeft) {
VelocityDirection = -UpdatedComponent->GetRightVector();
} else {
if (IsMovingForwardRight) {
VelocityDirection = UpdatedComponent->GetForwardVector() + UpdatedComponent->GetRightVector();
} else if (IsMovingForwardLeft) {
VelocityDirection = UpdatedComponent->GetForwardVector() - UpdatedComponent->GetRightVector();
} else if (IsMovingBackwardRight) {
VelocityDirection = UpdatedComponent->GetRightVector() - UpdatedComponent->GetForwardVector();
} else if (IsMovingBackwardLeft) {
VelocityDirection = -(UpdatedComponent->GetForwardVector() + UpdatedComponent->GetRightVector());
}
VelocityDirection = UKismetMathLibrary::Normal(VelocityDirection / 2);
}
Velocity -= Velocity - VelocityDirection * Velocity.Size();
}
}
|
73,421,127
| 73,421,180
|
Simple C++ code returns different outputs on different compilers
|
I wrote a program in C++ that receives 2 strings as input and checks if one is the inverse of the other.
#include<iostream>
#include<string>
int main() {
std::string word, word_inv;
std::cin >> word;
std::cin >> word_inv;
int n=word.size(), i=0;
while(word_inv[i] == word[n-i-1])
i++;
std::cout << ((i == n) ? "YES" : "NO") << std::endl;
}
However it gives different results on different compilers. For the input tests: code+edoc it prints "YES" on my computer but "NO" in the other.
I ran g++ -std=c++17 -Wshadow -Wall -o bin/program src/prog.cpp -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG -g and this is the output:
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/string:3341:30: runtime error: addition of unsigned offset to 0x00016ce73760 overflowed to 0x00016ce7375f
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/string:3341:30 in
=================================================================
==7114==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x00016ce7375f at pc 0x000102f8d750 bp 0x00016ce73730 sp 0x00016ce73728
READ of size 1 at 0x00016ce7375f thread T0
#0 0x102f8d74c in main 41A.cpp:12
#1 0x188a8542c in start+0x0 (libdyld.dylib:arm64e+0x1842c)
Address 0x00016ce7375f is located in stack of thread T0 at offset 31 in frame
#0 0x102f8d428 in main 41A.cpp:6
This frame has 2 object(s):
[32, 56) 'word' (line 7) <== Memory access at offset 31 underflows this variable
[96, 120) 'word_inv' (line 7)
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-underflow 41A.cpp:12 in main
Shadow bytes around the buggy address:
0x00702d9ee690: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702d9ee6a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702d9ee6b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702d9ee6c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702d9ee6d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x00702d9ee6e0: 00 00 00 00 00 00 00 00 f1 f1 f1[f1]00 00 00 f2
0x00702d9ee6f0: f2 f2 f2 f2 00 00 00 f3 f3 f3 f3 f3 00 00 00 00
0x00702d9ee700: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702d9ee710: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702d9ee720: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702d9ee730: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Shadow gap: cc
==7114==ABORTING
|
while(word_inv[i] == word[n-i-1])
This condition requires word_inv[i] to not be equal to word[n-i-1] for the loop to end. What if that doesn't happen while the indices are within bounds?
What happens then is that the program tries to read memory out of bounds with undefined behavior as a result, which means that anything could happen. It could look like it's working while compiling with one compiler but not another. The apparent look that it's working could also stop the next day even if you use the same compiler as the day before.
You need to make sure that i and n-i-1 are within bounds. If they are not, exit the loop.
Something that might help while developing these things is to use the bounds checking accessors. Many standard classes that provides operator[], like std::string, also provide the member function at. Using that in your program would look like this:
while (word_inv.at(i) == word.at(n - i - 1)) i++;
This will throw an exception (independent of which compiler you use) and the exception message for at is often very informative.
|
73,421,277
| 73,421,799
|
How does a shared_ptr handle copy to a pure virtual base class?
|
Class B expects to receive an instance of shared_ptr<IError>.
Class A implements IError and is passed by value to the constructor of B.
I would like to understand how this scenario is handled. How does the shared_ptr as a template class handle the conversion to IError?
In a simple case where B receives shared_ptr<A> I assume the copy constructor is called and the reference counter is increased. However since IError is pure virtual a normal copy constructor invocation seems not to be case here?
// Example program
#include <iostream>
#include <string>
class IError
{
public:
virtual ~IError(){};
virtual void OnError() = 0;
};
class A : public IError
{
public:
A(){};
void OnError(){std::cout << "Error Occured" << std::endl;}
};
class B
{
public:
B(std::shared_ptr<IError> errorReporter): mErrorReporter(errorReporter){}
void Action(){mErrorReporter->OnError();}
private:
std::shared_ptr<IError> mErrorReporter;
};
int main()
{
auto objA = std::make_shared<A>();
auto objB = std::make_shared<B>(objA);
objB->Action();
}
|
Debugging time! Let's find out what happens by using the tools we have available as developers.
The memory of the shared_ptr objA looks like this (type &objA in the memory window; it will be replaced by its address):
It has a pointer to the object (000002172badd8e0) and a pointer to the control block.
The control block looks like this (copy and paste the second value into a new memory window):
It has a pointer to the allocator (first 2 columns), the reference count (1) and the weak reference count (0 + offset 1).
After objB has been created, the control block of objA has changed to a reference count of 2:
And the shared_ptr objB looks like this:
It points to the a shared pointer and to the control block.
The shared pointer in objB points to the same object as before (000002172badd8e0), so no copy of the actual object has been made.
The control block of objB indicates that objB only has a reference count of 1:
a normal copy constructor invocation seems not to be case here?
Correct. No copy of the object is made, as we can confirm with a debugger. But a copy of the shared_ptr has been made.
|
73,421,698
| 73,479,188
|
C++ client socket send from port change with send to change?
|
I have a UDP based server/client application where on initial communication, the client sends a message to the server (on specific IP/port), then the server replies with a new port to talk to. The client then sends another message to the new port (same server IP as before), and communications normally continue from there.
I've had a couple complaints about this communication failing, but I haven't been able to reproduce it. The logs I have don't contain as much as I'd like, but I can see that when the issue occurs, the 2nd thread on the server that receives the 2nd message drops it because the client IP/port is unknown (the first thread logs it for the 2nd thread prior to replying to the client, mutexes and everything look correct for ensuring the data is there before the 2nd thread gets the next message).
This works fine every time I've tested it, and I know the assumption is that the first message from the client comes from the same IP/port as the 2nd message, which I unfortunately do not have logs to verify whether or not that was the case and I'm starting to wonder if that assumption is incorrect based on the client code. Here's the client code (windows):
SOCKET skt = socket(AF_INET, SOCK_DGRAM, 0);
std::string serverAddr("127.0.0.1");
int addrInt = inet_addr(serverAddr.c_str());
sockaddr_in toAddr;
toAddr.sin_family = AF_INET;
toAddr.sin_addr.s_addr = addrInt;
toAddr.sin_port = htons(12345);
uint8_t txBuf[] msg = "test_msg";
// this send works correctly
sendto(skt, (char*)txBuf, sizeof(txBuf), 0, (sockaddr*)&toAddr, sizeof(toAddr));
sockaddr_in rxAddr;
int fromAddrLen = sizeof(rxAddr);
uint8_t rxBuf[1000];
// this receive also works
recvfrom(skt, (char*)rxBuf, sizeof(rxBuf), 0, (sockaddr*)&rxAddr, fromAddrLen);
uint16_t nextPort = *((uint16_t*)rxBuf+0);
toAddr.sin_port = htons(nextPort);
// this send triggers the server log that the client IP/port is unknown
sendto(skt, (char*)txBuf, sizeof(txBuf), 0, (sockaddr*)&toAddr, sizeof(toAddr));
My question is, in the code above, is the 2nd send guaranteed to come from the same IP/port combination as the first send? And if not, how can I change the above code to gaurantee it without binding (I don't know the client IP to bind to and don't know what ports are available)?
EDIT:
I learned the hard way previously about how NATs prevent servers from making first contact (which is why the client sends to thread1, gets response, then sends to thread2 instead of thread1 directly telling thread2 to respond). Remembering this fun time, I'm starting to wonder if the behavior I'm seeing is due to NAT behavior that's different in some cases from all of the NATs my test assets have. I know NATs create a linkage between the client's IP and server's IP and that the server sees the NAT generated client IP/port instead of the IP/port that the client sees. I was thinking that the NAT used the same linkage when the client started sending to the new server port (same server IP). Was that wrong? Does the fact that the client starts sending to a different port potentially cause a different NAT IP/port that the server ultimately sees?
|
The answer turns out to be that the client IP/port is not guaranteed to stay the same. I added debug to the server and saw it happen again, so was able to verify that when the client changed it's send-to port, it caused the server to see a different client send-from port.
I'm not entirely sure if this is due to something in the OS being different for some clients or if it was because of different NAT behavior. For my purposes, it doesn't matter -- I had to change code to work with it either way. If anybody can definitively say (and hopefully point to documentation) that it was the OS and/or NAT, please do and I'll change the accepted answer to it
|
73,421,702
| 73,442,047
|
Feature clock_monotonic is already defined to be "OFF" and should now be set to "ON" when importing features from Qt6::Core
|
I tried to run my project that I did 2 months ago and get this error. I suppose that's because of new version or something like that but I do not know what to do.
The error itself:
/opt/homebrew/lib/cmake/Qt6/QtFeature.cmake:1249: error: Feature clock_monotonic is already defined to be "OFF" and should now be set to "ON" when importing features from Qt6::Core.
/opt/homebrew/lib/cmake/Qt6Core/Qt6CoreConfig.cmake:118 (qt_make_features_available)
/Users/me/Qt/Tools/CMake/CMake.app/Contents/share/cmake-3.21/Modules/CMakeFindDependencyMacro.cmake:47 (find_package)
/opt/homebrew/lib/cmake/Qt6/QtPublicDependencyHelpers.cmake:14 (find_dependency)
/opt/homebrew/lib/cmake/Qt6Widgets/Qt6WidgetsDependencies.cmake:96
(_qt_internal_find_dependencies)
/opt/homebrew/lib/cmake/Qt6Widgets/Qt6WidgetsConfig.cmake:40 (include) /opt/homebrew/lib/cmake/Qt6/Qt6Config.cmake:213 (find_package)
CMakeLists.txt:14 (find_package)
|
It's a not-uncommon issue in CMake where values are cached, but then updating libraries does not update the values as expected.
If you delete CMakeCache.txt in your build folder and reconfigure (call cmake / qt-cmake with your initial options again) then it will go away.
|
73,421,752
| 73,430,153
|
Expand tuple to parameters pack in member initializer lists
|
I need to initialize a base class with arguments stored in a std::tuple.
I have access to C++17 and managed to figure out that std::make_from_tuple may work but would require a copy constructor for the base class.
An example:
#include <tuple>
template<class Base>
class WithTupleConstructor : public Base // Sort of a Mixin class template
{
public:
// Creating a Base with arguments stored in tuple and then copying it
template<class Tuple>
WithTupleConstructor(const Tuple& base_args)
: Base(std::make_from_tuple<Base>(base_args)) }
{ }
};
class WithCopyConstructor
{
public:
WithCopyConstructor(int a, int b)
{};
WithCopyConstructor(const WithCopyConstructor& other)
{};
};
class WithoutCopyConstructor
{
public:
WithoutCopyConstructor(int a)
{};
WithoutCopyConstructor(const WithoutCopyConstructor& other) = delete;
};
int main()
{
WithTupleConstructor<WithCopyConstructor> m1(std::make_tuple(1,2));
// this do not compiles
//WithTupleConstructor<WithoutCopyConstructor> m2(std::make_tuple(1));
}
std::make_index_sequence and std::get seem to demand an auxiliary function and cannot see how they could be used to solve this (as explained here tuple-to-parameter-pack).
Is there a way to expand the tuple in the initialize list without requiring the copy constructor?
|
I found a solution based in this answer, turns out that it is achievable using std::make_index_sequence and std::get.
An auxiliary function that "unwraps" the tuple is required but it can be defined as a private constructor:
#include <tuple>
template<typename Tuple>
using make_tuple_index_sequence = std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>;
template<class Base>
class WithTupleConstructor : public Base // Sort of a Mixin class template
{
public:
// Passing tuple and index sequence to auxiliary constructor
template<class Tuple>
WithTupleConstructor(const Tuple& base_args)
: WithTupleConstructor(base_args, make_tuple_index_sequence<Tuple>{})
{}
private:
// Expanding tuple using std::get
template<class Tuple, std::size_t ...tuple_n>
WithTupleConstructor(const Tuple& base_args, std::index_sequence<tuple_n...> )
: Base(std::get<tuple_n>(base_args)...)
{}
};
class WithCopyConstructor
{
public:
WithCopyConstructor(int a, int b)
{}
WithCopyConstructor(const WithCopyConstructor& other)
{}
};
class WithoutCopyConstructor
{
public:
WithoutCopyConstructor(int a)
{}
WithoutCopyConstructor(const WithoutCopyConstructor& other) = delete;
};
int main()
{
WithTupleConstructor<WithCopyConstructor> m1(std::make_tuple(1,2));
WithTupleConstructor<WithoutCopyConstructor> m2(std::make_tuple(1));
}
This can be further extended to support rvalues and perfect forwarding by adding && and std::forward when receiving and passing the tuples.
|
73,422,091
| 73,425,424
|
What is the proper way to zoom in and out using orthographic projection?
|
I have a view matrix:
float left = -(float)viewPortWidth / 240, right = (float)viewPortWidth / 240, down = -(float)viewPortHeight / 240, up = (float)viewPortHeight / 240;
viewMatrix = glm::ortho(left, right, down, up, -1.0f, 1.0f);
I am dividing by 240 to be able to show 16:9 units when it is full screen. Here is how it looks like:
I have a class Camera2D and I want to give it a size capability like Unity or at least achieve something similar. Before, I was using the transformation matrix of the game object attached to the camera and multiplying it by viewMatrix, but that leads to many unwanted effects if I make game object a child of the camera. I tried adding the number of extra vertical and horizontal unites I want to left, right, down, up but it leads to stretching effects.
I want to be able to have a zoom feature where 1 would add one vertical or horizontal unit. How can I do this?
Update 1:
I tried this:
float left = -(float)(viewPortWidth + 240) / 240, right = (float)(viewPortWidth + 240) / 240, down = -(float)(viewPortHeight + 240) / 240, up = (float)(viewPortHeight + 240) / 240;
viewMatrix = glm::ortho(left, right, down, up, -1.0f, 1.0f);
But it still leads to stretching effects.
|
Try dividing all the parameters.
float zoom = 16.0f / 14.0f; // 114% zoom in
float left = -(float)viewPortWidth / 240, right = (float)viewPortWidth / 240, down = -(float)viewPortHeight / 240, up = (float)viewPortHeight / 240;
viewMatrix = glm::ortho(left / zoom, right / zoom, down / zoom, up / zoom, -1.0f, 1.0f);
Another approach
Or otherwise, if you'd like to control zoom level by specifying the number of units to be shown directly, try:
float n = 14.0f * unit_size; // Align 14 units horizontally in the screen.
const float aspectRatio = (float)viewPortWidth / viewPortHeight;
float left = -n * 0.5f, right = n * 0.5f, down = -n * 0.5f / aspectRatio, up = n * 0.5f / aspectRatio;
viewMatrix = glm::ortho(left, right, down, up, -1.0f, 1.0f);
|
73,422,114
| 73,429,394
|
C++ Language Parsing and Logical Operators's Short-Circuit
|
When it comes to the short-circuit of the logical operators, according to the Standard in 7.6.14 e 7.6.15 (N4868).
7.6.14 Logical AND operator
[...] the second operand is not evaluated if the first operand is false.
7.6.15 Logical OR operator
[...] the second operand is not evaluated if the first operand evaluates to true.
When this implementation is discussed in Logical Operators Chaining as (Cond1 && Cond2 && Cond3), in my interpretation, the presented is different from my current mental model on how the c++ code parsing/operator binding occurs in compiler-time.
For something as
if (cond1 && cond2 && cond3) {
//something
}
It is understood as "if cond1 is false, so occurs short-circuit, cond2 and cond3 are not evaluated and the expression is false".
For me, even if you have the same result, a more accurate expression about how the parsing should works is "The first 'AND' operation is an sub-expression of the second. If cond1 is false, so occurs short-circuit, cond2 is not evaluated and the sub-expression is evaluated to false. Then in the second operation occurs short-circuit, cond3 is not evaluated and this expression is also evaluted to false".
Like:
(cond1 && cond2) && cond3 : evaluation of cond1 and short-circuit of
sub-expression to false (cond2 is not evaluated)
false && cond3 : short-circuit of the full-expression to false (cond3 is not evaluated)
I am worrying about the model in an high level language like C ++ and not the implementation in runtime (the implementations of the compilers seem to be exactly the same as the first expression I showed, if cond1 is false occurs a jump).
The interpretation I did is accurate, pedantic or is incorrect and is inappropriate in this context (It is overthinking)?
|
You are correct as far as compiler's "mental model" and whoever wrote "if cond1 is false, so the full-expression is false" is correct as far as CPU's "mental model" in this specific case.
On the compiler side, parsing cond1 && cond2 && cond3 results in (using clang -ast-dump)
`-BinaryOperator 0x557a79f02230 <col:1, col:19> 'bool' '&&'
|-BinaryOperator 0x557a79f021d8 <col:1, col:10> 'bool' '&&'
| |-ImplicitCastExpr 0x557a79f021a8 <col:1> 'bool' <LValueToRValue>
| | `-DeclRefExpr 0x557a79f02168 <col:1> 'bool' lvalue Var 0x557a79f01da0 'cond1' 'bool'
| `-ImplicitCastExpr 0x557a79f021c0 <col:10> 'bool' <LValueToRValue>
| `-DeclRefExpr 0x557a79f02188 <col:10> 'bool' lvalue Var 0x557a79f01ec8 'cond2' 'bool'
`-ImplicitCastExpr 0x557a79f02218 <col:19> 'bool' <LValueToRValue>
`-DeclRefExpr 0x557a79f021f8 <col:19> 'bool' lvalue Var 0x557a79f01fa8 'cond3' 'bool'
evaluation of this tree starts at the root && at column 19, which must first evaluate its lhs: so it walks down to the && at column 10, which must first evaluate its lhs too: so it walks down to cond1. If that returned false, the col:10 && returns false also, without visiting the rhs branch, and then the col:19 && also returns false without visiting the rhs branch.
Both gcc and clang as I just tested produced runtime code that is the equivalent of
if (cond1 == false) goto done;
if (cond2 == false) goto done;
if (cond3 == false) goto done;
return true;
done:
return false;
So this evaluation is an example of a (very simple) compiler optimization
see https://godbolt.org/z/rYc11PvPb for the AST and the compiled code
|
73,422,693
| 73,422,762
|
C++: How can one get return type of a class member function using std::invoke_result_t?
|
How can one get return type of a class member function using std::invoke_result_t in C++?
#include <type_traits>
#include <vector>
template <class T>
struct C
{
auto Get(void) const { return std::vector<T>{1,2,3}; }
};
int main(void)
{
// what should one put below to make x to have type std::vector<int> ?
std::invoke_result_t<C<int>::Get, void> x;
// ^^^^^^^^^^^^^^^^^
return 0;
}
Thank you very much for your help!
|
std::invoke_result_t works on types, but C<int>::Get is not a type. It is a non-static member function.
The type of C<int>::Get is std::vector<int>(C<int>::)(): Member function of C<int> that returns std::vector<int> and accepts no parameters. That type is what you need to give to std::invoke_result_t. Or rather, a pointer to it, since you can't pass raw member function types around.
Also, std::invoke_result_t treats the first argument type as the type of object on which to call the member function when it's dealing with pointers to member functions.
Thus you need:
std::invoke_result_t<std::vector<int>(C<int>::*)(), C<int>>
Or, if you don't want to write out the whole member function type:
std::invoke_result_t<decltype(&C<int>::Get), C<int>>
Demo
Sidenote: void parameter lists are equivalent to empty parameter lists in C++. There's no reason to explicitly specify a void parameter list in C++ unless you want to share a function declaration with C code.
|
73,422,804
| 73,422,839
|
Initializing array of Objects in C++ Composition
|
I wanted to design a composition using C++ as shown below:
#define NUMBER (4)
class wheel {
int radius;
public:
wheel();
wheel(int);
//copy constructors prototype
//getters and setters prototypes
};
wheel::wheel() : radius(1) {}
wheel::wheel(int r) : radius(r) {}
//wheel class copy constructor definition
//wheel class setter and getter definitions
class car {
wheel fourwheels[NUMBER];
public:
car();
};
car::car() {
fourwheels[NUMBER] = {wheel(1), wheel(1), wheel(1), wheel(1)}; //error code
//wheel fourwheels[NUMBER] = {wheel(1), wheel(1), wheel(1), wheel(1)}; //non-error code
}
int main() {
car mycar;
return 0;
}
While compiling the code, I am getting the following error:
error: no match for 'operator=' (operand types are 'wheel' and '<brace-enclosed initializer list>')
Queries:
Why does this error occur ??
When I comment the error code line and uncomment the non-error code line, it works fine. Why do we have to add the type wheel for the array definition?
|
You are attempting to assign to an array element. And one that's out of range at that.
Using the constructor's initializer list, this will compile, though you should consider using STL containers rather than a raw array.
car::car() : fourwheels{wheel(1), wheel(1), wheel(1), wheel(1)}
{
}
The code you had commented out "worked" because it declared and initialized a new array of four wheels.
Since the default constructor for wheel provides a radius of 1, you could also write:
car::car() : fourwheels{wheel(), wheel(), wheel(), wheel()}
{
}
But, if we used std::array to hold our wheels, we can simplify this further, as the elements of fourwheels will be initialized using the wheel type's default constructor, which we don't have to write.
class car {
std::array<wheel, NUMBER> fourwheels;
};
|
73,423,005
| 73,423,035
|
Circular dependencies missing type specifier - int assumed. Note: C++ does not support default-int
|
I am still new with c++ and I was told that #pragma once was supposed to take care of circular dependencies
My GameManager.h and GameSetting.h both need to know each other and each have a pointer of the other
for my GameSettings.h i have:
#pragma once
#include "PlayerManager.h"
#include <fstream>
#include "GameManager.h";
class GameSettings {
private:
PlayerManager* pM;
GameManager* gM;
vector<Player*> players;
bool inGame = false;
double betValue = 5;
bool allowSplit = true;
bool allowInsurance = true;
GameSettings(PlayerManager* pM, GameManager* gM) { this->pM = pM; this->gM = gM; }
struct GameSettingData {
vector<int> playersId;
double betValue;
bool allowSplit;
bool allowInsurance;
};
... function declarations...
for the GameSettings.cpp I only have the #include "GameSettings.h"
And for the GameManager I only have
#pragma once
#include "GameSettings.h"
class GameManager {
private:
bool isActive = false;
GameSettings *gS;
public:
bool getIsActive() { return isActive; }
bool startGame() { return true; }
};
When I remove any mention of GameSettings in GameManager everything work
I mostly know c# so this kind of circular dependencies is kind of new for me.
I did try to look at other similar questions but it did not help
|
Use a forward declaration of GameSettings in GameMager.h. Pointers do not need complete class definitions until they are derefenced.
#pragma once
class GameSettings;
class GameManager {
private:
bool isActive = false;
GameSettings *gS;
public:
bool getIsActive() { return isActive; }
bool startGame() { return true; }
};
GameManager and PlayerManager can also participate in forward declarations in GameSettings.h.
#pragma once
#include <fstream>
class PlayerManager;
class GameManager;
class GameSettings {
private:
PlayerManager* pM;
GameManager* gM;
vector<Player*> players;
bool inGame = false;
double betValue = 5;
bool allowSplit = true;
bool allowInsurance = true;
GameSettings(PlayerManager* pM, GameManager* gM) { this->pM = pM; this->gM = gM; }
struct GameSettingData {
vector<int> playersId;
double betValue;
bool allowSplit;
bool allowInsurance;
};
Set required #include in .cpp files.
|
73,423,060
| 73,427,103
|
Is this out-of-bounds warning from gcc erroneous?
|
Earlier today, gcc gave me a warning that I belive to be erroneous and now I am very unsure if it is an actual compiler bug(usually highly unlikely) or a bug in my code(usually highly likely). I managed to reduce it down to the following code:
#include <algorithm>
#include <array>
#include <iostream>
int main()
{
std::array<int,8> test{};
int valid = 0;
for(int i=0;i<8;++i)
{
if(i==0)
test[valid++] = 0;
}
// if(valid<8)
std::sort(test.begin(),test.begin()+valid);
}
Here it is on Compiler explorer
When compiled with optimization level -O2 or higher with gcc 12.1 or trunk, this warning about an out-of-bounds access is emitted:
In file included from /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/algorithm:61,
from <source>:1:
In function 'void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = int*; _Compare = __gnu_cxx::__ops::_Iter_less_iter]',
inlined from 'void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = int*; _Compare = __gnu_cxx::__ops::_Iter_less_iter]' at /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/bits/stl_algo.h:1844:5,
inlined from 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = int*; _Compare = __gnu_cxx::__ops::_Iter_less_iter]' at /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/bits/stl_algo.h:1940:31,
inlined from 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = int*; _Compare = __gnu_cxx::__ops::_Iter_less_iter]' at /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/bits/stl_algo.h:1932:5,
inlined from 'void std::sort(_RAIter, _RAIter) [with _RAIter = int*]' at /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/bits/stl_algo.h:4820:18,
inlined from 'int main()' at <source>:16:15:
/opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/bits/stl_algo.h:1849:32: error: array subscript 16 is outside array bounds of 'std::array<int, 8> [1]' [-Werror=array-bounds]
1849 | std::__insertion_sort(__first, __first + int(_S_threshold), __comp);
| ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>: In function 'int main()':
<source>:7:27: note: at offset 64 into object 'test' of size 32
7 | std::array<int,8> test{};
I believe that to be mistaken. According to my limited understanding, valid is only incremented once and will always be 1.
Even if the condition were replaced with some unpredictable function call, in the worst case it would be true every time, yielding valid==8 at the end of the loop, which should still be alright?
Additionally, I have thus far made the following observations:
The warning is not produced at lower optimization levels, on gcc <=11 or on clang.
Interestingly, the warning is also not produce with array sizes >8 or <6, only for sizes 6,7, and 8.
When I remove the condition inside the loop body(the "if(i==0)", to increment every time and always yield valid==8), the warning disappears.
When I add the condition before the sort call(and thereby provide the compiler with an additional hint about the limits of valid), the warning disappears.
Especially the latter two make me believe I might have managed to confuse gcc's analysis somehow, but also make me question if I am overlooking something obvious or managed to introduce some subtle undefined behaviour in my code.
Am I misunderstanding something in my sleep deprived state or did I encounter a genuine, mostly harmless, compiler bug?
|
It is indeed a compiler bug, as can be seen in this bugzilla report, which contains almost identical code to the one in my question.
Thanks to Marc Glisse for providing this link to a lot of similar bugs and thereby helping me track down the relevant one.
|
73,423,280
| 73,425,123
|
How to install a cpp library using cmake on Windows x64?
|
I'm using CLion with MinGW-GCC on the Windows-x64 platform - This is the background of the problem.
I was trying to install gtest before. But a lot of confusion arose in the middle.
First time I ran those commands(in googletest-release-1.12.1\) according to the instructions of googletest-release-1.12.1\googletest\README.md:
mkdir build
cd build
cmake ..
But I got error messages like:
CMake Error at CMakeLists.txt:51 (project):
Failed to run MSBuild command:
C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe
to get the value of VCTargetsPath:
Then I changed my last command to
cmake -G "MinGW Makefiles" ..
because I use make provided by MinGW. I don't know whether it's right but, it ran properly.
then I called
make
make install
make ran smoothly. But when I ran make install, I got these messages:
Install the project...
-- Install configuration: ""
-- Installing: C:/Program Files (x86)/googletest-distribution/include
CMake Error at googlemock/cmake_install.cmake:41 (file):
file INSTALL cannot make directory "C:/Program Files
(x86)/googletest-distribution/include": No such file or directory.
Call Stack (most recent call first):
cmake_install.cmake:42 (include)
make: *** [Makefile:109: install] Error 1
I have no idea at all this time. So I changed my way. According to this answer, I copied the whole library into my project and edited CMakeLists.txt like this:
cmake_minimum_required(VERSION 3.23)
project(gtest_study)
set(CMAKE_CXX_STANDARD 20)
add_subdirectory(googletest-release-1.12.1)
include_directories(googletest-release-1.12.1/googletest/include)
include_directories(googletest-release-1.12.1/googlemock/include)
add_executable(gtest_study main.cpp)
target_link_libraries(gtest_study gtest gtest_main)
target_link_libraries(gtest_study gmock gmock_main)
So my questions are:
Is there any difference between the two which build it using make and cmake metioned firstly, and just use commands like include_directories and target_link_libraries in CMakeLists.txt? (maybe like .h and .dll file? Or just completely the same? I don't know)
When I use make install to install a library on Windows, what should I do in particular? Specify some directory (I don't know which one) or what?
Although in my system environment I use MinGW-makefile, in CLion which the libraries are eventually used, I use ninja as the generator for CMake (it just comes with CLion, not installed for the system). Do I have to specify it and how? (-G "Ninja"doesn't work in my native env)
|
The difference between
cmake ..
and
cmake -G "MinGW Makefiles" ..
Is the choice of generator: The former uses the default generator, the latter uses the generator you specified. (cmake --help should put a * next to the default generator.)
Based on the error message I assume this is a visual studio generator and you may not be able to run that one properly from within a MinGW terminal.
In the latter case the default install directory seems to be based on the target OS (Windows) but does not seem to incorporate the fact that you're running from a MinGW terminal where the default install path (C:/Program Files (x86)/googletest-distribution) is not valid.
You could try to fix this by providing it during cmake configuration (passing -D 'CMAKE_INSTALL_PREFIX=/c/Program Files (x86)/googletest-distribution' before the source dir) or by providing the install directory during the installation.
The following process should allow you to install the lib. I'm using my preferred way of building here, i.e. not using build system dependent commands, but using cmake to run the build/install commands. I assume the working directory to be the root directory of the gtest sources:
cmake -G "MinGW Makefiles" -S . -B build
cmake --build build
cmake --install build --prefix '/c/Program Files (x86)/googletest-distribution'
The last command needs to be run with admin privileges, the first 2 I don't recommend running as admin. You could instead install to a directory where you do have the permissions to create directories even without admin privileges.
The difference between using the process described above and using add_subdirectory is that the former results in a installation on the system which can be used via find_package and the google test libs won't be rebuilt for every project where you do this.
...
project(gtest_study)
...
# you may need to pass the install location via -D CMAKE_PREFIX_PATH=<install_location> during configuration for this to work
find_package(GTest REQUIRED)
target_link_libraries(gtest_study PRIVATE GTest::gtest_main GTest::gmock)
The latter builds the google test project as part of your own project build and for every project where you use this approach a seperate version of the google test libs is built. Note: there should be no need to specify the include dirs yourself, since this kind of information is attached to the cmake target and gets applied to the linking target automatically:
#include_directories(googletest-release-1.12.1/googletest/include)
#include_directories(googletest-release-1.12.1/googlemock/include)
add_executable(gtest_study main.cpp)
target_link_libraries(gtest_study PRIVATE gtest_main gmock)
As for 3.: The CMake generator used for building GTest should be independent of the generator of the project using it. The thing that's important is that the compilers used by the build systems are compatible. I cannot go into detail about this, since I've never used CLion and therefore have too little knowlege about the compilers used by it. (Personally I'm working with Visual Studio on Windows.)
|
73,423,328
| 73,423,422
|
Creating the Backtracking Algorithm for n-queen Problem
|
I have tried to come up with a solution to the n-queen problem, through backtracking. I have created a board, and I think I have created functions which checks whether a piece can be placed at position column2 or not, in comparison to a piece at position column1. And I guess I somehow want to loop through the columns, to check if the current piece is in a forbidden position to any of the power pieces already placed at the first row through the current minus one. I haven't done this yet, but I'm just confused at the moment, so I can't really see how I should do it.
Let me share the code I have written so far
// Method for creating chessboard
vector<vector<vector<int>>> create_chessboard(int size_of_board)
{
vector<int> v1;
vector<vector<int>> v2;
vector<vector<vector<int>>> v3;
for (int i = 0; i < size_of_board; i++)
{
for (int j = 0; j < size_of_board; j++)
{
v1.clear();
v1.push_back(i);
v1.push_back(j);
v2.push_back(v1);
}
v3.push_back(v2);
v2.clear();
}
return v3;
}
// Method for visualizing chessboard
void visualize_board(vector<vector<vector<int>>> chess, int dimension_of_board)
{
int i = 1;
for (vector<vector<int>> rows : chess)
{
for (int j = 0; j < dimension_of_board; j++)
{
cout << "(" << rows[j][0] << "," << rows[j][1] << ")" << " ";
}
cout << endl;
}
}
// Method for checking if two coordinates are on the same diagonal
bool check_diagonal(vector<int> coordinate1, vector<int> coordinate2)
{
if(abs(coordinate1[1] - coordinate2[1]) == abs(coordinate1[0] - coordinate2[0]))
{
return true;
}
return false;
}
bool check_column(vector<int> coordinate1, vector<int> coordinate2)
{
if(coordinate1[1] == coordinate2[1])
{
return true;
}
return false;
}
bool check_row(vector<int> coordinate1, vector<int> coordinate2)
{
if (coordinate1[0] == coordinate2[0])
{
return true;
}
return false;
}
bool check_allowed_positions(vector<int> coordinate1, vector<int> coordinate2, int column)
{
if (check_diagonal(coordinate1, coordinate2))
{
return false;
}
if (check_column(coordinate1, coordinate2))
{
return false;
}
if (check_row(coordinate1, coordinate2))
{
return false;
}
return true;
}
vector<vector<int>> solve_nqueen(vector<vector<vector<int>>> board, int dimension_of_board, int row)
{
vector<int> first_element = board[0][0];
vector<vector<int>> solution_space;
if (dimension_of_board == row)
{
cout << "we found a solution!";
}
/*
if (dimension_of_board == row)
{
}
for (int j = 0; j < dimension_of_board; j++)
{
if (check_allowed_positions(board, row, j))
{
do something here
solve_nqueen(board, dimension_of_board, row+1);
}
else
{
do something here;
}
}
return;
*/
return solution_space;
}
I would be really happy if someone could just lay up a few steps I have to take in order to build the solve_nqueen function, and maybe some remarks on how I could do that. If I should complement with some further information, just let me know! I'm happy to elaborate.
I hope this isn't a stupid question, but I have been trying to search the internet for a solution. But I didn't manage to use what I found.
Best wishes,
Joel
|
There is not always a solution, like e.g. not for 2 queens on 2x2 board, or for 3 queens on a 3x3 board.
This is a well-known problem (which can also be found in the internet). According to this, there is not a simple rule or structure, how you can find a solution. In fact, you could reduce the problem by symmetries, but that is not that simple, too.
Well according to this, you have to loop through all (n out of n x n) solutions, and do all tests for every queen. (In fact, reduce it to half again, by only checking a certain pair of queens, once only - but again that is not much, and such reduction takes some time, too).
Note: Your check routines are correct.
For 8 queens on a 8x8 board, write 8 nested loops from i(x)=0 to 63
(row is i(x)%8 and column is i(x)/8). You also need to check then, if a queen does not sit on queen, but your check routines will already find that. Within second nested loop, you can already check if the first two queens are okay, or otherwise, you do not have to go any deeper, but can already increment the value of first nested loop (move the second queen on a new position).
Also it would be nice, I propose not to write the search for a n-problem, but for a n=8 problem or n=7 problem. (That is easier for the beginning.).
Speed-Ups:
While going deeper into the nested loops, you might hold a quick
record (array) of positions which already did not work for upper
loops (still 64 records to check, but could be written to be faster than doing your check routines again).
Or even better, do the inner loops only through a list from remaining candidates, much less than (n x n) positions.
There should be some more options for speed-ups, which you might find.
Final proposal: do not only wait for the full result to come, but also track, when e.g. you find a valid position of 5 queens, then of 6 queens and so on - which will be more fun then (instead of waiting ages with nothing happening).
A further idea is not to loop, e.g. from 0 to 63 for each queen, but "randomly". Which also might lead to more surprising. For this, mix an array 0 .. 63 to a random order. Then, still do the loop from 0 to 63 but this is just the index to the random vector. Al right? Anyway, it would even be more interesting to create 8 random vectors, for each queen one random vector. If you run this program then, anything could happen ... the first few trials could (theoretically) already deliver a successful result.
If you would like to become super efficient, please note that the queen state on the 8x8 board can be stored in one 64-bit-integer variable (64 times '0' or '1' where '1' means here is queen. Keyword: bitboards). But I didn't mention this in the beginning, because the approach which you started is quite different.
And from that on, you could create 64 bit masks for each queen position, to each position to which a queen can go. Then you only need to do 1 "bitwise AND" operation of two (properly defined) 64-bit variables, like a & b, which replaces your (diagonal-, column-, row-) check routines by only one operation and thus is much faster.
Avoid too many function calls, or use inline.
... an endless list of possible dramatic speed-ups: compiler options, parallelization, better algorithms, avoid cache misses (work on a possibly low amount of memory or access memory in a regular way), ... as usual ...
|
73,423,556
| 73,425,542
|
elegant way to convert variadic inheritance members to tuple
|
consider a type that inherits from multiple classes. I want to iterate over the inherited classes, ideally making a get_tuple() member function that returns a reference tuple for precise manipulation:
struct A { int a; };
struct B { float b; };
struct C { const char* c; };
template<typename ... Ts>
struct collection : Ts...{
constexpr auto get_tuple() const {
return std::make_tuple(/*???*/);
}
std::string string() const {
std::ostringstream stream;
auto tuple = this->get_tuple();
std::apply([&](auto&& first, auto&&... rest) {
stream << first;
((stream << ", " << rest), ...);
}, tuple);
return stream.str();
}
};
int main() {
collection<A, B, C> a{ 1, 0.5f, "hello" };
std::cout << a.string();
}
Is there a nice way to achieve this?
this is one solution I found. Giving each base struct a get() function which will enable the std::make_tuple(Ts::get()...); syntax. the tuple will hold the fundamental types (int, float, const char*) but I am not limiting myself to that, I wouldn't also mind a solution where I receive a tuple of A, B and C's. I delete the inherited get(), since these symbols will appear multiple times in collection:
struct A {
int a;
constexpr auto& get() { return a; }
constexpr const auto& get() const { return a; }
};
struct B {
float b;
constexpr auto& get() { return b; }
constexpr const auto& get() const { return b; }
};
struct C {
const char* c;
constexpr auto& get() { return c; }
constexpr const auto& get() const { return c; }
};
template<typename ... Ts>
struct collection : Ts...{
constexpr auto get() = delete;
constexpr auto get() const = delete;
constexpr auto get_tuple() {
return std::make_tuple(Ts::get()...);
}
constexpr auto get_tuple() const {
return std::make_tuple(Ts::get()...);
}
std::string string() const {
std::ostringstream stream;
auto tuple = this->get_tuple();
std::apply([&](auto&& first, auto&&... rest) {
stream << first;
((stream << ", " << rest), ...);
}, tuple);
return stream.str();
}
};
int main() {
collection<A, B, C> a{1, 0.5f, "hello"};
std::cout << a.string();
}
this works, but is quite a work around, is there an easy solution / some sweet syntax sugar I missed here?
|
You could rely on the fact that every single one of the base classes allows for structured binding to work with one variable to extract the members.
/**
* Our own namespace is used to avoid applying AccessMember to arbitrary types
*/
namespace MyNs
{
struct A { int a; };
struct B { float b; };
struct C { const char* c; };
template<class T>
constexpr auto& AccessMember(T const& val)
{
auto& [member] = val;
return member;
}
template<class T>
constexpr auto& AccessMember(T& val)
{
auto& [member] = val;
return member;
}
} //namespace MyNs
template<typename ... Ts>
struct collection : Ts...
{
constexpr auto get_tuple() const
{
return std::tuple<decltype(AccessMember(std::declval<Ts>()))...>(AccessMember(static_cast<Ts const&>(*this))...);
}
constexpr auto get_tuple()
{
return std::tuple<decltype(AccessMember(std::declval<Ts&>()))...>(AccessMember(static_cast<Ts&>(*this))...);
}
std::string string() const {
std::ostringstream stream;
auto tuple = this->get_tuple();
std::apply([&](auto&& first, auto&&... rest) {
stream << first;
((stream << ", " << rest), ...);
}, tuple);
return stream.str();
}
};
int main() {
using MyNs::A;
using MyNs::B;
using MyNs::C;
collection<A, B, C> a{ 1, 0.5f, "hello" };
std::cout << a.string()<< '\n';
}
|
73,424,045
| 73,424,137
|
Will a heap allocated object get deleted when I assign it to a vector and then delete the vector?
|
I'm new to computer science and I want to know if an object is being deleted if I heap allocate it and then for e. put it in a vector of pointer and then delete the vector. Will the heap object be gone? Here is an example of what I mean.
int main()
{
Type* someHeapObject = new Type();
vector<Type*> someVector(0);
someVector.push_back(someHeapObject);
}
So here's the main part: Can I delete the heap object with delete someVector[0], and then I DON'T have to delete it anymore like this: delete someHeapObject
|
There are two things that you have to take care of:
Mistake 1
In delete [] someVector you're using the delete [] form when you should be using the delete form because you used the new form and not the new[] form for allocating memory dynamically. That is, delete [] someVector is undefined behavior.
Mistake 2
The second thing that you must take care of is that you should not use two or more consecutive delete's on the same pointer.
Now, when you wrote:
someVector.push_back(someHeapObject);
a copy of the pointer someHeapObject is added to the vector someVector. This means that now there are 2 pointers pointing to the same dynamically allocated memory. One pointer is the someHeapObject and the second is the one inside the vector.
And as i said, now you should only use delete on only one of the pointers. For example you can write:
delete someHeapOjbect; //now the memory has been freed
//YOU CAN'T USE delete someVector[0] anymore
Or you can write:
delete someVector[0]; //now te memory has been freed
//YOU CAN'T USE delete someHeapObject[0] anymore
Note that better option would be to use smart pointers instead explicitly doing memory management using new and delete.
|
73,424,050
| 73,427,930
|
How to use future / async in cppyy
|
I'm trying to use future from C++ STL via cppyy (a C++-python binding packet).
For example, I could run this following code in C++ (which is adapted from this answer)
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
using namespace chrono_literals;
int main () {
promise<int> p;
future<int> f = p.get_future();
thread t([&p]() {
this_thread::sleep_for(10s);
p.set_value(2);
});
auto status = f.wait_for(10ms);
if (status == future_status::ready) {
cout << "task is read" << endl;
} else {
cout << "task is running" << endl;
}
t.join();
return 0;
}
A similar implementation of the above in Python is
import cppyy
cppyy.cppdef(r'''
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
int test () {
promise<int> p;
future<int> f = p.get_future();
thread t([&p]() {
this_thread::sleep_for(10s);
p.set_value(2);
});
auto status = f.wait_for(10ms);
if (status == future_status::ready) {
cout << "task is read" << endl;
} else {
cout << "task is running" << endl;
}
t.join();
return 0;
}
''')
cppyy.gbl.test()
And the above code yields
IncrementalExecutor::executeFunction: symbol '__emutls_v._ZSt15__once_callable' unresolved while linking symbol '__cf_4'!
IncrementalExecutor::executeFunction: symbol '__emutls_v._ZSt11__once_call' unresolved while linking symbol '__cf_4'!
It looks like it's caused by using future in cppyy.
Any solutions to this?
|
Clang9's JIT does not support thread local storage the way the modern g++ implements it, will check again when the (on-going) upgrade to Clang13 is finished, which may resolve this issue.
Otherwise, cppyy mixes fine with threaded code (e.g. the above example runs fine on MacOS, with Clang the system compiler). Just that any TLS use needs to sit in compiled library code while the JIT has this limitation.
|
73,424,175
| 73,577,429
|
MacOS .app can't open file by double click
|
I have a c++ program, which should get the file name from argv, open this file, and work with it.
Program works perfectly well, because: when I call binary (Unix Executable) from the terminal, program gets th name from argv and works with it, but when I made from this binary MacOs program .app, then, by double clicking on file, which program should open, program throws this error:
And again, if I launch binary (which already in .app directory), everything works, but if i run programm .app from terminal, program will throw this error again
list of terminal commands, that I tested:
open -a /Applications/Sengine.app obj/rogers.mdl - didn't work
/Applications/Sengine.app/Contents/MacOS/SENGINE obj/rogers.mdl - did work
cmake-build-debug/SENGINE obj/rogers.mdl - did work
I'm compiling program with cmake:
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build cmake-build-debug --target SENGINE -- -j 3
File info.plist from .app program, just in case:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDisplayName</key>
<string>Sengine</string>
<key>CFBundleExecutable</key>
<string>Sengine</string>
<key>CFBundleIconFile</key>
<string>icon.icns</string>
<key>CFBundleIdentifier</key>
<string>com.zolars.sengine-department.SENGINE</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Sengine</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>3.0.0</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeIconFiles</key>
<string>mdl.icns</string>
<key>LSItemContentTypes</key>
<array>
<string>mdl</string>
</array>
<key>LSHandlerRank</key>
<string>Owner</string>
</dict>
</array>
</dict>
</plist>
If I understood rightly, for some reason name of the file, after double clicking, doesn't reach source binary. I can't figure out why, and how to fix it.
Help me please with this.
|
When you run a command line program it works as all command line programs, by reading argv/argc. But when you bundle it into a .app directory with a PLIST you are instructing it to use Launch Services and the Info.plist file.
By doing, so you change how it opens files. Using Launch Services, you can leave the application running and continue to hand it over new files without restarting. You had an example of how that is done in your question:
open -a /Applications/Sengine.app obj/rogers.mdl
To accomplish this, the application will need to handle the application(_:openFiles:) method. Without adding this functionality to your application you would need some intermediate launcher that provides openFiles and executes your application via system() or similar.
|
73,424,252
| 73,424,283
|
question about implementation of add_rvalue_reference
|
Implementation of add_rvalue_reference in cppreference is the following. What is the need for the int argument (i.e. 0) vs. no argument ?
namespace detail {
template <class T>
struct type_identity { using type = T; }; // or use std::type_identity (since C++20)
template <class T>
auto try_add_rvalue_reference(int) -> type_identity<T&&>;
template <class T>
auto try_add_rvalue_reference(...) -> type_identity<T>;
} // namespace detail
template <class T>
struct add_rvalue_reference : decltype(detail::try_add_rvalue_reference<T>(0)) {};
|
If the implementation was like this:
namespace detail {
template <class T>
struct type_identity { using type = T; }; // or use std::type_identity (since C++20)
template <class T>
auto try_add_rvalue_reference() -> type_identity<T&&>;
template <class T>
auto try_add_rvalue_reference() -> type_identity<T>;
} // namespace detail
template <class T>
struct add_rvalue_reference : decltype(detail::try_add_rvalue_reference<T>()) {};
Then with e.g. T an object type both T and T&& are valid types and so neither of the two overloads will SFINAE for the call detail::try_add_rvalue_reference<T>(). Both overloads will be viable. But now because there is no function parameter/argument pair distinguishing them anymore, both will be equally good in overload resolution with no tiebreaker applying and so the call detail::try_add_rvalue_reference<T>() will be ambiguous.
With int and ... as parameter, the int overload will always be considered a better candidate in overload resolution if both are viable. And the intention is that T&& is chosen whenever that is a valid type.
|
73,424,936
| 73,425,014
|
Given two arrays A & B with positive integers, find Maximum product of Array A after atmost N operation
|
We are given two Arrays of size n with positive integers. we are allowed to modify elements of array A such that A[i]=A[i]*B[j] or A[i]=A[i]+B[j], where 0<=i,j<n. we are allowed to use each element of array B only once. Find the maximum product of Array A after at most n operation.
The purpose of my question is to look for correct and better algorithms.
example:
A={2,3,5};
B={1,6,4};
output= 1080
Explanation:
A[0]=2+1=3
A[1]=3*4=12
A[2]=5*6=30
product=30*12*3=1080
My approach:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int testcases; cin>>testcases;
for(int i=0;i<testcases;i++){
int n;cin>>n;
vector<int>a(n);
vector<int>b(n);
for(int j=0;j<n;j++){
cin>>a[j];
}
for(int j=0;j<n;j++){
cin>>b[j];
}
sort(a.begin(),a.end());
sort(b.begin(),b.end());
for(int j=0;j<n;j++){
a[j]=max(a[j]+b[j],a[j]*b[j]);
}
int answer=a[0];
for(int j=1;j<n;j++){
answer=answer*a[j];
}
cout<<answer<<endl;
}
}
Howver, it passed only one testcase, and was getting wrong answer for others.
|
Your for loop is wrong.
for(int j=0;j<n;j++){
a[i]=max(a[i]+b[i],a[i]*b[i]);
}
You're assigning using i as index instead of j. It should be
for(int j=0;j<n;j++){
a[j]=max(a[j]+b[j],a[j]*b[j]);
}
Edit: Since you've corrected your input, there's another logical fallacy. Consider the following case:
A = [1,2]
B = [1,2]
Your answer = 8
Correct answer = 9 [(1+2) * (1+2)]
The algorithm is correct otherwise, but if you don't handle this case, your final answer would be wrong.
|
73,425,423
| 73,425,562
|
Why PCRE regex only capture 19 groups?
|
My Question:
My regex pattern is: (a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)
and My string is: abcdefghijklmnopqrstuvwxyz
the code's output is:
i_0:0 i_1:26 i_2:0 i_3:1 i_4:1 i_5:2 i_6:2 i_7:3 i_8:3 i_9:4 i_10:4 i_11:5 i_12:5 i_13:6 i_14:6 i_15:7 i_16:7 i_17:8 i_18:8 i_19:9 i_20:9 i_21:10 i_22:10 i_23:11 i_24:11 i_25:12 i_26:12 i_27:13 i_28:13 i_29:14 i_30:14 i_31:15 i_32:15 i_33:16 i_34:16 i_35:17 i_36:17 i_37:18 i_38:18 i_39:19 i_40:0 i_41:0 i_42:0 i_43:0 i_44:0 i_45:0 i_46:0 i_47:0 i_48:0 i_49:0 i_50:0 i_51:0 i_52:0 i_53:0 i_54:0 i_55:0 i_56:0 i_57:0 i_58:0 i_59:0
Question: Why PCRE regex only capture 19 groups?
My Code
#include <pcre.h>
#include <iostream>
pcre* _rex;
pcre_extra* _rexEx;
void CompileRexStr(const std::string& rex) {
const char* errorinfo;
int errpos = 0;
_rex = NULL;
_rexEx = NULL;
_rex = pcre_compile(rex.c_str(), PCRE_UTF8, &errorinfo, &errpos, NULL);
_rexEx = pcre_study(_rex, PCRE_STUDY_JIT_COMPILE, &errorinfo);
}
int main(){
std::string rex = "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)";
CompileRexStr(rex);
std::string str = "abcdefghijklmnopqrstuvwxyz";
int result[60] = {0};
int cur = 0;
int pos = pcre_exec(_rex, _rexEx, str.c_str(), str.length(), cur, 0, result, 60);
for(int i=0;i < 60; i++) {
std::cout << "i_" << i << ":" << result[i] << " ";
}
return 0;
}
|
It returns 19 capture groups, because you provided space to return 20 matches, and one is used for whole matching string
Captured substrings are returned to the caller via a vector of integers whose address is passed in ovector. The number of elements in the vector is passed in ovecsize, which must be a non-negative number. Note: this argument is NOT the size of ovector in bytes.
The first two-thirds of the vector is used to pass back captured substrings, each substring using a pair of integers. The remaining third of the vector is used as workspace by pcre_exec() while matching capturing subpatterns, and is not available for passing back information. The number passed in ovecsize should always be a multiple of three. If it is not, it is rounded down.
Source: Manual for PCRE
If you have 26 capture groups, you need to pass a vector containing (26 + 1)×3 = 81 element at least.
|
73,425,691
| 73,433,745
|
Check the viability of a conversion function
|
I have the following code:
struct S {
operator int(); // F1
operator double(); // F2
};
int main() {
int res = S();
}
Since neither F1 nor F2 is cv-qualified, the type of the implicit object parameter is S&, and the corresponding argument to be matched against is S().
Now, per [over.match.viable]/4: (emphasis mine)
Third, for F to be a viable function, there shall exist for each
argument an implicit conversion sequence that converts that argument
to the corresponding parameter of F. If the parameter has reference
type, the implicit conversion sequence includes the operation of
binding the reference, and the fact that an lvalue reference to
non-const cannot bind to an rvalue and that an rvalue reference cannot
bind to an lvalue can affect the viability of the function (see
[over.ics.ref]).
According to the above quote (bold), I'm expecting that neither F1 nor F2 is viable, because the implicit object parameter for both is of type S& and it cannot bind to an rvalue, S().
But, when I tried to compile the code, I found out both functions are viable candidates. Which is best match is not what I am asking about here.
So, why are both F1 and F2 viable candidates, even though the implicit object parameter (of type S&) cannot bind to class prvalue S()?
|
The main concern expressed in your question appears to be how a given rvalue argument can bind to an implicitly declared lvalue reference parameter. (I'm not here even attempting to make an adjudication on the extensive discusssion in the comments to your question about whether or not any actual overloads are involved in your code sample.)
This (main) concern is addressed – quite clearly, IMHO – in another part of the [over.match.funcs] section of the C++ Standard you cite (bold emphasis mine):
12.2.2.1 General[over.match.funcs.general]
…
5 During overload resolution, the implied
object argument is indistinguishable from other arguments. The implicit
object parameter, however, retains its identity since no user-defined
conversions can be applied to achieve a type match with it. For
implicit object member functions declared without a ref-qualifier,
even if the implicit object parameter is not const-qualified, an
rvalue can be bound to the parameter as long as in all other respects
the argument can be converted to the type of the implicit object
parameter.
Without this paragraph, implicit conversion functions would lose a great deal of their usefulness, such as the use-case you have provided in your example.
|
73,425,887
| 73,426,169
|
CMake, Public private folder structure
|
If I have a folder-structure like this:
.
├── Core
│ ├── Private
│ │ └── example.cpp
│ └── Public
│ └── example.h
└── Math
├── Private
│ └── Math.cpp
└── Public
└── Math.h
How would I accomplish it, in CMake, to make a import, in example the folder Math/Private, like this:
#include <Core/example.h>
Of course example.h is the header file from example.cpp. Even there, how would I link them without writing:
#include <../Public/example.h>
Is this possible?
|
You cannot accompilish this with the given project structure: There simply is no example.h file with a parent directory Core.
Restructure the project and use target_include_directories().
Project structure
.
├── Core
│ ├── Private
│ │ └── example.cpp
│ └── include
│ └── Core
│ └── example.h
├── Math
│ ├── Private
│ │ └── Math.cpp
│ └── include
│ └── Math
│ └── Math.h
└── CMakeLists.txt
CMakeLists.txt
set(CORE_SRC
Private/example.cpp
include/Core/example.h
)
list(TRANSFORM CORE_SRC PREPEND Core/)
set(MATH_SRC
Private/Math.cpp
include/Math/Math.h
)
list(TRANSFORM MATH_SRC PREPEND Math/)
add_executable(my_program
${CORE_SRC}
${MATH_SRC}
)
target_include_directories(my_program PRIVATE
Math/include
Core/include
)
Note: If you want to create separate targets for the components Math and Core, you could use PUBLIC instead of PRIVATE for the visibility of the include directories which would result in any cmake targets linking your cmake library targets to automatically gain access to those include directories without the need to repeat this kind of in multiple places.
|
73,426,525
| 73,436,622
|
Scaling an input range by minimum in (upcoming) C++23 (using zip_transform and repeat)
|
In ADSP Podcast Episode 91 (2022-08-19, around 14:30 ... 16:30) Bryce Lelbach and Conor Hoekstra talk about an example application of the (hopefully) upcoming C++23 ranges views zip_transform and repeat: scaling a range of values by the (non-zero) minimum value of that range.
Since to my knowledge at the time of writing, no library of any compiler implements these yet (and no link was given), I wonder how to implement it. The closest I came up with, was
auto scale_by_min(auto&& range)
{
auto m = std::ranges::min(range);
return std::views::zip_transform(
range,
std::views::repeat(m),
[](auto x, auto min)
{
return x / min;
}
);
}
((non-working) example in godbolt). Did I get it right?
Edit / Clarification:
Replacing the return statement by
return range | std::views::transform([m](auto x){ return x / m; });
it works in C++20, also without zip_transform and repeat, as correctly stated in a comment. This question is not about conciseness, style, or meaningfulness of the example. I just try to get the syntax right for using the upcoming ranges-views.
|
Did I get it right?
No. zip_transform accepts variadic template arguments as input ranges, the first argument of zip_transform must be the transform functor, so you should
auto m = std::ranges::min(range);
return std::views::zip_transform(
std::divides{},
range,
std::views::repeat(m)
);
It's worth noting that views::repeat(m) gives you an infinite range, which makes zip_transform_view not model sized_range. You can pass the second parameter of repeat_view by detecting whether the range is sized_range, e.g.
auto m = std::ranges::min(range);
auto repeat = [&] {
if constexpr (std::ranges::sized_range<decltype(range)>)
return std::views::repeat(m, std::ranges::size(range));
else
return std::views::repeat(m);
}();
return std::views::zip_transform(std::divides{}, range, repeat);
which makes zip_transform_view preserve the properties of sized_range.
|
73,426,849
| 73,528,223
|
Fastest way to upload OHLC in C++
|
I'm implementing a class to store time-series (OHLCV) which will contain methods applied to parsed file. I'm trying to figure it out if there is a faster way to upload the content of each file (.csv which are ≈ 40000 rows) into a std::unordered_map<std::string, OHLCV>. Knowing that the structure of the file is fixed (order of header):
.
├── file.csv
│
└── columns:
├── std::string datetime
├── float open
├── float high
├── float low
├── float close
└── float volume
The class is implemented as follows:
class OHLCV {
private:
const char* format = "%Y-%m-%d %H:%M:%S";
std::vector<long int> timestamps;
std::vector<float> opens, highs, lows, closes, volumes;
public:
void upload(
const std::string& filepath,
const char& sep,
const bool& header
)
{
std::ifstream stream(filepath);
if (stream) {
std::string line, timestamp, open, high, low, close, volume;
if (header) {
std::getline(stream, line);
}
while (std::getline(stream, line)) {
std::stringstream ss(line);
std::getline(ss, timestamp, sep);
std::getline(ss, open, sep);
std::getline(ss, high, sep);
std::getline(ss, low, sep);
std::getline(ss, close, sep);
std::getline(ss, volume, sep);
timestamps.emplace_back(timestamp);
opens.emplace_back(std::stof(open));
highs.emplace_back(std::stof(high));
lows.emplace_back(std::stof(low));
closes.emplace_back(std::stof(close));
volumes.emplace_back(std::stof(volume));
}
}
}
};
I tried to launch I bit of test to see how the OHLC::upload was performing with and these are some of the registred times:
[timer] ohlcv::upload ~ 338(ms), 338213700(ns)
[timer] ohlcv::upload ~ 329(ms), 329451900(ns)
[timer] ohlcv::upload ~ 345(ms), 345494100(ns)
[timer] ohlcv::upload ~ 328(ms), 328179800(ns)
Knowing that my optimization setting is currently at Maximum Optimization (Favor Speed) (/O2) and I'm testing in Release mode, could I improve the velocity of the upload without using an std::array with a const unsigned int MAX_LEN known at compile time?
Little note: Pandas (Python) takes ≈ 63ms for uploading one of these files.
|
Increasing buffer size to reduce number of writes. As referenced here, "With a user-provided buffer, reading from file reads largest multiples of 4096 that fit in the buffer"; following a test published in another answer, the optimal buffer size should be around 64KB. Also, note that for my compiler is ok to open the file and then next to call pubsetbuf, but depends on compiler. I found that my optimal size is with char buffer[65536].
Using string::find() instead of stringstream to split the string following advice provided by @rustyx here.
Taking advantage of knowing the structure of data incoming (knowing columns but not number of rows). Therefore, while reading each line not checking for std::string::npos but instead iterating for the expected fields in line.
Instead of using a number of vectors equal to the number of columns, creating a struct which stores the records for each row. Then, initializing a std::vector<record> and reserving enough capacity to avoid multiple needless allocations. To approximate the number of rows I am using std::filesystem::file_size. Note, I am not copying the data into the vector but instead im creating the struct directly inside the vector with records.emplace_back(std::forward<Args>(args)...)
Optimizing type conversion: In my case I got two types of conversion: 1) string to timestamp; In this I found that Howard Hinnat's date.h library brings an incredible speed increase. 2) string to float: In this case I do not need my substring to be allocated but I simply create a std::string_view read by from_chars increase speed quite a lot.
Using static size array: Despite my initial need of dynamism, is not a secret that if you use some kind of static size array you will have the best optimization gain . In my case im using std::shared_ptr < std::array<record, rows>> records;.
|
73,426,856
| 73,427,382
|
C++20 : Parameter pack partial expansion
|
I need a way to partially expand a parameter pack. The size of the subset has to be determined by another variadic parameter. It will be more clear what I mean with sample code.
struct EntityA {
EntityA(int, char, unsigned) {}
EntityA(int, char, unsigned*) {}
EntityA(int, char*, unsigned*) {}
EntityA(int*, char*, unsigned*) {}
}
// various types of entities
// ...
// Service provides Args.
template <typename ... Args>
struct Service {
// returns provided Args
template <typename T>
T get() { return T{}; }
};
// this function should call appropriate overload of E by looking at sizeof...(pArgs)
template <typename E, typename ... SArgs>
E
construct(Service<SArgs ...>& service, auto&& ... pArgs) {
// somehow i need to expand and get first half from service and get others from parameters
return E{service.get<SArgs> ..., std::forward<decltype(pArgs)>(pArgs) ...};
}
int main() {
Service<int, char, unsigned> service;
construct<EntityA>(service);
construct<EntityA>(service, (unsigned*)nullptr);
construct<EntityA>(service, (char*)nullptr, (unsigned*)nullptr);
construct<EntityA>(service, (int*)nullptr, (char*)nullptr, (unsigned*)nullptr);
return 0;
}
Some objects(template parameter E) need to be constructed with parameters partially from service and partially from client code. Is there a way to implement this?
|
you can use std::index_sequence for that
template <typename E, typename ... SArgs, typename ... PArgs>
E construct(Service<SArgs...>& service, PArgs&& ... pargs) {
constexpr auto size = sizeof...(PArgs);
constexpr auto missing_size = 3 - size; // note: you need to somehow know the parameter count
using default_types = std::tuple<SArgs...>;
return [&]<std::size_t ...I>(std::index_sequence<I...>){
return E{
service.template get<std::tuple_element_t<I,default_types>>()...,
std::forward<PArgs>(pargs)...
};
}(std::make_index_sequence<missing_size>());
}
https://godbolt.org/z/PY4hYrqK7
|
73,426,985
| 73,427,478
|
Is it possible for implicit object creation to not create objects in certain situations?
|
According to [intro.object]/10:
Some operations are described as implicitly creating objects within a specified region of storage. For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types ([basic.types.general]) in its specified region of storage if doing so would result in the program having defined behavior. If no such set of objects would give the program defined behavior, the behavior of the program is undefined. If multiple such sets of objects would give the program defined behavior, it is unspecified which such set of objects is created.
it can choose not to create objects if that would make the program legal.
Consider the following code (from this question):
void* p = operator new(1);
new (p) char;
delete static_cast<char*>(p);
operator new implicitly creates objects, according to [intro.object]/13:
Any implicit or explicit invocation of a function named operator new or operator new[] implicitly creates objects in the returned region of storage and returns a pointer to a suitable created object.
It also follows [intro.object]/10, so consider two options:
Implicitly creates a char object. See this answer.
Does not create a char object. First, p points to uninitialized memory allocated by operator new. Then, explicitly create a char object on it by placement new. Finally, it is used on delete-expression.
The question is whether option 2 is legal, that is, whether p automatically points to the object created by placement new.
The standard rules at [basic.life]/8:
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if the original object is transparently replaceable (see below) by the new object.
But no object occupies the memory pointed to by p. Therefore, no replacement takes place, [basic.life]/8 doesn't apply in this case.
I didn't find a stipulation in the standard. So, does the standard allow option 2?
|
it can choose not to create objects if that would make the program legal.
Um, no; it cannot. The literal text you quoted says "that operation implicitly creates and starts the lifetime of ... if doing so would result in the program having defined behavior." There is no conditional here, no choice about it. So if the program would otherwise have undefined behavior, and creating a particular object type would give it defined behavior, IOC will do that.
It is not optional; if it is available, it must happen.
Option 1 is not only possible, it is required. It is required because option 2 is undefined behavior.
Let's take it step by step.
void* p = operator new(1);
If IOC does not happen, then p does not point to an object. It merely points to memory. That's just what operator new does.
new (p) char;
This creates a char object in the storage pointed to by p. However, this does not cause p to point to that object. I can't cite a portion of the standard because the standard doesn't say what doesn't happen. [expr.new] explains how new expressions work, and nothing there, or in the definition of the placement-new functions, says that it changes the nature of the argument that it is given.
Therefore, p continues to point at storage and not an object in that storage.
delete static_cast<char*>(p);
This is where UB happens. [expr.delete]/11 tells us:
For a single-object delete expression, the deleted object is the object denoted by the operand if its static type does not have a virtual destructor, and its most-derived object otherwise.
Well, p does not denote an object at all. It just points to storage. static_cast<char*>(p) does not have the power to reach into that storage and get a pointer to an object in that storage. At least, not unless the object is pointer-interconvertible with the object pointed to by p. But since p doesn't point to an object at all at this point... the cast cannot change this.
Therefore, we have achieved undefined behavior.
However, this is where IOC gets triggered. There is a way for IOC to fix this. If operator new(1) performed implicit object creation, and that object would be a char, then this expression would return a pointer to that char. This is what the "pointer to a suitable created object" wording you cited means.
In this case, p points to an actual object of type char.
Then we create a new char, which overlays the original char. Because of that, [basic.life]/8 is triggered. This defines a concept called "transparently replaceable". The new object transparently replaces the old one, and therefore, pointers/references to the old object transparently become pointers/references to the new one:
a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object
Therefore, from this point onward, p points to the new char.
So the static_cast will now return a char* that points to a char, which delete can delete with well-defined behavior. Since the code otherwise would have UB and IOC can fix that UB... it must do so.
Now, if your example had been:
void* p = operator new(1);
auto p2 = new (p) char;
delete p2;
Does an object get created in p? The answer is... it doesn't matter. Because you never use p in a way that requires it to point to a created object, this program has well-defined behavior either way. So the question is irrelevant.
|
73,427,089
| 73,427,104
|
Merge Sorted array Error in c++: reference binding to null pointer of type 'int' (stl_vector.h)
|
https://leetcode.com/problems/merge-sorted-array/
In this leetcode question, this is the logic, I used
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = 0;
int j = 0;
int k = 0;
vector<int> ans;
while (i<m && j<n) {
if (nums1[i] < nums2[j]){
ans[k++] = nums1[i++];
}
else {
ans[k++] = nums2[j++];
}
}
while (i<m) {
ans[k++] = nums1[i++];
}
while (j<n) {
ans[k++] = nums2[j++];
}
for (int h = 0; h<(m+n); h++) {
nums1[h] = ans[h];
}
}
};
while running the code, I get this runtime error.
Error Image
How do I solve this
|
This is a vector of size zero
vector<int> ans;
This code attempts to change an element of the size zero vector.
ans[k++] = nums1[i++];
That's the cause of your error.
If you want to add an element to the end of a vector use push_back
ans.push_back(nums1[i++]);
C++ vectors don't change size automatically, you have to use push_back or resize or insert or something similar.
Alternatively make the vector the correct size to begin with
vector<int> ans(m + n);
though I prefer the push_back method myself.
|
73,427,275
| 73,431,953
|
QML - Cannot assign to non-existent property "onYes" or "onNo" in MessageDialog
|
I'm just making a simple message dialog using MessageDialog in QML. I got a problem about connecting onYes (also onNo) signal to a slot. Here's my code
import QtQuick
import QtQuick.Dialogs
import QtQuick.Controls
MessageDialog {
title: "Save File?"
text: "The file has been modified"
informativeText: "Do you want to save your changes?"
buttons: MessageDialog.Yes | MessageDialog.No | MessageDialog.Cancel
onYes: console.log("You clicked Yes") // The error started occur here
onNo: console.log("You clicked No")
}
I ran this code and the compiler said Cannot assign to non-existent property "onNo" // Also onYes.
How can I fix it? I'm using Qt 6.3.1
|
Ok guys, I found the answer.
First, Add QT += widgets to the .pro file, then add the following code to the main.cpp:
#include <QApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
After that, add import Qt.labs.platform to the qml MessageDialog file. Finally, follow the answer of Sergey Lebedev: use onYesClicked, onNoClicked instead of onYes, onNo. Like this:
Before
import QtQuick
import QtQuick.Dialogs
import QtQuick.Controls
MessageDialog {
title: "Save File?"
text: "The file has been modified"
informativeText: "Do you want to save your changes?"
buttons: MessageDialog.Yes | MessageDialog.No | MessageDialog.Cancel
onYes: console.log("You clicked Yes") // The error started occur here
onNo: console.log("You clicked No")
}
After
import QtQuick
import QtQuick.Dialogs
import QtQuick.Controls
import Qt.labs.platform
MessageDialog {
title: "Save File?"
text: "The file has been modified"
informativeText: "Do you want to save your changes?"
buttons: MessageDialog.Yes | MessageDialog.No | MessageDialog.Cancel
onYesClicked: console.log("You clicked Yes") // Now we fixed the error!
onNoClicked: console.log("You clicked No")
}
|
73,427,352
| 73,427,391
|
Scaling models influences position in OpenGL
|
The scale of my models seems to changed their positions, but I don't know why. I am doing it in the S-R-T order. The blue plane has (0,0,0) as it's origin.
The model matrix is calculated like this:
// set model matrix
glm::mat4 model = glm::mat4( 1.0f );
// scale
model = glm::scale( model, _entity.Scale );
// rotate
model = glm::rotate( model, glm::radians( _entity.Rotation.x ), glm::vec3( 1.0f, 0.0f, 0.0f ) );
model = glm::rotate( model, glm::radians( _entity.Rotation.y ), glm::vec3( 0.0f, 1.0f, 0.0f ) );
model = glm::rotate( model, glm::radians( _entity.Rotation.z ), glm::vec3( 0.0f, 0.0f, 1.0f ) );
// translate
model = glm::translate( model, _entity.Position );
Shader::setMat4( _shader, "model", model );
In the shader it looks like this:
vs_out.FragPos = vec3(model * vec4(aPos, 1.0));
vs_out.Normal = mat3(transpose(inverse(model))) * aNormal;
vs_out.TexCoord = aTexCoord;
gl_Position = projection * view * vec4(vs_out.FragPos, 1.0);
The first picture is with 1.0 scale, the second with 10.0 scale:
|
I am doing it in the S-R-T order.
No. You do it in the order T-R-S. The order S-R-T is p' = translation * rotation * scale * p. You have to read it from right to left.
// set model matrix
glm::mat4 model = glm::mat4( 1.0f );
//translate
model = glm::translate( model, _entity.Position );
// rotate
model = glm::rotate(model, glm::radians(_entity.Rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
model = glm::rotate(model, glm::radians(_entity.Rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
model = glm::rotate(model, glm::radians(_entity.Rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
//scale
model = glm::scale(model, _entity.Scale);
Shader::setMat4( _shader, "model", model );
|
73,427,878
| 73,432,548
|
Python Bindings with C++
|
I am interested in writing functions in C++ that can later be "imported" in Python. For example I wrote a simple function in C++ that adds two int numbers:
//function declaration
int addition(int a,int b);
//function definition
int addition(int a,int b)
{
return (a+b);
}
I also have a header file which contains:
extern "C" MATHLIBRARY_API int addition(int a, int b);
Then in Python the code is straightforward due to the help of ctypes:
import ctypes
path = "C:\\my path to the .dll file"
# load the library
lib = ctypes.CDLL('{0}\MathLibrary.dll'.format(path))
answer = lib.addition(14, 2)
print(answer) // OUTPUT: 16
Everything works good so far, but I would like to do some math with more complex data structures such as vectors.
I would like to have a vector of elements (example: {12, 10, 2, 14}) and add a number to all of the elements inside the vector. For example, n = 2, vector = {12, 10, 2, 14}, output = {14, 12, 4, 16}.
I wrote a function that works in C++ but I can't manage to do the binding to Python. I believe that is due to the fact I am working with vectors and that extern "C" in the header file.
|
ctypes only allows you to interact with a library using C types, not C++. boost.python, pybind11, etc allow you pass C++ objects.
However, there is a way to do what you want to do in ctypes using C-style arrays.
Declare a function like this:
extern "C" MATHLIBRARY_API void addToArray(int *array, int num, int size);
and define it like this:
void addToArray(int *array, int num, int size)
{
for (int i=0; i < size; ++i)
{
array[i] = array[i] + num;
}
}
Then in your Python script do this:
nums = [12, 10, 2, 14]
array_type = ctypes.c_int * len(nums)
lib.additionArray.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int]
array = array_type(*nums)
lib.addToArray(array, ctypes.c_int(2), ctypes.c_int(len(nums)))
# copy modified array into original list
nums[:] = list(array)
print(nums)
|
73,427,939
| 73,428,196
|
How to set Boost RTree Node with template class
|
I have two files: header.h and code.cpp, I can not write any boost namespace on code.cpp, so all "boost::geometry::etc..." calls go on header.h. The idea is to implement two template classes: one for the RTree and other for the RTree Node, this way the user may include the header.h file and implement the RTree on code.cpp using the two template classes on header.h. This is what I have so far:
header.h:
template< class TT > class Node
{
using PointType = boost::geometry::model::d2::point_xy< TT >;
using BoxType = boost::geometry::model::box< PointType >;
using NodeType = std::pair< BoxType, std::string >;
NodeType node;
public:
Node(){}
template< class T >
Node( const BBox< T > &box, const std::string nodeName ){
node = std::make_pair( BoxType{ PointType{ box.xLo(), box.yLo() },
PointType{ box.xHi(), box.yHi() } }, nodeName );
}
};
template< class TT > class RTree
{
using RTreeType = boost::geometry::index::rtree< TT, boost::geometry::index::quadratic< 16 > >;
RTreeType rtree;
public:
RTree(){}
template< T >
void insertBox( const BBox< T > &box, const std::string nodeName ) {
rtree.insert( Node< T >( box, nodeName ) );
}
template< T >
void query( const BBox< T > &box, std::vector< Node< T > > &queryResult ) {
rtree.query( boost::geometry::index::intersects( Node< T >( box, "" ) ),
std::back_inserter( queryResult ) );
}
};
Some of the errors I am getting:
error: could not convert 'boost::geometry::index::detail::indexable<Node<int>, false>::NOT_VALID_INDEXABLE_TYPE31::assert_arg()' from 'mpl_::failed************(boost::geometry::index::detail::indexable<Node<int>, false>::NOT_VALID_INDEXABLE_TYPE::************)(Node<int>)' to 'mpl_::assert<false>::type' {aka 'mpl_::assert<false>'}
31 | BOOST_MPL_ASSERT_MSG(
| ^
| |
| mpl_::failed************ (boost::geometry::index::detail::indexable<Node<int>, false>::NOT_VALID_INDEXABLE_TYPE::************)(Node<int>)
...
error: could not convert 'boost::geometry::traits::point_type<Node<int> >::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE45::assert_arg()' from 'mpl_::failed************ (boost::geometry::traits::point_type<Node<int> >::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE::************)(mpl_::assert_::types<Node<int>, mpl_::na, mpl_::na, mpl_::na>)' to 'mpl_::assert<false>::type' {aka 'mpl_::assert<false>'}
45 | BOOST_MPL_ASSERT_MSG
| ^
| |
| mpl_::failed************ (boost::geometry::traits::point_type<Node<int> >::NOT_IMPLEMENTED_FOR_THIS_POINT_TYPE::************)(mpl_::assert_::types<Node<int>, mpl_::na, mpl_::na, mpl_::na>)
...
error: no type named 'type' in 'struct boost::geometry::traits::point_type<Node<int> >'
66 | >::type type;
| ^~~~
It seems to me I have to use indexable. Although I am not sure how I am supposed to do it with the code I already have. Any help is welcome, thanks in advance.
|
We had to guess what BBox is. But all in all it looks like you "just" want a tree with nodes that are (box, name).
I'd suggest skipping the Node class (and all of the generics that wouldn't work anyways because you hardcoded the conversion to Node<T> anyways, which only works if the geometries were convertable (box and box don't interconvert).
Live On Coliru
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/index/rtree.hpp>
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
namespace detail {
template <typename Coord> using Point = bg::model::d2::point_xy<Coord>;
template <typename Coord> using BBox = bg::model::box<Point<Coord>>;
template <class Coord> using Node = std::pair<BBox<Coord>, std::string>;
}
template <class Coord> struct RTree {
using Point = detail::Point<Coord>;
using Box = detail::BBox<Coord>;
using Node = detail::Node<Coord>;
using RTreeType = bgi::rtree<Node, bgi::quadratic<16>>;
void insertBox(Box box, const std::string nodeName) {
rtree.insert(Node(box, nodeName));
}
using Result = std::vector<Node>;
void query(Box box, Result& queryResult) {
rtree.query(bgi::intersects(box), back_inserter(queryResult));
}
private:
RTreeType rtree;
};
int main() {
using Tree = RTree<double>;
Tree x;
x.insertBox({{1.0, 2.0}, {7.0, 8.0}}, "first");
x.insertBox({{2.0, 3.0}, {6.0, 7.0}}, "second");
Tree::Result v;
x.query({{3.0, 4.0}, {5.0, 6.0}}, v);
for (auto& [box,name] : v)
std::cout << std::quoted(name) << ": " << bg::wkt(box) << "\n";
}
Prints
"first": POLYGON((1 2,1 8,7 8,7 2,1 2))
"second": POLYGON((2 3,2 7,6 7,6 3,2 3))
More
If really you're not showing the full picture, and you need Node<T> to be more than shown, consider
deriving from std::pair and using the existing indexable<> implementation
providing your own IndexableGetter
Showing the second Live On Coliru:
namespace detail {
template <typename Coord> using Point = bg::model::d2::point_xy<Coord>;
template <typename Coord> using BBox = bg::model::box<Point<Coord>>;
template <class Coord> struct Node {
using Indexable = BBox<Coord>;
using Id = std::string;
Indexable box;
Id name;
Node(Indexable b, Id n) : box(std::move(b)), name(std::move(n)) {}
struct Getter {
using result_type = Indexable const&;
result_type operator()(Node const& v) const { return v.box; }
};
};
}
template <typename Coord>
struct bgi::indexable<::detail::Node<Coord>>
: ::detail::Node<Coord>::Getter {};
No further changes, still printing
"first": POLYGON((1 2,1 8,7 8,7 2,1 2))
"second": POLYGON((2 3,2 7,6 7,6 3,2 3))
|
73,428,067
| 73,430,778
|
align right-to-left text with QPainter::drawText
|
I am trying to paint a right-to-left text with QPainter. It however still aligns the text to left despite the fact that it should be right-aligned. Or at least it is right-aligned when displayed in QTextEdit. That am I doing wrong? See the example:
QTextOption option;
option.setTextDirection(Qt::LayoutDirectionAuto);
painter->drawText(rect, "خامل\nخاملخامل", option); // this is just testing text, I have no idea what it means, hopefully it is not something offensive :)
This is what I get. The red arrow shows where it should be aligned.
Of course I cannot use fixed right alignment because I do not whether the text in question is left-to-right or right-to-left text. So it must work for both directions automatically depending on the text.
UPDATE: I want to emphasize that I need a solution which automatically recognizes the language/writing system of the text (left-to-right, such as English, versus right-to-left, such as Arabic) and aligns the text automatically.
|
you should check your text with isRightToLeft() function.
QString isRightToLeft():
Returns true if the string is read right to left.
This will help you to understand your text language.
I checked the QTextEdit source and understand it uses this function.
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QRect rect = QRect(0, 0, width(), height());
QString txt = tr("خامل\nخاملخامل");
// QString txt = tr("ABCD\nABCD");
QTextOption option;
if (txt.isRightToLeft())
{
option.setTextDirection(Qt::RightToLeft);
}
else
{
option.setTextDirection(Qt::LeftToRight);
}
painter.drawText(rect, txt, option);
}
|
73,429,034
| 73,429,136
|
Vector iterator inconsistent and Expression: cannot seek vector iterator after end
|
I'm trying to add a value to a vector after every 5 elements. This example gives me an assert error
Expression: cannot seek vector iterator after end
The error is self explanatory however the code executes in an online compiler and gives the desired result. I can just do 1 less iteration in which case the final insert won't happen and return an error. I also know creating a struct would be a better way to tackle this, but I'd like to know how/why I'm struggling with this iterator method.
The vertexSize divides evenly into targetBuffer in every case so that isn't an issue.
//error example
int vertexSize = 5;
int size = targetBuffer.size() / vertexSize;
std::cout << targetBuffer.size() << std::endl;
std::cout << vertexSize << std::endl;
std::vector<float>::iterator it;
it = targetBuffer.begin() + vertexSize;
std::cout << std::distance(targetBuffer.begin(), it) << std::endl;
for (int i = 0; i < size; i++) {
it = targetBuffer.insert(it, (unsigned int)(i * vertexSize) / (24 * vertexSize));
it += vertexSize + 1;
}
However if I run this below example in an online compiler and it runs and gives the desired result.
int vertexSize = 3;
std::vector<int> targetBuffer;
for(int i = 0; i < 1002; i++){
targetBuffer.push_back(-1);
}
int size = targetBuffer.size() / 3;
for (int i = 0; i < 110; i++) {
std::cout << i <<":" << " " << targetBuffer[i] << std::endl;
}
std::vector<int>::iterator it;
it = targetBuffer.begin() + vertexSize;
for (int i = 0; i < size; i++) {
//(unsigned int)(i*5)/(24*5)
it = targetBuffer.insert(it, (unsigned int)(i * vertexSize) / (24 * vertexSize));
std::advance(it, 3);
}
std::cout << "NEW SIZE " << targetBuffer.size() << std::endl;
for (int i = 0; i < 110; i++) {
std::cout << i <<":" << " " << targetBuffer[i] << std::endl;
}
for (int i = 900; i < targetBuffer.size(); i++) {
std::cout << i <<":" << " " << targetBuffer[i] << std::endl;
}
Original vector
0: -1
1: -1
2: -1
3: -1
4: -1
5: -1
6: -1
7: -1
8: -1
intial iterator
it = targetBuffer.begin() + vertexSize;
Inserting attribute
it = targetBuffer.insert(it, (unsigned int)(i * vertexSize) / (24 * vertexSize));
it += vertexSize + 1;
0: -1
1: -1
2: -1
3: 0
4: -1
5: -1
6: -1
7: 0
8: -1
9: -1
10: -1
11: 0
So I have a few observations about using iterators.
If I disinclude the +1 from the addition it then inserts only 2 places instead of 3 as seen below. But the first inserts after 3 spaces.
it = targetBuffer.insert(it, (unsigned int)(i * vertexSize) / (24 * vertexSize));
it += vertexSize;
0: -1
1: -1
2: -1
3: 0
4: -1
5: -1
6: 0
7: -1
8: -1
9: 0
My guess is that this is due to the resizing of the vector and the iterator not accounting for the newly added value or something along those lines? Maybe I should reevaluate the iterator in each iteration of the loop i.e.
for(...)
it = targetBuffer.begin() + i * vertexSize;
or something along these lines
|
The issue is simply that it is forbidden to increment an iterator beyond the end iterator even if you never try to dereference the result.
When you write std::advance(it, 3); or it += vertexSize + 1; and the size of the original vector is not divisible by the step size you chose, the resulting value of it may be beyond the end of the vector in the last loop iteration. Because it is the last loop iteration you don't actually reenter the loop body and use that value of it, but it is simply not allowed to form this iterator in the first place and doing so causes undefined behavior. That it happens to work sometimes doesn't change that. (That's the problem with undefined behavior. It may appear to work sometimes but there is absolutely no guarantee about how it will behave.)
You can resolve this by rewriting your loop so that you increment the iterator in the loop first before inserting, so that the problematic increment you currently have in the last loop iteration is dropped:
it = targetBuffer.begin();
for (int i = 0; i < size; i++) {
std::advance(it, vertexSize);
it = targetBuffer.insert(it, (unsigned int)(i * vertexSize) / (24 * vertexSize));
// `insert` inserts _before_ the passed iterator,
// so get back to that element
std::advance(it, 1);
}
However, this algorithm has terrible performance. Its time complexity is quadratic in the length of the vector. It would be better to create a new vector, call .reserve (or .resize) on it to reserve the correct size, then loop through the vector and .push_back copies of the old and the new elements (or index into it instead of using .push_back). Finally move-assign or swap the new vector with the old one.
|
73,429,167
| 73,429,440
|
C++ No ouput when Trying to run two functions at once using threads
|
Hello i am trying to run two functions at the same time.
Because i want to learn to make a timer or countdown of some kind.
And i have an idea on how to do so. But when i create two threads.
I get no output in my console application.
Here is my code.
#include <iostream>
#include <Windows.h>
#include <thread>
#include <random>
#include <string>
void timer()
{
int x{ 0 };
if (x < 1000)
{
std::cout << x++;
Sleep(1000);
}
}
void timer2()
{
int x{ 0 };
if (x < 10000)
{
std::cout << x++;
Sleep(1000);
}
}
int main()
{
std::thread one(timer);
std::thread two(timer2);
one.detach();
two.detach();
return 0;
}
|
You should use join instead of detach. Otherwise, the main thread won't wait for the other threads and the program will exit almost immediately. You can use std::this_thread::sleep_for instead of Sleep to make the code portable (no Windows.h required).
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
void timer()
{
int x{ 0 };
if (x < 1000)
{
std::cout << x++;
std::this_thread::sleep_for(1s);
}
}
void timer2()
{
int x{ 0 };
if (x < 10000)
{
std::cout << x++;
std::this_thread::sleep_for(1s);
}
}
int main()
{
std::thread one(timer);
std::thread two(timer2);
one.join();
two.join();
return 0;
}
|
73,429,589
| 73,433,830
|
How to perform exponentiation using boost multiprecision and boost math?
|
I am running a biased Monte Carlo simulation, and I need to process the energies being reported. I essentially have to compute exp(-beta*energy), where energy is a negative number and beta can be around 100. If energy = 90, std::exp starts outputting inf.
This is a test run:
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/special_functions/expm1.hpp>
#include <iostream>
#include <cmath>
int main()
{
// using namespace boost::multiprecision;
double u = std::exp (900.0);
boost::multiprecision::cpp_dec_float_50 v = 2.71;
// loop for e^900
for(unsigned i = 1; i < 901; ++i){
v *= 2.71;
}
boost::multiprecision::cpp_dec_float_50 x = boost::math::expm1 (900.0);
std::cout << "u = " << u << std::endl;
std::cout << "v = " << v << std::endl;
std::cout << "x = " << x << std::endl;
return 0;
}
Results:
u = inf
v = 1.27447e+390
x = inf
My question is, how do i perform this exponentiation, and get the answer like in v?
|
Just use exp! Live On Compiler Explorer
boost::multiprecision::cpp_dec_float_50 x = 900.0;
std::cout << "v = " << exp(x) << std::endl;
Prints
v = 7.32881e+390
The difference between exp(900.0) and exp(x) is that 900.0 is of type double and x is cpp_dec_float_50.
ADL finds the correct overload for exp in the associated namespace.
|
73,429,788
| 73,432,143
|
How to link OpenSSL in windows using MSYS2?
|
I wrote a c++ program using OpenSSL, it works fine on linux but when I try to compile on windows I get an error that libcrypto-1_1-x64.dll, libssl-1_1-x64.dll are missing
I am compiling using
g++ main.cpp -lws2_32 -LC:\msys64\mingw64\bin -IC:\msys64\mingw64\include\openssl
Both dll files can be found in C:\msys64\mingw64\bin, but the executable does not work
|
I just came up with a simple openssl example and compiled/linked fine
$ g++ ssltest.cpp -lssl -lcrypto -o ssltest
$ ls -l
-rw-r--r-- 1 Fred None 1072 Aug 21 01:18 ssltest.cpp
-rwxr-xr-x 1 Fred None 77824 Aug 21 01:18 ssltest.exe
It just works out of the box.
I am using the CLANG64 environment and I have the mingw-w64-clang-x86_64-openssl package installed. The files are installed on
$ pacman -Ql mingw-w64-clang-x86_64-openssl | grep '.dll'
mingw-w64-clang-x86_64-openssl /clang64/bin/libcrypto-1_1-x64.dll
mingw-w64-clang-x86_64-openssl /clang64/bin/libssl-1_1-x64.dll
mingw-w64-clang-x86_64-openssl /clang64/lib/engines-1_1/capi.dll
mingw-w64-clang-x86_64-openssl /clang64/lib/engines-1_1/padlock.dll
mingw-w64-clang-x86_64-openssl /clang64/lib/libcrypto.dll.a
mingw-w64-clang-x86_64-openssl /clang64/lib/libssl.dll.a
|
73,430,330
| 73,667,696
|
Triangulation of polygon with holes using ear clipping algorithm
|
After parsing the contours from a truetype font file, I generated the points that compose the polygon that I want to triangularize.
These points are generated by merging the different holes into one polygon:
Generated Polygon of the letter A:
As you can see i "merged" the holes by picking two points between the inner and outer polygon with the minimum distance.
This polygon breaks my current implementation of the ear clipping algorithm:
static bool
is_point_in_triangle(triangle Triangle, vec2 Point) {
vec2 AB = Triangle.B - Triangle.A;
vec2 BC = Triangle.C - Triangle.B;
vec2 CA = Triangle.A - Triangle.C;
vec2 AP = Point - Triangle.A;
vec2 BP = Point - Triangle.B;
vec2 CP = Point - Triangle.C;
float Cross1 = cross(AB, AP);
float Cross2 = cross(BC, BP);
float Cross3 = cross(CA, CP);
return (Cross1 <= 0.0f) && (Cross2 <= 0.0f) && (Cross3 <= 0.0f);
}
static triangle_list
triangulate_ear_clip(memory_arena* Arena, polygon SimplePolygon) {
triangle_list List = {};
unsigned int TriangleCount = 0;
triangle* Triangles = allocate_array(Arena, triangle, SimplePolygon.Count - 2);
unsigned int* Indices = allocate_array(Arena, unsigned int, SimplePolygon.Count);
int IndexCount = SimplePolygon.Count;
for(int Index = 0; Index < IndexCount; ++Index) {
Indices[Index] = Index;
}
while(IndexCount > 3) {
for(int Index = 0; Index < IndexCount; ++Index) {
int IndexA = Indices[Index];
int IndexB = Indices[Index ? (Index - 1) : (IndexCount - 1)];
int IndexC = Indices[(Index + 1) % IndexCount];
check((IndexA != IndexB) && (IndexA != IndexC) && (IndexC != IndexB));
vec2 A = SimplePolygon.Elements[IndexA];
vec2 B = SimplePolygon.Elements[IndexB];
vec2 C = SimplePolygon.Elements[IndexC];
vec2 AB = B - A;
vec2 AC = C - A;
check((A != B) && (A != C) && (B != C));
if(cross(AB, AC) >= 0.0f) {
bool IsEar = true;
for(int OtherIndex = 0; OtherIndex < (int)SimplePolygon.Count; ++OtherIndex) {
if((OtherIndex != IndexA) && (OtherIndex != IndexB) && (OtherIndex != IndexC)) {
vec2 D = SimplePolygon.Elements[OtherIndex];
if(is_point_in_triangle(triangle_from(B, A, C), D)) {
IsEar = false;
break;
}
}
}
if(IsEar) {
Triangles[TriangleCount++] = triangle_from(B, A, C);
move(Indices + Index, Indices + Index + 1, sizeof(unsigned int) * (IndexCount - Index - 1));
IndexCount--;
break;
}
}
}
}
check(IndexCount == 3);
check(TriangleCount == SimplePolygon.Count - 3);
Triangles[TriangleCount++] = triangle_from(SimplePolygon.Elements[Indices[0]], SimplePolygon.Elements[Indices[1]], SimplePolygon.Elements[Indices[2]]);
List.Count = TriangleCount;
List.Elements = Triangles;
return List;
}
For some reason cross(AB, AC) is always negative and the loop stalls forever.
I can't figure out why this happens since the polygon should be ok to be triangulated.
I also provided a list of the generated points in the second image link.
Even if some types in the provided code are non-standard they should easily be recognizable, feel free to ask otherwise. memory_arena is just a custom allocator i use.
Thanks for your attention.
PS: I dont want to use a library
|
The problem was that in is_point_in_triangle() the function was considering points on the outline inside the triangle (and then not consider the triangle as an ear).
This breaks because when merging the polygon and the hole, some points overlap.
I fixed this by removing the =: (Cross1 < 0.0f) && (Cross2 < 0.0f) && (Cross3 < 0.0f) and by doing a special check:
vec2 D = SimplePolygon.Elements[OtherIndex];
if((D != A) && (D != B) && (D != C)) {
if(is_point_in_triangle(triangle_from(B, A, C), D)) {
IsEar = false;
break;
}
}
|
73,430,379
| 73,430,417
|
Understanding the convertible_to concept in c++20
|
I'm still new to the C++20 concepts and I want to know why this does not work. I want to create a function template that concatenates numbers as strings. So I wanted to try concepts. I used std::convertible_to to check whether the entered datatype (which is int in this case) can be converted to std::string. But I'm facing an error that I don't understand.
//building the concept
template <typename T>
concept ConvertibleToStdString = std::convertible_to<T,std::string>;
//using the concept
template <ConvertibleToStdString T>
std::string concatenate(T a, T b){
return std::to_string(a) + std::to_string(b);
}
int main(){
int x{623};
int y{73};
auto result = concatenate(x,y);
std::cout << result << std::endl;
return 0;
}
Error:
main.cpp:21:34: error: use of function 'std::string concatenate(T, T) [with T = int; std::string = std::basic_string<char>]' with unsatisfied constraints
21 | auto result = concatenate(x,y);
What am I doing wrong ?
|
You appear to want a concept for types that can be passed to std::to_string().
This code will achieve that.
template <typename T>
concept ConvertibleToStdString = requires(T a){ std::to_string(a); };
What am I doing wrong ?
You are misunderstanding the meaning of std::convertible_to<T,std::string>.
That concept validates (among other things) that T can implicitly convert to a std::string, as in:
std::string s;
s = 623; // This will NOT compile. int is not convertible_to std::string
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.