question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,231,700 | 69,232,007 | Recommended C++ Include Practice | In the following scenario, what would be the best approach to include the <string> header?
main.cpp
#include "extra.h"
int main() {
func("A string");
return 0;
}
extra.h
#ifndef EXTRA_H
#define EXTRA_H
#include <string>
void func(std::string);
#endif
extra.cpp
#include <iostream>
#include "extra.h"
void func(std::string str) {
std::cout << str << '\n';
}
| Your extra.h includes <string> because it uses it directly. There is no direct use of std::string in your main.cpp so it would be strange to include <string> there.
Further, including <string> in extra.cpp is totally unnecessary because the use of std::string is in a function signature which you know is declared in extra.h, plus the maintenance of the two extra files can reasonably be expected to be done as a single operation, so there's no worry about extra.h suddenly not including <string> and then breaking extra.cpp, because they'd be maintained together.
|
69,231,701 | 69,232,126 | I can't understand how the time complexity of following c++ code is calculated? | Following code prints union of two unsorted arrays using C++ STL set.
I know that the time complexity of inserting an element in a set is O(log N), where N is the size of the set.
This code is from https://www.geeksforgeeks.org/find-union-and-intersection-of-two-unsorted-arrays/.
// C++ program for the union of two arrays using Set
#include <bits/stdc++.h>
using namespace std;
void getUnion(int a[], int n, int b[], int m)
{
// Defining set container s
set<int> s;
// Inserting array elements in s
for (int i = 0; i < n; i++)
s.insert(a[i]);
for (int i = 0; i < m; i++)
s.insert(b[i]);
cout << "Number of elements after union operation: " << s.size() << endl;
cout << "The union set of both arrays is :" << endl;
for (auto itr = s.begin(); itr != s.end(); itr++)
cout << *itr
<< " "; // s will contain only distinct
// elements from array a and b
}
// Driver Code
int main()
{
int a[9] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 };
int b[10] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 };
getUnion(a, 9, b, 10);
}
Time Complexity: O(m * log(m) + n * log(n)).
Please explain how the above time complexity is calculated.
| In C++, a set is internally implemented using a self-balancing Binary Search Tree (BST). This means that everytime a new element is inserted into a set, internally it has to check the correct place of insertion of this new element in the BST, and then rebalance that BST. This operation of inserting a new element and performing rebalance of the BST takes approximately O(log(n)) time where n is the number of elements in the BST.
The below code snippet runs n times, and each insert operation has O(log(n)) time complexity in the worst case, hence the time complexity of the below piece of code is O(n * log(n)).
for (int i = 0; i < n; i++)
s.insert(a[i]);
Now, after the above code snippet is executed, the set will have n elements in the worst case (if all the n elements in int a[] are unique).
The next code snippet provided below runs m times, and each insert operation has O(log(n + m)) time comlexity in the worst case (because there might already be n elements in the set before this below loop starts), hence the time complexity of the below piece of code is O(m * log(m + n)).
for (int i = 0; i < m; i++)
s.insert(b[i]);
This last for loop below runs for all the n + m elements in the worst case (if all the n elements in array a[] and all the m elements in array b[] are unique). Hence, the time complexity of the below code is O(n + m), because the below code visits all the n + m elements in the internal BST.
for (auto itr = s.begin(); itr != s.end(); itr++)
cout << *itr
<< " "; // s will contain only distinct
// elements from array a and b
All the above 3 code snippets run serially (one after the other), hence the total time complexity has to be added to find the final time complexity.
Time Complexity = O(nlog(n) + mlog(m + n) + (m + n))
Out of all the above 3 terms, nlog(n) and mlog(m + n) terms are larger than (m + n), hence we can omit (m + n) and write the time complexity as O(nlog(n) + mlog(m + n)).
Relevant Links -
GeeksForGeeks Article on set vs unordered_set in C++
GeeksForGeeks Article on Searching and Insertion in Binary Search Tree
|
69,232,463 | 69,233,763 | Switch default c++ library from std=c++14 to std=c++17 on ubuntu | I have tried to install a package on ubuntu that needs c++17 or newer libraries.
I installed gcc-10 and g++-10. I also found that the default c++ library is c++14 by using this code:
man g++ | grep "This is the default for C++ code"
But I don't know how to change it to other versions.
To run a simple code we can use -std=c++17. But I think Installing a package needs to change the default library.
| The c++ standard library traditionally is part of the compiler. On GNU/Linux systems typically GCC is used in conjunction with its standard library. An alternative would be CLang.
Note that the standard version is not only about the library, but even more so about language features that need to be implemented by the compiler directly.
Each compiler version has a default standards version, but supports several.
The correct way to select a specific standards version during compilation is through a compiler flag. This should be part of a software's build system if the software depends on a specific version.
Compiler flags may be set in environmental variables, e.g. CXXFLAGS. These are then recognized by the popular build helpers like GNU Make or CMake. As the standards version to use is closely tied to the piece of software to be compiled, it would not be good practice to put the standards version into the environment.
But is it a problem if several pieces of software are built with a different standards version? No, not at all. Even when you link them together, the ABI compatibility is given across standards. See https://stackoverflow.com/a/49119902/21974 for a detailed answer on that topic.
Note that packages you install in Ubuntu are all pre-compiled, so you have no sway over how they are compiled.
|
69,232,521 | 69,235,328 | Convert a Tabled PDF data into a text (or any other readable format) file using C++ or Python | I have a PDF file that contains Timetable of a university, generated from aSc Timetables software.
The data looks something like this,
There are about 29 such pages in the PDF file.
I want to process this data for a program and therefore, want it to be in readable form in any programming language, and preferably in C++ or in Python language.
Can anyone guide me how could I do it? Maybe some library that I can use to convert this data into a Text file using C++?
What I need the data to be in is in this kind of form,
Suppose in C++, we have a class with the name of Section (one object will represent each section, for example "BCS-1A"'s object or "BCS-7E" object and etc.)
So, for BCS-1A
Section Object:
section_name: "BCS-1A" // (section_name is a string data member)
// There will be 7 arrays, each representing one day of the week and each array will be of size 16. One index of the array will represent one time slot of that day. So, in this case,
moday_schedule[16]; // it will be an **linked list** array of 16 size. Each index can be empty or may contain as many slots as possible. Each index represents the time slot in the timetable. For example "0th" index will represent the time slot of 8:45 to 9:15, 16th index will represent 4:15 to 4:40 and etc.
// For example, monday_schedule[0] will be EMPTY.
// monday_schedule[4] will contain an object that will have following information,
// Subject: Digital Logic Design
// Teacher: Mirza Waqar Baig
// Sub-section: None (there is a sub-section in some lectures)
// Room: R-5
// monday_schedule[5] will also contain same information
// monday_schedule[12] will have two objects.
// and both the objects will have an attribute of "Sub-section" as well
| I've compiled up a repository on GitHub
I used pdf2image to first convert the pdf to image files and store those files in an images folder.
Then used pytesseract to convert those images to txt files and store those txt files in texts folder.
After that, I formatted the text a little and store it in csv format in csvs folder.
|
69,233,057 | 69,233,089 | C++ - auto return reference and non reference type | When writing a function with auto return type we can use constexpr if to return different types.
auto myfunc()
{
constexpr if (someBool)
{
type1 first = something;
return first;
}
else
{
type2 second = somethingElse;
return second;
}
}
However, I'm struggling to work out how to make just one of the types a reference. It seems like the following code still returns an r-value for both branches
auto myfunc()
{
constexpr if (someBool)
{
type1 &first = refToSomething;
return first;
}
else
{
type2 second = somethingElse;
return second;
}
}
Is there a way to do this? Google isn't revealing much as there are so many tutorials on more general use of auto and return by reference. In my particular case the function is a class method and I want to either return a reference to member variable or a view of an array.
| Just auto will never be a reference. You need decltype(auto) instead, and also put the return value inside parentheses:
decltype(auto) myfunc()
{
if constexpr (someBool)
{
type1 &first = refToSomething;
return (first);
}
else
{
type2 second = somethingElse;
return second;
}
}
|
69,233,616 | 69,251,610 | Trouble accessing Unityplayer.log on Hololens | I want to see my debug statements after running an app on Hololens which are stored in the Unityplayer.log file.
I am not able to download this logfile from the Windows Device Portal after running the app.
I am not sure what is causing this problem. The following issue pops up on the browser : This site can't be reached.
I restarted the Hololens and also checked my internet connection. Sometimes it works and most of times it doesn't get downloaded.
About the App
I am using HololensforCV project files to access sensor data and want to build an application around this. More specifically I am using ArUcodetectionHololens-Unity
I am using Hololens 1 and Unity 2019.4.7f1.
| The issue was that the project solution would not stop running in the Visual Studio when I closed the app on the Hololens. When I stopped the Deployment on the VS, I had no issue downloading the log file. In addition, sometimes the Hololens got disconnected from the internet now and then.
|
69,234,502 | 69,235,193 | How to pass a member function to a gloabal function in cpp? | Im on a Cpp beginner project. making a library system. And I wrote the following void Student::show(void) function to show student's details. Also I have written the first function to avoid repeating. I want to pass the create function to the printAtEnd function as a argument. But it gives me some errors. What I did wrong here.
// conclusion menu
template <typename R, typename A, typename C>
// R - return type
// A - argument type
// C - class type
void printAtEnd(R (C::*func)(A)){
int i;
cout << "Choose one of following.\n";
cout << "\t1. go to main menu.\n";
cout << "\t2. try again.\n";
cout << "\t3. exit the program\n";
cin >> i;
switch(i){
case 1: mainMenu(); break;
case 2: func(); break;
case 3: exit(0); break;
}
}
void Student::show(void){
system("clear");
cout << "\tStudent details\n\n";
cout << "Name: " << name << endl;
cout << "Addmission No: " << addmission_no << endl;
cout << "Email: " << email << endl;
cout << "Telephone No: " << telephone_no << endl;
cout << "Issued books: \n";
for (string x: issued_books)
cout << x << endl;
printAtEnd<void, void, Student>(&Student::show);
}
I get following error when compiling.
library.cpp: In member function ‘void Student::show()’:
library.cpp:151:36: error: no matching function for call to ‘printAtEnd<void, void, Student>(void (Student::*)())’
151 | printAtEnd<void, void, Student>(&Student::show);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~
library.cpp:79:6: note: candidate: ‘template<class R, class A, class C> void printAtEnd(R (C::*)(A))’
79 | void printAtEnd(R (C::*func)(A)){
| ^~~~~~~~~~
library.cpp:79:6: note: template argument deduction/substitution failed:
library.cpp: In substitution of ‘template<class R, class A, class C> void printAtEnd(R (C::*)(A)) [with R = void; A = void; C = Student]’:
library.cpp:151:36: required from here
library.cpp:79:6: error: invalid parameter type ‘void’
library.cpp:79:6: error: in declaration ‘void printAtEnd(R (C::*)(A))’
All I want is call printAtEnd function after every other functions. So I need to pass the pointer to a function to printAtEnd function.
| Removing useless code from the question, it could be something like:
void printAtEnd(std::function<void ()> fn)
{
fn();
}
void Student::show()
{
printAtEnd([this](){ this->show(); });
}
However, the problem with your code it that it is recursive and if the user always select the option 2, you might eventually get a stack overflow if you run on some small memory device.
In a case like this one, a loop would usually be a better option.
|
69,234,680 | 69,351,394 | Multiple source paths in batch-mode rule [nmake] | Im using the batch-mode rule for my makefile. Currently i have the following targets:
DIR_SRC = src
DIR_INCLUDE = include
DIR_LIB = lib
DIR_BIN = bin\x64
DIR_BUILD = build\x64
{$(DIR_SRC)}.cpp{$(DIR_BUILD)}.obj ::
@echo Compiling...
cl /c /EHsc /Fo$(DIR_BUILD)\ /MD /I$(DIR_INCLUDE) $<
$(EXECUTABLE_NAME) : $(DIR_BUILD)\*.obj
@echo Linking $(EXECUTABLE_NAME)...
link /out:$(DIR_BIN)\$(EXECUTABLE_NAME) $(DIR_BUILD)\*.obj
The "bin/x64/*.obj" target uses all cpp files inside the "src" folder. Is it possible to add another source path to it?
I want something like this
{$(DIR_SRC) $(ANOTHER_DIR)}.cpp{$(DIR_BUILD)}.obj ::
| If you add a second build directory to match your second source directory, you can get this to work. For example, if we modify your makefile to be:
DIR_SRC = src
DIR_SRC2 = another
DIR_INCLUDE = include
DIR_BIN = bin\x64
DIR_BUILD = build\x64
DIR_BUILD2 = build_another\x64
EXECUTABLE_NAME = foo.exe
{$(DIR_SRC)}.cpp{$(DIR_BUILD)}.obj ::
@echo Compiling...
cl -nologo /c /EHsc /Fo$(DIR_BUILD)\ /MD /I$(DIR_INCLUDE) $<
{$(DIR_SRC2)}.cpp{$(DIR_BUILD2)}.obj ::
@echo Compiling...
cl -nologo /c /EHsc /Fo$(DIR_BUILD2)\ /MD /I$(DIR_INCLUDE) $<
$(DIR_BIN)\$(EXECUTABLE_NAME) : $(DIR_BUILD)\*.obj $(DIR_BUILD2)\*.obj
@echo Linking $(EXECUTABLE_NAME)...
link -nologo /out:$@ $**
then we will get:
nmake -nologo
Compiling...
cl -nologo /c /EHsc /Fobuild\x64\ /MD /Iinclude src\*.cpp
s1.cpp
s2.cpp
Generating Code...
Compiling...
cl -nologo /c /EHsc /Fobuild_another\x64\ /MD /Iinclude another\*.cpp
a1.cpp
a2.cpp
Generating Code...
Linking foo.exe...
link -nologo /out:bin\x64\foo.exe build\x64\*.obj build_another\x64\*.obj
where src contains s1.cpp and s2.spp, and where another contains a1.cpp and a2.cpp.
|
69,235,162 | 69,237,834 | How can I find the number of elements in an already declared array of size n, if it's partially filled? | Suppose I created an array of size 5. Filled two number 1 and 2 at index 0 and 1 respectively. Now I want to return number of elements currently present in the array, i.e. 2 and not 5 given by size below. How can I do that?
int arr[5];
arr[0] = 1;
arr[1] = 2;
//size returns 5 but I want it to return 2, since it has only 2 elements.
int size = sizeof(arr)/sizeof(arr[0]);
cout << size;
| If you use a classic array, it is not possible to do what you say, you will get 5 outputs each time. But if you use std::vector, the size of the vector will change automatically every time you add a new element to the vector. Then, you can easily count the number of elements in the vector by using the size() function. you can print to the screen.
#include<iostream>
#include<vector>
int main() {
std::vector<int> vec;
for (size_t i = 1; i <= 2; ++i) { vec.push_back(i); }
std::cout << "number of elements= " << vec.size();
return 0;
}
|
69,235,185 | 69,235,357 | find difference between max and min element within a range of an array | Say I got following array
a = [4 5 2 1 3 4]
and I want to find the difference between two elements (the max and min) excluding some consecutive elements.
For example, excluding the 2nd and 3rd so that I need to find the difference of max/min of:
a = [4 1 3 4]
which in this case is
diff = 4-1
Now I am looking for an efficient algorithm that can do this over and over.
I was considering having a prefix and suffix but not sure how to move forward
| So we have an array a of size N and M queries of this form: "Excluding the interval [L, R], what's the difference between the max and min element in a?". Consider we have an efficient way to query the min and max value on an arbitrary interval [X, Y], then we can use the following algorithm:
Query min/max on the interval [0, L)
Query min/max on the interval (R, N)
Combine the min and max from both intervals
Subtract the two
Later edit: I initially proposed a solution much more complicated than necessary. I will leave it if you are curious about other approaches, but here it is a simpler one.
As we know that we will always query only intervals of form [0, something) and (something, N), we could precompute the min/max values in linear time. Consider storing them like this:
min_from_left[i] = minimum item considering only items 0..i
min_from_right[i] = minimum item considering only items i..N
same for max
Now, the minimum value excluding the interval [L, R] is min(min_from_left[L-1], min_from_right[R+1]) (I omitted the bound checks). Thus, you can achieve O(N) for precomputing and O(1) per query.
The generic (but unnecessary approach)
To find the min/max value in a given interval you have plenty of options, it just depends what are your time and memory constraints and if you need updates or not:
Segment trees (support updates)
Sparse tables (does not support updates)
Generally, you can obtain O(N + M * log N) time complexity if you need updates or O(N log N + M) if you don't need them.
See more options here https://cp-algorithms.com/sequences/rmq.html
|
69,235,381 | 69,235,854 | What would new int[3] do to the int pointer? | I was looking for uses for pointers and this turned out to be one of them. Dynamically allocating memmory. I am a little confused with the keyword new, and when adding [number] in the end. new int[3]. I do understand that this question might be bad. I'm only 13.
#include <iostream>
using namespace std;
int main() {
int* scores;
cout << "Enter top 3 scores: ";
//dynamically allocate memory
scores = new int[3];
for (int i = 0; i < 3; i++) {
"Enter score: ";
cin >> scores[i];
}
cout << endl << "Scores are: ";
for (int i = 0; i < 3; i++) {
cout << scores[i] << " ";
}
delete[] scores;
return 0;
}
| A pointer is basically a variable pointing to a specific address in memory. An array is a group of variables allocated consecutively in memory. When you write scores = new int[3] you allocate a memory for three int-type variables and make the scores variable reference the first one's address. Now, when referencing the array fields: scores[i], you take the address of the first field of the array and you add the variable i, giving you the address of the ith element.
|
69,235,389 | 69,235,776 | why do two getline() lead to no input? | I am creating a simple login program.
#include <iostream>
#include <string>
using namespace std;
void showRegister()
{
string user;
string pw;
cout << "Enter your username:";
getline(cin, user);
cout << "Enter your password:";
getline(cin, pw);
cout << "You have successfully registered!" << endl;
writeIntoFile(user, pw);
showMenu();
}
void showMenu() {
int select;
do {
cout << "1. Register"<<endl;
cout << "2. Login" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> select;
} while (select > 3);
switch (select)
{
case 1:
showRegister();
break;
case 2:
showLogin();
break;
case 3:
default:
break;
}
}
int main()
{
showMenu();
return 0;
}
This is the result when I choose 1:
As you see, I can not enter username. In function showRegister(), when I add cin.ignore() before getline(cin, user), this is the result:
As I understand, getline() reads a line until it reaches character \n and skip the rest. So why in this case, two successive getline() commands (getline(cin, user) and getline(cin, pw) lead to the fact that I can not enter username?
| The fact is getline takes input from buffer if something exists in buffer else it ask the user for value. What actually happens in your code is as soon as you enter value for select which is not greater than 3 it comes out of the loop after with a value you entered for select and the entered (which stands for \n) that you pressed get stored in buffer. So know when you come to getline for user it sees '\n' from the buffer as getline first check in buffer, so it skip the value insertion and buffer gets emptied and now when you come to getline that is used for password it ask the user for password as buffer was empty.
|
69,235,560 | 69,235,646 | How can an operating system detect an out of range segmentation fault in C? | I encounter this problem when learning Operating System and I'm really interested in how operating system detecs whether an array index is out of range and therefore produce a segmentation fault?
int main(){
char* ptr0;
ptr0[0] = 1;
}
The code above will absolutely produce a segmentation fault, since ptr0 is not allocated with any memory.
But if add one line, things change.
int main(){
char* ptr0;
char* ptr1 = ptr0;
ptr0[0] = 1;
}
This code won't cause any fault, even you change ptr0[0] to ptr0[1000], it still won't cause any segmentation fault.
I don't know why the line has such power
char* ptr1 = ptr0
I tried to disassmbly these codes but find little information.
Could somebody explain that to me on the perspective of memory allocation? thanks a lot.
| A segmentation fault happens when a process attempts to access memory it's not supposed to, not necessarily if an array is read out of bounds.
In your particular case the variable ptr0 is uninitialized, and so if you attempt to read it any value may be read and it need not even be consistent. So in the case of the first program the value that was read happened to be an invalid memory address and attempting to read from that address triggered a sigfault, while in the case of the second program the value read happened to be a valid address for the program and so a segfault was not generated.
When I ran these programs, both resulted in a segfault. This demonstrates the undefined behavior present in the program which attempts to dereference an invalid pointer.
When a program has undefined behavior, the C standard makes no guarantees regarding what the program will do. It may crash, it may output unexpected results, or it may appear to work properly.
|
69,235,641 | 69,235,715 | Why is not jthread::get_stop_source const? | The question says it. [thread.jthread.stop]/1 says:
[[nodiscard]] stop_source get_stop_source() noexcept;
Effects: Equivalent to: return ssource;
Why is it not a pure observer?
| A stop_source object allows you to request that the thread which has such an object (or its attendant stop_token) perform a stop. Such a request is not logically const. As such, if you fetch a stop_source for a jthread, it is expected that you are going to perform the aforementioned "not logically const" operation.
So the function you used to retrieve it is not const. Note that getting a stop_token is const, as this is an observer of thread-safe state, not a modifier of it.
|
69,235,904 | 69,236,026 | Print address of iterator | Why is it not possible to change the cout line with following in order to get the address of the iterator?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main (int argc, const char* argv[]) {
vector<int> inputs = {15, 20, 10, 5, 19};
vector<int>::iterator i;
i = inputs.begin();
cout << *i << endl;
return 0;
}
Above example of iterator. Clear.
cout << i << endl;
| It's not possible because there is no overload for operator<< that takes vector<>::iterator as its second argument. If you want to print the address of the iterator object, you'd need &i.
Or you could overload it yourself:
std::ostream &operator<<(std::ostream &os, const std::vector<int>::iterator &i) {
os << &i;
return os;
}
Live sample
|
69,236,089 | 69,236,151 | Error C2280 : Class::Class(void) : Attempting to reference a deleted function | So, I am working on a project, and I have two files in this project:
main.cpp, matrix.h
The problem is that My code seemed to work perfectly a few hours ago, and now it doesn't
main.cpp:
#include <iostream>
#include "matrix.h"
#include <vector>
int main() {
Matrix f;
f.create(10, 1, {3, 4, 5, 6, 7, 8, 9});
}
matrix.h:
#pragma once
#include <iostream>
#include <string>
#include <Windows.h>
#include <vector>
class Matrix {
public:
const size_t N;
bool ifMatrixCreated;
const char* NOTENOUGH = "The size of the array should match to the width*height elements";
std::vector<int> arr;
int w, h;
void create(int width, int height, const std::vector<int> a) {
w = width;
h = height;
if (a.size() != width * height) {
ifMatrixCreated = false;
std::cout << "bello";
}
else {
ifMatrixCreated = true;
arr = a;
std::cout << "hello";
}
}
};
And when I compile, it generates this error (Using VS2019):
Error C2280 | 'Matrix::Matrix(void)': attempting to reference a deleted function Matrix | Line 5
It keeps saying that "The default constructor of Matrix cannot be referenced - It is a deleted function"
Can you help solve this error?
Thanks in advance.
| Here is the correct working example. The error happens because every const data member must be initialized. And
The implicitly-declared or defaulted default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true:
T has a const member without user-defined default constructor or a brace-or-equal initializer (since C++11).
#pragma once
#include <iostream>
#include <string>
//#include <Windows.h>
#include <vector>
class Matrix {
public:
//const size_t N;//this const data member must be initialised
const size_t N = 6;
bool ifMatrixCreated;
const char* NOTENOUGH = "The size of the array should match to the width*height elements";
std::vector<int> arr;
int w, h;
void create(int width, int height, const std::vector<int> a) {
w = width;
h = height;
if (a.size() != width * height) {
ifMatrixCreated = false;
std::cout << "bello";
}
else {
ifMatrixCreated = true;
arr = a;
std::cout << "hello";
}
}
};
|
69,236,159 | 69,236,352 | Why can't I unpack entries of std::map into references? | I have noticed that unpacking keys and values from std::map does not give me references. I am assuming that individual entries in std::map is stored as a pair of const key and value.
What works:
Manually taking .second of pair from std::map into reference.
Unpacking a pair made using std::make_pair into references.
Taking references from result of std::views::values
What doesn't work:
Directly unpacking map entries in for loop into references
Unpacking map entry obtained from iterator into references
Why do above two not work? Attached is a sample source code, and deduced types from the IDE. The compiler does result in same error messages with the insertions.
#include <map>
#include <type_traits>
#include <ranges>
int main() {
std::map<int, int> data;
for (const auto& kv : data) {
auto& v = kv.second;
auto& [a, b] = kv;
static_assert(std::is_reference_v<decltype(v)>);
}
for (const auto& v : data | std::views::values)
static_assert(std::is_reference_v<decltype(v)>);
for (const auto& [k, v] : data)
static_assert(std::is_reference_v<decltype(v)>); // error
{
auto& kv = *data.begin();
auto& [k, v] = kv;
static_assert(std::is_reference_v<decltype(v)>); // error
}
{
auto kv = std::make_pair(3, 5);
auto& k = kv.first;
auto& v = kv.second;
static_assert(std::is_reference_v<decltype(v)>);
}
return 0;
}
| It is a reference. However, there is a special rule that decltype on a structured binding does (from [dcl.type.decltype]/1.1):
if E is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]), decltype(E) is the referenced type as given in the specification of the structured binding declaration;
And the referenced types for a map's pair (which is a pair<Key const, Value>) are just Key const and Value, never any kind of reference.
|
69,236,331 | 69,236,332 | Conda MacOS Big Sur ld: unsupported tapi file type '!tapi-tbd' in YAML file | When compiling a c++ project in a conda environment on MacOS Big Sur, the error
ld: unsupported tapi file type '!tapi-tbd' in YAML file may occur. How to proceed?
| On Big Sur, the SDK that comes with Command Line Tools is too new. An older one needs to be downloaded and used:
Download the 10.10 SDK "MacOSX10.10.sdk.tar.xz" from here.
Extract it: tar xf MacOSX10.10.sdk.tar.xz -C /opt
Add following lines to ~/.condarc:
conda_build:
config_file: ~/.conda/conda_build_config.yaml
create ~/.conda/conda_build_config.yaml if it doesn't exist and add:
CONDA_BUILD_SYSROOT:
- /opt/MacOSX10.10.sdk # [osx]
Many thanks to ihnorton on this thread.
|
69,236,391 | 71,255,560 | why pass window pointer in callback function opengl | why do we pass GLFWwindow pointer to parameter when we don't use the window pointer variable
example:
coid sizecallb(GLFWwindow* window, int w, int h){
glViewport(0,0,w,h);
screeenw = w;
screeenh = h;
}
| This is done because GLFW is written in C, not C++. Therefore, there's not so much ways to distinguish one window from another. Also, it's not us who pass info to callbacks, it's GLFW that executes callbacks from its code. It specifies window handle so that you can choose the window for which this callback is meant to be called. When you have only one window, this argument can be left unused. But when you create multiple windows, and you have all window handles, you can choose a window object with the handle passed in callback and execute a method on only one exact window object.
Note that you can specify different callbacks for different windows.
|
69,236,441 | 69,236,504 | Right method to declare a struct as member in another struct | Recently, I've asked a question about how to declare a struct member in another struct:
How to allocate memory for struct as member in other struct?
My question was marked as a duplicate. But really, do I need to initialize all members with default values?
In my project code base, the struct has 3 such members. And when I describe all struct members with default values, the Member Initializer List reaches three very long code lines.
Is this way right?
struct A
{
public:
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;
int k;
A(int c_a, int c_b, int c_c, int c_d, int c_e, int c_f, int c_g, int c_h, int c_i, int c_j, int c_k)
{
a = c_a;
b = c_b;
c = c_c;
d = c_d + 3;
e = c_e;
f = c_f;
g = c_g - 9;
h = c_h;
i = c_i * 4;
j = c_j;
k = c_k;
}
};
struct B
{
public:
A a;
B(A c_a) : a{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{
a = c_a;
}
};
int main(int argc, char const *argv[])
{
A a = A(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
B b = B(a);
return 0;
}
| While this constructor "works":
B(A c_a) : a{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{
a = c_a;
}
It is needlessly complex, as it initializes a with default values, just to overwrite it with new values afterwards.
At the very least, you could give A a default constructor that initializes the members to 0:
A()
{
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
g = 0;
h = 0;
i = 0;
j = 0;
k = 0;
}
And then your B constructor can omit the Member Initialization List:
B(A c_a) /*: a{}*/
{
a = c_a;
}
However, B's constructor can and should utilize A's compiler-generated copy constructor instead, to avoiding having the initialize a with default zeros at all:
B(A c_a) : a{c_a}
{
}
|
69,236,476 | 69,238,577 | Compile-time C++ function to check whether all template argument types are unique | There is a nice question (Which substitution failures are not allowed in requires clauses?) proposing the next problem.
One needs to write a compile-time function template<typename... Ts> constexpr bool allTypesUnique() that will return true if all argument types are unique, and false otherwise. And the restriction is not to compare the argument types pairwise. Unfortunately, the answer only explains why such function cannot be implemented with some particular approach.
I think the solution can be achieved using multiple inheritance. The idea is to make a class inherited from a number of classes: one for each type T in Ts. And each such class defines a virtual function with a signature depending on T. If some T is found more than once in Ts then function f in a child class will override the function in a base class and it can be detected:
template<typename> struct A{};
template<typename T, typename... Ts>
struct B : B<Ts...> {
using B<Ts...>::f;
constexpr virtual void f(A<T>, bool & unique) { if( ++count > 1 ) unique = false; }
int count = 0;
};
template<typename T>
struct B<T> {
constexpr virtual void f(A<T>, bool & unique) { if( ++count > 1 ) unique = false; }
int count = 0;
};
template<typename... Ts>
constexpr bool allTypesUnique() {
B<Ts...> b;
bool res = true;
( b.f( A<Ts>{}, res ), ... );
return res;
}
int main() {
static_assert( allTypesUnique<void>() );
static_assert( allTypesUnique<void, int&>() );
static_assert( !allTypesUnique<int&, int&>() );
static_assert( allTypesUnique<char, short, int>() );
static_assert( !allTypesUnique<char, short, char>() );
}
Demo: https://gcc.godbolt.org/z/8jhnE7P11
Just curious, is the solution correct and is there a simpler solution for this problem?
| If you use virtual base classes depending on each of the given types, you will get exact one base class instance for every unique type in the resulting class. If the number of given types is the number of generated base classes, each type was unique. You can "measure" the number of generated base classes by its size but must take care that you have a vtable pointer inside which size is implementation dependent. As this, each generated type should be big enough to hide alignment problems.
BTW: It works also for reference types.
template < typename T> struct AnyT { char i[128]; };
template < typename FIRST, typename ... T>
struct CheckT: virtual AnyT<FIRST>, virtual CheckT<T...> { };
template < typename FIRST >
struct CheckT<FIRST>: virtual AnyT<FIRST> {};
template < typename ... T>
constexpr bool allTypesUnique()
{
using T1 = CheckT<int>;
using T2 = CheckT<bool, int>;
constexpr std::size_t s1 = sizeof( T1 );
constexpr std::size_t s2 = sizeof( T2 );
constexpr std::size_t diff = s2 - s1;
constexpr std::size_t base = s1 - diff;
constexpr std::size_t measure = sizeof( CheckT< T...> );
return !((sizeof...(T)*diff+base) - measure);
}
int main() {
static_assert( allTypesUnique<void>() );
static_assert( allTypesUnique<void, int>() );
static_assert( !allTypesUnique<void, void>() );
static_assert( allTypesUnique<char, short, int>() );
static_assert( !allTypesUnique<char, short, char>() );
}
Demo
|
69,236,646 | 69,236,898 | Using poppler as a subproject in Cmake with `CMAKE_MODULE_PATH` set incorrectly | I'm new to CMake to I'm not sure what I'm doing
I'm using poppler as a library via CMake for my application. I've imported it as a submodule.
If I include popper in my top-level CMake file using add_subdirectory(...), it get the following errors
[cmake] CMake Error at external/poppler/CMakeLists.txt:7 (include):
[cmake] include could not find requested file:
[cmake]
[cmake] PopplerDefaults
[cmake]
[cmake]
[cmake] CMake Error at external/poppler/CMakeLists.txt:8 (include):
This is most likely because the CMAKE_MODULE_PATH is incorrect.
After some digging, it looks like poppler is setting the module path instead of appending to it.
https://gitlab.freedesktop.org/poppler/poppler/-/blob/master/CMakeLists.txt#L5
So I can't really override it it seems.
My (probably overly complicated) setup is here, which the poppler line commented out.
https://github.com/bdurrani/cmake-test/blob/master/CMakeLists.txt#L69
This works fine if I run cmake from within the poppler folder.
Is there a way around this? How to you handle such scenarios?
| So in your CMakeLists.txt just store and restore the CMAKE_MODULE_PATH before including the subproject.
set(tmp ${CMAKE_MODULE_PATH})
add_subdirectory(...)
# suffix the poppler stuff too.
set(CMAKE_MODULE_PATH "${tmp};${CMAKE_MODULE_PATH}")
You could also separately notify developers of the poppler project of the issue, or at best create a patch for them that Will fix the problem.
|
69,236,857 | 69,236,927 | "ReadProcessMemory" how to get std::string? | Programm_A
int main()
{
std::cout << "Process ID = " << GetCurrentProcessId() << "\n"; // Id my process (i get something like '37567')
std::string My_String = "JoJo"; // My string
std::cout << &My_String << std::endl; //here i get something like '0x0037ab7'
system("pause");
}
This program just outputs reference of string "JoJo" to console.
Programm_B
int main()
{
int id;
std::cin >> id;
DWORD ProcessId = id;
HANDLE ProcessHandle = OpenProcess(PROCESS_VM_READ, FALSE, ProcessId);
if (!ProcessHandle) {
std::cout << "Process is not found...\n";
return 0;
}
std::string r;
std::cin >> r; // this is me writing the link that I get in programs_A
DWORD address = std::strtoul(r.c_str(), NULL, 16);
std::string JoJo_string = " ";
ReadProcessMemory(ProcessHandle, (LPVOID)(address), &JoJo_string, sizeof(JoJo_string), 0); //here I want to get the JoJo_string value by reference from programm_A
std::cout << JoJo_string << std::endl;
}
The funny thing is that everything works fine with the "int" variable type. But std::string is not working. The exact value reads, but the program immediately gives an error:
[-- programm_B --]
[-- error --]
| You can't easily read a std::string across process boundaries.
Different standard library implementations of std::string use different memory layouts for its data members. The std::string in your program may be using a different implementation than the program you are trying to read from.
But even if the two programs used the exact same implementation, it still wouldn't matter, because std::string is simply too complex to read with a single ReadProcessMemory() call. std::string uses dynamic memory for its character data, so one of its data members is a char* pointer to the data stored elsewhere in memory. Which is complicated by the fact that std::string might also implement a local Short-String Optimization buffer so short string values are stored directly in the std::string object itself to avoid dynamic memory allocations.
So, you would have to know the exact implementation of std::string being used by the target program in order to decipher its data members to discover where the character data is actually being stored, and in the case where SSO is not active then read the char* pointer, as well as the number of characters being pointed at (which itself is also determinate in an implementation-specific way), so you could then read the character data with another ReadProcessMemory() call.
In short, what you are attempting to do is a futile effort.
|
69,237,361 | 69,237,431 | What is the best way to store a value that will have to be read by multiple source files but is only know at runtime | I have a function that runs when the program is started and initializes all variables that will be needed by the program but that can only be obtained during runtime. These variables will have to be read by multiple source files.
What is the best way to store these values?
One of these variables is the file path to the local Appdata directory. I don't know how expensive it is to run the function to get this path so I just want to get it once and store it for later use by the program.
I have tried using a const std::string but since (as far as I know) a constant can't be initialized at runtime that option doesn't work. Of course I can just use a global variable but that doesn't really seem like good practice. In addition this could cause problems if the variable accidentally gets edited (I can already feel the pain debugging for hours to find that one line of code).
I know that c# offers static readonly which would be perfect for me so I was interested if either something similar to this exists in c++ or if there is an alternative solution better than using a non constant global variable.
| Use a function-local static variable. It will be initialized on the first use.
const std::string &GetAppDataPath()
{
static const std::string ret = /*do stuff here*/;
return ret;
}
A global variable (which are initialized at program startup) would be inferior, because you can accidentally access it before it's initialized (from an initializer of a different global variable).
Note that you must do everything in the initializer. For example, this would be wrong:
const std::string &GetAppDataPath()
{
static const std::string ret;
ActuallyGetAppDataPath(&ret);
return ret;
}
If you can't fit everything directly into the initializer, use an immediately-invoked lambda:
const std::string &GetAppDataPath()
{
static const std::string ret = []{
std::string ret;
ActuallyGetAppDataPath(&ret);
return ret;
}();
return ret;
}
|
69,237,455 | 69,237,516 | How to return a WM_COPYDATA message instantly and also call a function? | How to return a response when receiving a WM_COPYDATA message 'instantly' and also call a function?
I tried to use chrono but the app that sent the message only receive a response after the sendCommand function has been executed.
#include <thread>
#include <future>
#include <iostream>
void sendCommand(std::chrono::seconds delay, std::string cmd)
{
std::this_thread::sleep_for( delay );
std::cout << "\nThe waited command is =" << cmd;
}
switch (msg)
{
case WM_COPYDATA:
{
OutputDebugStringW(L"\nWM_COPYDATA!");
PCOPYDATASTRUCT pcds = reinterpret_cast<PCOPYDATASTRUCT>(lParam);
//....
auto s1 = std::async(std::launch::async, sendCommand, std::chrono::seconds(5), "Command1");
return 1;
}
}
| What you're looking for is called a lambda function (https://en.cppreference.com/w/cpp/language/lambda) and looks like this:
With std::thread:
std::thread t([]
{
sendCommand(std::chrono::seconds(5), "Command1");
});
With std::async
Solution with shared future, by capturing it the lifetime of the future is extended to the life time of the lambda.
If you're on windows/msvc this has the small benefit of using a thread from a threadpool. Otherwise just use the thread solution.
#include <memory>
auto ft = std::make_shared<std::future<void>>();
*ft = std::async(std::launch::async, [ft]
{
sendCommand(std::chrono::seconds(5), "Command1");
});
|
69,237,483 | 69,237,533 | How to separate the count of odd numbers in loops | I am currently making a program which asks the user to input 10 integers and the code will have to count how many odd numbers there are. At the end of the program it prompts the user whether to retry it again, essentially in a loop if they choose to input a new set of 10 integers.
int i, value;
int odd = 0;
char option;
do
{
for (i=1;i<=10;++i)
{
cout << "Enter integer no. " << i << ": ";
cin >> value;
if (value % 2 == 1)
{
odd++;
}
}
cout << "\nThere are " << odd << " odd numbers.\n";
cout << "\nDo you want to try again? \nEnter Y for Yes and N for No: ";
cin >> option;
if (option == 'N')
{
cout << "\nThank you for using this program. \nProgram Terminating!";
break;
}
} while (option == 'Y');
return 0;
My problem is that the counted and displayed odd numbers on the previous count is added to the next count in the loop. If the previous count had 5 odd numbers and the next count had 4 odd numbers, it would then display a total of 9 odd numbers. How do I separate the count of odd numbers without them adding up with each other with every new input of 10 integers?
| The definition/initializationint odd = 0; is outside of the do…while loop so it is not being reinitialized for each loop iterations. There are two options to accomplish what you want to do:
Move int odd = 0; to the beginning of the do…while loop after do{. This reduces the variable scope to each iteration of the loop and will force it to reinitialize to zero each time.
Add the statement odd=0 either at the end or the beginning of the loop.
|
69,238,325 | 69,238,528 | Return unique_ptr by value or by reference? | I want to create a wchar_t* which length is dynamic. So I decided to write the following function:
std::unique_ptr<wchar_t> mem::TO_WCHAR_T_PTR(char* str)
{
size_t len = strlen(str) + 1; // Size of my wchar_t string
std::unique_ptr<wchar_t> wStr_ptr(new wchar_t[len]); // Compiler supports C++17
size_t convertedChars = 0;
mbstowcs_s(&convertedChars, wStr_ptr.get(), len, str, _TRUNCATE);
return wStr_ptr; // Is this save to use?
}
int main(int argc, char** argv)
{
char str[] = "Hello world";
auto ptr1 = TO_WCHAR_T_PTR(str);
// Do some stuff ...
return 0;
} // ptr1 out of scope so it gets deleted or was it already deleted(?)
My question: Is it ok to use smart-pointert by value or do I need to pass them by reference? I know about move when using unique_ptr I just want to make sure I can use the smart_ptr like this.
The next question: Does it work with shared_ptr as well?
| Your way of returning std::unique_ptr is correct. It'll either be placed in ptr1 directly via NRVO (Named Return Value Optimization) or moved into it. You should NOT return std::move(wStr_ptr), however, since that will prevent (N)RVO. And it works the same way for std::shared_ptr.
|
69,238,821 | 69,238,932 | Compile time subclass byte-offset with virtual inheritance | Is it possible to compute, at compile time, the byte offset of a virtual base in an inheritance hierarchy?
Example -
class A {};
class B : public virtual A {};
class C : public virtual A {};
class D : public virtual B, public virtual C {};
I would like to compute the byte offset of instance of B, C, and D w.r.t. A at compile time i.e. without using any real instance of either of these classes.
From what I have read so far online, compilers implement the logic (used by static_cast and dynamic_cast) with help of virtual tables and since there are no true instance of any of these classes there is no virtual table to piggyback on. But hoping there is some template magic that could make this work.
Purpose - I am attempting to get this Custom RTTI implementation working with virtual inheritance.
|
Is it possible to compute, at compile time, the byte offset of a virtual base in an inheritance hierarchy?
No, because it's different for different object instances. It is not a property of the class.
Let's look at your example. B has a virtual base class A. So B has to have some byte offset to an A. The same is true for C.
However, D inherits a virtual A through both B and C. The whole point of virtual inheritance is that, if you inherit the same base class, then all of the paths to reach that base class will refer to the same subobject of the dynamic type. So D only has a single instance of A.
But where is it? The offsets that B and C use cannot both be correct. Unless... the offset itself is stored in the vtable.
Which is (basically) how virtual inheritance works. When you create a D, it is the D which is responsible for assigning where all of the virtually inherited objects go. Those offsets will be different from when you create an object whose dynamic type is B or C.
There's no way to do what you're trying to do. Not without actually creating instances of objects. While C++20 does allow you to create instances of virtual types at compile time (so long as they have viable constexpr constructors, so you can't do it with everything), you still can't do what you need. If you have pointers to two different types, to compute a byte offset between them, you have to reinterpret_cast those pointers into integers or unsigned char*s. And reinterpret_cast is forbidden at compile-time (and bit_cast isn't constexpr when given a pointer type or a type that contains a pointer).
|
69,238,937 | 69,239,007 | Why is the array (sentence) printing 38 elements when it only have space for 30? | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
int main() {
//initialising the char array and vector
char sentence[30] = {};
vector<string> words{"The", "only", "thing", "to", "fear", "is", "fear", "itself"};
//For loop iterates through the vector and adds the converted strings to the char array
for(int i = 0; i < words.size(); i++){
//if statements check if there is overflow and breaks the loop if there is
/*if(strlen(sentence) >= 30){
cout << "stop" << endl;//comment out later
break;
}*/
//strcat method adds the strings from words to sentence one at a time
strcat(sentence, words[i].c_str());
/*if(strlen(sentence) >= 30){
cout << "stop" << endl;//comment out later
break;
}*/
//strcat method adds a space in between each word in the cstring
strcat(sentence, " ");
}
//couts the full sentence and the length of sentence
cout << sentence << " " << strlen(sentence) << endl;
cout << sentence[29] << endl;
return 0;
}
I commented out my if statements that break if the array goes above 30 elements but now its returning 38. When I try accessing the elements above what the array can hold, it still gives me an error. Shouldn't the compiler throw an error as soon as the number of elements in the array goa above 30? I am pretty new to C++ so I am not sure if this is something with the language itself or something on my end. any help is appreciated.
| Indexing an array with index that is greater then size ot the array is undefined operation. You'll never know what will be an output.
For example in your case, if you try to access
char c = sentence[37], this is undefined operation. Means that char c could be whatever is read from memory location of sentence + 37 * sizeof(char) (address of the 37th element).
My advice is to use vector, and use at() method when indexing it. Method at() will throw out_of_range exception if you try to access element outside space reserved for that vector.
|
69,239,132 | 69,239,151 | C++ inherited parent calling all constructor overloads | I'm working through this course on udemy and I'm baffled at this output.
The default parent constructor for Creature() is called even when I call the constructor through the child's constructor. I've been in JavaScript land the last 8 years so I've seen some wacky stuff, but I'm not sure how I'm accident pull this off.
P.S. I know this isnt pretty code, its for the course.
#include <iostream>;
#include <string>;
using namespace std;
class Creature
{
public:
Creature();
Creature(string name, float health);
string Name;
float Health;
};
class Dragon:public Creature
{
public:
Dragon();
Dragon(string name, float health);
};
int main()
{
Dragon dragon2("Smaug", 100.f);
cout << "The Dragon's name should be Smaug: " << dragon2.Name << endl;
return 0;
}
Creature::Creature(string name, float health)
{
Name = name;
Health = health;
cout << "Creature constructor WITH arguments" << endl;
};
Creature::Creature()
: Name("UNAMED"), Health(100.f)
{
cout << "Creature constructor with NO arguments" << endl;
}
Dragon::Dragon(string name, float health)
{
Creature(name, health);
cout << "Dragon constructor WITH arguments" << endl;
}
Dragon::Dragon()
{
cout << "Dragon Constructor with NO arguments" << endl;
}
Output:
Creature constructor with NO arguments
Creature constructor WITH arguments
Dragon constructor WITH arguments
The Dragon's name should be Smaug: UNAMED
I understand (sorta) why and how default constructors would be called, but I expected the output to be:
Creature constructor WITH arguments
Dragon constructor WITH arguments
The Dragon's name should be Smaug: Smaug
| This is wrong:
Dragon::Dragon(string name, float health)
{
Creature(name, health);
cout << "Dragon constructor WITH arguments" << endl;
}
Well, it is syntactically correct but it is not doing what you think it does. Creature(name,health); calls the constructor of Creature to create a temporary that lives till the end of that line. You see the default constructor getting called because you do not call the Creature constructor for the Dragon that is being constructed, hence the Creature part of the Dragon is default constructed.
To call the base constructor:
class Dragon : public Creature
{
public:
Dragon();
Dragon(string name, float health) : Creature(name,health) {
cout << "Dragon constructor WITH arguments" << endl;
}
};
|
69,240,067 | 69,338,025 | CMake with Conan cannot find assimp-vc142-mt.lib | I'm trying to link assimp into a simple C++ project using Conan and CMake. However, when I build, it's giving me the following error:
LINK : fatal error LNK1104: cannot open file 'assimp-vc142-mt.lib' [C:\dev\test0\build\test.vcxproj]
Here is my conan default profile:
[settings]
os=Windows
os_build=Windows
arch=x86_64
arch_build=x86_64
compiler=Visual Studio
compiler.runtime=MD
compiler.version=16
build_type=Release
[options]
[build_requires]
[env]
I've made sure to use the same architecture for installing with Conan and building with CMake.
I've double checked that the library is installed.
I've installed other libraries (e.g. glfw) with no issues. Is this an issue with the Conan package, or am I missing something?
| https://github.com/conan-io/conan-center-index/issues/7342
I had the CMake directives in the wrong order. You must do conan_basic_setup() before creating your executable and linking any libraries.
|
69,240,165 | 69,241,708 | How to detect the last iteration of std::map using structured bindings from C++17? | How could I detect the last iteration of a map using structured bindings?
Here's a concrete example: I have the following simple code whereby I print elements from an std::map using structured bindings from C++17:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, size_t> mymap {{"a", 0}, {"b", 1}, {"c", 2}, {"d", 3}};
// using structured bindings, C++17
for (auto const& [key, value] : mymap) {
std::cout << "key: " << key << ", value: " << value << ", ";
}
return 0;
}
The problem is, this will result in a trailing comma, i.e.
key: a, value: 0, key: b, value: 1, key: c, value: 2, key: d, value: 3,
Inspired by this question: How can I detect the last iteration in a loop over std::map?, I can write code with an iterator to print out the std::map contents without the trailing comma, i.e.
for (auto iter = mymap.begin(); iter != mymap.end(); ++iter){
// detect final element
auto last_iteration = (--mymap.end());
if (iter==last_iteration) {
std::cout << "\"" << iter->first << "\": " << iter->second;
} else {
std::cout << "\"" << iter->first << "\": " << iter->second << ", ";
}
}
How does one do this with for (auto const& [key, value] : mymap)? If I know the final key in std::map, I could write an conditional for it; but is there another way without resorting to iter?
| Yakk's answer inspired me to write an iterators_of using Ranges and without introducing a new class:
#include <iostream>
#include <map>
#include <string>
#include <ranges>
template<class Range>
auto iterators_of(Range&& r){
return std::ranges::views::iota(std::begin(r), std::end(r));
}
int main() {
std::map<std::string, size_t> mymap {{"a", 0}, {"b", 1}, {"c", 2}, {"d", 3}};
for(auto it : iterators_of(mymap) ) {
auto const& [key, value] = *it;
if(std::next(it) != mymap.end()) {std::cout << "key: " << key << ", value: " << value << ", ";}
else {std::cout << "key: " << key << ", value: " << value;}
}
return 0;
}
https://godbolt.org/z/rx15eMnWh
|
69,240,330 | 69,240,364 | Comparing pointers that are not necessarily associated with the same array | The C Programming Language book by Brian W Kernighan & Dennis M. Ritchie, 2e, states the following on Pages 102-103:
… pointers may be compared under certain circumstances. If p and q
point to members of the same array, then relations like ==, !=, <, >=,
etc., work properly. But the behavior is undefined for arithmetic or
comparisons with pointers that do not point to members of the same
array. (There is one exception: the address of the first element past
the end of an array can be used in pointer arithmetic).
Does this restriction apply to C++ as well? We have some legacy code that compares pointers (especially void*) based on their absolute address values, without considering whether or not they belong to the same array, and I am worried whether we need to revisit that code.
| Yes. Well, unspecified not undefined, which is much safer.
Converting to int_ptr is a guaranteed round trip however. Also std::less<>{}( a, b ) is guaranteed to be well behaved and consistent with < when < is specified.
This unspecified behaviour permits three things.
Originally, segmented memory; pointers could ignore the segment and compare faster.
Now, it permits certain optimizations. Like assuming compared pointers where derived in certain ways. And if the assumption is violated, the compiler can return anything.
Blocks this comparison in constant evaluated code.
However, most compilers do not aggressively blow up when you violate that rule. So it isn't a super high priority fix. At least one compiler actually implements less as a raw <.
|
69,240,486 | 69,240,663 | Program to calculate distance between two points in 3D with class and operator overload | I can't speak english very well, sorry. I am having a problem with a practice question given to me. I am asked to write a code that finds the distance between 2 points in 3D space according to their x, y and z coordinates. But while doing this, it wants me to use the class structure, use the get-set functions, use the concepts of public and private, and overload the "*" operator to find the distance. I wrote a code and it gives correct result but it does not meet the desired conditions. I would really appreciate if you could help. thank you so much.
#include<iostream>
#include<math.h>
using namespace std;
class coordinat
{
private:
int x1, y1, z1, x2, y2, z2;
public:
void get()
{
cout << "1. point X value: ";
cin >> x1;
cout << "1. point Y value: ";
cin >> y1;
cout << "1. point Z value: ";
cin >> z1;
cout << "2. point X value: ";
cin >> x2;
cout << "2. point Y value: ";
cin >> y2;
cout << "2. point Y value: ";
cin >> z2;
}
void calculate()
{
float distance;
distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2));
cout << "Distance between 2 points: " << distance << endl;
}
};
int main()
{
coordinat c;
c.get();
c.calculate();
return 0;
}
|
#include <cmath> not math.h
Make coordinat store only one point (x, y, z).
Add a member function for subtracting one coordinat from an other:
coordinat& operator-=(const coordinat& rhs) {
// add code to subtract the values in rhs from the values stored in *this
return *this;
}
Add a member function to return a coordinat's distance from origo
double length() const { return std::sqrt(x * x + y * y + z * z); }
Add a free function to subtract two coordinat's, returning a new coordinat:
coordinat operator-(const coordinat& lhs, const coordinat& rhs) {
coordinatrv(lhs); // copy
rv -= rhs; // use the member function "operator-="
return rv;
}
With these additions, you can ask the user for input:
coordinat a, b;
std::cout << "Enter data for point 1:\n";
a.get();
std::cout << "Enter data for point 2:\n";
b.get();
and calculate the distance:
coordinat distance = a - b;
std::cout << distance.length();
|
69,240,507 | 69,245,639 | Ambiguity in case of multiple inheritance and spaceship operator in C++20 | In the following simplified program, struct C inherits from two structs A and B. The former defines both spaceship operator <=> and less operator, the latter – only spaceship operator. Then less operation is performed with objects of class C:
#include <compare>
struct A {
auto operator <=>(const A&) const = default;
bool operator <(const A&) const = default;
};
struct B {
auto operator <=>(const B&) const = default;
};
struct C : A, B {};
int main() {
C c;
c.operator<(c); //ok everywhere
return c < c; //error in GCC
}
The surprising moment here is that the explicit call c.operator<(c) succeeds in all compliers, but the similar call c<c is permitted by Clang but rejected in GCC:
error: request for member 'operator<=>' is ambiguous
<source>:8:10: note: candidates are: 'auto B::operator<=>(const B&) const'
<source>:4:10: note: 'constexpr auto A::operator<=>(const A&) const'
Demo: https://gcc.godbolt.org/z/xn7W9PaPc
There is a possibly related question: GCC can't differentiate between operator++() and operator++(int) . But in that question the explicit operator (++) call is rejected by all compilers, unlike this question where explicit operator call is accepted by all.
I thought that only one operator < is present in C, which was derived from A, and starship operator shall not be considered at all. Is it so and what compiler is right here?
| gcc is correct here.
When you do:
c.operator<(c);
You are performing name lookup on something literally named operator<. There is only one such function (the one in A) so this succeeds.
But when you do c < c, you're not doing lookup for operator<. You're doing two things:
a specific lookup for c < c which finds operator< candidates (member, non-member, or builtin)
finding all rewritten candidates for c <=> c
Now, the first lookup succeeds and finds the same A::operator< as before. But the second lookup fails - because c <=> c is ambiguous (between the candidates in A and B). And the rule, from [class.member.lookup]/6 is:
The result of the search is the declaration set of S(N,T).
If it is an invalid set, the program is ill-formed.
We have an invalid set as the result of the search, so the program is ill-formed. It's not that we find nothing, it's that the whole lookup fails. Just because in this context we're looking up a rewritten candidate rather than a primary candidate doesn't matter, it's still a failed lookup.
And it's actually good that it fails because if we fix this ambiguous merge set issue in the usual way:
struct C : A, B {
+ using A::operator<=>;
+ using B::operator<=>;
};
Then our lookup would be ambiguous! Because now our lookup for the rewritten candidates finds two operator<=>s, so we end up with three candidates:
operator<(A const&, A const&)
operator<=>(A const&, A const&)
operator<=>(B const&, B const&)
1 is better than 2 (because a primary candidate is better than a rewritten candidate), but 1 vs 3 is ambiguous (neither is better than the other).
So the fact that the original fails, and this one also fails, is good: it's up to you as the class author to come up with the right thing to do - since it's not obvious what that is.
|
69,240,827 | 69,243,549 | Makefile returns an error when I try to use cl.exe as the compiler | I have activated vcvarsall.bat in my makefile, however I still get this error when I try compiling my program:
**********************************************************************
** Visual Studio 2019 Developer Command Prompt v16.11.1
** Copyright (c) 2021 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
process_begin: CreateProcess(NULL, cl /Z7 /W3 C:\Dev\LearningC++\main.cpp
, ...) failed.
make (e=2): The system cannot find the file specified.
make: *** [build] Error 2
[Process exited 2]
Makefile:
all: build run
build: main.cpp
@call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
@cl /Z7 /W3 C:\Dev\LearningC++\main.cpp
run:
@bin\main.exe
When I type the commands manually, the code does get compiled and I produce and executable which works, however I also get these weird warning messages from the compiler:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MS
VC\14.29.30133\include\ostream(746): warning C4530: C++ exception handler
used, but unwind semantics are not enabled. Specify /EHsc
main.cpp(4): note: see reference to function template instantiation 'std:
:basic_ostream<char,std::char_traits<char>> &std::operator <<<std::char_t
raits<char>>(std::basic_ostream<char,std::char_traits<char>> &,const char
*)' being compiled
Microsoft (R) Incremental Linker Version 14.29.30133.0
Copyright (C) Microsoft Corporation. All rights reserved.
I am using Windows 10.
| In a makefile recipe, every command line is run in its own shell. In Windows the vcvarsall.bat file sets a bunch of environment variables and environment variables are in effect only for the current shell; when the shell exits they are gone. When you run:
build: main.cpp
@call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
@cl /Z7 /W3 C:\Dev\LearningC++\main.cpp
first make starts a shell and runs the call in it which sets the Visual Studio environment, then the shell exits and all those variable settings are lost. Then make starts another shell and runs cl but the environment settings it wants are no longer there so it fails.
I think the way to put multiple commands on a single line in Windows cmd.exe is using & so you can try rewriting your makefile like this:
build: main.cpp
@call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64 \
& cl /Z7 /W3 C:\Dev\LearningC++\main.cpp
(note the backslash at the end of the call line, then the &).
|
69,240,902 | 69,258,919 | Protoc failed to parse input if integer value more than 127 in Unreal Engine 5 c++ | Environment:
Unreal Engine 5
Windows 10
Protocol Buffers v3.18.0
I'm trying to decode serialized data in Unreal Engine 5 (c++) by using protoc. If the message contains the value of int var less than 127 everything is okay. But if the value more than 127 I catch the error: Failed to parse input.
player.proto:
syntax = "proto3";
package com.game;
message Player {
string username = 1;
int64 experience = 2;
}
Success case
C++ serialization and save to file:
com::game::Player MyPlayer;
MyPlayer.set_username("test user name");
MyPlayer.set_experience(127); // <-- PAY ATTENTION
// serialization
std::string MyPlayerString;
if(!MyPlayer.SerializeToString(&MyPlayerString))
{
UE_LOG(LogGameInstance, Error, TEXT("Can't serialize MyPlayer to String"));
return;
}
const FString MyPlayerFString(MyPlayerString.c_str());
// save to file
const FString File = *FPaths::Combine(FPaths::GameSourceDir(), FApp::GetProjectName(), TEXT("temp.dat"));
FFileHelper::SaveStringToFile(
MyPlayerFString,
*File,
FFileHelper::EEncodingOptions::AutoDetect,
&IFileManager::Get()
);
protoc --decode_raw < temp.dat
1: "test user name"
2: 127
Fail case
C++ serialization and save to file:
...
MyPlayer.set_experience(128); // <-- PAY ATTENTION
...
protoc --decode_raw < temp.dat
Failed to parse input.
I guess the problem occurs when I try to convert std::string -> FString. Any ideas?
| I found a solution.
I'll keep it here, maybe it will help somebody.
I changed the implementation to avoid string conversion.
Before:
...
// serialization
std::string MyPlayerString;
if(!MyPlayer.SerializeToString(&MyPlayerString))
{
UE_LOG(LogGameInstance, Error, TEXT("Can't serialize MyPlayer to String"));
return;
}
const FString MyPlayerFString(MyPlayerString.c_str());
// save to file
const FString File = *FPaths::Combine(FPaths::GameSourceDir(), FApp::GetProjectName(), TEXT("temp.dat"));
FFileHelper::SaveStringToFile(
MyPlayerFString,
*File,
FFileHelper::EEncodingOptions::AutoDetect,
&IFileManager::Get()
);
After:
// serialization
const auto MyPlayerSize = MyPlayer.ByteSizeLong();
const auto MyPlayerBytes = new uint8[MyPlayerSize]();
if(!MyPlayer.SerializeToArray(MyPlayerBytes, MyPlayerSize))
{
UE_LOG(LogGameInstance, Error, TEXT("Can't serialize MyPlayer to Array"));
return;
}
TArray64<uint8>* MyPlayerArray = new TArray<uint8, FDefaultAllocator64>(MyPlayerBytes, MyPlayerSize);
// save to file
const FString File = *FPaths::Combine(FPaths::GameSourceDir(), FApp::GetProjectName(), TEXT("temp.dat"));
FFileHelper::SaveArrayToFile(
*MyPlayerArray,
*File,
&IFileManager::Get()
);
|
69,240,967 | 69,240,976 | string uppercasing adds junk to the end of char array | I am learning c++, I write some code to convert a string to uppercase and display it. I assign a string str with "asdf" and then create a char array pointer and allocate a length same as that of the string.
But after I assign indices of char array with uppercase chars when I try to display char array there are many junk characters appended to the end. Why does this happen as I have only allocated the char array with a size = "length of string" then how does char array have junk chars at the end even after the actual allocated size.
string str{ "asdf" };
char* str_c = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
str_c[i] = toupper(str[i]);
}
cout << str_c; // displays ASDF²▌r┐│w²A∙
| Your char array needs to be one character longer than the length of the string, for the null terminator
string str{ "asdf" };
char* str_c = new char[str.length() + 1];
for (int i = 0; i < str.length(); i++) {
str_c[i] = toupper(str[i]);
}
str_c[str.length()] = '\0';
cout << str_c; // displays ASDF
In C-style strings (char*) the length of the string is not stored in memory. Thus, it must use some other way to determine where the string ends. The way it does that is by assuming that the string is all the bytes until the byte that is equal to zero (so-called null-terminator).
Without explicitly allocating an extra byte for the null terminator, and setting it, your string continues with the garbage that happens to be after the bytes you have allocated until it encounters (accidentally) the nearest 0.
|
69,241,099 | 69,241,152 | What does std::move do when called on a function? | I'm working on making some changes to a piece of code, and have a doubt in understanding the behavior of std::move in below case:
struct Timer {
Timer (boost::asio::io_service& ios) : timer_{ios} {}
boost::asio::steady_timer timer_;
};
struct TimerContext {
void *ctxt_;
};
class A {
std::function<void(Timer *, const TimerContext&)> callback_;
boost::asio::io_service ios_;
};
A's constructor:
A::A (std::function<void(Timer *, const TimerContext&)> cb) : callback_{std::move(cb)}
{
}
The callback function definition:
void
customCallback (Timer *timer, const TimerContext& ctxt) {
...
}
In main(),
for (int i = 0; i < 5; ++i) {
A *a = new A{customCallback};
}
My doubt is for this line:
A::A (std::function<void(Timer *, const TimerContext&)> cb) : callback_{std::move(cb)}
Class A is getting instantiated in a loop, and the same customCallback function is getting moved to the custom constructor for each new object.
Will the first std::move not make callback function unusable for next call? As I understood, if you use std::move(t), then t cannot be used again in that scope.
I'm confused what is happening internally here for all 5 calls to std::move(cb) on the same function in new A. Is this the right way to do how it is implemented?
| Look carefully at A's constructor:
A::A (std::function<void(Timer *, const TimerContext&)> cb)
The function, cb is being passed by value. That means a copy of the function has already occurred from when it was invoked via new:
A *a = new A{customCallback};
The std::move in the constructor initializer list exists to avoid a redundant copy into the member variable. The original function defined by the caller who invoked new A remains unmoved. This is preferred because copying a std::function variable can be expensive. (sizeof(cb) - might be way bigger than you expected).
An alternative implementation: The function could have been passed as a const reference and allow the copy to occur in the constructor itself:
A::A (const std::function<void(Timer *, const TimerContext&)>& cb) : callback_{cb}
|
69,241,697 | 69,241,954 | How can I determine parameters of lambda in C++? | I want to transform all functions, which take tuples as arguments, passed to Foo into functions which take plain arguments.
auto f = [](const std::tuple<int, char>& t) { return std::get<0>(t); };
template <typename F>
auto Foo(F&& f) {
...
}
Foo(f)(42, 'a')
My idea was to do something like this
template <typename ReturnType, typename... Args>
auto Foo(std::function<ReturnType(const std::tuple<Args...>&)> f) {
return [&](Args&&... args) -> ReturnType {
return f({std::forward<Args>(args)...});
};
}
But compiler couldn't infer template arguments for a lambda and ignored this candidate.
| If you don't really need the parameter types. simply
template <typename Callable>
auto Foo(Callable f) {
return [=](auto&&... args)->decltype(auto){
return f({std::forward<decltype(args)>(args)...});
};
}
the plus side is Foo can now accept more generic f, which could have multiple opreator() defined.
|
69,241,721 | 69,242,817 | Why not apply [[nodiscard]] to every constructor? | Since C++20, [[nodiscard]] can be applied to constructors. http://wg21.link/p1771 has the example:
struct [[nodiscard]] my_scopeguard { /* ... */ };
struct my_unique {
my_unique() = default; // does not acquire resource
[[nodiscard]] my_unique(int fd) { /* ... */ } // acquires resource
~my_unique() noexcept { /* ... */ } // releases resource, if any
/* ... */
};
struct [[nodiscard]] error_info { /* ... */ };
error_info enable_missile_safety_mode();
void launch_missiles();
void test_missiles() {
my_scopeguard(); // warning encouraged
(void)my_scopeguard(), // warning not encouraged, cast to void
launch_missiles(); // comma operator, statement continues
my_unique(42); // warning encouraged
my_unique(); // warning not encouraged
enable_missile_safety_mode(); // warning encouraged
launch_missiles();
}
error_info &foo();
void f() { foo(); } // warning not encouraged: not a nodiscard call, because neither
// the (reference) return type nor the function is declared nodiscard
Usually constructors have no side effects. So discarding the result is pointless. For example, discarding std::vector as below is pointless:
std::vector{1,0,1,0,1,1,0,0};
It would be useful if std::vector constructor is [[nodiscard]], so that the above code produced a warning.
Notable constructors that do have side effects are lock constructors, like unique_lock or lock_guard. But then those are good target to be marked as [[nodiscard]] as well, to avoid missed scope, like here:
std::lock_guard{Mutex};
InterThreadVariable = value; // ouch, not protected by mutex
It would be useful if std::lock_guard constructor is [[nodiscard]], so that the above code produced a warning.
Sure there's a case like return std::lock_guard{Mutex}, InterThreadVariable;. But it is rare enough to still have [[nodiscard]] guards, and to suppress them locally like return ((void)std::lock_guard{Mutex}, InterThreadVariable);
So, is there any case when a constructor should not be nodiscard?
| An example from the pybind11 library: To wrap a C++-class for python, you do:
PYBIND11_MODULE(example, m) {
py::class_<MyClass>(m, "MyClass"); // <-- discarded.
}
|
69,241,781 | 69,241,847 | Factorial loops with C++ | I'm trying to write a loop in C++ that calculates the factorial of a given input between (1 and 10 inclusive) then displays that factorial. The code only breaks when 0 is used as input. I have written the loop which does all these except that the only correct answer I get is the first input, all other successive iterations are wrong figures. I am not sure what I am doing wrong. Kindly help.
Here's the code:
#include <iostream>
using namespace std;
int main (){
int n,
factorial = 1;
do{
cout << "Enter a number between 1 and 10 (or 0 to end program): ";
cin >> n;
while (n < 0 || n > 10) {
cout << "Error: " << n << " is outside the valid range \n";
break;
}
if (n > 0 && n <= 10) {
for(int i = 1; i <= n; ++i){
factorial *= i;
}
cout << "Factorial of " << n << " is " << factorial << endl;
} else if (n==0){
cout << "Good bye! \n";
break;
}
n++;
} while (n != 0);
return 0;
}
| As mentioned in the comment, you don't reset the temporary variable when going into 2nd and subsequent loop operations. The easiest way to remedy that is to move the variable definition lower, limiting its scope:
do {
...
if (n > 0 && n <= 10) {
int factorial = 1; // <- here
for (int i = 1; i <= n; ++i){
factorial *= i;
}
cout << "Factorial of " << n << " is " << factorial << endl;
}
As it's not used past this point anyway. That being said, this code would benefit from some (pun not intended) refactoring. Ideally, factorial would be a function called in the input routine, like so:
int factorial(int n) {
int f = 1;
for (int i = 2; i <= n; ++i) { // you can start with 2 here
f *= i;
}
return f;
}
Then it's impossible to use this function incorrectly from the outside, as the control for the temporary variable is encapsulated inside of the function.
Of course, it also makes the callsite much cleaner:
if (n > 0 && n <= 10) {
cout << "Factorial of " << n << " is " << factorial(n) << endl;
}
|
69,241,797 | 69,241,813 | Sized array in function signature | Does defining a sized array in a function signature (as opposed to the more commonly used unsized array or pointer syntax) have any bearing at all? My compiler is ignoring it completely, as the following sample code shows (which runs, although it prints some garbage values when a smaller-sized array is passed).
#include <iostream>
using namespace std;
void printArray(int intArray[5]) {
for (int i = 0; i < 5; i++) {
cout << intArray[i] << " ";
}
cout << endl;
}
int main()
{
int array1[1] = {1}; // Smaller array size than in the function signature
cout << "\nInvocation 1\n";
printArray(array1);
int array2[4] = {1, 2, 3, 4}; // Smaller array size than in the function signature
cout << "\nInvocation 2\n";
printArray(array2);
int array3[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // Larger array size than in the function signature
cout << "\nInvocation 3\n";
printArray(array3);
return 0;
}
|
Does defining a sized array in a function signature (as opposed to the more commonly used unsized array or pointer syntax) have any bearing at all?
No, it has not, the passed array argument will always decay to a pointer to its first element, placing a size is indeed pointless from the compiler standpoint, it will ignore it, having void printArray(int intArray[5]){...}, void printArray(int intArray[]){...} or void printArray(int* intArray){...} will be basically the same.
My compiler is ignoring it completely, as the following sample code shows (which runs, although it prints some garbage values when a smaller-sized array is passed).
Which makes sense because in the loop you are accessing elements outside the bounds of the array, so the behavior is undefined.
|
69,242,776 | 69,242,826 | c++ why priority_queue greater<> result is different from sort`s greater result? | I searched for similar contents, but I don't understand the answer, so I'm asking you again.
vector<int> v;
v.push_back(3);
v.push_back(11);
v.push_back(13);
v.push_back(-1);
v.push_back(-8);
v.push_back(324);
v.push_back(55);
sort(v.begin(),v.end(), greater<int>() );
for(auto i : v)
{
cout << i << " ";
}
// result is descending order
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(3);
pq.push(5);
pq.push(4);
pq.push(9);
pq.push(13);
pq.push(15);
while(!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
// result is ascending order
also greater`s implementation is here
struct greater : public binary_function<_Tp, _Tp, bool>
{
_GLIBCXX14_CONSTEXPR
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x > __y; }
}
x > y means descending, but why?? why especially in priority queue greater means ascending? Plz someone clarify this clearly.. Thank you.
| From this std::priority_queue reference:
A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element
[Emphasis mine]
So the default sorting using std::less is descending. By using std::greater you reverse that. ordering.
|
69,243,308 | 69,243,415 | problem with accesing protected methods in friend class | I'm starting a new project and I have trouble with accessing protected methods of Organism inside World class. I suppose there must be some error with my definition of World being a friend of organism. I tried calling some method from Organism inside World, but the compiler says that it is inaccessible. The method was of course set as protected, so only derived classes and friends could call them.
World.h:
#include <vector>
#include <iostream>
using std::vector;
#include <map>
using std::map;
#include "Organism.h"
#pragma once
class World
{
private:
map<int, std::shared_ptr<Organism>> organims_map;
vector <std::shared_ptr<Organism>> animals_vector;
int x_size, y_size;
void initiate_aniamals();
public:
World();
World(int x, int y);
void make_turn();
};
Organism.h:
#pragma once
#include "World.h"
class Organism
{
friend class World;
private:
int strength, vigor;
int x_pos, y_pos;
float level;
protected:
int get_vigor() const;
virtual void action() = 0 ;
virtual void collision() = 0;
/// <summary>
/// compares animals by their vigor
/// </summary>
/// <param name="other organism"></param>
/// <returns>which animal has higher vigor</returns>
bool operator<(const Organism& other_organism);
};
Then In file world.cpp i try to define method make_turn():
void World::make_turn()
{
//stable sort animals by their vigor
std::stable_sort(begin(this->animals_vector), end(this->animals_vector),
[](const Organism& organism_1, const Organism& organism_2)
{
return organism_1.get_vigor(); //
});
I get error in line:
return organism_1.get_vigor();
says that function get_vigor is inacessible.
| The problem was the fact that #pragma once was not at the beginning of World.h But after including Organism.h. That leads to tons of weird errors including the fact that despite being friends of Organism, World couldn't use its private methods.
This is correct:
#pragma once
#include "Organism.h"
This, however is absolutely not:
#include "Organism.h"
#pragma once
|
69,243,670 | 69,244,233 | Integration with right rectangle rule | I am trying to complete the task of integrating with the right rectangle rule, but I am stuck at one moment. The first two values are being outputted, but further ones are just 0...
The task is about starting with iteration count 3 and continuing up to 512, by multiplying iteration count by 2 every time.
I feel something is wrong here, but I can't see what. Let the test values be, as in the task: lower: -3, upper: 6, starting iteration count: 3
#include <iostream>
using namespace std;
double Function(double x)
{
if (x < 0)
return (1 / sqrt(25 + (3 * x)));
else
return pow(x, 2) + 0.2;
}
double Integrate(int upper, int lower, int iteration_count)
{
double pre_sum = (double)((double)(upper - lower) / iteration_count);
double sum = 0;
for (int i = 1, step ; i < iteration_count; i++)
{
sum += Function(lower + pre_sum + i);
}
return sum * pre_sum;
}
int main()
{
int upper, lower, iteration_count;
cout << "Enter lower bound: ";
cin >> lower;
cout << "Enter upper bound: ";
cin >> upper;
cout << "Enter iteration count: ";
cin >> iteration_count;
for (int i = iteration_count; i < iteration_count * 512; i=i*2)
{
cout << "Integration result: " << Integrate(upper, lower, i) << endl;
}
return 0;
}
But values keep increasing drastically:
Enter lower bound: -3
Enter upper bound: 6
Enter iteration count: 3
Integration result: 16.2
Integration result: 33.0094
Integration result: 198.962
Integration result: 1138.16
Integration result: 5578.55
Integration result: 24809.2
Integration result: 104733
Integration result: 430463
Integration result: 1.74547e+06
|
Change sum += Function(lower + pre_sum + i); to sum += Function(lower + pre_sum * i);. That is, you should multiply by i rather than add it. i represents the index of the iteration (indexed by 1 for right-rectangle integration; indexed by 0 for left-rectangle integration.)
Change for (int i = 1, step ; i < iteration_count; i++) to for (int i = 1; i <= iteration_count; i++). That is, check for less-than-or-equal rather than less-than inequality. Otherwise, the number of iterations performed is actually one less than iteration_count, which is likely unintended behavior. step was also removed, since it's dead code.
Output:
Enter lower bound: -3
Enter upper bound: 6
Enter iteration count: 3
Integration result: 136.8
Integration result: 103.081
Integration result: 87.911
Integration result: 80.7481
Integration result: 77.2722
Integration result: 75.5606
Integration result: 74.7114
Integration result: 74.2885
Integration result: 74.0774
|
69,243,826 | 69,243,868 | C++ code to print the number of words in a given string | This is the link above of the code of printing the number of words.
It's running properly but sometimes it's showing the error "out of range", I don't know the reason,
can someone please explain why?
#include <iostream>
using namespace std;
int main()
{
string str;
getline(cin, str);
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.at(i) == ' ')
{
i++;
}
else
{
while (str.at(i) != ' ')
{
i++;
if (str.at(i) == str.length())
{
break;
}
}
count++;
}
}
cout << "number of words are : " << count;
}
Online demo
| Simple answer is:
while (str.at(i) != ' ')
might go out of bound.
Think what would happen if you enter these lines?
Hello!!!!
Hello world!!!
It will hit that while() loop and loop forever.
Why are you getting error sometimes, and not all the times? Because you are causing undefined behavior.
Your if statement is not doing what you think it is doing. It is comparing characters to str.lenght(). So basically you are comparing H, e, l, l and o against str.lenght().
If we look int ASCII char values we get this:
char | decimal value | str.lenght()
-----+---------------+--------------
H | 72 | 5
e | 102 | 5
l | 108 | 5
l | 108 | 5
o | 111 | 5
! | 33 | 5
! | 33 | 5
! | 33 | 5
Your line:
if (str.at(i) == str.length())
break;
should be:
if (i == str.length())
break;
to compare position in string with string length. Further more you should never use == to check if i against str.lenght() you should use >=, just in case there is a bug in memory somewhere and i skips value of str.lenght().
if (i >= str.length())
break;
|
69,243,906 | 69,244,291 | circular dependencies in member function specializations ....... "instantiation before specialization" | the code below doesn't compile
#include <iostream>
using namespace std;
template<class T> class A;
template<class T> class B;
//@@@@@@@@@@@@@y
template<class T>
class B{
int x=1;
public:
void write(A<T> x);
void add(A<T> x);
};
template<class T>
class A{
int x=1;
public:
void write(B<T> x);
void add(B<T> x);
};
template<class T> void A<T>::write(B<T> x){cout<<"write generic A"<<endl;x.add(*this);};
template<class T> void A<T>::add(B<T> x){cout<<"add generic A"<<endl;};
template<> void A<int>::write(B<int> x){cout<<"write special A"<<endl;x.add(*this);};
template<> void A<int>::add(B<int> x){cout<<"add special A int"<<endl;};
template<class T> void B<T>::write(A<T> x){cout<<"write generic B"<<endl;x.add(*this);};
template<class T> void B<T>::add(A<T> x){cout<<"add generic B"<<endl;};
template<> void B<int>::write(A<int> x){cout<<"write special B"<<endl;x.add(*this);};
template<> void B<int>::add(A<int> x){cout<<"add special B"<<endl;};
int main(){
B<int> b;
A<int> a;
b.write(a);
}
as the specialized "write" method of A and B instantiate a template of "add" of A or B. When compiling the compiler complaints
error: specialization of ‘void B<T>::add(A<T>) [with T = int]’ after instantiation
32 | template<> void B<int>::add(A<int> x){cout<<"add special B"<<endl;};
I cannot see at the moment how the functions can be ordered to avoid this problem, except I drop the specialization.
Any suggestions highly appreciated.
| You can declare specializations of template methods after each class declaration:
#include <iostream>
using namespace std;
template<class T> class A;
template<class T> class B;
//@@@@@@@@@@@@@y
template<class T>
class B{
int x=1;
public:
void write(A<T> x);
void add(A<T> x);
};
// declare specializations:
template<> void B<int>::write(A<int> x);
template<> void B<int>::add(A<int> x);
template<class T>
class A{
int x=1;
public:
void write(B<T> x);
void add(B<T> x);
};
// declare specializations:
template<> void A<int>::write(B<int> x);
template<> void A<int>::add(B<int> x);
template<class T> void A<T>::write(B<T> x){cout<<"write generic A"<<endl;x.add(*this);};
template<class T> void A<T>::add(B<T> x){cout<<"add generic A"<<endl;};
template<> void A<int>::write(B<int> x){cout<<"write special A"<<endl;x.add(*this);}; // method "B<int>::add(A<int> x)" is called but was not declared or defined before
template<> void A<int>::add(B<int> x){cout<<"add special A int"<<endl;};
template<class T> void B<T>::write(A<T> x){cout<<"write generic B"<<endl;x.add(*this);};
template<class T> void B<T>::add(A<T> x){cout<<"add generic B"<<endl;};
template<> void B<int>::write(A<int> x){cout<<"write special B"<<endl;x.add(*this);};
template<> void B<int>::add(A<int> x){cout<<"add special B"<<endl;};
int main(){
B<int> b;
A<int> a;
b.write(a);
}
There is a comment in the code about method B<int>::add(A<int> x) is called in A<int>::write(B<int> x) but was not declared or defined before.
|
69,244,973 | 69,245,067 | C++ How to store odd numbers in an array and access them using a pointer notation? | I found an error in the book solution, the below solution is using the pointer notation to access the array as requested, but the printed results are not odd numbers, instead its printing 1 to 50 and 50 - 1.
Original instructions: Write a program that declares and initializes an array with the first 50 odd (as in not even) numbers. output the numbers from the array ten to a line using pointer notation and then output them in reverse order, also using pointer notation.
Below attaching the wrong solution from the book, appreciate your help:
// Storing odd numbers in an array and accessing them using pointer notation
#include <iostream>
#include <iomanip>
int main()
{
const size_t n {50};
size_t odds[n];
for (size_t i {}; i < n; ++i)
odds[i] = i + 1;
const size_t perline {10};
std::cout << "The numbers are:\n";
for (size_t i {}; i < n; ++i)
{
std::cout << std::setw(5) << *(odds + i);
if ((i + 1) % perline == 0)
std::cout << std::endl;
}
std::cout << "\nIn reverse order the numbers are:\n";
for (int i {n - 1}; i >= 0; --i)
{
std::cout << std::setw(5) << *(odds + i);
if (i % perline == 0)
std::cout << std::endl;
}
}
| Just write
for (size_t i = 0; i < n; ++i)
{
odds[i] = 2 * i + 1;
}
And the last loop rewrite using the variable i of the type size_t like
for ( size_t i = n; i != 0; --i )
{
std::cout << std::setw(5) << *(odds + i - 1 );
if (i % perline == 0)
std::cout << std::endl;
}
or like
for ( size_t i = n; i-- != 0; )
{
std::cout << std::setw(5) << *(odds + i );
if (i % perline == 0)
std::cout << std::endl;
}
|
69,245,695 | 69,461,101 | Pragma ignoring comment [-Werror=unknown-pragmas] | I'm trying to make function which will return version from FileVersionInfo,
so far i built funtcion, but i have issue when i want to include version.lib
#pragma comment(lib, "version.lib")
I have tried to link, libversion.a, something like this
#pragma comment(lib, "libversion.a")
but, again compiler was returning error like first time
Pragma ignoring comment [-Werror=unknown-pragmas]
I have tried, many combinations from internet, i cant even remember all of them. I'm using MinGW compiler.
Thanks for your time i appricitate it :)
|
"This pragma to link libraries from C++ source code is only supported by MSVC"
Switched compiler from gcc/g++ to MSVC, that's only solution :(
|
69,246,212 | 69,247,123 | How To Pass Component Pointer From QML To C++? | What is the easiest way to pass a component pointer created in a QML file to C++? From Qt Documentation explanations we could take the QML file root object and then search for our component objectName. But it's hard to keep sync the components objectName in both C++ codes and QML codes:
Just for Copy/Paste: qml_pass_objectName_example
auto const root = engine.rootObjects();
if(!root.empty())
{
auto const obj = root.first()->findChild<test_item*>("testItem");
if(obj)
{
c.setup_test(obj);
}
else
{
qDebug() << "Couldn't Cast";
}
}
else
{
qDebug() << "Empty";
}
I tried to pass the component from QML code on Component.onCompleted:
main.qml (for copy/paste: qml_pass_id_example/main.qml)
TestItem
{
id: testItemId;
Component.onCompleted: controller.setup_test(testItemId);
}
main.cpp (for copy/paste: qml_pass_id_example/main.cpp)
class controller : public QObject
{
Q_OBJECT
public slots:
Q_INVOKABLE void setup_test(test_item* item)
{
item->f();
}
};
#include "main.moc"
int main(int argc, char* argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
controller c;
qmlRegisterType<test_item>("qml.pass.id", 1, 0, "TestItem");
engine.rootContext()->setContextProperty("controller", &c);
engine.load("qrc:/qml_pass_id_example/main.qml");
return app.exec();
}
And I think this is much simpler than using objectName, but I couldn't find any related documentation about passing the component's ID to C++ functions. So my questions:
What is the easiest way to passing the QML component pointer to C++?
Is passing the QML component ID as the component C++ type pointer to the C++ function valid?
Qt: 6.2.0 and 5.15.2.
Compiler: GCC 11.1.0 and MSVC 2019.
Platforms: MS Windows and GNU/Linux
|
The easy thing is debatable since it depends on the definition of what is easy or difficult for each case so I will not answer this question since it falls outside of SO.
Yes, it is valid to export any QML object to C ++. The id is the reference to the object so you are not passing the name "testItemId" but you are passing a test_item object that has as identifier "testItemId".
Note: It is recommended not to expose any QML object to C ++ (or do it for a minimum time) since its life cycle is managed by QML so it could be eliminated at any moment causing you to access pointers that no longer have associated objects. .
|
69,246,294 | 69,246,735 | Why is this counting sort in C++ not working? | Why is this counting sort not working?
#include <bits/stdc++.h>
using namespace std;
void countSort(vector<int>& input)
{
int max = *max_element(input.begin(), input.end());
vector<int> counter(max + 1);
vector<int> output;
for(int i = 0; i < max + 1; ++i)
{
counter[i] = 0;
}
for(int i = 0; i < input.size(); ++i)
{
counter[input[i]]++;
}
for(int i = 0; i < max + 1; ++i)
{
while(counter[i] > 0)
{
output.push_back(counter[input[i]]);
counter[i]--;
}
}
}
int main()
{
vector<int> array = {9, 8, 9, 1, 5, 7, 1, 2};
countSort(array);
}
When I run this code, it just send me an error message,
The process finished with exit code 1073741819 (0xC0000005)
but I can't understand where the mistake is.
| The main problem is in your push_back.
output.push_back(counter[input[i]]);
It should simply be:
output.push_back(i);
You also do not save the result of the sorted output array. You could return it or replace input. In my example below, I'm replacing input.
Another potential problem is that you are sorting signed integers so you should expect negative ones. If you get a negative value now, you'll access your counter array out of bounds.
A simple remedy is to check for both the min and max values first and to subtract min from all subscripting in counter.
Example:
#include <algorithm>
#include <iostream>
#include <vector>
void countSort(std::vector<int>& input) {
auto[minit, maxit] = std::minmax_element(input.begin(), input.end());
auto min = *minit;
auto max = *maxit;
std::vector<int> counter(max - min + 1);
for(auto in : input) ++counter[in-min]; // -min offset
input.clear(); // clearing it to fill with the sorted values
for(int i = min; i <= max; ++i) {
for(;counter[i-min] > 0; --counter[i-min]) { // -min offset
input.push_back(i);
}
}
}
int main() {
std::vector<int> array = {9, 8, 9, 1, 5, 7, 1, 2, -10}; // negative value added
countSort(array);
for(auto v : array) std::cout << v << ' ';
}
Output:
-10 1 1 2 5 7 8 9 9
|
69,246,328 | 69,249,592 | C++: redefining public class methods from imported shared library? | Suppose I have a shared library with a class that defines public non-virtual methods, and I want to import said shared library but re-defining some of those class methods without creating a new class, in a way that the library would call the methods I redefine when those are used internally within the shared library.
From some experiments with GCC in linux, everything seems to work as intended, but I am wondering if I am just getting lucky or if what I am doing is guaranteed to work correctly in other environments.
Example:
shared.h:
class Myclass {
public:
int val;
void set_myval(); //I want to override this
void set_myval_v2();
void print_myval();
};
shared.cpp:
#include <iostream>
#include "shared.h"
void Myclass::set_myval() {
this->val = 100;
}
void Myclass::set_myval_v2() {
this->set_myval();
}
void Myclass::print_myval() {
std::cout << "val:" << this->val << std::endl;
}
app.cpp:
#include "shared.h"
void Myclass::set_myval() {
this->val = 200;
}
int main()
{
Myclass obj;
obj.set_myval();
obj.print_myval();
obj.set_myval_v2();
obj.print_myval();
return 0;
}
I then compile it and run as follows:
g++ -c -fPIC shared.cpp -o shared.o
gcc shared.o -shared -o libshared.so
g++ app.cpp -L<path> -l:libshared.so -Wl,-rpath=<path>
./a.out
val:200
val:200
Is this guaranteed to work when done in other compilers/OSes/etc.?
| No, this is a violation of C++ ODR rule and is handled in different ways on different platforms. It is not portable even for GCC - interposition will not work if e.g. the symbols in code have protected visibility or library has been linked with -Wl,-Bsymbolic or with -fno-semantic-interposition.
|
69,246,465 | 69,246,717 | Is there any way to perform this type of recursion in C++ or python? | Let us say I have a function called my_func(a,b,s,t). Suppose, I want a and b to be passed by value, but I want s and t to be passed by reference. As in, I want to some how pass in let us say (4,5,s',t'). The function performs computations by calling my_func(a/2,b/2,s/2,t/2). The thing is, there is a base case at the "bottom" of the recursion that gives concrete values to s and t.
Let me give a mini example:
def e_euclid(a,b,s,t):
if (a == b):
s = 4
t = -3
return a
if (a%2 == 0 and b%2 == 0):
if (s%2 == 0 and t%2 == 0):
return 2*e_euclid(a/2,b/2,s/2,t/2)
else:
return 2*e_euclid(a/2,b/2,(s+b)/2,(t-a)/2)
...
So, I would call this function as e_euclid(a,b, something, something) but then I would have to supply concrete values for s and t. Can you guys kind of see what I'm trying to do here?
Doing recursion where I return (s,t) would lead to a tough computation that I don't wish to perform, so I would like to do it this way.
| Your code seems broken, already that base case (?) with a == b and s = 4 and t = -3 doesn't make sense. But see this C++ implementation and my Python translation using single-element lists instead of C++'s references:
def gcd(a, b, x=[None], y=[None]):
if b == 0:
x[0] = 1
y[0] = 0
return a
x1, y1 = [None], [None]
d = gcd(b, a % b, x1, y1)
x[0] = y1[0]
y[0] = x1[0] - y1[0] * (a // b)
return d
a, b = 123, 321
x, y = [None], [None]
print(gcd(a, b, x, y), x, y, a*x[0] + b*y[0])
Output (Try it online!):
3 [47] [-18] 3
I think you're trying to use the binary version of the algorithm, that should be doable the same way.
|
69,246,546 | 69,246,710 | makefile is skipping target | I have the following makefile for a project:
VIEW := View
CONTROLLER := Controller
MODEL := Model
all: compilar
compilar: criterio acta persona director jurado asistente universidad view main
g++ -o Salida Criterio.o Acta.o Persona.o Director.o Jurado.o Asistente.o Universidad.o View.o main.o
criterio: ${MODEL}/Criterio.cpp ${MODEL}/Criterio.h
g++ -c ${MODEL}/Criterio.cpp
acta: ${MODEL}/Acta.cpp ${MODEL}/Acta.h ${MODEL}/Criterio.h
g++ -c ${MODEL}/Acta.cpp
persona: ${MODEL}/Persona.cpp ${MODEL}/Persona.h ${MODEL}/Acta.h
g++ -c ${MODEL}/Persona.cpp
director: ${MODEL}/Director.cpp ${MODEL}/Director.h ${MODEL}/Persona.h
g++ -c ${MODEL}/Director.cpp
jurado: ${MODEL}/Jurado.cpp ${MODEL}/Jurado.h ${MODEL}/Persona.h
g++ -c ${MODEL}/Jurado.cpp
asistente: ${MODEL}/Asistente.cpp ${MODEL}/Asistente.h ${MODEL}/Persona.h
g++ -c ${MODEL}/Asistente.cpp
universidad: ${MODEL}/Universidad.cpp ${MODEL}/Universidad.h ${MODEL}/Asistente.h ${MODEL}/Jurado.h ${MODEL}/Director.h ${MODEL}/Acta.h
g++ -c ${MODEL}/Universidad.cpp
view: ${VIEW}/View.cpp ${VIEW}/View.h ${MODEL}/Universidad.h
g++ -c ${VIEW}/View.cpp
main: main.cpp ${VIEW}/View.h
g++ -c main.cpp
clean: #comando para borrar los .o y el .exe
@echo "Cleaning compilation..."
del *.o, del *.exe
But when I execute make on the console it skips the target view
g++ -c Model/Criterio.cpp
g++ -c Model/Acta.cpp
g++ -c Model/Persona.cpp
g++ -c Model/Director.cpp
g++ -c Model/Jurado.cpp
g++ -c Model/Asistente.cpp
g++ -c Model/Universidad.cpp
g++ -c main.cpp
g++ -o Salida Criterio.o Acta.o Persona.o Director.o Jurado.o Asistente.o Universidad.o View.o main.o
g++: error: View.o: No such file or directory
As you can see, it skips the target "view" so it does not generate View.o
However if I change the name of the target "view" to something like "doview" it works perfectly. I tried looking up for reserved words on makefiles but I could not find anything related to this. Why does this happen? I'm new to makefiles.
| view: ${VIEW}/View.cpp ${VIEW}/View.h ${MODEL}/Universidad.h
g++ -c ${VIEW}/View.cpp
declares that you are going to create a file called view and that the inputs are ${VIEW}/View.cpp ${VIEW}/View.h ${MODEL}/Universidad.h. As your command actually produces a file called View.o your makefile won't work. You need:
View.o: ${VIEW}/View.cpp ${VIEW}/View.h ${MODEL}/Universidad.h
g++ -c ${VIEW}/View.cpp
(your other targets have the same issue).
You also need to mark all your targets that don't produce a file as phony:
.PHONY: clean all
As compilar isn't a phony target and produces a single file it should be renamed to Salida
|
69,246,823 | 69,246,878 | Does it need to initialise the variable after allocating memory? | I am trying to implement matrix multiplication in c++. I found a sample code using a class that writes in .h and .cpp files. This is just a part of the code that related to my question:
#include "Matrix.h"
// Constructor - using an initialisation list here
Matrix::Matrix(int rows, int cols, bool preallocate): rows(rows), cols(cols), size_of_values(rows * cols), preallocated(preallocate)
{
// If we want to handle memory ourselves
if (this->preallocated)
{
// Must remember to delete this in the destructor
this->values = new double[size_of_values];
}
}
void Matrix::matMatMult(Matrix& mat_left, Matrix& output)
{
// The output hasn't been preallocated, so we are going to do that
output.values = new double[this->rows * mat_left.cols];
// Set values to zero before hand
for (int i = 0; i < output.size_of_values; i++)
{
output.values[i] = 0;
}
I wonder why they initialised using the output matrix with 0s output.values[i] = 0; while it has been allocated memory before?
| From cppreference on new expression:
The object created by a new-expression is initialized according to the following rules:
[...]
If type is an array type, an array of objects is initialized.
If initializer is absent, each element is default-initialized
If initializer is an empty pair of parentheses, each element is value-initialized.
"default-initialized" ints are colloquially not initialized. They have indeterminate values. The empty pair of parantheses refers to what Ted mentioned in a comment:
output.values = new double[this->rows * mat_left.cols]{};
Value initialization is described here. The case that applies here is
otherwise, the object is zero-initialized.
I wonder why they initialised using the output matrix with 0s output.values[i] = 0; while it has been allocated memory before?
Allocating memory and initializing an object are two seperate steps. Yes, the elements have to be initialzed, allocating memory is not sufficient.
|
69,246,931 | 69,246,992 | How to make a c++ project from command prompt? | Note that this is referred to make a project from command prompt, not build or run it, by "make", i mean, creating a .vcxproj file like Visual Studio does.
I am unable to use Visual Studio for now, this is why i'm asking to make a project through cmd, i tried gcc, but it doesn't generate these project stuff.
| GCC is just a compiler, rather than a full IDE like Visual Studio. It takes source code (and some binary libraries), and then outputs compiled executables or object files.
You can use a build system like CMake or Meson, which can make the building process easier for you and those who clone your code, and can even be integrated into Visual Studio. You can actually use CMake to convert projects into Visual Studio format.
|
69,247,041 | 69,260,057 | Linkers: file was built for archive which is not the architecture being linked (x86_64) GLFW | Hello, this problem make me crazy and i need your help.
I am on a IOS High Sierra v10.13.6 and i am trying to try OpenGL on VSC on mac without XCode.
So i have downloaded the library GLFW for the right OS.
I have tried the basic exemple from the GLWF website.
#include "../GLFW/glfw3.h"
// g++ -v main.cpp -o main.o -L/Library/Developer/CommandLineTools/usr/include -lglfw3 -framework OpenGL
// file was built for archive which is not the architecture being linked (x86_64):
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
i have the following directory:
When i do this command:
g++ -v main.cpp -o main.o -L/Library/Developer/CommandLineTools/usr/include -lglfw3 -framework OpenGL
I have the following error in the terminal:
Undefined symbols for architecture x86_64:
"_glfwCreateWindow", referenced from:
_main in main-ca9141.o
"_glfwInit", referenced from:
_main in main-ca9141.o
"_glfwMakeContextCurrent", referenced from:
_main in main-ca9141.o
"_glfwPollEvents", referenced from:
_main in main-ca9141.o
"_glfwSwapBuffers", referenced from:
_main in main-ca9141.o
"_glfwTerminate", referenced from:
_main in main-ca9141.o
"_glfwWindowShouldClose", referenced from:
_main in main-ca9141.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I understand that i came from this warning:
ld: warning: ignoring file /Library/Developer/CommandLineTools/usr/include/libglfw3.a, file was built for archive which is not the architecture being linked (x86_64): /Library/Developer/CommandLineTools/usr/include/libglfw3.a
I have checked the library with the lipo command and it say that his architecture is x86_64!
I don't know why it does not work, can you help me?
Thanks in advance.
| i want to say that i have found the solution for my problems.
You have to double check that the library libglfw3.a is compiled in the good architecture witch is the x86_64.
Here the official link to download the GLFW library in the right OS
Also here is the command you need to run for make it compile:
You need to make sure to specify the path to the library through -L
g++ main.cpp -o main -L/Library/Developer/CommandLineTools/usr/include -lglfw3 -framework Cocoa -framework OpenGL -framework IOKit
Hope it will help for the futur dev who are stuck in the same problem
|
69,247,650 | 69,271,899 | How do I create a class with reference member and vector of pointers? | I am fairly new to C++ and am working on a personal project. I want to create a vector<Entity*> entitities in C++ where each Entity object is unique. I have a class inside header Entity.h that I want to create. Now Entity takes two member variables:
Rectangle rect - an Object of type Rectangle that has four float variables as member variables (x1, y1, x2, y2) which are the coordinates of two opposite corners of a rectangle
vector<Component*> - a number of different components of Base class type Component with some Derived classes. The code for Class Component looks like so:
/*************************** BASE CLASS **************************/
class Component
{
public:
virtual ~Component() = default;
virtual Component* Clone() = 0;
};
/*************************** DERIVED CLASS 1 **************************/
class BasicComponent: public Component
{
private:
int B= 0;
public:
BasicComponent* Clone() override {
return new BasicComponent(B);
}
BasicComponent(const int& mB) :B(mB){}
BasicComponent() :B(0) {}
};
/*************************** DERIVED CLASS 2 **************************/
class AdvancedComponent: public Component
{
private:
float A = 0.f;
int iA = 0;
public:
AdvancedComponent* Clone() override {
return new AdvancedComponent(A, iA);
}
AdvancedComponent(const float& mA, const int& miA) :A(mA),iA(miA) {}
AdvancedComponent() :A(0.f),iA(0) {}
};
Since I want each Entity in the vector of entities to be unique, that is, have it's own rectangle and components, how should I create the class ?
My question here is, what should the class Entity look like ? Should I create separate CopyConstructor, Assignment Constructor and Destructor for this class ? Also if I want to implement copying one Entity into another (deep copying), is it necessary to have all 3 (Copy, Assignment and Destructor) ?
|
My question here is, what should the class Entity look like ? Should I create separate CopyConstructor, Assignment Constructor and Destructor for this class ? Also if I want to implement copying one Entity into another (deep copying), is it necessary to have all 3 (Copy, Assignment and Destructor) ?
The answer to this doesn't really depend on what the Entity looks like, but on what semantics it is intended to have.
You say every Entity is "unique", but every object in C++ (even every int, even when they happen to have the same value) is technically unique. So what do you really mean?
Should an Entity be copyable? Copy-constructing an Entity would mean two Entity objects have the same contents (literally if the component pointers are shallow-copied, and logically if they're deep-copied).
If not, you probably don't want to write a (or may explicitly delete the) copy constructor and/or copy-assignment operator.
Should an Entity be moveable? Probably yes, since it doesn't violate uniqueness and makes them easier to use efficiently.
If so, you should make sure it has a move constructor and move-assignment operator (either by writing it or arranging for the compiler to generate useful defaults).
Also if I want to implement copying one Entity into another (deep copying)
That seems to violate your uniqueness constraint, but yes, you'd want a copy constructor and copy-assignment operator for this.
However, best practice is to avoid interleaving resource management with your program logic. So, instead of writing all these, consider having a smart pointer automate it for you. See for comparison the Rule of Zero mentioned in this answer.
In fact, we can illustrate all the reasonable semantics with very little code:
template <typename ComponentPtr>
struct ZeroEntity
{
Rectangle bound;
std::vector<ComponentPtr> components;
};
using ShallowCopyZeroEntity = ZeroEntity<std::shared_ptr<Component>>;
using NoCopyOnlyMoveEntity = ZeroEntity<std::unique_ptr<Component>>;
using DeepCopyZeroEntity = ZeroEntity<my::clone_ptr<Component>>;
except for the fact that we still need to write a deep-copying clone_ptr, something like
namespace my {
template <typename T>
class clone_ptr
{
std::unique_ptr<T> p_;
std::unique_ptr<T> clone() const { return std::unique_ptr<T>{p_ ? p_->Clone() : nullptr}; }
public:
using pointer = typename std::unique_ptr<T>::pointer;
explicit clone_ptr(pointer p) : p_(p) {}
// copy behaviour is where the cloning happens
clone_ptr(clone_ptr const& other) : p_(other.clone()) {}
clone_ptr& operator=(clone_ptr other)
{
other.swap(*this);
}
// move behaviour (and destructor) generated by unique_ptr
clone_ptr(clone_ptr&& other) = default;
clone_ptr& operator=(clone_ptr&&) = default;
// now write all the same swap, release, reset, operator* etc. as std::unique_ptr
};
}
... and if that looks like a lot, imagine how messy it would have been interleaved with your Entity code instead of collected into one place like this.
|
69,247,777 | 69,247,826 | c++ Thread pool std::promise and function type error | I try to write my own version of a Thread pool but have difficulties with lines
template <typename F, typename...Args>
auto addWork(F&& f, Args&&... args) -> std::future<decltype (f(args...))>
{
using ReturnType = decltype(f(args...));
//...
result.set_value(f(args...));
std::promise<ReturnType> result;
result.set_value(f(args...));
return result.get_future();
//...
Everything seems to work except when f has no parameter or is void type. I don't know how to make "set_value()" work.
Thank for reading.
| In case where your ReturnType is void, your std::promise<ReturnType> result variable is a specialisation - std::promise<void>. Its set_value(4) method does not take any arguments.
To fix the issue, you can just use if constexpr to check whether you are dealing with the special case that involves a function returning void. Simply change this:
std::promise<ReturnType> result;
result.set_value(f(args...));
return result.get_future();
to this:
std::promise<ReturnType> result;
if constexpr (std::is_same_v<ReturnType, void>) {
f(args...);
result.set_value();
} else {
result.set_value(f(args...));
}
return result.get_future();
|
69,247,796 | 69,248,017 | Why does a `char *` allocated through malloc prints out gibberish after the function allocating it returns? | I'm trying to write a function to parse and extract the components of a URL. Moreover, I need the components (e.g. hostname) to have the type char * since I intend to pass them to C APIs.
My current approach is to save the components in the parse_url function to the heap by calling malloc. But for some reason, the following code is printing gibberish. I'm confused by this behavior because I thought memory allocated on the heap will persist even after the function allocating it returns.
I'm new to C/C++, so please let me know what I did wrong and how to achieve what I wanted. Thank you.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
void cast_to_cstyle(string source, char *target)
{
target = (char *)malloc(source.size() + 1);
memcpy(target, source.c_str(), source.size() + 1);
}
void parse_url(string url, char *protocol_cstyle, char *hostname_cstyle, char *port_cstyle, char *path_cstyle)
{
size_t found = url.find_first_of(":");
string protocol = url.substr(0, found);
string url_new = url.substr(found + 3); // `url_new` is the url excluding the "http//" part
size_t found1 = url_new.find_first_of(":");
string hostname = url_new.substr(0, found1);
size_t found2 = url_new.find_first_of("/");
string port = url_new.substr(found1 + 1, found2 - found1 - 1);
string path = url_new.substr(found2);
cast_to_cstyle(protocol, protocol_cstyle);
cast_to_cstyle(hostname, hostname_cstyle);
cast_to_cstyle(port, port_cstyle);
cast_to_cstyle(path, path_cstyle);
}
int main() {
char *protocol;
char *hostname;
char *port;
char *path;
parse_url("http://www.example.com:80/file.txt", protocol, hostname, port, path);
printf("%s, %s, %s, %s\n", (protocol), (hostname), (port), (path));
return 0;
}
| The problem is that arguments are passed by value, so the newly created string never leaves the function (albeit exists until program termination as free is never called on it). You can pass by reference¹ like:
void cast_to_cstyle(string source, char *&target)
or better, pass the source string by (constant) reference too (string is expensive to copy):
void cast_to_cstyle(const string &source, char *&target)
(neither function body nor the call site need to be changed).
But you may not need even that.
If the API doesn’t actually modify the string despite using non-const pointer (pretty common in C AFAIK), you can use const_cast, like const_cast<char *>(source.c_str()).
Even if it may modify the string, &source[0] is suitable (at least since C++11). It may not seem right but it is:
a pointer to s[0] can be passed to functions that expect a pointer to the first element of a null-terminated (since C++11)CharT[] array.
— https://en.cppreference.com/w/cpp/string/basic_string
(and since C++17 data() is the way to go).
However, unlike that obtained from malloc any such pointer becomes invalid when the string is resized or destroyed (be careful “the string” means “that particular copy of the string” if you have several).
¹ Strictly speaking, pass a reference; references aren’t restricted to function arguments in C++.
|
69,247,811 | 69,247,910 | C++ Why is the output of this code 3? (structs) | Can someone help me understand step-by-step why the following C++ code outputs a 3?
#include <iostream>
using namespace std;
struct sct
{
int t[2];
};
struct str
{
sct t[2];
};
int main() {
str t[2] = { {0,2,4,6}, {1,3,5,7} };
std::cout << t[1].t[0].t[1];
}
| t[1] is {1,3,5,7}.
str is represented in memory as four integers back-to-back, organized into 2 sct structures. In this case, the first one has the values 1 and 3, while the second contains 5 and 7.
Thus, t[1].t[0] is {1,3}, so t[1].t[0].t[1] is 3.
|
69,247,901 | 69,247,943 | When the user enters the letter n as the major mark, the major mark will instead be represented by the number: | My code goes like this
#include <iostream>
#include <string>
using namespace std;
int main() {
string z,zz ="";
int x,y;
cin >> x >> y >> z >> zz;
for (int a = 1; a <= x; ++a) {
cout << z;
for (int b = 1; b <= y; ++b) {
cout << zz;
}
}
cout << z;
return 0;
}
If my input is
3 9 n a
It should print out
0aaaaaaaaa1aaaaaaaaa2aaaaaaaaa3
But my code prints out
naaaaaaaaanaaaaaaaaanaaaaaaaaan
| If you:
Move the declaration of a outside of the outer for loop.
Change both cout << z; statements to cout << a;.
Change the outer for loop to start at 0 instead of 1, and to use < insted of <=.
Then you will get the output you want.
#include <iostream>
#include <string>
using namespace std;
int main() {
string z, zz;
int x, y;
cin >> x >> y >> z >> zz;
int a;
for (a = 0; a < x; ++a) {
cout << a;
for (int b = 1; b <= y; ++b) {
cout << zz;
}
}
cout << a;
return 0;
}
Online Demo
Note that in this case, z becomes redundant and can be eliminated if you can remove n from your input.
|
69,248,025 | 69,248,204 | operator overloading about Abstract class (cpp) | In student.h file
class Student {
protected:
string Name;
int Stu_num;
public:
virtual void print() = 0;
// constructor...
}
class Grad_Student: public Student {
private:
string Lab;
public:
void print();
// constructor...
}
class Undergrad_Student: public Student {
private:
string Major;
public:
void print();
// constructor...
}
in student.cpp file
bool operator == (const Student& x, const Student& y) {
if (typeid(x) != typeid(y)) return false;
else // dosomething..
}
I want to compare child of Student class; Grad and Undergrad.
in main.cpp when i comapre two student class, it doesn't work..
Grad_Student grad1 = Grad_Student("Max", 11, "Hubo");
Student *std1 = &grad1;
Grad_Student grad2 = Grad_Student("Max", 11, "Hubo");
Student *std2 = &grad2;
cout << (std1 == std2) << endl; // it always prints 0.
cout << (*std1 == *std2) << endl;
// I think this line should work, but makes error.
// error: invalid operands to binary expression ('Student' and 'Student')
Should i overload operator== in student class?
give me a hint...
| So, your overloaded equality operator does nothing... You need to compare something in the body and return a boolean result.
Also, your Undergrad_Student currently doesn't derive from Student..
Furthermore, since you're comparing 2 Student objects you can just make the equality operator overload a member function taking 1 argument.
Something like this:
class Student {
public:
explicit Student( int id )
: id_{ id }
{ }
bool operator==( const Student& other ) const {
return id_ == other.id_;
}
virtual void print() const = 0;
virtual ~Student( ) = default;
protected:
int id_;
};
class Grad: public Student {
public:
explicit Grad( int id )
: Student{ id }
{ }
void print() const override {}
};
class Undergrad : public Student {
public:
explicit Undergrad( int id )
: Student{ id }
{ }
void print() const override {}
};
int main( ) {
Grad s1{ 11 };
Undergrad s2{ 12 };
// Prints false.
std::cout << std::boolalpha << ( s2 == s1 ) << '\n';
Grad s3{ 42 };
Undergrad s4{ 42 };
// Prints true.
std::cout << std::boolalpha << ( s3 == s4 ) << '\n';
}
|
69,248,248 | 69,248,387 | How to start my else if for loop start with 01 - 09? | How do I make my code specifically on else if to print out this if my input is 45?
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
21.22.23.24.25.26.27.28.29.30
31.32.33.34.35.36.37.38.39.40
41.42.43.44.45
#include <iostream>
#include <string>
using namespace std;
int main() {
string dot = "";
int x;
cin >> x;
if (x<=10){
for (int n=1; n<=x; n++){
cout << dot << n ;
dot =".";
}
}
else if(x>10&&x<=100) {
for (int i = 1; i <=x; ++i){
for (int j = 1; j <=10; ++j){
cout << dot << x;
dot=".";
}
cout << endl;
}
}
else{
cout << "OUT OF RANGE";
}
return 0;
}
| Your entire program can be simplified using setw and setfill to do the hard work for you of inserting leading zero chars where needed. #include <iomanip> to have access to these stream modification functions.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int x;
cin >> x;
for (int i = 1; i <= x; i++)
{
cout << setw(2) << setfill('0') << i;
char delimiter = ((i % 10) && (i != x)) ? '.' : '\n';
cout << delimiter;
}
cout << endl;
}
|
69,248,633 | 69,248,913 | Better system than having multiple vectors for each event type | I am trying to implement a basic event system. This event system consists of a series of void pointers used for callback functions. The code below is BAD design. If I want to add many events, the code quickly gets bloated.
Currently, the bad solution needs to know what vector to add to, and which vector to run based off of the event type. Ideally, I could store all the void pointers in a single vector, and based off of the type of event that occurs, the function pointers using that event could be run.
If anyone has any ideas they would like to give for a better implementation, it would be greatly appreciated.
Example event handler class:
#include <vector>
typedef void(*CALLBACK)();
enum EventType {
WINDOW_RESIZE,
WINDOW_CLOSE,
};
class EventManager {
public:
// Add a callback function
void bind(CALLBACK f, EventType type) {
switch(type) {
// Note I would need to implement a case for all the events
case WINDOW_RESIZE: {
window_resize_event.push_back(f);
}
///...
}
}
// This would poll the event queue, and based on the
// event, run the callback functions
void update() const {
unsigned int event;
if (event == WINDOW_RESIZE) {
///iterate through vector
}
///...
}
private:
std::vector <callback> window_resize_event;
std::vector <callback> window_close_event;
};
Edit: The implemented solution using a multi map
#include <stdio.h>
#include "event.hpp"
EventManager::EventManager() {
std::vector <CALLBACK> callbacks;
// Copy callbacks vector into each
events.insert(std::pair <EventType, std::vector <CALLBACK>> (WINDOW_CLOSE , callbacks));
events.insert(std::pair <EventType, std::vector <CALLBACK>> (WINDOW_RESIZE , callbacks));
events.insert(std::pair <EventType, std::vector <CALLBACK>> (KEY_DOWN , callbacks));
events.insert(std::pair <EventType, std::vector <CALLBACK>> (KEY_UP , callbacks));
events.insert(std::pair <EventType, std::vector <CALLBACK>> (MOUSE_DOWN , callbacks));
events.insert(std::pair <EventType, std::vector <CALLBACK>> (MOUSE_UP , callbacks));
events.insert(std::pair <EventType, std::vector <CALLBACK>> (MOUSE_MOVED , callbacks));
events.insert(std::pair <EventType, std::vector <CALLBACK>> (MOUSE_SCROLLED, callbacks));
}
void EventManager::bind(const CALLBACK &f, const EventType &type) {
std::multimap <EventType, std::vector <CALLBACK>>::iterator it;
for (it = events.begin(); it != events.end(); it++) {
if (it->first == type) {
it->second.push_back(f);
return;
}
}
printf("Unknown event type\n");
}
void EventManager::update() {
std::multimap <EventType, std::vector <CALLBACK>>::iterator it;
while (SDL_PollEvent(&event)) {
for (it = events.begin(); it != events.end(); it++) {
// Cast event to the SDL equivalent
if (event.type == static_cast <uint32_t> (it->first)) {
run(it->second);
}
}
}
}
void EventManager::run(const std::vector <CALLBACK> &callbacks) {
// Call the registered functions
for (unsigned int i = 0; i < callbacks.size(); i++) {
(*callbacks[i])();
}
}
|
This event system consists of a series of void pointers used for callback functions.
Use std::function in a suitable form / shape / wrapper.
Currently, the bad solution needs to know what vector to add to, and which vector to run based off of the event type.
Use a std::multimap from the event type enum to a suitable polymorphic handler type. With a polymorphic type you will need to reference it by (e.g.) a std::unique_ptr rather than directly embedding it in the multimap. Alternatively, a std::variant is something you could use (to avoid the extra pointer hops), but call sites may look slightly uglier. (OTOH, you don’t need std::visit or the like, because the multimap key already determines what type is expected.)
Ideally, I could store all the void pointers in a single vector, and based off of the type of event that occurs, the function pointers using that event could be run.
There is nothing ideal about this. It sounds like an unnecessary linear treversal through the common vector with all event types, only to run one event type. Bad idea.
|
69,250,055 | 69,251,578 | operator overloading abstract class | There is an Student abstract class, and two derived class Grad and Undergrad; and I want to overload operator in several ways.
student.h
class Student {
protected:
string Name;
int Stu_num;
public:
virtual void print() = 0;
bool operator==(const Student& x) const;
// constructor...
}
class Grad_Student : public Student {
private:
string Lab;
public:
void print();
bool operator==(const Grad_Student& x) const;
// constructor...
}
class Undergrad_Student : public Student {
private:
string Major;
public:
void print();
bool operator==(const Undergrad_Student& x) const;
// constructor...
}
student.cpp
bool Student::operator==(const Student& x) const {
if (this->Name == x.Name && this->Stu_num == x.Stu_num) {
if (typeid(*this).name() != typeid(x).name()) {
return false;
}
else if (!(strcmp(typeid(*this).name(), "12Grad_Student"))) {
return *dynamic_cast<const Grad_Student *>(this) == *dynamic_cast<const Grad_Student *>(&x);
}
else {
return *dynamic_cast<const Undergrad_Student *>(this) == *dynamic_cast<const Undergrad_Student *>(&x);
}
}
else {
return false;
}
}
bool Grad_Student::operator==(const Grad_Student& x) const {
return this->Lab == x.Lab;
}
bool Undergrad_Student::operator==(const Undergrad_Student& x) const {
return this->Major== x.Major;
}
To find student object in Student *students[300]
this operation == overloading works and doen't have problem,
but I want to implement overloading in different way using below.
How can I implement this function??
bool operator==(const Student& x, const Student& y)
{
// do comparison...
}
| While that may appear to work, type_info::name() is
implementation-dependent,
not guaranteed to be unique between different types,
not guaranteed to be the same between different executions of the same program.
Comparing type_infos directly is reliable though, so you could do things like if (typeid(*this) == typeid(Grad_Student)) and it would work as expected.
However, polymorphism already exists, so you don't need to implement it yourself, and you can avoid a lot of trouble (and overhead) by dispatching to a virtual function instead of enumerating subclasses.
Something like this:
class Student {
public:
bool equals(const Student& s) const
{
return Name == s.Name
&& Stu_num == s.Stu_num
&& typeid(*this) == typeid(s)
&& equals_internal(s);
}
private:
virtual bool equals_internal(const Student& s) const = 0;
string Name;
int Stu_num;
};
bool operator==(const Student& lhs, const Student& rhs)
{
return lhs.equals(rhs);
}
class Grad_Student : public Student {
private:
string Lab;
bool equals_internal(const Student& s) const override
{
return Lab == static_cast<const Grad_Student&>(s).Lab;
}
};
class Undergrad_Student : public Student {
private:
string Major;
bool equals_internal(const Student& s) const override
{
return Major == static_cast<const Undergrad_Student&>(s).Major;
}
};
Note that the static_casts are safe, since Student has already established the type equality.
|
69,250,533 | 69,251,509 | Starting the default terminal on Linux | Tell me, please, is it possible to call the Linux Terminal, which is installed by default, in some way (method)?
Now, I run the process in the xfce4-terminal terminal, specifying this terminal and the arguments to it:
QProcess up;
QString cArg;
cArg="/tmp/cp.py -y " + ye;
up.start("xfce4-terminal", QStringList()<< "--geometry=120x40" << "--command" << "python3 "+ cArg << "-H");
up.waitForFinished();
up.close();
| No, there is no general way in the Linux kernel to find out which (or whether a) terminal emulator is installed on the system by default.
Although the (fairly ubiquitous) freedesktop.org specifications describe how to associate MIME type with a default application, there isn't a specification for default application without an associated file to be opened as far as I can tell. Each desktop environment that has a concept of "default terminal emulator" has their own way of configuring it.
Debian has has "update-alternatives" system that allows configuration of "default" applications based on aliases, and it has a package that creates an alias x-terminal-emulator that can be used to configure the default terminal emulator.
Here is a reasonable strategy for choosing the command in your program:
Let the user configure the command. Use this with highest priority if configured.
Use XDG_CURRENT_DESKTOP environment variable, and implement logic for each desktop environment to read their configuration to find out the configured default emulator. Use this as the second highest priority when available.
Collect a list of commonly used terminal emulators. Put aliases such as x-terminal-emulator with higher priority in the list.
With this list starting with user configuration and ending with your hard-coded list, check each command and see if it's executable and pick the first one that is. In case user has configured the command, and it isn't executable, I recommend an optional error message.
|
69,250,948 | 69,251,878 | How to combine two relative URIs into one in C++ | I have one base URI like https://stackoverflow.com/questions/ask and a relative URI.
I want to combine them all into one absolute URI.
Examples:
Relative URI: ../
Result: https://stackoverflow.com/questions
Relative URI: /abc/kk?6
Result: https://stackoverflow.com/abc/kk?6
Relative URI: task.php?ui=4
Result: https://stackoverflow.com/questions/task.php?ui=4
How can I do this?
| It seems the proposal to add URI-handling to standard C++, https://isocpp.org/files/papers/n3975.html, is dead and/or stuck in committee.
You therefore have to write your own or use a 3rd party - e.g., Qt has QUrl with https://doc.qt.io/qt-5/qurl.html#resolved
QUrl QUrl::resolved(const QUrl &relative) const
|
69,251,112 | 69,256,111 | Take inputs from keyboard and increase/decrease sides of a shape using GLUT | Take inputs from keyboard such as "+" or "-" and increase/decrease sides accordingly. For example if a triangle is currently displayed and if i press "+", it should transform into a rectangle etc. How can I achieve that?
static void DisplayShape(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,0.1,0.6);
glBegin(GL_POINTS);
for(int i=0;i<n;++i) // n - sides count
{
glVertex2f(); // the n-sided shape is to be drawn here
}
glEnd();
glutSwapBuffers();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q': // quit
exit(0);
break;
case '+': // increase sides count
n++;
break;
case '-': // decrease sides count
if (n > 3) // cannot be less than 3
{
n--;
}
break;
}
glutPostRedisplay();
}
static void idle(void)
{
glutPostRedisplay();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("GLUT Shapes");
glutDisplayFunc(DisplayShape);
glutKeyboardFunc(key);
glutIdleFunc(idle);
glutMainLoop();
return EXIT_SUCCESS;
}
| Distribute the N-points around a circle. Compute the angle between the vectors from the center of the circle to the points (360°/N). Calculate the points using their Polar Coordinates:
const float x0 = 0.0f;
const float y0 = 0.0f;
const float sideLen = 0.5;
float dist = sideLen / 2.0f / sin(M_PI * 2.0f / n / 2.0f);
float startAngle = -M_PI * (n - 2) / 2 / n;
glBegin(GL_LINE_LOOP);
for (int i = 0; i < n; ++i) // n - sides count
{
float sideAngle = M_PI * 2.0 * i / n + startAngle;
float x = x0 + dist * cos(sideAngle);
float y = y0 + dist * sin(sideAngle);
glVertex2f(x, y);
}
glEnd();
Complete example:
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/freeglut.h>
#define _USE_MATH_DEFINES
#include <math.h>
int n = 3;
static void DisplayShape(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1, 0.1, 0.6);
const float x0 = 0.0f;
const float y0 = 0.0f;
const float sideLen = 0.5;
float dist = sideLen / 2.0f / sin(M_PI * 2.0f / n / 2.0f);
float startAngle = -M_PI * (n - 2) / 2 / n;
glBegin(GL_LINE_LOOP);
for (int i = 0; i < n; ++i) // n - sides count
{
float sideAngle = M_PI * 2.0 * i / n + startAngle;
float x = x0 + dist * cos(sideAngle);
float y = y0 + dist * sin(sideAngle);
glVertex2f(x, y);
}
glEnd();
glutSwapBuffers();
glutPostRedisplay();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27:
case 'q': // quit
exit(0);
break;
case '+': // increase sides count
n++;
break;
case '-': // decrease sides count
if (n > 3) // cannot be less than 3
n--;
break;
}
glutPostRedisplay();
}
static void reshape(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double aspect = (double)width / height;
glOrtho(-aspect, aspect, -1.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640, 480);
glutInitWindowPosition(10, 10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("GLUT Shapes");
glutReshapeFunc(reshape);
glutDisplayFunc(DisplayShape);
glutKeyboardFunc(key);
glutMainLoop();
return EXIT_SUCCESS;
}
|
69,251,173 | 69,251,622 | When you have a number which has over 1 digit in a created board, what should you do prevent it from affecting the shape of the board | I am new to C++. And I am trying to implement a 2048 game based on C++ for practice. And I am trying to create a board first.
The problem I have is that when the number is become a two digit numbers it will affect the shape of the wall like this:
Here is the test code:
#include<iostream>
using namespace std;
int main()
{
string gameboard[24][25];
int p = 24 / 4;
for (int i = 0; i < 24;i++)
{
for (int j = 0; j < 25; j++)
{
if (i == 0 || j == 0 || i == 23|| j == 24 || (i % p) == 0 || (j % p) == 0)
{
gameboard[i][j] = '*';
}
else
{
gameboard[i][j] = " ";
}
}
}
gameboard[3][15] = "128";
for (int i = 0; i < 24; ++i)
{
for (int j = 0; j < 25; ++j)
{
cout << gameboard[i][j] << " ";
}
cout << endl;
}
}
So I put a string number "128", it will break the wall. What should I do to prevent this?
| It looks like you actually want a char gameboard[24][25]; rather than a 2d array of strings. When each cell of the board is exactly 1 character wide then you just need to print it character by character to get expected output.
If you do that you need to place individual digits rather than the complete number as string:
gameboard[3][13] = '1';
gameboard[3][14] = '2';
gameboard[3][15] = '8';
I recommend to wrap this inside a function:
void place_number(int number, int row, int col,char gameboard[24][25]) {
int x = row * a + b;
int y = col * c + d;
std::string s = std::to_string(number);
for (int i=0; i<s.size(); ++i) {
gameboard[x][y+i] = s[i];
}
}
With coefficients a,b,c and d choosen such that the numbers end up in the right positions.
Doing such formatted printing can become cumbersome rather fast. If you need more sophisticated control I suggest to use a library for that, for example ncurses.
|
69,252,152 | 69,252,215 | String isn't printed after using strcpy | I'm trying to copy string s to r using strcpy(). But it does not print out any result. Why?
#include <iostream>
using namespace std;
#include <string.h>
int main() {
char s[] = "john lemon";
char r[] = "";
strcpy(s, r);
cout<<s<<" "<<r;
return 0;
}
| strcpy(a,b) copies the string b into the string a
You have copied the empty string to the the string s. After the copy it also contains the empty string.
Printing empty string results with no characters outputted as empty string does not contain any printable ones.
If you want to copy in the opposite direction you must make sure that the destination array has enough elements to accommodate the source string.
char s[] = "john lemon";
char r[sizeof(s)] = "";
strcpy(r, s);
|
69,252,287 | 69,252,430 | Can I reorder elements in map by value? C++ | I want to make a table of letter frequency, just like this
So, I have variable str that contains some text, and I have map<char, int> m, that contains number of occurrences of each letter.
So I have something like that:
vector<char> get_rank(const string& str)
{
map<char, int> m;
for (char i = 'a'; i <= 'z'; i++)
m[i] = 0;
for (char ch : str)
m[ch]++;
for (auto& it : m)
v.push_back(it.first);
return v;
}
But map is ordered by keys, not by values. Is there a way to "overload" the comparator of map to order each element by value? If the answer is no, how can I implement the same idea but with the same elegancy. Because every idea I have seems a little dull and rough.
| It is not possible to sort a map with respect to its mapped values. The order of elements of a map is managed by the map according to its comparator which only considers keys.
However, you do not need a map to count frequencies when the keys are contiguous and of limited range.
Instead of a map, use a std::vector<letter_and_count> with
struct letter_and_count {
char letter;
int count = 0;
};
Initialize the vector with elements with letter initialized to a till z then increment v[ i - 'a'] when you encounter the letter i in the string. Then use std::sort to sort the vector according to the count member.
PS: Note comments below. The letters a till z are not necessarily contiguous. However (idea also from eerorika) you can use a simple lookup table:
std::string alphabet{"abcdefghijklmnopqrstuvwxyz"};
Then first find the letter in that alphabet and use its index in the alphabet for the counting.
|
69,252,437 | 69,252,860 | Run c++ function from python | I am trying to access GPIO of my IDS camera via python using pyueye. The original function is defined as: INT is_IO(HIDS hCam, UINT nCommand, void* pParam, UINT cbSizeOfParam). This is an example of usage:
Example 2
INT nRet = IS_SUCCESS;
IO_GPIO_CONFIGURATION gpioConfiguration;
// Set configuration of GPIO1 (OUTPUT LOW)
gpioConfiguration.u32Gpio = IO_GPIO_1;
gpioConfiguration.u32Configuration = IS_GPIO_OUTPUT;
gpioConfiguration.u32State = 0;
nRet = is_IO(hCam, IS_IO_CMD_GPIOS_SET_CONFIGURATION, (void*)&gpioConfiguration,
sizeof(gpioConfiguration));
I'm trying to do it in python as follows:
from pyueye import ueye
from ctypes import pointer
gpioConfiguration = ueye.IO_GPIO_CONFIGURATION
gpioConfiguration.u32Gpio = ueye.IO_GPIO_1
gpioConfiguration.u32Configuration = ueye.IS_GPIO_OUTPUT
gpioConfiguration.u32State = 1
pt = pointer(gpioConfiguration)
stat = ueye.is_IO(hCam, ueye.IS_IO_CMD_GPIOS_SET_CONFIGURATION,byref(gpioConfiguration),ueye.sizeof(gpioConfiguration))
But I get the error: TypeError: type must have storage info.
Any ideas on what I need to change?
| The error is actually being thrown by your call to ctypes.pointer rather than pyueye. Specifically, gpioConfiguration is a _ctypes.PyCStructType rather than an instance. (This is what was meant by 'must have storage', i.e. you actually have to store something looking like that struct before you can get a pointer to it. This is likely a bit odd coming from c++, but ctypes thinks of structs as being like Classes you have to instantise. docs.
So if you really needed a pointer you would have to do:
myConfig = gpioConfiguration()
pt = pointer(myConfig)
# you probably want to set properties on the *instance*:
myConfig.u32Gpio = ueue.IO_GPIO_1
myConfig.u32State = 1
# and then use this instance later when passing `byref`
If you just need to pass these params by reference, see the section on byref (though this too needs an instance).
I don't have a camera to test with sadly (they look very good fun), so this is far as I can go. But hopefully you can get the semantics of ueye behaving for you.
Incidentally, you don't need semicolons in python (unlike in JS you really don't and nobody thinks you should put them in)
|
69,252,632 | 69,252,897 | vcpkg: How do I submit a request for a package update, or see if the package is due an update? | I am (obviously) new to vcpkg but I can't figure out how to either see if a package is due for on upgrade on vcpkg or submit a request for an upgrade on a package. I have seen how to specify an older version of a package in the docs but not request an upgrade, see the planed versions etc.
Any links and explanation please. Specifically at the moment I am looking at sqlite 3.35.5 and wondering if there is a plan for 3.36 (current) if not how to submit.
Many Thanks!
| That's not how vcpkg works, the maintainers of vcpkg do not manage package upgrades. It is the responsibility of the package maintainers to create pull requests for vcpkg that upgrade their packages: https://github.com/microsoft/vcpkg/pulls
There isn't an open PR for sqlite, so either create one yourself or ask the sqlite maintainers to do so.
|
69,252,739 | 69,252,964 | Deleting node that doesn't exist in linked list causes segmentation fault | So I am new to data structures and I am trying out linked lists. I have made a class Node with an int key, int del and Node* next.
When I try to delete nodes by giving delete function (Del) a key, it works perfectly for head node or any node existing in the list but when I give a key that doesn't exist in the list it returns with a segmentation fault.
void Node::Del(int k) // here k is the key given to search
{
Node *curr = head; // ptr that traverses the list
Node *temp = NULL; // the pointer trails behind curr to store value of node one position behind curr
while (curr->key != k && curr != NULL)
{
temp = curr;
curr = curr->next;
}
if (curr == NULL) // if key not found (not working properly)
{
return;
}
else if (curr == head) // if head contains the key
{
head = curr->next;
delete curr;
return;
}
else if (curr->key == k) // if key exists in the node
{
temp->next = curr->next;
delete curr;
}
}
int main()
{
Node n1;
n1.Insert(1, 1);
n1.Insert(2, 2);
n1.Insert(3, 3);
n1.Insert(4, 4);
n1.Insert(5, 5);
n1.Del(7);
n1.print();
}
Output:
1 1
2 2
3 3
4 4
5 5
zsh: segmentation fault
I have a condition after traversing that if( curr == NULL ){ return;} meaning it searched till the end and didn't find the key and exit the loop (as per my understanding) , but instead it It returns segmentation fault.
| in this line (curr->key != k && curr != NULL) you should check if curr is null first and before accessing curr to check it's key value, so it should be (curr != NULL && curr->key != k).
explanation :
when node isn't exist - i see in your code you assume node key is unique - so you still loop over the linked list till curr become null and the while condition check for the last time, and in this moment curr is null, so it accessing a NULL pointer which rasie your segmantation fault. but in case you check if curr is null firstly the compiler is treating the AND condition as a false before continuing to check the later statments and you go safe.
|
69,252,898 | 69,252,983 | Why can functions with different calling conventions still call each other? | int __cdecl funcB(int a, int b) {
return 0;
}
int __stdcall funcA(int a, int b) {
return funcA(a, b);
}
I wrote this two functions and they have different calling conventions: __stdcall and __cdecl.
And my question is why MSVC didn't throw a compile error?
Because in my view two functions with different calling conventions can't call each other
If caller think callee should clean the stack, and callee think caller should clean the stack, and that's my problem
Any answers will be helpful
|
Because in my view two functions with different calling conventions can't call each other
That's simply an incorrect view. A calling convention is just a set of rules for how arguments are handled across the call. The compiler generates instructions at each call site and within the body of the function that follow whichever convention the function is defined with.
If caller think callee should clean the stack, and callee think caller should clean the stack, and that's my problem
The problem you are thinking of is when the calling convention is omitted, and different translation units are compiled with different default conventions. The declarations in one TU are used in a manner incompatible with the definition in another TU.
|
69,253,347 | 69,253,885 | Passing the partially constructed object in pimpl | I have a class setup that I have converted to use pimpl, something like this:
(outline only, I'm aware this doesn't compile)
struct GAME
{
unique_ptr<GAME_IMPL> _impl;
explicit GAME() : _impl( new GAME_IMPL( *this ) );
IMAGES getImages() { return _impl._images; }
};
struct GAME_IMPL
{
IMAGES _images;
PLAYER _player;
explicit GAME_IMPL( GAME& game ) : _player( game ) { }
};
struct PLAYER
{
SPRITE _sprite;
explicit PLAYER( GAME& game ) { _sprite.load( game.getImages() ); }
};
Before I converted to a pimpl pattern, this was fine.
_sprite.load( game.getImages() ) could access GAME::_images because GAME::_images instantiates before GAME::_player.
However, after converting to pimpl, you can see that _sprite.load( game.getImages() ) will fail - PLAYER cannot access GAME::_images, because GAME::getImages uses GAME::_impl, which is not assigned until after all of GAME_IMPL has been constructed.
Obviously my example is contrived. But is there some way to allow the _impl pointer to be set before or while the GAME_IMPL object is still being constructed?
I considered the following:
Passing PLAYER only the necessary elements. This is messy since it involves modifying the API of PLAYER::PLAYER every time I adjust PLAYER's fields. Also in practice PLAYER's constructor may end up taking 30 odd parameters.
Using a two-stage initialisation, e.g. PLAYER::PLAYER(), PLAYER::Load() - this is even more messy since it means converting references to pointers throughout.
Passing PLAYER GAME_IMPL instead - this loses any benefits of using pimpl in the first place.
| I think you missed some details, here is a setup that compiles.
#include <memory>
struct GAME_IMPL;
struct IMAGES {};
// A 'trick' I often use
// for pimpl you can define an abstract base
// helps you check if public and impl class
// implement the same functions
//
// it also ensures you only have a pointer to an interface
// of your implementation in your public header file
struct GAME_ITF
{
virtual ~GAME_ITF() = default;
virtual IMAGES get_Images() = 0;
protected:
GAME_ITF() = default; // prevent accidental instantiation.
};
// in pimpl, game is just forwarding to game_impl
struct GAME : public GAME_ITF
{
std::unique_ptr<GAME_ITF> _impl;
GAME();
virtual ~GAME() = default;
IMAGES get_Images() override
{
return _impl->get_Images();
}
};
struct SPRITE
{
void load(IMAGES) { /*..*/ }
};
struct PLAYER
{
SPRITE _sprite;
explicit PLAYER(GAME_ITF& game)
{
_sprite.load(game.get_Images());
}
};
struct GAME_IMPL : public GAME_ITF
{
IMAGES _images;
PLAYER _player;
GAME_IMPL() :
_player{*this} // <=== player can refer to the implementation's interface (no impl. details needed either)
{
}
IMAGES get_Images() override
{
return IMAGES{};
}
};
GAME::GAME() :
_impl(std::make_unique<GAME_IMPL>())
{
}
int main()
{
GAME game;
IMAGES images = game.get_Images();
}
|
69,253,581 | 69,253,641 | Using pragma once in .cpp file | Recently reading some pieces of code I encountered several .cpp files that contained
#pragma once in the beginning of file. I know that it is usually used in .h files as guards.
What are the cases when #pragma once should/can/must be used in .cpp files?
| #pragma once shouldn't be used in source files, its one goal is to act as include guard. It won't do much harm .cpp files are normally going to be "scanned" once during compilation anyway. Note: Clang tidy will warn you if you do it.
Warning clang-diagnostic-pragma-once-outside-header #pragma once in main file
|
69,254,531 | 69,254,576 | Calling GetDesktopWindow() function in winuser.h instead of CWnd::GetDesktopWindow() in an MFC OnButtonClick function | For my own education, I am playing around with the code snippets of some on-line examples.
Early in these examples, there are these lines:
HWND hDesktopWnd = GetDesktopWindow();
HDC hDesktopDC = GetDC(hDesktopWnd);
For convenience reasons, I added a new button to my dialog-based demo MFC project, and the code I expect to test gets written into the ::OnBnClickedRuntest() function.
This was working well in the past, with various other code snippets I studied, modified, and tested this way. For these lines, however, I get a E0144 compile-time error:
a value of type "CWnd *" cannot be used to initialize an entity of type "HWND"
I figured that I run into some sort of name-matching/visibility issue. As I am hoping to call GetDesktopWindow() and GetDC() defined in winuser.h, but apparently the CWnd class also has methods with these exact same names and different return types.
https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdesktopwindow
https://learn.microsoft.com/en-us/cpp/mfc/reference/cwnd-class?view=msvc-160#getdesktopwindow
Obviously, my test code being placed in the OnButtonClicked function of an MFC dialog, GetDesktopWindow() and GetDC() prefers to call the CWnd::GetDesktopWindow() and CWnd::GetDC() methods, instead of the intended winuser.h functions.
How do I clarify to the compiler that instead of the CWnd methods, I want to use the winuser.h functions of the same names?
| Use the scope resolution operator on the functions:
::GetDesktopWindow();
::GetDC();
|
69,254,545 | 69,254,643 | How can I replace this code with one if statement? | For the sake of challenge, how can I replace this code with only one if statement?
unsigned int x, y;
cin>>x;
if((x>=0)&&(x<=1)) y = 1;
else if (x<=3) y = 2;
else if(x<=5) y = 3;
else y = 6;
| Without knowing why you want to use a single if, it's hard to tell. Of course, you can use ternary operators without any ifs:
unsigned int x, y;
cin>>x;
y = x<=1
? 1
: x<=3
? 2
: x<=5
? 3
: 6;
Or ugly boolean casting hacks for exactly one if (please don't actually do this outside of a puzzle or codegolf context):
unsigned int x, y;
cin>>x;
if (x<=5) {
y = 1 + (int)(x == 2 || x == 3) + (int)(x == 4 || x == 5);
} else {
y = 6;
}
Or, if you insist on exactly one if:
unsigned int x, y;
cin>>x;
if (x <= 5) {
y = x/2 + 1;
} else {
y = 6;
}
@Pietrek's answer shows you the better variant with a ternary operator (slightly modified here):
unsigned int x, y;
cin>>x;
auto const cutoff = 6;
y = x < cutoff ? x/2 + 1 : cutoff;
Note that in any case x >= 0 is always true when working with unsigned data types, so I omitted it.
If this is not purely a puzzle challenge but actual production code, please use the last example and make the number 6 a const or constexpr with a meaningful name.
|
69,254,721 | 69,254,848 | template member function resolution fails when declaring const | the code below shows some interesting behavior:
#include <iostream>
using namespace std;
template<class T>
class B{
public:
void foo(B<T> &x)const;
template<class F> void foo(F f);
};
template<typename T> void B<T>::foo(B<T> &x)const{cout<<"foo_B"<<endl;}
template<typename T> template<typename F> void B<T>::foo(F f){cout<<"foo_F"<<endl;}
int main(){
B<int> a;
B<int> b;
b.foo(a);
b.foo([](){;});
return(0);
}
my expected output is
foo_B
foo_F
but the actual output is
foo_F
foo_F
it depends on whether void foo(B<T> &x) is declared const. If const is omitted the output is as expected.
Further, if const is added to void foo(F f) the output is as expected as well.
However, void foo(B<T> &x) will not change the this, whereas void foo(F f) will change this. So the current layout is the one required.
Any idea how to resolve this without dropping const is much appreciated.
| The issue here is that since void foo(B<T> &x)const; is const qualified, It would have to const qualify the object you are calling the function on. This isn't as exactly as a match as template<class F> void foo(F f); provides as it doesn't need to do that const qualification. That is why it is used for both calls.
You can fix this by also const qualifying the template version like:
#include <iostream>
using namespace std;
template<class T>
class B{
public:
void foo(B<T> &x)const;
template<class F> void foo(F f)const;
};
template<typename T> void B<T>::foo(B<T> &x)const{cout<<"foo_B"<<endl;}
template<typename T> template<typename F> void B<T>::foo(F f)const{cout<<"foo_F"<<endl;}
int main(){
B<int> a;
B<int> b;
b.foo(a);
b.foo([](){;});
return(0);
}
Which will print
foo_B
foo_F
Another option would be to use SFINAE to constrain the template version from excepting B<T>'s. That would look like
#include <iostream>
using namespace std;
template<class T>
class B{
public:
void foo(B<T> &x)const;
template<class F, std::enable_if_t<!std::is_same_v<B<T>, F>, bool> = true>
void foo(F f);
};
template<typename T> void B<T>::foo(B<T> &x)const{cout<<"foo_B"<<endl;}
template<typename T> template<class F, std::enable_if_t<!std::is_same_v<B<T>, F>, bool>>
void B<T>::foo(F f){cout<<"foo_F"<<endl;}
int main(){
B<int> a;
B<int> b;
b.foo(a);
b.foo([](){;});
return(0);
}
and has the same output as the first example.
|
69,254,792 | 69,256,013 | Qt: QAudioInput vs QAudioRecorder | I am using Qt Multimedia 5 to analyze audio (FFT, LUFS, and dBFS, etc.) from audio input device.
To get audio data, there are two main options, QAudioRecorder and QAudioInput.
They can all read audio data with PCM (QAudioInput use QBuffer and QAudioRecorder use QAudioBuffer) and set format (e.g., sample rate), what should I use? I want to know the difference between QAudioRecorder and QAudioInput.
| QAudioBuffer is very convenient, and you'd use the QAudioProbe class to get notified whenever a new buffer is available - in Qt 5. QAudioProbe is not supported on Mac OS unfortunately.
QAudioProbe doesn't exist in Qt 6, and wasn't fully supported in Qt 5 either.
The only way to access "live" raw audio data in both Qt 5 and Qt 6 with minimal latency is by making your own QIODevice and being fed data from QAudioSource in push mode - see the Audio Source example, specifically the AudioInfo class.
The process is as follows:
Create an instance of your io device.
Pass it to QAudioSource::start(QIODevice*). The audio source will be writing raw data to the device you provided.
In the device's implementation, you can either work on the data directly, or synthesize a QAudioBuffer instance and send it out in a signal.
Something like the following would work:
class AudioProbeDevice : public QIODevice
{
Q_OBJECT
QAudioFormat m_format;
public:
AudioProbeDevice (QObject* parent = {}) : QIODevice(parent) {}
void start(QAudioInput *source)
{
Q_ASSERT(source);
m_format = source->format();
open(QIODevice::WriteOnly);
}
qint64 readData(char *, qint64) override { return 0; }
qint64 writeData(const char *data, qint64 count) override
{
QAudioBuffer buffer({data, static_cast<int>(count)}, m_format);
emit audioAvailable(buffer);
return count;
}
Q_SIGNAL void audioAvailable(const QAudioBuffer &buffer);
};
|
69,254,971 | 69,255,183 | How to use do while function but also not stop other codes | I am trying to fix this problem where if you use do and while code, it will stop other commands, but if it is done, then it will continue those commands.
for (int i = 0; i < 1000; i++) {
std::cout << "hey";
Sleep(1000);
}
for (int i = 0; i < 1000; i++) {
std::cout << "hey number 2";
Sleep(1000);
}
it is supposed to output together
hey
hey number 2
but instead it's just
hey
and then once it's done it's just
hey number 2
| I think you'll need threads.
Take this example. It should do the trick
#include <iostream>
#include <thread>
#include <synchapi.h>
using namespace std;
void fun1() {
for(int i = 0 ; i < 1000 ; i++) {
std::cout << "Hey";
Sleep(1000);
}
}
void fun2() {
for(int i = 0 ; i < 1000 ; i++) {
std::cout << "Hey you too";
Sleep(630);
}
}
int main()
{
std::thread first(fun1);
std::thread second(fun2);
first.join();
second.join();
std::cout << "done";
return 0;
}
|
69,255,022 | 69,257,708 | Mesh generation algorithm gives visual artifacts | Right now I am trying to implement terrain generation. I am using msvc visual studio 2019. And when I got to decreasing level of details in my function, generation started to be very glitchy. Everything is fine when I am not using any of level of details decreasing values. But everything changes after 1 and more - generation starts to be glitchy and generates atifacts. Here is some examples.
This one is correct as it should be. In my function this stands for parameter 0 in LevelOfDetails.
And Incorect examples. LevelOfDetails=1:
LevelOfDetails=3-6:
This is a function for generating meshes:
static void
GenerateTerrainMesh(world* World, noise_map* NoiseMap, float HeightMultiplier, int LevelOfDetail)
{
int Width = NoiseMap->Width;
int Height = NoiseMap->Height;
//float TopLeftX = (Width - 1) / (-2.0f);
//float TopLeftZ = (Height - 1) / ( 2.0f);
if(LevelOfDetail < 0) LevelOfDetail = 0;
if(LevelOfDetail > 6) LevelOfDetail = 6;
int SimplificationInc = (LevelOfDetail == 0) ? 1 : (LevelOfDetail * 2);
int VerticesPerLineX = (Width - 1) / SimplificationInc + 1;
int VerticesPerLineY = (Height - 1) / SimplificationInc + 1;
InitializeMeshTerrain(World, VerticesPerLineX, VerticesPerLineX);
int VertIndex = 0;
int TrigIndex = 0;
for(int Y = 0; Y < Height; Y += SimplificationInc)
{
for(int X = 0; X < Width; X += SimplificationInc)
{
World->Terrain.Vertices[VertIndex] = V3((float)X, HeightMultiplier * HeightFlatten(World->NoiseMap.Values[Y*World->NoiseMap.Width + X]).y * HeightMultiplier, (float)Y);
World->Terrain.UVs[VertIndex] = V2(X/(float)Width, Y/(float)Height);
if((X < (Width - 1)) && (Y < (Height - 1)))
{
AddTriangle(World, &TrigIndex, VertIndex, VertIndex + VerticesPerLineX + 1, VertIndex + VerticesPerLineX);
AddTriangle(World, &TrigIndex, VertIndex + VerticesPerLineX + 1, VertIndex, VertIndex + 1);
}
VertIndex += 1;
}
}
}
And helper functions, but there should not be any errors:
static void
InitializeMeshTerrain(world* World, int Width, int Height)
{
World->Terrain.VerticesCount = Width * Height;
World->Terrain.FacesCount = (Width - 1)*(Height - 1)*2;
World->Terrain.UVCount = Width * Height;
World->Terrain.Faces = (face*)malloc(sizeof(face)*World->Terrain.FacesCount);
World->Terrain.Vertices = (v3*)malloc(sizeof(v3)*World->Terrain.VerticesCount);
World->Terrain.UVs = (v2*)malloc(sizeof(v2)*World->Terrain.UVCount);
}
static void
AddTriangle(world* World, int* Index, int a, int b, int c)
{
World->Terrain.Faces[*Index].a = a;
World->Terrain.Faces[*Index].b = b;
World->Terrain.Faces[*Index].c = c;
*Index += 1;
}
What problem could be there? Thank you.
UPD: I added some additional data to work with such as Mesh Data and Vertices Data for each LevelOfDetail:
Correct:
LevelOfDetail=0
Incorect 1:
Incorect LevelOfDetail=1
Incorect 4:
Incorect LevelOfDetail=4
Incorect 6:
Incorect LevelOfDetail=6
| Like PaulMcKenzie mentioned, seams that I just used Even Numbers instead of Odd numbers and that was entirely of the problem. And even more, sometimes It couldn't work correctly, because I used too small numbers for generating mesh grid like 90 or 100. So, for correct working of this mesh algorithm Width should be divisible on 1, 2, 4, 6, 8, 10 and 12, and then It should work pretty fine
|
69,255,065 | 69,258,963 | Creating a target for a non-CMake module | I'm pretty new to CMake and am trying to learn about modern CMake.
I'm creating a project using the poppler-cpp libraries on ubuntu.
The libraries are installed using sudo apt install libpoppler-cpp-dev so they should all be available on the system paths.
My goal is to make this build work on multiple platforms eventually. But baby steps...
Previously I was setting up to import the library as follows using pkg-config
find_package(PkgConfig REQUIRED)
pkg_check_modules(POPPLER_CPP REQUIRED poppler-cpp)
target_link_libraries(${PROJECT_NAME}
# prefer to statically link poppler
# the other option would be POPPLER_LIBRARIES
PRIVATE ${POPPLER_CPP_STATIC_LIBRARIES}
)
target_include_directories(${PROJECT_NAME}
PUBLIC ${PROJECT_SOURCE_DIR}/include
# Include output from pkg_config
PUBLIC ${POPPLER_CPP_INCLUDE_DIRS}
# Need to add this to use
# generated export headers
${PROJECT_BINARY_DIR}
)
target_compile_options(${PROJECT_NAME}
PUBLIC ${POPPLER_CPP_CFLAGS_OTHER})
After reading some more about modern CMake, I decided to make this a target instead.
So I created a FindPopplerCpp.cmake and added the following
find_package(PkgConfig REQUIRED)
pkg_check_modules(PC_POPPLER_CPP REQUIRED poppler-cpp)
set(PopplerCpp_VERSION ${PC_POPPLER_CPP_VERSION})
set(PopplerCpp_INCLUDE_DIRS ${PC_POPPLER_CPP_INCLUDE_DIRS})
set(PopplerCpp_CFLAGS_OTHER ${PC_POPPLER_CPP_CFLAGS_OTHER})
if(PC_POPPLER_CPP_FOUND AND NOT TARGET poppler::Cpp)
add_library(poppler::Cpp INTERFACE IMPORTED)
set_target_properties(poppler::Cpp PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
INTERFACE_INCLUDE_DIRECTORIES "${PC_POPPLER_CPP_INCLUDE_DIRS}"
INTERFACE_LINK_LIBRARIES "${PC_POPPLER_CPP_STATIC_LIBRARIES}"
INTERFACE_COMPILE_OPTIONS "${PC_POPPLER_CPP_CFLAGS}"
VERSION "${PC_POPPLER_CPP_VERSION}"
)
ELSE (PC_POPPLER_CPP_FOUND)
MESSAGE(FATAL_ERROR "Could not find library")
endif()
mark_as_advanced(PopplerCpp_FOUND PopplerCpp_INCLUDE_DIRS PopplerCpp_VERSION)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(PopplerCpp
REQUIRED_VARS PopplerCpp_INCLUDE_DIRS
VERSION_VAR PopplerCpp_VERSION
)
And then I am importing the target
target_link_libraries(${PROJECT_NAME}
PRIVATE poppler::Cpp
)
My understanding is that this will take care of all the linker and include paths.
I am able to build the target fine and it seems to work.
The use of the static libs is intentional. I am statically linking the poppler-cpp libraries to my shared libraries.
I just wanted to be sure that I'm setting this up properly, especially considering I would like to build this project on the mac and on windows at some point. I know pkg-config won't work here. But I'll cross that bridge when I get there.
Thanks for your help
| You should just use the IMPORTED_TARGET option of pkg_check_modules...
find_package(PkgConfig REQUIRED)
pkg_check_modules(poppler-cpp REQUIRED IMPORTED_TARGET poppler-cpp)
target_link_libraries(my_target PRIVATE PkgConfig::poppler-cpp)
|
69,256,391 | 69,256,539 | my code is too cumbersome, how can I fix it? | My code is similar to CTRL + C + CTRL + V, outwardly I don't like it.
In the code, only one variable changes, and everything else is the same. What are some ways you can shorten this code?
struct offsets {
std::vector<DWORD> energy = { 0x168, 0x1B8, 0x30, 0x8 };
std::vector<DWORD> minerals = { 0x168, 0x1B8, 0x30, 0x10 };
std::vector<DWORD> foods = { 0x168, 0x1B8, 0x30, 0x18 };
std::vector<DWORD> influence = { 0x168, 0x1B8, 0x30, 0x38 };
std::vector<DWORD> unity = { 0x168, 0x1B8, 0x30, 0x40 };
std::vector<DWORD> alloys = { 0x168, 0x1B8, 0x30, 0x4C };
std::vector<DWORD> consumer_goods = { 0x168, 0x1B8, 0x30, 0x54 };
};
struct cheats{
bool energy = false;
bool minerals = false;
bool foods = false;
bool influence = false;
bool unity = false;
bool alloys = false;
bool consumer_goods = false;
};
cheats hackMenu;
uintptr_t* energy = readOffset(finallyAddress, offsetsList.energy);
uintptr_t* minerals = readOffset(finallyAddress, offsetsList.minerals);
uintptr_t* foods = readOffset(finallyAddress, offsetsList.foods);
uintptr_t* influence = readOffset(finallyAddress, offsetsList.influence);
uintptr_t* unity = readOffset(finallyAddress, offsetsList.unity);
uintptr_t* alloys = readOffset(finallyAddress, offsetsList.alloys);
uintptr_t* consumer_goods = readOffset(finallyAddress, offsetsList.consumer_goods);
if (hackMenu.minerals)
{
*minerals += add_resource;
hackMenu.minerals = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130)); // analog Sleep()
}
if (hackMenu.influence)
{
*influence += add_resource;
hackMenu.influence = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130));
}
if (hackMenu.alloys)
{
*alloys += add_resource;
hackMenu.alloys = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130));
}
if (hackMenu.unity)
{
*unity += add_resource;
hackMenu.unity = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130));
}
if (hackMenu.foods)
{
*foods += add_resource;
hackMenu.foods = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130));
}
if (hackMenu.consumer_goods)
{
*consumer_goods += add_resource;
hackMenu.consumer_goods = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130));
}
how to reduce the number of if and add it all to the function?
how to reduce the number of if and add it all to the function?
| With function, you can do
void foo(bool& m, uintptr_t* ptr, uintptr_t add_resource)
{
if (m)
{
*ptr += add_resource;
m = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130));
}
}
and then
foo(hackMenu.minerals, minerals, add_resource);
foo(hackMenu.influence, influence, add_resource);
foo(hackMenu.alloys, alloys, add_resource);
foo(hackMenu.unity, unity, add_resource);
foo(hackMenu.foods, foods, add_resource);
foo(hackMenu.consumer_goods, consumer_goods, add_resource);
You can even create a collection for the different variables to do a loop.
|
69,256,902 | 69,257,439 | do..while loop not terminating | I am trying to find if the given number is a perfect square, and if so find the next perfect square for this codewars problem.
#include <cmath>
using namespace std;
long int findNextSquare(long int sq) {
// Return the next square if sq if a perfect square, -1 otherwise
long int k = sq;
do{
k++;
//cout << round(sqrt(k)) << endl;
//cout << k << endl;
}while(pow(round(sqrt(k)), 2) != k);
if(pow(sqrt(sq), 2) == sq)
return k;
else
return -1;
}
I am not sure why my loop is not terminating once k = 144. Printing out k and round(sqrt(k)) shows that after k = 144, it jumps to 626, for which I also do not know the reason.
| You should never try to check if a float is equal to an integer (or float) as a looping condition, as there are likely rounding problems (leading to infinite loops). That means you need to reformulate your problem using only integers.
Start with the root of sq in an integer, which can be rounded off.
compare the square of root, rsq, with sq
If it's smaller, increase root and compare again
If it is the same, sq is a perfect square (of root) and we can return the next square
If its bigger, sq is not a perfect square: return -1.
That could lead to something like:
static long next_square(long sq) {
long root = sqrt(sq);
long rootSquared = root * root;
while (rootSquared < sq) {
root++;
rootSquared = root * root;
}
if (rootSquared == sq) {
root++;
return root * root;
}
return -1;
}
|
69,256,908 | 69,257,043 | Cannot use std::future to store polymorphic object | struct Base {
virtual void squawk () {
std::cout << " I am base" << std::endl;
}
};
struct Derived : public Base {
void squawk () override {
std::cout << "I am derived" << std::endl;
}
};
int main () {
std::future<std::shared_ptr<Base>> f = std::async([](){return std::make_shared<Derived>();});
}
This gives the following error :
error: conversion from 'future<shared_ptr<Derived>>' to non-scalar type 'future<shared_ptr<Base>>' requested
However, this compiles :
std::promise<std::shared_ptr<Base>> p;
std::future<std::shared_ptr<Base>> f = p.get_future();
p.set_value(std::make_shared<Derived>());
Could you please explain why? And what is the recommended pattern to create futures to hold polymorphics objects?
| The return type of your lambda is a shared_ptr<Derived>. Therefore, the future that async will create contains a shared_ptr<Derived>. If you want it to have a different type, you need to make the lambda's return type the correct type, by static_pointer_casting the return value to shared_ptr<Base>.
auto f = std::async( [](){return std::static_pointer_cast<std::shared_ptr<Base>>std::make_shared<Derived>();});
|
69,256,940 | 69,258,123 | Why does this lambda [=] capture create several copies? | In the following code:
#include <iostream>
#include <thread>
using namespace std;
class tester {
public:
tester() {
cout << "constructor\t" << this << "\n";
}
tester(const tester& other) {
cout << "copy cons.\t" << this << "\n";
}
~tester() {
cout << "destructor\t" << this << "\n";
}
void print() const {
cout << "print\t\t" << this << "\n";
}
};
int main() {
tester t;
cout << " before lambda\n";
thread t2([=] {
cout << " thread start\n";
t.print();
cout << " thread end\n";
});
t2.join();
cout << " after join" << endl;
return 0;
}
When compiled with cl.exe (on Windows) I get the following:
constructor 012FFA93
before lambda
copy cons. 012FFA92
copy cons. 014F6318
destructor 012FFA92
thread start
print 014F6318
thread end
destructor 014F6318
after join
destructor 012FFA93
And with g++ (on WSL) I get:
constructor 0x7ffff5b2155e
before lambda
copy cons. 0x7ffff5b2155f
copy cons. 0x7ffff5b21517
copy cons. 0x7fffedc630c8
destructor 0x7ffff5b21517
destructor 0x7ffff5b2155f
thread start
print 0x7fffedc630c8
thread end
destructor 0x7fffedc630c8
after join
destructor 0x7ffff5b2155e
I would expect that the [=] capture would create exactly 1 copy of tester. Why are there several copies that are immediately destroyed?
Why the divergence between MSVC and GCC? Is this undefined behavior or something?
| The standard requires that the callable passed to the constructor for std::thread is effectively copy-constructible ([thread.thread.constr])
Mandates: The following are all true:
is_constructible_v<decay_t<F>, F>
[...]
is_constructible_v<decay_t<F>, F> is the same as is_copy_constructible (or rather, it's the other way around).
This is to allow implementations to freely pass around the callable until it reaches the point where it gets invoked. (In fact, the standard itself suggests the callable is copied at least once.)
Since a lambda is compiled into a small class with the function call operator overloaded (a functor), each time your lambda gets copied, it will create a copy of the captured tester instance.
If you do not wish for copying to happen, you can take a reference to your instance in the capture list instead:
thread t2([&ref = t] {
cout << " thread start\n";
ref.print();
cout << " thread end\n";
});
Live Demo
Output:
constructor 0x7ffdfdf9d1e8
before lambda
thread start
print 0x7ffdfdf9d1e8
thread end
after join
destructor 0x7ffdfdf9d1e8
|
69,257,162 | 69,257,906 | Trouble calling function via pthread | I have a function that counts the number of occurences of a string in a char array. Calling this function normally with findword(copy, "polar") works perfectly fine and prints an int that's the number of times the string "polar" occurs in the char array "copy". Calling the function via a pthread however gives me compilation issues and I don't know why. This is my first time implementing multithreading.
Here is the function I want to call:
void findword(char *str, string word)
{
char *p;
vector<string> a;
p = strtok(str, " ");
while (p != NULL)
{
a.push_back(p);
p = strtok(NULL, " ");
}
int c = 0;
for (int i = 0; i <= a.size(); i++)
if (word == a[i])
c++;
printf("%d", c);
}
And here is the thread I'm trying to create that is supposed to call the function:
struct findwordargs {
char *str;
string word;
};
struct findwordargs firstwordArguments;
firstwordArguments.str = copy;
firstwordArguments.word = "polar";
pthread_t thread_id = 1;
pthread_create(&thread_id, NULL, findword, (void *)(&firstwordArguments));
pthread_join(thread_id, NULL);
whenever I compile using g++ and the -pthread flag I get this compile error:
error: invalid conversion from ‘int (*)(char*, std::string)’ {aka ‘int (*)(char*, std::__cxx11::basic_string<char>)’} to ‘void* (*)(void*)’ [-fpermissive]
101 | pthread_create(&thread_id, NULL, findword, (void *)(&firstwordArguments));
All the necessary header files are included, thank you for the help.
| Your findword() function does not match the signature that pthread_create() requires:
void *(*start_routine)(void *)
Try this instead:
struct findwordargs
{
char *str;
std::string word;
};
void* findword(void *param)
{
findwordargs *args = static_cast<findwordargs*>(param);
std::vector<std::string> a;
char *p = strtok(args->str, " ");
while (p) {
a.push_back(p);
p = strtok(NULL, " ");
}
int c = 0;
for (size_t i = 0; i < a.size(); ++i) {
if (args->word == a[i])
c++;
}
printf("%d", c);
/* alternatively, using more C++-ish routines:
std::istringstream iss(args->str);
std::string word;
while (iss >> word) a.push_back(word);
std::cout << std::count(a.begin(), a.end(), args->word);
*/
return NULL;
}
...
findwordargs firstwordArguments;
firstwordArguments.str = copy;
firstwordArguments.word = "polar";
pthread_t thread_id = 1;
pthread_create(&thread_id, NULL, findword, &firstwordArguments);
pthread_join(thread_id, NULL);
That being said, there is no point in creating a thread just to immediately join it. That blocks the calling thread until the spawned thread exits, which is the same effect as simply calling the function directly, but without the overhead of context switching between threads:
void findword(const std::string &str, const std::string &word)
{
std::vector<std::string> a;
std::istringstream iss(str);
std::string word;
while (iss >> word) a.push_back(word);
std::cout << std::count(a.begin(), a.end(), word);
}
...
findword(copy, "polar");
|
69,258,220 | 69,259,757 | Difference between UuidCreate and CoCreateGuid | Is there a difference between the UUIDs created by calling UuidCreate and CoCreateGuid from the Win32 API?
The documentation says CoCreateGuid just calls UuidCreate, but the remarks in the documentation are quite different.
Only CoCreateGuid specifically mentions the use case:
[...] absolutely unique number that you will use as a persistent identifier in a distributed environment.
While Uuidcreate is instead focused on explaining the non-traceability:
[...] generates a UUID that cannot be traced to the ethernet address of the computer on which it was generated. It also cannot be associated with other UUIDs created on the same computer.
I assume the difference might just be historic, the doc mentions UuidCreate was changed from MAC-based version 1 UUIDs to random non-traceable version 4 some time in the past for security reasons. UuidCreateSequential was introduced if MAC based UUIDs are needed.
If so, the return values of UuidCreate (RPC_S_OK, RPC_S_UUID_LOCAL_ONLY, RPC_S_UUID_NO_ADDRESS) are nowadays just included for legacy compatibility, and basically obsolete?
Does anyone know more about this? As far as I can tell, there is no difference.
| CoCreateGuid calls UuidCreate.
UuidCreate used to be the only function, and it was a type 1 (mac + datetime) uuid.
Later, after a kid was arrested after software he wrote was traced back to his laptop because of his MAC address, Windows Vista changed UuidCreate to be a type 4 (random) uuid.
And Microsoft added UuidCreateSequential as the legacy type 1 uuid.
For security reasons, UuidCreate was modified so that it no longer uses a machine's MAC address to generate UUIDs. UuidCreateSequential was introduced to allow creation of UUIDs using the MAC address of a machine's Ethernet card.
|
69,258,942 | 69,259,001 | Why exception not the same when catching exception pointer? | I'm new to C++ exception handling. I tried to throw an exception pointer and caught it but it seems the later caught exception isn't the same as which I thrown.
Here's my code:
try {
bad_exception e2 = bad_exception();
cout << e2.what() << endl;
cout << &e2 << endl;
throw &e2;
}
catch (bad_exception* ex) {
cout << ex << endl;
cout << ex->what() << endl;
cout << (*ex).what() << endl;
}
output:
bad exception
00CFFCF8
00CFFCF8
Unknown exception
Unknown exception
I'd expected the later will show the same name "bad exception". Can you explain this?
updated:
It seems the exception has the "auto delete" feature? I tried throwing a pointer to normal object (not inherited from exception). But I can still access the object and its properties in the catch block.
try {
char str[5] = "eed8";
A a = A();
a.name1 = str;
cout << a.show() << endl;
cout << &a << endl;
throw &a;
}
catch (A* exp) {
cout << exp << endl;
cout << exp->show() << endl;
cout << exp->name1 << endl;
}
output:
eed8
007BF9DC
007BF9DC
eed8
eed8
| You should throw exceptions by value (usually).
The problem here is you are throwing a pointer to an object. Unfortunately, by the time the pointer is caught, the object that it is pointing to has been destroyed, and thus you have an invalid pointer.
try {
bad_exception e2 = bad_exception();
cout << e2.what() << endl;
cout << &e2 << endl;
throw &e2;
} // At this point the object "e2" goes out of scope
// Thus its destructor is called.
// So the pointer you threw now points at an invlalid object
// Thus accessign the object via this pointer is UB.
catch (bad_exception* ex) {
cout << ex << endl;
cout << ex->what() << endl;
cout << (*ex).what() << endl;
}
Rewrite it like this:
try {
bad_exception e2 = bad_exception();
cout << e2.what() << endl;
cout << &e2 << endl;
throw e2; // Throw a copy.
// Throw an object that gets copied to a secure location
// so that when you catch it is still valid.
}
catch (bad_exception const& ex) { // catch and get a reference to the copy.
cout << &ex << endl;
cout << ex.what() << endl;
}
If you absolutely must throw a pointer, then use new to make sure the pointer has a dynamic life span (but remember, you will need to clean it up).
Update:
It seems the exception has the "auto delete" feature?
Not a thing.
I tried throwing a pointer to normal object (not inherited from exception).
There is nothing special about the exception object (or any of its derived classes). It is simply a normal object. Like all objects (that are a class), the destructor of the object is run when the object reaches the end of its lifetime. If A does not have a destructor then the memory used by the object may not change (but it is not usable by other objects that are not your object).
But I can still access the object and its properties in the catch block.
That is the bad side of "Undefined Behavior". I may look like it is working. It's not working, it just looks like it is. And it is just as likely to not work on some other situation.
|
69,258,968 | 69,259,798 | HDF5 Cpp - getting names of all groups in h5 file | I want to get all group names from h5 file. I was able to do that using a global variable that collects the names. My question is how to do it without the global variable? I dont want to have any global variables but i have a vector that will need to contain all the group names.
//this is the global variable i am trying to avoid.
std::vector<std::string> myVec;
herr_t op_func(hid_t loc_id, const char* name, const H5O_info_t* info, void opdata)
{
if(info->type == H5O_TYPE_GROUP)
{
myVec.push_back(std::string(name));
}
}
//here is my function and i pass a vector that i want the names to be in via reference.
void getGroupNames(hid_t fileId, std::vector<std::string>& someVec)
{
herr_t status;
status = H5Ovisit(fileId, H5_INDEX_NAME, H5_ITER_NATIVE, op_func, NULL);
someVec = myVec;
}
| One way to do that would be to pass someVec to H5Ovisit in the last parameter, i.e.:
status = H5Ovisit(fileId, H5_INDEX_NAME, H5_ITER_NATIVE, op_func, static_cast<void*>(&someVec);
Then in op_func push directly to it:
auto vec = static_cast<std::vector<std::string>*>(opdata);
vec->push_back(std::string(name));
(Note that the last parameter to op_func should be void*)
|
69,258,971 | 69,265,607 | How to connect slot with mutable argument to signal with const argument | I need to connect binaryMessageReceived signal of QWebSocket to my slot which modifies the QByteData
The QByteData may be large so it might be really costly to copy it again in mutable variable each time. I want to reuse the existing QByteData
when I try to compile with following slot
void route(QByteArray& msg);
I get compilation error
/usr/include/qt/QtCore/qobject.h:255:9: error: static assertion failed: Signal and slot arguments are not compatible.
255 | Q_STATIC_ASSERT_X((QtPrivate::CheckCompatibleArguments<typename SignalType::Arguments, typename SlotType::Arguments>::value),
| ^~~~~~~~~~~~~~~~~
/usr/include/qt/QtCore/qobject.h:255:9: note: ‘(((int)QtPrivate::CheckCompatibleArguments<QtPrivate::List<const QByteArray&>, QtPrivate::List<QByteArray&> >::value) != 0)’ evaluates to false
but if I change the slot to
void route(const QByteArray& msg);
it compiles just fine
I'm connecting slot like this:-
connect(this, &QWebSocket::binaryMessageReceived, this, &WSManager::route);
| You probably don't want to do that.
The signal argument is not meant to be modified if passed as const &. You are not even sure of the lifetime of the binary data in the emitter object (QWebSocket).
The QByteData is emitted from here : https://code.woboq.org/qt5/qtwebsockets/src/websockets/qwebsocketdataprocessor.cpp.html#181
Nested in multiple classes hidden from the API, it's very dangerous to rely on this kind of attribute/data.
QByteArray uses the implicit-sharing Qt mecanism which avoid deep copy.
https://doc.qt.io/qt-5/implicit-sharing.html
That means you can pass the object around without concern about the performances. And if at some point you need to modify it, you might end up working on the only actual instance of the data thanks to the move operator.
|
69,259,025 | 69,261,160 | QColor not a registered metatype? | This is a follow-on from this question.
That article should explain why I am using a quint16 to extract the variant type.
I have derived class MyVariant from QVariant and implemented the QDataStream read operator.
This allows constructs like:
MyVariant vt;
str >> vt;
This is the streaming implementation:
QDataStream& operator>>(QDataStream& str, MyVariant& vt)
{
vt.clear();
quint16 type;
str >> type;
const QMetaType vtype(type);
if (vtype.isValid()) {
vt.create(type, nullptr);
if (!QMetaType::load(str, type, const_cast<void *>(vt.constData()))) {
Q_ASSERT_X(false, "MyVariant", qPrintable(QString("Cannot load type %u").arg(type)));
str.setStatus(QDataStream::ReadCorruptData);
}
}
else {
Q_ASSERT_X(false, "MyVariant", qPrintable(QString("Type %1 is not supported").arg(type)));
}
return str;
}
When the stream comes across a QColor (67), this code fails to create a valid QMetaType for it. QMetaType::isValid() returns false.
What could I possibly have forgotten to do?
Not sure if it matters, but I have added QT += gui to my .pro file.
Edit
I have added...
int type = qRegisterMetaType<QColor>("QColor");
... to my main function.
It returns 67, yet when I hit my streaming function the QMetaType creation still fails.
| Okay, I solved this one by pure luck.
In my main, I register the type using...
qRegisterMetaTypeStreamOperators<QColor>("QColor");
And now it works!
Let me know in the comments if I did the right thing or not.
|
69,259,061 | 69,259,149 | Reference returning blank value | I'm writing a linked list, and using my main function to test it. Here's my code:
#include <iostream>
using namespace std;
class LinkedList {
int value;
LinkedList* next;
public:
LinkedList(int valueIn, LinkedList* nextIn) {
value = valueIn;
next = nextIn;
}
LinkedList(int valueIn) {
value = valueIn;
}
int getValue() {
return value;
}
void addNode(LinkedList* node) {
next = node;
}
LinkedList& getNext() {
return *next;
}
};
int main() {
cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
cout << list1.getValue() << " --> " << list1.getNext().getValue() << std::endl;
return 0;
}
I expect the output to be 1 --> 2, but I get 1 -->. As far as I understand, getNext() should return a reference to another list (list2 in this case), but something seems to be going wrong. My debugging efforts show me that list2 does have the correct value 2 when it's initialized, but when it's referenced for the final output, it doesn't seem to have anything for value. I can't for the life of me figure out why this is. Could someone help me to understand?
| You are insertin list1(which is actually a node) to the end of list2, not the other way around, yet you call getNext() on list1. You should change the code in main to the below:
int main() {
std::cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
std::cout << list2.getValue() << " --> " << list2.getNext().getValue() << std::endl;
return 0;
}
Please note that there are a couple of other things which would be better to change:
Create a list class and a Node class woud make things clearer
Initializing the pointer to be NULL(or nullptr from C++11) in the LinkedList(int valueIn) constructor
Return the pointer to the node in getNext() rather than copy the node
|
69,259,072 | 69,259,246 | Searching std::map in O(n) for a partial key | I have a (C++ 14) map
using MyTuple = tuple<A, B, C>;
map<MyTuple, MyData>
where MyTuple has the obvious operator<() that compares first A, then B, then C.
I want to do an O(ln N) search for keys that match some constant (a, b). Obviously if any are present they will be consecutive. So basically I want
map<MyTuple, MyData> my_map = GetMyData();
tuple<A, B> my_key = make_tuple(a, b);
auto iter = my_map.lower_bound_if([my_key](const MyTuple& key) {
if (get<0>(my_key) == get<0>(key) &&
get<1>(my_key) == get<1>(key)) {
return true;
}
return false;
});
while( /* iter.first is still an (a,b) */) {
// Do something with iter.
// Increment iter.
}
But there's no function map::lower_bound_if and yet map::find and map::lower_bound take a full MyTuple. I could (hackishly) find a value of C that is lower than anything in my data, though this is fragile over time. I could write the function myself though it would likely be dependent on my current local implementation of std::map.
Have I missed an obvious solution?
Update
The solution, which I've accepted, was to use partial key mathing in the compare function (transparent operator functors), which are new since C++14 and took me longer than I care to admit to understand. This article was a good mental ice breaker and this SO question was good once I understood.
The basic insight is to consider a set of objects sorted on some key that is part of the object. For example, a set of employees with the sort key being employee.id. And we'd like to be able to search on employee or on the integer id. So we make a struct of bool operator()() that encompasses the various ways we might want to compare. And then overload resolution does the rest.
In my case, this meant that I could provide the strict total ordering I needed to make my code work but also provide a comparator that only imposes a partial ordering which I only use for lower_bound() lookups. Because the extra comparator doesn't provide a strict total ordering, it would not be suitable for, say, find() unless we meant "find one of".
As an aside, I realised after posing my question that it was a bit daft in a way. I wanted an O(ln n) lookup but wanted to use a different sort function. That can't be guaranteed to work: it depends on me providing a sort function that really does provide an ordering that is a sub-ordering of the strict total ordering. If I did otherwise, it would clearly fail. And so this is why there's no O(ln n) function find_if(), because that can only be linear.
Indeed, the technique of transparent operator functors is clever but does depend on the programmer providing no worse than a subordering.
| In c++14 you can use the overload to search on a partial key:
struct CompareFirstTwo {
using is_transparent = void;
bool operator()(const tuple<A, B, C>& lhs, const tuple<A, B, C>& rhs) const ...
bool operator()(const tuple<A, B>& lhs, const tuple<A, B, C>& rhs) const ...
bool operator()(const tuple<A, B, C>& lhs, const tuple<A, B>& rhs) const ...
};
Use the comparator above in a call to equal_range to ignore the third field in the tuple.
|
69,259,778 | 69,352,037 | Does QMovie support an alpha channel? | I swapped out QImageReader for QMovie to easily loop an animated GIF. However, the QImage returned by QMovie::currentImage() does not have an alpha channel. If I use QImageReader::read(), it does have an alpha channel. The documentation does not mention any difference between the two regarding alpha. Is there any way to preserve the alpha channel when using QMovie?
QMovie movie( "ExampleAnimation.gif" );
movie.jumpToFrame( 0 );
const auto movieFrame = movie.currentImage();
DEBUG_LOG() << movieFrame.hasAlphaChannel(); // false
QImageReader reader( "ExampleAnimation.gif" );
reader.jumpToImage( 0 );
const auto readerImage = reader.read();
DEBUG_LOG() << readerImage.hasAlphaChannel(); // true
| I figured out the issue and I would like to provide an answer in case others are in a similar situation.
The GIF file I was using had an alpha channel, but it didn't have any transparent pixels. Internally, QMovie calls QPixmap::fromImage(), which seems to remove the alpha channel if it is not used.
|
69,259,995 | 69,267,591 | How to write a portable constexpr std::copysign()? | In particular, it must work with NaNs as std::copysign does. Similarly, I need a constexpr std::signbit.
constexpr double copysign(double mag, double sgn)
{
// how?
}
constexpr bool signbit(double arg)
{
// how?
}
// produce the two types of NaNs
constexpr double nan_pos = copysign(std::numeric_limits<double>::quiet_NaN(), +1);
constexpr double nan_neg = copysign(std::numeric_limits<double>::quiet_NaN(), -1);
// must pass the checks
static_assert(signbit(nan_pos) == false);
static_assert(signbit(nan_neg) == true);
The story behind is that I need two types of NaNs at compile time, as well as ways to distinguish between them. The most straightforward way I can think of is to manipulate the sign bit of the NaNs. It does work at run time; now I just want to move some computations to compile time, and this is the last hurdle.
Notes: at the moment, I'm relying on GCC, as it has built-in versions of these functions and they are indeed constexpr, which is nice. But I want my codebase to compile on Clang and perhaps other compilers too.
| Use of __builtin... is not really portable, but works in compilers that mentioned as target. __builtin_copysign is contexpr, but __builtin_signbit is apparently not on clang, so doing signbit with __builtin_copysign:
#include <limits>
constexpr double copysign(double mag, double sgn)
{
return __builtin_copysign(mag, sgn);
}
constexpr bool signbit(double arg)
{
return __builtin_copysign(1, arg) < 0;
}
// produce the two types of NaNs
constexpr double nan_pos = copysign(std::numeric_limits<double>::quiet_NaN(), +1);
constexpr double nan_neg = copysign(std::numeric_limits<double>::quiet_NaN(), -1);
// must pass the checks
static_assert(signbit(nan_pos) == false);
static_assert(signbit(nan_neg) == true);
int main() {}
https://godbolt.org/z/8Wafaj4a4
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.