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 |
|---|---|---|---|---|
70,139,565 | 70,141,674 | c++: error: unrecognized command-line option ‘-target’ | Im compiling a program I made using make and I get this error
c++: error: unrecognized command-line option ‘-target’
make[3]: *** [libs/system/CMakeFiles/system.dir/build.make:76: libs/system/CMakeFiles/system.dir/src/system/syscalls.cpp.o] Error 1
make[2]: *** [CMakeFiles/Makefile2:504: libs/system/CMakeFiles/system.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:243: CMakeFiles/image-uefi.dir/rule] Error 2
make: *** [Makefile:137: image-uefi] Error 2
Im running Arch Linux with Clang-13, CMake and all of base-devel installed.
Any help would be appreciated, please dont be condescending I just installed Arch Linux and am getting this error, in Fedora compiling the exact same app provides no error.
The line which created the error is this, it should be the offending linux since the error in question(the top line) complains about -target being unrecognized.
cd /home/user/toy-kernel/build/libs/system && /usr/bin/c++ -I/home/user/toy-kernel/libs/system/src -target x86_64-none-elf -mcmodel=kernel -fno-exceptions -fno-use-cxa-atexit -fno-rtti -nostdlib -ffreestanding -fno-threadsafe-statics -mno-mmx -mno-sse -mno-sse2 -mno-sse3 -mno-sse4.1 -mno-sse4.2 -mno-sse4a -mno-3dnow -mno-3dnowa -std=gnu++20 -MD -MT libs/system/CMakeFiles/system.dir/src/system/syscalls.cpp.o -MF CMakeFiles/system.dir/src/system/syscalls.cpp.o.d -o CMakeFiles/system.dir/src/system/syscalls.cpp.o -c /home/user/toy-kernel/libs/system/src/system/syscalls.cpp
| In my case, c++ was the g++ compiler instead of the clang compiler, if you are having a similar issue try updating g++ or clang++(on older macs you may need to have to use brew to install those) or going in your /usr/bin directory(for mac and linux, I never used windows cant help you) and replacing the files(though only do that if you absolutely know what your doing!).
|
70,140,233 | 70,143,000 | C++ Vector not changing value after being altered in a method | I'm trying to create a class for a node in a directed graph (I don't know much about them so forgive if I've messed up any terms).
Whenever I add a pointer to n2 to n1's outNodes vector, I want a pointer to n1 to be added to n2's inNodes vector. I hope that made sense and here is my code.
#include <iostream>
#include <vector>
class Node {
private:
static int nextId;
int id;
std::vector<Node*> ptr_outNodes;
std::vector<Node*> ptr_inNodes;
public:
Node() {
id = nextId++;
}
int getId() {
return id;
}
void setInNodes(Node n) {
ptr_inNodes.push_back(&n);
}
void setOutNodes(Node n) {
ptr_outNodes.push_back(&n);
n.setInNodes(*this);
}
std::vector<Node*> getOutNodes() {
return ptr_outNodes;
}
std::vector<Node*> getInNodes() {
return ptr_inNodes;
}
};
int Node::nextId = 0;
int main() {
Node n1;
Node n2;
n1.setOutNodes(n2);
std::cout << n2.getInNodes().size();
return 0;
}
As you can see, I have it set to return the size of n2's inNodes. When I run the program I see that it's size is 0. If I print out the size within the setInNodes method, I get the result 1 which is odd to me. Also, if I change my main function to this:
int main() {
Node n1;
Node n2;
n1.setOutNodes(n2);
n2.setInNodes(n1);
std::cout << n2.getInNodes().size();
return 0;
}
I get the result 1. Adding that line shows that the function is working, so I believe something is going wrong when I call setInNodes() from setOutNodes(). I've been staring at this for the past half hour, so if someone could help me that would be great, thanks!
| You are providing the methods setInNodes and setOutNodes with copies of the original Node object. The pointer you're pushing into the vector is the address of that copy, not of the original object.
To push the address of the original Node object, you need to pass a Node-pointer to the function.
Code:
... // Your Node class code
void setInNodes(Node *n) {
ptr_inNodes.push_back(n);
}
void setOutNodes(Node *n) {
ptr_outNodes.push_back(n);
n.setInNodes(this);
}
...
// in the main function:
n1.setOutNodes(&n2);
n2.setInNodes(&n1);
|
70,140,320 | 70,140,356 | While loop repeats for every word in a string in C++ | I am trying to make a magic 8 ball that provides a random preset answer to any input except "bye". Each time the void function magic8ball() is called, it generates a random number from 0 - 19 and prints a corresponding response to the console.
int main()
{
string question;
cin >> question;
while (question != "bye") {
magic8ball();
cout << "~Ask another question.\n";
cin >> question;
}
return 0;
}
For some reason, if the input for question has more than one word / has whitespace between characters, the loop repeats for each word before asking for input again. I stuck a "cout << question << endl;" in there and it showed each word in the string (as well as a call of magic8ball and "ask another").
e.g
>hi frend
... Ask again later
hi
~Ask another question.
... Don't count on it
frend
~Ask another question.
How do I prevent the while loop from treating the string as a series of words? Why is cin not triggering along with magic8ball() and cout ?
| std::cin stops reading when it sees whitespace. Space also counts as a whitespace.
If you want your string to have space, use std::getline()
int main()
{
string question;
std::getline(std::cin, question);
while (question != "bye") {
magic8ball();
cout << "~Ask another question.\n";
std::getline(std::cin, question);
}
return 0;
}
|
70,140,551 | 70,140,565 | Both variables end up having same value when trying to swap them using references | I'm trying to swap two variables' contents. I did it just fine using pointers. But trying to implement it using references is not working.
#include <iostream>
//Implementing a reference based swap
void RefSwap(int& x, int& y)
{
int extra;
extra = x; //automatically de-referenced
x = y;
y = extra;
}
int main()
{
int a = 3, b = 10;
int& ref_a = a, ref_b = b; //refs don't actually exist in memory, they act like aliases
RefSwap(ref_a, ref_b);
std::cout << a << " " << b << std::endl;
}
My output:
10 10
Expected output:
10 3
Using VS Community 2022
| int& ref_a = a, ref_b = b;
This is
int& ref_a = a;
int ref_b = b;
Not:
int& ref_a = a;
int& ref_b = b;
Change:
int& ref_a = a, ref_b = b;
To:
int& ref_a = a;
int& ref_b = b;
will produce the correct result.
|
70,140,674 | 70,140,802 | Why is a pointer being returned in function? | I am trying to take a file of a 2d array of grades (for example, file "grades2.txt") and store it into a 2d array. I am not sure how pointers work, as I haven't got that far yet, so I am not sure why a pointer is being returned.
So far, I have a main function that just plugs in values to the parameters, and I have my read function which opens the file and tries to read the file and put the file's values into the grades array.
It is okay if the output is wrong, I just want an array to show.
So far, I have tried to check if the array had the same dimension as the file, but that did not help.
grades2.txt
10.0 20.0 30.0 40.0 50.0
100.0 90.0 80.0 70.0 60.0
95.0 85.0 75.0 65.0 55.0
25.2 27.2 29.3 31.2 33.2
88.9 78.8 68.7 58.6 48.5
10.1 20.1 30.1 40.1 50.1
100.1 90.1 80.1 70.1 60.1
95.1 85.1 75.1 65.1 55.1
25.2 27.3 29.4 31.3 33.3
88.0 78.9 68.8 58.7 48.6
10.9 20.8 30.7 40.6 50.5
100.9 90.8 80.7 70.6 60.5
95.9 85.8 75.7 65.6 55.5
25.8 27.7 29.6 31.5 33.4
88.7 78.6 68.5 58.4 48.3
20.0 30.0 40.0 50.0 60.0
90.0 80.0 70.0 60.0 50.0
85.0 75.0 65.0 55.0 45.0
45.2 47.2 49.3 51.2 53.2
48.9 58.8 68.7 78.6 88.5
0.01 0.02 0.03 0.04 0.05
code
#include <iostream>
#include <fstream>
using namespace std;
void read (string filename, double grades[30][5]);
//main function
int main() {
double grades[30][5];
read("grades2.txt", grades);
return 0;
}
void read (string filename, double grades[30][5]){
ifstream input_file(filename);
if(input_file.is_open()){
for(int i = 0; i < 30; i++) {
for (int j = 0; j < 5; j++) {
input_file >> grades[i][j];
}
}
cout << grades << endl;
}
input_file.close();
}
My result should be
grades [30]{{10.0, 20.0, 30.0, 40.0, 50.0}
{100.0, 90.0, 80.0, 70.0, 60.0}
{95.0, 85.0, 75.0, 65.0, 55.0}
{25.2, 27.2, 29.3, 31.2, 33.2}
{88.9, 78.8, 68.7, 58.6, 48.5}
{10.1, 20.1, 30.1, 40.1, 50.1}
{100.1, 90.1, 80.1, 70.1, 60.1}
{95.1, 85.1, 75.1, 65.1, 55.1}
{25.2, 27.3, 29.4, 31.3, 33.3}
{88.0, 78.9, 68.8, 58.7, 48.6}
{10.9, 20.8, 30.7, 40.6, 50.5}
{100.9, 90.8, 80.7, 70.6, 60.5}
{95.9, 85.8, 75.7, 65.6, 55.5}
{25.8, 27.7, 29.6, 31.5, 33.4}
{88.7, 78.6, 68.5, 58.4, 48.3}
{20.0, 30.0, 40.0, 50.0, 60.0}
{90.0, 80.0, 70.0, 60.0, 50.0}
{85.0, 75.0, 65.0, 55.0, 45.0}
{45.2, 47.2, 49.3, 51.2, 53.2}
{48.9, 58.8, 68.7, 78.6, 88.5}
{0.01, 0.02, 0.03, 0.04, 0.05}}
| Note that you don't necessarily have to use arrays for storing the information(like double values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input file(grades2.txt). So you don't have to allocate memory beforehand for rows and columns. You can add the values dynamically.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line;
double word;
std::ifstream inFile("data.mat");
//create/use a std::vector instead of builit in array
std::vector<std::vector<double>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<double> tempVec;
std::istringstream ss(line);
//read word by word(or double by double)
while(ss >> word)
{
//std::cout<<"word:"<<word<<std::endl;
//add the word to the temporary vector
tempVec.push_back(word);
}
//now all the words from the current line has been added to the temporary vector
vec.emplace_back(tempVec);
}
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
for(std::vector<double> &newvec: vec)
{
for(const double &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
return 0;
}
The output of the above program can be seen here.
|
70,141,439 | 70,141,540 | User-defined object containing pointer breaks when stored in array | When I store a plain int in A and perform a simple get function:
#include <iostream>
class A
{
int p;
public:
void setint(int p_x);
int getint();
};
void A::setint(int p_x) {p = p_x;} // set p (type int)
int A::getint() {return p;} // get p (type int)
int main()
{
A arr_a[5];
arr_a[0].getint();
}
it compiles and exits with code 0. However when I change int to int* and try to do the same:
#include <iostream>
class A
{
int* p;
public:
void setint(int p_x);
int getint();
};
void A::setint(int p_x) {*p = p_x;} // set int pointed to by p (type int)
int A::getint() {return *p;} // get int pointed to by p (type int)
int main()
{
A arr_a[5];
arr_a[0].getint();
}
it compiles fine but exits with code 3221225477. Why is this so and is there still a way I can store pointers in A and store A in arrays?
| In your 2nd case A arr_a[5] just create a array that contains 5 A. but
for every A, the pointer is an undefined number (maybe 0x0), so *p is a undefined behavior. You should add A::A() and A::~A() to manage your pointer in your class
just like this:
#include <iostream>
class A
{
int *p;
public:
A();
~A();
void setint(int p_x);
int getint();
};
A::A() : p(new int) {}
A::~A() { delete p; }
void A::setint(int p_x) { *p = p_x; } // set int pointed to by p (type int)
int A::getint() { return *p; } // get int pointed to by p (type int)
int main()
{
A arr_a[5];
arr_a[0].getint();
}
|
70,141,699 | 70,141,768 | Template class initialization in main | class Q
{
Q(const Q &obj) {} // copy constructor
Q& operator= (const Q& a){} // equal op overload
}
template <class T>
class B{
public : T x;
B<T>(T t) {
// x = t; }
}
int main()
{
Q a(2);
a.init(1,0);
a.init(2,1);
B <Q> aa(a); // this line gives error
}
How to initialize template class with copy constructor? B aa(a); // this line gives error
I want to solve it but I could not.
Error:
no matching function for call to 'Q::Q()'|
candidate: Q::Q(const Q&)|
candidate expects 1 argument, 0 provided|
candidate: Q::Q(int)|
candidate expects 1 argument, 0 provided|
| To solve the mentioned error just add a default constructor inside class Q as shown below
class Q
{
Q() //default constructor
{
//some code here if needed
}
//other members as before
};
The default constructor is needed because when your write :
B <Q> aa(a);
then the template paramter T is deduced to be of type Q and since you have
T x;
inside the class template B, it tries to use the default constructor of type T which is nothing but Q in this case , so this is why you need default constructor for Q.
Second note that your copy constructor should have a return statement which it currently do not have.
|
70,142,090 | 70,142,235 | How to know if compiler is taking advantage of the pch.h.gch file? | Is there a way to check to see if GCC uses the precompiled header or not?
Also, I generate pch.h.gch file like this:
g++ -std=c++20 -Wall -O3 -flto pch.h -o pch.h.gch
But the generated file is always named as pch.h and without the .gch extension. Why is this happening? It used to automatically add the extension. But now it doesn't.
Edit: Another question is that, is it necessary to add an include guard (e.g. #pragma once) to the precompiled header?
| The question is:
How to know if compiler is taking advantage of the pch.h.gch file?
With the following source files:
==> f.hpp <==
static inline int f() { return 1; }
==> main.cpp <==
#include "f.hpp"
int main() {
return f();
}
We can inspect system calls made by gcc to see if it opens the precompiled header:
$ gcc f.hpp
$ strace -e openat -ff gcc -c main.cpp 2>&1 | grep 'f\.hpp\.gch'
[pid 877340] openat(AT_FDCWD, "f.hpp.gch", O_RDONLY|O_NOCTTY) = 4
We see above that gcc opens, so we assume based on that that gcc uses f.hpp.gch.
|
70,142,196 | 70,142,302 | How do you bring all enum constants into scope? | Is there a way to bring all enum constants into scope? I don't mean the type, I mean the constants themselves.
struct Foo {
enum Bar {
A = 1, B = 2, C = 4, D = 8
};
};
int main() {
using E = Foo;
int v = E::A | E::B | E::C | E::D;
// But is it possible to instead do...
using Foo::Bar::*; // (not real C++)
int v = A|B|C|D; // <-- all enum constants are brought into scope
}
|
// This already works, of course.
using E = Foo;
Foo::Bar v = E::A | E::B | E::C | E::D;
Well, not really, because E::A | E::B | E::C | E::D is an int and you can't implicitly convert an int to an enum.
But that's not stopping you from using c++20's using enum (unless you can't use C++20):
struct Foo {
enum Bar {
A = 1, B = 2, C = 4, D = 8
};
};
int main() {
using enum Foo::Bar; // (real C++20!)
Foo::Bar v = D;
}
|
70,142,451 | 70,142,498 | Overloading << operator for my own class why is this not working? | I have a class and I wanna overload the << operator in it:
class Vector3
{
int x;
int y;
int z;
public:
Vector3(int a, int b, int c) : x{a}, y{b}, z{c} {}
Vector3 operator+(const Vector3& v);
friend std::ostream& operator<<(std::ostream& ost, const Vector3& v);
};
But basically I want to be able to access the data members so here I did it with a friend function and just defined the function in a different file:
std::ostream& operator<<(std::ostream& ost, const Vector3& v)
{
return ost << '(' << v.x << ',' << v.y << ',' << v.z << ')';
}
But my question is how come when I don't use a friend function and just declare the function like this:
std::ostream& operator<<(std::ostream& ost);
Then define it in a different file:
std::ostream& Vector3::operator<<(std::ostream& ost)
{
return ost << '(' << x << ',' << y << ',' << z << ')';
}
When I try to actually use it
int main()
{
Vector3 u(2,4,3);
std::cout << u;
}
It just says:
> no operator matches these operands operand types are:
> std::ostream << Vector3
But if I do u.operator<<(std::cout);
Then it works? But why? I thought that std::cout << u; is basically the same as u.operator<<(std::cout);
| A a;
B b;
a << b;
The compiler looks for the member operator<< in A here, i.e. if A::operator(B const&) exists, the code snipped above uses it, but B::operator<<(A&) is not considered.
For your code this means the member operator required is std::ostream::operator<<(Vector3 const&) which you cannot add, since std::ostream is defined in the standard library. Your only choice here is a free function.
|
70,142,784 | 70,142,918 | How to make sure input into a char isn't too long? | So I'm trying to make sure the user enters only one charcter.
Like if the input is "ab", the code will throw an exception.
char ch = ' ';
std::cin >> ch;
// I'm stuck here
| You can enter the input into an entire string, and process just the first character:
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
char ch = ' ';
if ( input.size() > 1 )
{
// Entered more than 1 character
}
else
ch = input[0];
}
|
70,143,030 | 70,143,422 | I want to output 1 4 2 3 5 odd number ascending order and even numbers in descending order | I want to output odd numbers in ascending order and even numbers in descending order my code is here.
When I give input n=5 array 5 2 4 3 1, I want to output 1 4 2 3 5,
but I got output 4 2 1 3 5. I don't want the position of array.
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
// odd number ascending order
for (int i = 0; i <= n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (arr[i] < arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < n; ++i)
{
if (arr[i] % 2 == 0)
{
cout << arr[i]<< " ";
}
}
// numbers in descending order
for (int i = 0; i <= n - 1; i++)
{
for (int j = i + 1; j <= n; j++)
{
if (arr[j] < arr[i])
{
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
if (arr[i] % 2 == 1)
{
cout << arr[i]<<" ";
}
}
return 0;
}
| We, beginners, should help each other.:)
The task is not easy for such beginners as you and me.
I can suggest an approach based on the bubble sort method.
Here you are.
#include <iostream>
#include <utility>
template <typename UnaryPredicate>
void conditional_bubble_sort( int a[], size_t n,
UnaryPredicate &&unary_predicate,
bool order = false )
{
while ( n && !unary_predicate( *a ) )
{
++a;
--n;
}
for ( size_t i = 0, last = 0; !( n < 2 ); n = last )
{
last = 0;
for ( size_t current = 0, next = 0; next < n; current = next )
{
while ( ++next < n && !unary_predicate( a[next] ) );
if ( next != n )
{
if ( !order /* ascending */ ? a[next] < a[current] : a[current] < a[next] )
{
std::swap( a[current], a[next] );
last = next;
}
}
}
}
}
int main()
{
int a[] = { 5, 2, 4, 3, 1 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
conditional_bubble_sort( a, N, []( const auto &item ) { return item % 2 != 0;} );
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
conditional_bubble_sort( a, N, []( const auto &item ) { return item % 2 == 0;}, true );
for ( const auto &item : a )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
5 2 4 3 1
1 2 4 3 5
1 4 2 3 5
|
70,143,449 | 70,143,777 | Reading a text file in c++ after taking a file name from user | I am just trying to take a file name(example: file.txt) from user and reading it out. But getting some error. Can any body please help me out to perform this task successfully. If their is any other way of doing this please let me know. And please check your solution before answering.
ifstream myfile;
string myline, filename;
cin >> filename; // Reading the filename
myfile.open(filename);
if ( myfile.is_open() )
{
while ( myfile )
{
getline (myfile, myline);
cout << myline << " ";
}
}
for example I have a text file myfile.txt having content as
abc
def
fgh
So i will be getting the same thing as an output.
input: myfile.txt
output :
abc
def
fgh
| If you have an old compiler then as commented by @πάνταῥεῖ .open() function may have no support for std::string filename, then you can use .open(filename.c_str()) to pass const char *. This correction is present in following code.
Also if you have older compiler, still you may solve your issue if you try to specify compiling option -std=c++11 to GCC/CLang compilers or /std:c++latest to MSVC compiler. This also may possibly solve your issue.
Otherwise update you compiler to new one.
As commented by @Someprogrammerdude instead of while (myfile) { getline(...); ... } you should use while (getline(...)) { ... }. This correction is also present in following code.
In following code I added first block in main() that writes to myfile.txt, this is only for testing example for StackOverflow visitors, so that example code is fully self-contained. You should remove this file-writing block, because you already have myfile.txt and this block will just overwrite it.
Full corrected code:
Try it online!
#include <iostream>
#include <fstream>
using namespace std;
int main() {
{
ofstream myfile("myfile.txt");
myfile << "abc\ndef\nfgh";
}
ifstream myfile;
string myline, filename;
cin >> filename; // Reading the filename
myfile.open(filename.c_str());
if ( myfile.is_open() )
{
while ( getline (myfile, myline) )
{
cout << myline << endl;
}
}
}
Output:
abc
def
fgh
|
70,143,471 | 70,143,526 | Why use an initializer list when it initializes nothing? | In this snippet:
struct Result
{
Result() : output1(){};
int output1[100];
}
What does Result() : output1(){}; do?
I know that : output1() is the initializer list, but why even mention it when it does nothing?
| It does something: It zero-initializes output1 instead of leaving it uninitialized.
To elaborate, this is called value initialization and is explained in detail here: https://en.cppreference.com/w/cpp/language/value_initialization
The effects of value initialization are:
if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
if T is an array type, each element of the array is value-initialized;
otherwise, the object is zero-initialized.
Since it is an array, case 3 applies. Then the rule applies recursively for each value in the array, leading to case 4 which sets the value to 0.
|
70,143,856 | 70,144,073 | How to convert hex color string to RGB using regex in C++ | How to convert the hex color string to RGB using regex?
I am using the regex but it is not working. I am not familiar with regex. Is it the correct way?
Below is the sample code:
int main()
{
std::string l_strHexValue = "#FF0000";
std::regex pattern("#?([0-9a-fA-F]{2}){3}");
std::smatch match;
if (std::regex_match(l_strHexValue, match, pattern))
{
auto r = (uint8_t)std::stoi(match[1].str(), nullptr, 16);
auto g = (uint8_t)std::stoi(match[2].str(), nullptr, 16);
auto b = (uint8_t)std::stoi(match[3].str(), nullptr, 16);
}
return 0;
}
| You can use
std::regex pattern("#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})");
Here, the FF, 00 and 00 are captured into a separate group.
Or, you can use a bit different approach.
std::string l_strHexValue = "#FF0000";
std::regex pattern("#([0-9a-fA-F]{6})");
std::smatch match;
if (std::regex_match(l_strHexValue, match, pattern))
{
int r, g, b;
sscanf(match.str(1).c_str(), "%2x%2x%2x", &r, &g, &b);
std::cout << "R: " << r << ", G: " << g << ", B: " << b << "\n";
}
// => R: 255, G: 0, B: 0
See the C++ demo.
|
70,145,190 | 70,145,449 | What all are considered in the Class scope? | Just trying to grab the concept revolving around the scope of the Class in C++. If we take an example something like:
#include <iostream>
using namespace std;
string barValue="OUTSIDE CLASS";
class foo
{
public:
void print_bar()
{
cout<<barValue<<endl;
}
};
int main()
{
foo f;
f.print_bar();
return 0;
}
I am wondering:
Is the barValue variable is in the Class scope?
Can the barValue be accepted even if it is defined in one of the included files?
Is the file and all the included files can be called as the scope of the foo Class?
I can understand that the barValue will not be considered if it is defined after the Class body. To follow up is that means all the included files comes before the Class body and in general before the current file content?
| Question 1
Is the barValue variable is in the class scope?
barValue is a global variable since you have defined it outside any function and class. Therefore barValue can be used inside the class as you did.
Question 2
Can the barValue be accepted even if it is defined in one of the included files?
Yes even if barValue is defined in a header file it can be used in other files because/if it has external linkage as shown in the below example.
file.h
int barvalue = 34;//barvalue has external linkage
main.cpp
#include <iostream>
#include "file.h"
int main()
{
std::cout<<barvalue<<std::endl;//prints 34
return 0;
}
Question 3
Is the file and all the included files can be called as the scope of the foo class?
No
Question 4
I can understand that the barValue will not be considered if it is defined after the class body. To follow up is that means all the included files comes before the Class body and in general before the current file content?
You should clarify this question more because i think it is not clear what your are asking here but i will try to answer what i understand from your question.
If you define barValue after the class foo definition then the program will not work because since you have defined it after the class definition, therefore it has not been defined/declared at the point when you write cout<<barValue<<endl; which is what the error says as shown below:
#include <iostream>
using namespace std;
class foo
{
public:
void print_bar()
{
cout<<barValue<<endl;//error: ‘barValue’ was not declared in this scope
}
};
int main()
{
foo f;
f.print_bar();
return 0;
}
string barValue="OUTSIDE CLASS";
|
70,145,202 | 70,147,883 | Avoid reading punctuation from a file in C++ | I'm trying to find the longest word on a file in c++. I have the solution for that but the code is also considering the punctuation and I don't know how to avoid this.
This is the function "get_the_longest_word()":
string get_the_longest_word(const string &file_name){
int max=0;
string s,longest_word;
ifstream inputFile(file_name);
if(inputFile.is_open())
{
while(inputFile>>s)
{
if(s.length()>max)
{
max=s.length();
s.swap(longest_word);
}
}
inputFile.close();
}else
cout<<"Error while opening the file!!\n";
return longest_word;}
Thanks in advance for the help
| In c++ we have since long a good method to specify patterns of characters, that form a word. The std::regex. It is very easy to use and very versatile.
A word, consisting of 1 or many alphanum characters can simply be defined as \w+. Nothing more needed. If you want other patterns, then this is also easy to create.
And for such programs like yours, there is also no complexity overhead or runtime issue with regexes. So, it should be used.
Additionally, we have a very nice iterator, with which we can iterate over such patterns in a std::string. The std::sregex_token_iterator. And this makes life really simple. With that, we can use many useful algorithms provided by C++.
For example std::maxelement which takes 2 iterators and then returns the max element in the given range. This is, what we need.
And then the whole program boils down to just a few simple statements.
Please see:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <regex>
#include <algorithm>
const std::regex re{ "\\w+" };
std::string getLongestWord(const std::string& fileName) {
std::string result{};
// Open the file and check, if it could be opened
if (std::ifstream ifs{ fileName }; ifs) {
// Read complete file into a string. Use range constructor of string
std::string text(std::istreambuf_iterator<char>(ifs), {});
// Get the longest word
result = *std::max_element(std::sregex_token_iterator(text.begin(), text.end(), re), {}, [](const std::string& s1, const std::string& s2) {return s1.size() < s2.size(); });
} // Error, file could not be opened
else std::cerr << "\n*** Error. Could not open file '" << fileName << "'\n\n";
return result;
}
int main() {
std::cout << getLongestWord("text.txt") << '\n';
}
|
70,146,392 | 70,146,425 | std::function & std::forward with variadic templates | Recently I was reading about variadic templates and based on an example I've seen online I was trying to implement a basic event-system. So far it seems to work fine but I was trying to go a step further and allow N number of arguments to be passed to an event handler function / callback, unfortunately the build error I'm getting is the following and I'm not sure what I'm doing wrong. I looked into similar source codes but still cant figure out what's the issue.
D:\Development\lab\c-cpp\EventEmitter3\src\main.cpp:30:68: error: parameter packs not expanded with '...':
return std::any_cast<std::function<R(Args)>>(eventCallback)(std::forward<Args>(args)...);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:\Development\lab\c-cpp\EventEmitter3\src\main.cpp:30:68: note: 'Args'
Build finished with error(s).
Here is what I have so far, if you remove the ... the event system works fine for the 2 registered events in main.
#include <any>
#include <string>
#include <iostream>
#include <functional>
#include <unordered_map>
class EventEmitter
{
private:
std::unordered_map<std::string, std::any> events;
public:
EventEmitter() {}
void on(const std::string &eventName, const std::any &eventCallback)
{
events[eventName] = eventCallback;
}
template <typename R>
R emit(const std::string &eventName)
{
const std::any &eventCallback = events[eventName];
return std::any_cast<std::function<R(void)>>(eventCallback)();
}
template <typename R, typename... Args>
R emit(const std::string &eventName, Args &&...args)
{
const std::any &eventCallback = events[eventName];
return std::any_cast<std::function<R(Args)>>(eventCallback)(std::forward<Args>(args)...);
}
virtual ~EventEmitter() {}
};
int fun1()
{
std::cout << "fun1" << std::endl;
return 1;
}
double fun2(int i)
{
std::cout << "fun2" << std::endl;
return double(i);
}
double fun3(int x, int y)
{
std::cout << "fun3" << std::endl;
return double(x + y);
}
int main(int argc, char *argv[])
{
EventEmitter e;
e.on("fun1", std::function<int(void)>(fun1));
e.on("fun2", std::function<double(int)>(fun2));
e.emit<int>("fun1");
e.emit<double, int>("fun2", 1);
// Variadic would have been handy right here I guess?
// e.on("fun3", std::function<double(int, int)>(fun3));
// e.emit<double, int>("fun3", 1, 2);
return 0;
}
How can I fix this?
| Well, you need to expand it.
return std::any_cast<std::function<R(Args...)>>(eventCallback)(std::forward<Args>(args)...);
^^^^^^^
|
70,146,539 | 70,146,666 | check if map contains a certain value | Hello I am currently facing a problem or maybe I thinking too complicated.
I have a map that looks like this:
std::map<int,int> mymap;
and I insert values doing this
std::map<char,int>::iterator it = mymap.begin();
mymap.insert (it, std::pair<int,int>(1,300));
now I want to find out if the map contains the value 300.
Lets assume I have a variable called input with the value 300.
int input = 300;
Now with this input I want to check whether my map has the value 300 stored in it.
I know that with map.find() I can check whether a certain key exists in a map.
But I can't use map.find(input) in my case because 300 isn't the key it's the value.
How can I check whether there is a value of 300 in my map?
| You can use std::find_if to find if a value exists in a std::map or not shown below:
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
int main()
{
// Create a map of three strings (that map to integers)
std::map<int, int> m { {1, 10}, {2, 15}, {3, 300}, };
int value = 300;
auto result = std::find_if(std::begin(m), std::end(m), [value](const auto& mo) {return mo.second == value; });
if(result != std::end(m))
{
std::cout<<"found"<<std::endl;
}
else
{
std::cout<<"not found"<<std::endl;
}
}
The output of the above program can be seen here.
|
70,146,860 | 70,146,971 | glCopyImageSubData gives me GL_INVALID_VALUE | I have made a minimal code example that reproduces a bug in my game.
I'm trying to copy a region of a TEXTURE_1D_ARRAY to another one.
u32 tex0;
glGenTextures(1, &tex0);
glBindTexture(GL_TEXTURE_1D_ARRAY, tex0);
glTexImage2D(GL_TEXTURE_1D_ARRAY, 0, GL_RGBA8, 64, 2, 0, GL_RGBA, GL_FLOAT, initTexData);
glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
u32 tex1;
glGenTextures(1, &tex1);
glBindTexture(GL_TEXTURE_1D_ARRAY, tex1);
glTexImage2D(GL_TEXTURE_1D_ARRAY, 0, GL_RGBA8, 64, 3, 0, GL_RGBA, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glCopyImageSubData(
tex0, GL_TEXTURE_1D_ARRAY,
0, 0, 0, 0,
tex1, GL_TEXTURE_1D_ARRAY,
0, 0, 0, 0,
64, 2, 1
);
The texture tex0 is initialized with some pixel data and has dimensions 64x2.
Then I create tex1 with dimensions 64x3 and empty data.
And finally I copy the contents from tex0 to tex1, but it fails in the operation.
It gives error GL_INVALID_VALUE. According to the documentation there are a few different causes for that error. But I have debugged it with ApiTrace and it gave some useful info:
major api error 1281: GL_INVALID_VALUE error generated. The y values exceeds the boundaries of the corresponding image object.
glGetError(glCopyImageSubData) = GL_INVALID_VALUE
The error message suggests that I'm getting out of bounds but I just don't see how. I'm copying a region of 64x2, which should fit on both textures. There must be some silly mistake I can't see myself.
If you want to see the full code: https://gist.github.com/tuket/2198c17107c513c667d7381bbb34386d
| You get the INVALID_VALUE error, because the srcHeight argument of glCopyImageSubData exceeds the boundaries of the corresponding image object.
The height of an one dimensional texture is always 1. However the depth of an on dimensional texture array can be grater than 1:
glCopyImageSubData(
tex0, GL_TEXTURE_1D_ARRAY,
0, 0, 0, 0,
tex1, GL_TEXTURE_1D_ARRAY,
0, 0, 0, 0,
64, 1, 2 // height = 1, but depth = 2
);
Don't let glTexImage2D confuse you where to specify the layers of the one-dimensional texture array using the height argument.
|
70,146,951 | 70,173,849 | OpenGL: How to fix missing corner pixel in rect (lines or line loop) | Take a look at the bottom-left corner of the green rectangles in the middle:
They're missing one pixel at the bottom left.
I drew those like this:
class Rect: public StaticModel {
public:
Rect() {
constexpr glm::vec2 vertices[] {
{-0.5,0.5}, // top left
{0.5,0.5}, // top right
{0.5,-0.5}, // bottom right
{-0.5,-0.5}, // bottom left
};
_buf.bufferData<glm::vec2>(vertices,BufferUsage::StaticDraw);
_idxBuf.bufferData<GLuint>({0,1,3,2,0,3,1,2},BufferUsage::StaticDraw);
}
void bind() const override {
_buf.bindVertex();
_idxBuf.bind();
}
void draw() const override {
gl::drawElements(8,DrawMode::Lines);
}
private:
VertexBuffer _buf{sizeof(glm::vec2)};
ElementArrayBuffer _idxBuf{};
};
That code is using a bunch of my helper methods/classes but you should be able to tell what it does. I tried drawing the rect using a simple GL_LINE_LOOP but that had the same problem, so now I'm trying GL_LINES and drawing all the lines in the same direction: top to bottom and left to right, but even still I'm missing a pixel.
These coordinates are going through orthographic projection:
gl_Position = projection * model * vec4(inPos, 0.0, 1.0);
So the shader is scaling those 0.5 coords up to pixel coords, but I don't think it's a rounding error.
Anything else I can try to get that corner to align?
| OpenGL gives a lot of leeway for how implementations rasterize lines. It requires some desirable properties, but those do not prevent gaps when mixing x-major ('horizontal') and y-major ('vertical') lines.
First thing, the "spirit of the spec" is to rasterize half-open lines; i.e. include the first vertex and exclude the final one. For that reason you should ensure that each vertex appears exactly once as a source and once as destination:
_idxBuf.bufferData<GLuint>({0,1,1,2,2,3,3,0},BufferUsage::StaticDraw);
This is contrary to your attempt of drawing "top to bottom and left to right".
GL_LINE_LOOP already does that though, and you say that it doesn't solve the problem. That is indeed not guaranteed to solve the problem because you mix x-major and y-major lines here, but you still should follow the rule in order for the next point to work.
Next, I bet, some of your vertices fall right between the pixels; i.e. the window coordinates fractional part is exactly zero. When rasterizing such primitives the differences between different implementations (or in our case between x-major and y-major lines on the same implementation) become prominent.
To solve that you can snap your vertices to the pixel grid:
// xy - vertex in window coordinates, i.e. same as gl_FragCoord
xy = floor(xy) + 0.5
You can do this either in C++, or in the vertex shader. In either case you'll need to apply the projection and viewport transformations, and then undo them so that OpenGL can re-apply them afterwards. It's ugly, I know.
The only bullet-proof way to rasterize pixel-perfect lines, however, is to render triangles to cover the shape (either each line individually or the entire rectangle) and compute the coverage analytically from gl_FragCoord.xy in the fragment shader.
|
70,146,977 | 70,147,073 | My C++ program behaves strange with wrong output? | I want to view all solution for: X^12≡1(mod27) So I wrote the following C++ program which outputs only 1 even though 8 and 10 are possible values for x too.
Why is that?
#include <iostream>
#include <cmath>
int main() {
for (int i = 0; i <= 2700000; ++i) {
if (int(pow(i, 12))% 27 == 1) {
std::cout << i << std::endl;
}
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
| The inbuild pow() function is not capable of handling so large number.
Rather we have to use custom function to achieve that.
Here it is
#include <iostream>
#include <cmath>
long long binpow(long long a, long long b, long long m) {
a %= m;
long long res = 1;
while (b > 0) {
if (b & 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
int main() {
for (int i = 0; i <= 2700000; ++i) {
if (binpow(i, 12, 27) == 1) {
std::cout << i << std::endl;
}
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
You can read more about that function from here:
https://cp-algorithms.com/algebra/binary-exp.html
|
70,147,043 | 70,147,192 | Creating a vector of all instances of a class when objects are being instantiated in a loop? | I am trying to keep a pointer to all of the instances of a class inside of a static member variable.
#include <iostream>
#include <vector>
class Person {
public:
static std::vector<Person*> allPeople;
int age;
Person(int a) {
age = a;
allPeople.push_back(this);
}
};
std::vector<Person*> Person::allPeople;
int main() {
static std::vector<Person> children;
for(int i=0;i<10;i++) {
children.push_back(Person(i));
}
for(int i=0;i<Person::allPeople.size();i++) {
std::cout << Person::allPeople[i]->age;
}
return 0;
}
Right now, this code has 10 instances of the same object stored inside Person::allPeople. I think that it has to do something with how every time it loops around, the object goes out of scope. One of my solutions would be to make copies of the object and add pointers to those, except in my actual code, the objects' values would be changing frequently. If anyone knows what the best solution is please let me know, sorry if this is a bit of a messy question I can clarify if needed.
| children.push_back(Person(i));
This is what happens here:
Person(i) creates a temporary object. Person's constructor saves a pointer to this object in its private allPeople vector.
The temporary object gets push_backed into the children vector. This copies/moves this object into the vector. The vector holds a copy of the original object that was added to it. The vector now has a completely different instance of the Person object, that was copy/move-constructed.
After push_back() returns, the temporary Person object gets destroyed. allPeople is left with a dangling pointer to a destroyed object.
The reason you're seeing ten copies of the same pointer is because, it just so happens, every instance of the temporary object gets created in automatic scope at the same memory address. The shown code is completely blind to copy-constructed instances of Person, they get completely missed.
The rules of automatically and dynamically-scoped objects in C++ are complicated, and everything must be handled correctly. At the very least:
Person() must implement a destructor to remove its this pointer from the allPeople vector.
Person must implement, at the very least, a copy constructor that also stores the this pointer of the copy-constructed object in allPeople.
P.S. And let's not forget that every time std::vector reallocates its contents, this creates another batch of copy/move constructed objects, with the old objects getting destroyed.
|
70,147,485 | 70,147,525 | How can I create an array of member function pointers coupled with different objects? | Say I have class A with function foo(int i) and class B with function bar(int i), as well as objectA (of class A) and objectB (of class B). I can call the functions like so
objectA.foo(10);
objectB.bar(20);
What I would like to do is have them both as function pointers in an array arr and calling them like so
arr[0](10);
arr[1](20);
Is there a way of doing this in C++? If so, how efficient is it?
| You could store std::function objects in a std::vector that you create from lambda functions capturing objectA or objectB. Calling std::function objects comes with a little overhead so if time is critical, you'll have to measure if it's good enough.
Example:
#include <functional>
#include <iostream>
#include <vector>
struct A {
void foo(int x) { std::cout << "A::foo " << x << '\n'; }
};
struct B {
void bar(int x) { std::cout << "B::bar " << x << '\n'; }
};
int main() {
A objectA;
B objectB;
std::vector< std::function<void(int)> > arr{
[&objectA](int x) { objectA.foo(x); },
[&objectB](int x) { objectB.bar(x); },
};
arr[0](10);
arr[1](20);
}
Output:
A::foo 10
B::bar 20
|
70,147,830 | 70,148,555 | C++ Weird File Line Read | I'm new to C++ programming and trying to figure out a weird line read behavior when reading a line from a text file. For this specific program, I have to wait for the user to press enter before reading the next line.
If I hard code the file name, the file read starts at line 1 as expected:
#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
ifstream in_file;
in_file.open("test.txt");
// read line by line
string line;
while (getline(in_file, line)) {
cout << line;
cin.get();
}
in_file.close();
return 0;
}
I compile with g++ -Wall -std=c++14 test1.cpp -o test1 and get:
$ ./test
This is line one.
**user presses enter**
This is line two.
**user presses enter**
This is line three.
etc. etc.
But when I add in the option to have the user type in a file name, the line read starts at line 2:
#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
string filename;
cin >> filename;
ifstream in_file;
in_file.open(filename);
// read line by line
string line;
while (getline(in_file, line)) {
cout << line;
cin.get();
}
in_file.close();
return 0;
}
The same compile command gives me:
$ ./test2
test.txt
This is line two.
**user presses enter**
This is line three.
**user presses enter**
This is line four.
etc. etc.
Am I missing something here? I have no idea why it starts reading at line 2 when I add in the code to specify a file name. Am I not finishing the cin statement properly or something?
Thanks!
| by default cin operator>> reads data up to the first whitespace characte and whitespace characte is not extracted reference. So if you read file name like this cin>>file; file variable will contains only first part of your string without whitespace. So that when reading you do not have such problems use getline
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(void) {
string filename;
getline(cin, filename, '\n');
ifstream in_file;
in_file.open(filename);
// read line by line
string line;
while (getline(in_file, line)) {
cout << line;
cin.get();
}
in_file.close();
return 0;
}
|
70,147,832 | 70,148,060 | My vector elements keep changing themselves after each input | char* name = (char*)malloc(sizeof(char));
char* highscore = (char*)malloc(sizeof(char));
char* password = (char*)malloc(sizeof(char));
player* c = new player(name, highscore, password);
int i;
int j = 0;
int score = 0;
vector <player*> players;
vector <char*>* names = new vector <char*>;
vector <char*>* passwords = new vector <char*>;
vector <int> scores;
ifstream input;
input.open("user.csv");
do {
cout << "Welcome to Champion Yahtzee\n";
cout << "Player Name Highest Score\n";
cout << "----------- -------------\n";
while (input.good())
{
input >> *c;
players.emplace_back(c);
names->push_back(name);
score = atoi(highscore);
scores.push_back(score);
passwords->push_back(password);
j++;
}
This is my code, I know that in order to input into it we have to expand the vector? at least from what I read to fit in the new char and I genuinely don't know how to fix it. I've tried initializing the vector as vector <player*> players; but that was of no use since after each input it overrode the previous pointers and sets all the elements to the input. How do I go about fixing this?
| The reason you are getting the same values everywhere is because you only allocate your storage memory once, then push the same memory address in to your vectors over and over.
Basically, you always have only one object.
To fix this, you must allocate new objects inside the loop, like so:
vector <player*> players;
vector <char*> names;
vector <char*> passwords;
vector <int> scores;
ifstream input;
input.open("user.csv");
cout << "Welcome to Champion Yahtzee\n";
cout << "Player Name Highest Score\n";
cout << "----------- -------------\n";
while (input) { //this is the proper way in c++ 11 and up
char* name = new char[MAX_NAME_LEN];
char* highscore = new char[MAX_SCORE_LEN];
char* password = new char[MAX_PASSWORD_LEN];
player* c = new player(name, highscore, password);
input >> *c;
players.emplace_back(c);
names.push_back(name);
int score = atoi(highscore);
scores.push_back(score);
passwords.push_back(password);
}
Here are the explanations to changes to your code:
Unless there is some weird requirement in your homework, the vectors do not need to be pointers, they only need to contain pointers.
We allocate new objects at the beginning of every loop, so every time you read in data it will go in to a new place in memory.
If you have to use char * you should define constants (or macros) like MAX_NAME_LEN for maximum length of the name field.
Your homework probably specifies maximum input length for all fields to make things simpler.
The condition in the while loop is simply the stream object.
Starting with C++11 it overrides the casting to bool to return true while more data can be read.
If you are using older C++ standard use while (!input.eof()) or check the return value of input >> *c and break if it is false.
If you are writing C++ you should use new to allocate memory.
Though malloc will work correctly, it is considered to be "the C way" and its use in C++ is discouraged.
|
70,147,879 | 70,147,932 | Getting incorrect sum while using a recursive function and a do-while loop | I just finished coding a small function for a school project and got the right answer. However, after adding a do-while loop (as it is required), I started running into issues. The first loop works just fine and I get the right answer (i.e., if I input 20 into the function, it outputs 210 which is correct), but if I input that same number or a different one, the number adds ON to the previous total (so if I added 1, then the "total" for that would be 211). I want each loop to find the total, output that total, and then when a new loop occurs, starts fresh. How do I fix this?
#include <iostream>
using namespace std;
int n, total = 0; /* Global variables since I only have to declare it once rather than two times! */
int sum(int n);
// Recursive version to calculate the sum of
// 1 + 2 + .... + n
int main()
{
char choice;
do {
cout << "Enter a positive integer:";
cin >> n;
sum(n);
cout << "The sum of 1+...+" << n << " is: " << total << endl;
cout << "Would you like to try another entry (Y/N): ";
cin >> choice;
}while(choice == 'Y' || choice == 'y');
cout << "Goodbye!" << endl;
return 0;
}
int sum(int n){
if(n == 0)
{
return total;
}
else
{
total = total + n;
return sum(n-1);
}
}
| You could try the following code for sum:
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
|
70,148,520 | 70,148,535 | Question regarding polymorphiic functions in C++ | I am new to C++ and currently I am studying polymorphism.
I have this code:
#include <iostream>
class Base
{
public:
void say_hello()
{
std::cout << "I am the base object" << std::endl;
}
};
class Derived: public Base
{
public:
void say_hello()
{
std::cout << "I am the Derived object" << std::endl;
}
};
void greetings(Base& obj)
{
std::cout << "Hi there"<< std::endl;
obj.say_hello();
}
int main(int argCount, char *args[])
{
Base b;
b.say_hello();
Derived d;
d.say_hello();
greetings(b);
greetings(d);
return 0;
}
Where the output is:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the base object
This is not recognizing the polymorphic nature in the greetings functions.
If I put the virtual keyword in the say_hello() function, this appears to work as expected and outputs:
I am the base object
I am the Derived object
Hi there
I am the base object
Hi there
I am the Derived object
So my question is:
The polymorphic effect is retrieved when using a pointer/reference?
When I see tutorials they will present something like:
Base* ptr = new Derived();
greetings(*ptr);
And I was wondering if had to always resort to pointers when using polymorphism.
Sorry if this question is too basic.
| For polymorphic behavior you need 2 things:
a virtual method overridden in a derived class
an access to a derived object via a base class pointer or reference.
Base* ptr = new Derived();
Those are bad tutorials. Never use owning raw pointers and explicit new/delete. Use smart pointers instead.
|
70,148,525 | 70,149,012 | Cpp/C++ Output allingment in one line from right AND left | I need to write ints from the right and strings from the left into a single line and have them line up properly (view output below the code).
Basically I just need a way to write a table only using iostream and iomanip and change the allingment from right for ints to left for strings and back.
Other tips are also appreciated :)
#include <iostream>
#include <iomanip>
using namespace std;
class foo
{
public:
int i;
std::string s;
int j;
foo(int i1,std::string s1,int j1) : i(i1), s(s1),j(j1) {};
};
int main()
{
foo f1(1, "abc",50);
foo f2(100, "abcde",60);
cout << resetiosflags(ios::adjustfield);
cout << setiosflags(ios::right);
cout << setw(6) << "i" << setw(15) << "s" << setw(15) << "j"<<endl;
cout << setw(8) << f1.i << setw(15)
<< resetiosflags(ios::adjustfield) << setiosflags(ios::left) << f1.s <<setw(5)
<< resetiosflags(ios::adjustfield) << setiosflags(ios::right) << setw(15) << f1.j << endl;
cout << setw(8) << f2.i << setw(15)
<< resetiosflags(ios::adjustfield) << setiosflags(ios::left) << f2.s <<setw(5
<< resetiosflags(ios::adjustfield) << setiosflags(ios::right) << setw(15) << f2.j << endl;
/*i s j
1abc 50
100abcde 60*/
return 0;
}
This is the output:
i s j
1abc 50
100abcde 60
And this is what i need:
i s j
1 abc 50
100 abcde 60
| Using left and right in the same line isn't a problem. It looks like the issue you have is not allowing for space after the first value. It looks like the setw(5) may have been for that, but since there's nothing printed after it there's no effect. I used 7 to match the 15 total used for the string width.
Maybe something like this would work? Probably best to extract the magic numbers into constants so you can adjust all of them easily in one place. You could also wrap this in an operator<< to contain all the formatting code in one place.
The first line headings offset one to the left looks weird to me, but it matches your example and is easy to adjust if necessary.
#include <iostream>
#include <iomanip>
using namespace std;
class foo
{
public:
int i;
std::string s;
int j;
foo(int i1, std::string s1, int j1) : i(i1), s(s1), j(j1)
{};
};
int main()
{
foo f1(1, "abc", 50);
foo f2(100, "abcde", 60);
cout
<< right << setw(7) << "i" << setw(7) << ' '
<< left << setw(15) << "s"
<< right << "j"
<< endl;
cout
<< right << setw(8) << f1.i << setw(7) << ' '
<< left << setw(15) << f1.s
<< right << f1.j
<< endl;
cout
<< right << setw(8) << f2.i << setw(7) << ' '
<< left << setw(15) << f2.s
<< right << f2.j
<< endl;
return 0;
}
Output:
i s j
1 abc 50
100 abcde 60
|
70,148,912 | 70,149,448 | User-defined literals | In "User-defined literals" on cppreference.com, what does it mean by this?
b) otherwise, the overload set must include either, but not both, a raw literal operator or a numeric literal operator template. If the overload set includes a raw literal operator, the user-defined literal expression is treated as a function call operator "" X("n")
Please, I need a simple example that illustrate this text.
|
unsigned long long operator "" _w(unsigned long long);
unsigned operator "" _u(const char*);
int main() {
12_w; // calls operator "" _w(12ULL)
12_u; // calls operator "" _u("12")
}
A little bit changes based on the example in your link.
Here 12_w calls operator "" _w(12ULL) since there is a literal operator with the parameter type unsigned long long, while 12_u calls operator "" _u("12") since there is only a raw literal operator.
|
70,149,108 | 70,149,155 | false expression must have a constant value in visual studio 2022 c++ | hello there i was writing a code in a compiler but my compiler had this error :"false expression must have a constant value" in one of the program lines
i used other compilers but they didn't say this and i could write my program , but in visual studio 2022 it gives me the error
the sample of the program is :
stack<char> stack;
queue<char> queue;
string str;
cin >> str;
char ch[str.length()];
the error is in the
char ch[str.length()];
i dont know how to fix this
i would be glad if you guys help me in this
| Variable-length arrays is not C++ standard, see here. Because str.length() is known at runtime, but the size of the array has to be known at compile-time, this will cause an error.
You should use std::vector instead:
Replace:
char ch[str.length()];
With:
std::vector<char> ch(str.length());
|
70,149,189 | 70,208,825 | vector assign issue in template of c++ | I am writing a program to implement queue using vectors. I am using the class as template. And in main function am trying to create both string vector and int vector based on template data type. However am getting compilation error from vector assign method.
template <class T>
class queueWithArray {
private:
vector<T> queueArray;
int numberOfElements;
int size;
int head;
int tail;
public:
queueWithArray(int n) {
numberOfElements = 0;
head = -1;
tail = -1;
size = n;
if(is_same<T,string>::value) {
cout << "data type is string" << endl;
queueArray.assign(n,"");
} else {
queueArray.assign(n,0);
}
}
...
int main() {
string InputArray[] = {"to", "be", "or", "not", "to", "-", "be", "-", "-", "that", "-", "-", "-", "is"};
queueWithArray<string> obj(2);
for(auto i=0; i < (signed int)(sizeof(InputArray)/sizeof(InputArray[0])); ++i) {
if(InputArray[i] == "-") {
string item = obj.dequeue();
cout << "dequeue->" << item << endl;
} else {
obj.enqueue(InputArray[i]);
cout << "enqueue->" << InputArray[i] << endl;
}
obj.printQueue();
}
int InputArray_int[] = {10,20,30,40,50,-1,20,-1,-1,60,-1,-1,-1,70};
queueWithArray<int> obj_int(2);
for(auto i=0; i < (signed int)(sizeof(InputArray_int)/sizeof(InputArray_int[0])); ++i) {
if(InputArray_int[i] == -1) {
int item = obj_int.dequeue();
cout << "dequeue->" << item << endl;
} else {
obj_int.enqueue(InputArray_int[i]);
cout << "enquque->" << InputArray_int[i] << endl;
}
obj.printQueue();
}
return 0;
}
..\QueueUsingTemplate.cpp:135:31: required from here
..\QueueUsingTemplate.cpp:45:4: error: no matching function for call to >'std::vector::assign(int&, const char [1])'
queueArray.assign(n,"");
^~~~~~~~~~
In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\vector:64:0,
from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\queue:61,
from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\mingw32\bits\stdc++.h:86,
from ..\QueueUsingTemplate.cpp:18:
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\stl_vector.h:489:7: note: candidate: void >std::vector<_Tp, _Alloc>::assign(std::vector<_Tp, _Alloc>::size_type, const value_type&) [with >_Tp = int; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::size_type = unsigned int; >std::vector<_Tp, _Alloc>::value_type = int]
assign(size_type __n, const value_type& __val)
^~~~~~
| Thank you so much VainMan. queryArray.assign(n, T{}); solves the issue. Hi Louis, please find the complete program with include statements here.
/*
* queueUsingArray.cpp
*
* Created on: 02-Nov-2021
* Author: Admin
*/
#include <iostream>
#include <ctype.h>
#include <bits/stdc++.h>
#include <vector>
#include <typeinfo>
#include <type_traits>
using namespace std;
template <class T>
class queueWithArray {
private:
vector<T> queueArray;
int numberOfElements;
int size;
int head;
int tail;
public:
queueWithArray(int n) {
numberOfElements = 0;
head = -1;
tail = -1;
size = n;
queueArray.assign(n,T{});
}
void enqueue(T item) {
if(numberOfElements == size) {
resize(size * 2);
}
if((head == -1) && (tail == -1)) {
head = tail = 0;
} else {
tail = (tail + 1) % size;
}
queueArray[tail] = item;
numberOfElements++;
}
T dequeue() {
T item;
if(numberOfElements == 0) {
cout << "No elements to dequeue" << endl;
} else {
if(numberOfElements == size/4) {
resize(size/2);
}
item = queueArray[head];
if(head == tail) {
head = tail = -1;
} else {
head = (head + 1) % size;
}
numberOfElements--;
}
return item;
}
bool isEmpty() {
return ((head == -1) && (tail == -1));
}
void resize(int newSize) {
if(newSize > 0) {
size = newSize;
int newIndex = 0;
for(int i=head; i<=tail; ++i){
queueArray[newIndex] = queueArray[i];
newIndex++;
}
queueArray.resize(newSize);
head=0;
tail=newIndex-1;
} else {
return;
}
}
void printQueue() {
if(!isEmpty()) {
for(auto i=head; i<tail; i++) {
cout << queueArray[i] << "->";
}
cout << queueArray[tail] << endl;
} else {
cout << "Queue is Empty" << endl;
}
}
};
int main() {
string InputArray[] = {"to", "be", "or", "not", "to", "-", "be", "-", "-", "that", "-", "-", "-", "is"};
queueWithArray<string> obj(2);
for(auto i=0; i < (signed int)(sizeof(InputArray)/sizeof(InputArray[0])); ++i) {
if(InputArray[i] == "-") {
string item = obj.dequeue();
cout << "dequeue->" << item << endl;
} else {
obj.enqueue(InputArray[i]);
cout << "enqueue->" << InputArray[i] << endl;
}
obj.printQueue();
}
int InputArray_int[] = {10,20,30,40,50,-1,20,-1,-1,60,-1,-1,-1,70};
queueWithArray<int> obj_int(2);
for(auto i=0; i < (signed int)(sizeof(InputArray_int)/sizeof(InputArray_int[0])); ++i) {
if(InputArray_int[i] == -1) {
int item = obj_int.dequeue();
cout << "dequeue->" << item << endl;
} else {
obj_int.enqueue(InputArray_int[i]);
cout << "enquque->" << InputArray_int[i] << endl;
}
obj_int.printQueue();
}
return 0;
}
|
70,149,246 | 70,149,965 | I have an error creating a top down shooter C++ project in Unreal, Compilation error | I get an error when trying to create a top-down shooter c++ project in Unreal. I think it might have something to do with paging files but I'm not sure. I have visual studio 2022 community installed for the compiler and use Rider for Unreal Engine as an actual IDE, it's the default. If anybody knows how to fix this, that would be greatly appreciated.
The Error Message:
The project could not be compiled. Would you like to open it in Rider?
Running C:/Program Files/Epic Games/UE_4.27/Engine/Binaries/DotNET/UnrealBuildTool.exe Development Win64 -Project="C:/Users/Admin/Documents/Unreal Projects/Survival/Survival.uproject" -TargetType=Editor -Progress -NoEngineChanges -NoHotReloadFromIDE
Creating makefile for SurvivalEditor (no existing makefile)
@progress push 5%
Parsing headers for SurvivalEditor
Running UnrealHeaderTool "C:\Users\Admin\Documents\Unreal Projects\Survival\Survival.uproject" "C:\Users\Admin\Documents\Unreal Projects\Survival\Intermediate\Build\Win64\SurvivalEditor\Development\SurvivalEditor.uhtmanifest" -LogCmds="loginit warning, logexit warning, logdatabase error" -Unattended -WarningsAsErrors -abslog="C:\Users\Admin\AppData\Local\UnrealBuildTool\Log_UHT.txt" -installed
LogInit: Display: Loading text-based GConfig....
Reflection code generated for SurvivalEditor in 10.9429744 seconds
@progress pop
Building SurvivalEditor...
Using Visual Studio 2019 14.30.30705 toolchain (C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705) and Windows 10.0.19041.0 SDK (C:\Program Files (x86)\Windows Kits\10).
Building 13 actions with 4 processes...
@progress 'Compiling C++ source code...' 0%
@progress 'Compiling C++ source code...' 8%
[1/13] Default.rc2
@progress 'Compiling C++ source code...' 15%
[2/13] SharedPCH.Engine.ShadowErrors.cpp
Detected compiler newer than Visual Studio 2019, please update min version checking in WindowsPlatformCompilerSetup.h
@progress 'Compiling C++ source code...' 23%
[3/13] SurvivalGameMode.cpp
c1xx: error C3859: Failed to create virtual memory for PCH
c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
c1xx: note: please visit https://aka.ms/pch-help for more details
c1xx: fatal error C1076: compiler limit: internal heap limit reached
@progress 'Compiling C++ source code...' 31%
[4/13] SurvivalCharacter.gen.cpp
c1xx: error C3859: Failed to create virtual memory for PCH
c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
c1xx: note: please visit https://aka.ms/pch-help for more details
c1xx: fatal error C1076: compiler limit: internal heap limit reached
@progress 'Compiling C++ source code...' 38%
[5/13] Survival.cpp
@progress 'Compiling C++ source code...' 46%
[6/13] SurvivalPlayerController.gen.cpp
@progress 'Compiling C++ source code...' 54%
[7/13] Survival.init.gen.cpp
c1xx: error C3859: Failed to create virtual memory for PCH
c1xx: note: the system returned code 1455: The paging file is too small for this operation to complete.
c1xx: note: please visit https://aka.ms/pch-help for more details
c1xx: fatal error C1076: compiler limit: internal heap limit reached
@progress 'Compiling C++ source code...' 62%
[8/13] SurvivalPlayerController.cpp
@progress 'Compiling C++ source code...' 69%
[9/13] SurvivalGameMode.gen.cpp
@progress 'Compiling C++ source code...' 77%
[10/13] SurvivalCharacter.cpp
| Just too many symbols or template instantiations.
Use /Zm to adjust the compiler heap limit and follow other recommendations here:
https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/fatal-error-c1076?view=msvc-170
|
70,149,296 | 70,149,322 | How to avoid multiple -l in C++ compiling when using libraries | I really have met lots of problems while using external libraries in c++.
The library includes a include file of header files, and a lib file which includes all .la, .so files. I added the library in to usr/local/include and usr/local/lib, and also edited the ld.so.conf file. After all these is done, I supposed that my program could be compiled successfully. However, an error occured:
$ g++ -o b try.cpp
/usr/bin/ld: /tmp/ccTWcUvt.o: in function `main':
try.cpp:(.text+0x36): undefined reference to `OsiClpSolverInterface::OsiClpSolverInterface()'
/usr/bin/ld: try.cpp:(.text+0x45): undefined reference to `OsiClpSolverInterface::~OsiClpSolverInterface()'
then I typed all the library file names behind -l manually and compiled again with this command:
g++ -o b try.cpp -lCbc -lCbcSolver -lCgl -lClp -lcoinasl -lcoinglpk -lcoinmumps -lCoinUtils -lOsi -lOsiCbc -lOsiClp -lOsiCommonTest -lOsiGlpk
This time it did compile successfully and the program worked great.
I'm wondering whether there is any method to avoid this verbosity? Also, if anyone could expain to me why just adding the path to the lib files are not enough, but must point out the names explicitly, I would be so very very grateful as well.
Thanks a lot!
| The linker knows which functions you are calling. It does not know which libraries those functions are contained in, and it's not going to go searching through many hundreds or thousands of libraries to find them.
With gcc, more so than with Visual C++, the order of the libraries can be important, so they don't even support the pragma to specify libraries.
This is not verbosity. You need to be using Makefiles if it is too much typing for you.
|
70,149,710 | 70,149,787 | Why is decltype'ing members of the parent class forbidden if it's a template? | Why are members of a base class not available in a derived class if the base is templated in the derived?
At compile time all of the types should be instantiated, so I don't see what or why it is different. I can see an argument for this being able to create unresolvable types; but, that feels like a compile time error, not a restriction to the language.
More explicitly, why does this work?
template<typename T>
class A{
protected:
int member;
};
class B: public A<int>{
decltype(member) another_member;
};
But, this doesn't?
template<typename T>
class A{
protected:
int member;
};
template<typename T>
class B: public A<T>{
decltype(member) another_member;
};
| There is an ISOCPP FAQ for this question.
https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members
and read the next one too about how it can silently hurt you
https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-silent-bug
Basically the compiler will not look into templated base classes. The reason is likely that the concrete class does not exist at that point.
The previous example works because A<int> is a concrete class while A<T> is not. For the same reason you are forced to add typename to arguments and members.
You should put the scope back as in
decltype(B::member)
Warning: Don't use this.
decltype(A<T>::member)
This will temporarily silence the warning until a B is instantiated; but, won't work unless B<T> is a friend of A<T>, since B can't access A<T>'s protected members though that name.
|
70,149,716 | 70,149,818 | How to directly use vector as parameter in a function? | I know how to initilize a new vector before using it, but how to convenitently use it as paramter in a function?
For example, when I init v1, it can get result in the end, but when I use v2, it shows error :cannot use this type name.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> Add(vector<int>&nums, int target)
{
cout << nums[0] + target;
}
};
int main(){
Solution Sol1;
vector <int> v1 {1,2,3};
Sol1.add(v1, 8);
Sol1.add(vector <int> v2{4,5,6}, 8);
}
Besides, I tried to correct v2 as Sol1.add(vector <int> {4,5,6}, 8); However, it shows error: The initial value of a non-constant reference must be an left value
| The problem you are having has nothing to do with vector.
Sol1.add(vector<int> v2{4,5,6}, 8);
Here, it seems like you are trying to declare an object name v2 in the middle of this expression, which isn't something you can do in C++.
However, you can create a unnamed temporary object in the middle of it like:
Sol1.add(vector<int>{4,5,6}, 8);
or even:
Sol1.add({4,5,6}, 8);
But now you would face a different problem, like you mentioned:
The initial value of a non-constant reference must be an left value
The reason for that is you can't create a reference to a temporary object. To solve it, you can either copy the vector to your function, by changing the signature of your add function:
vector<int> add(vector<int> nums, int target)
{
⋮
}
However, this solution need to copy the entire vector to the function, hence it might be quite slow if your vector is large. Another way is to change the signature to const reference of a vector, which can bond to a temporary object. The downside is that you will not be able to modify the object inside the function, if you were looking to do that:
vector<int> add(const vector<int>& nums, int target)
{
⋮
}
|
70,149,907 | 70,734,278 | How to distinguish ADS (Alternate Data Stream) vs Main stream changes with ReadDirectoryChangesW | I'm developing file sync client for Windows.
I use ReadDirectoryChangesW API for detecting file events (modifying, remove, create, etc.).
But ReadDirectoryChangesW reports NTFS ADS changes same as file modifications.
For example, when eml file is created, OS System add ADS on this file. (stream name is OECustomProperty). In this case, My Client can't distinguish between main stream and alternate data stream.
How to distinguish between modifying ADS and modifying the main stream?
| There are a number of alternative APIs you might consider. In particular, there's the NTFS Journal, with which you can review and sync based on things that happened since the last time you visited. You'd have to keep the last-read journal identifier...the USN...so you'd know where to start your processing.
It's kind of arcane, but it's super useful...especially for things like backup and sync programs. You can find an entry point to this world of wonder here.
Also, you'd be better off reading the entire $MSFT (the volume catalog) than iterating through folders. It's also a moderately arcane API, but orders of magnitude faster than iterating over folders. There's a description of how to read that in my answer to this question.
|
70,149,917 | 70,149,950 | no match for 'operator<' (operand types are 'const Vehicle' and 'const Vehicle') | I have this class:
class Vehicle {
private:
char dir_;
public:
char car_;
// functions
//
// overloaded operators
bool operator==(Vehicle&);
bool operator<(const Vehicle& v);
//
// other functions
};
which has this implementation:
bool Vehicle::operator<(const Vehicle& v) {
return (car_ < v.car_);
}
And I'm getting this error:
"no match for 'operator<' (operand types are 'const Vehicle' and 'const Vehicle')"
which is in "stl_funxtion.h"
| To make a function usable on a const object, you need to declare that function const:
class Vehicle {
⋮
bool operator<(const Vehicle& v) const;
⋮ ^^^^^
⋮
};
bool Vehicle::operator<(const Vehicle& v) const {
⋮ ^^^^^
}
|
70,149,947 | 70,156,298 | Why are access specifiers treated differently when expanding template parameters? | Expanding on the question "Why is decltype'ing members of the parent class forbidden if it's a template?".
Both Clang and GCC complain that B can't access A::member, because it is protected.
But, B can access A::member if a particular instance of B is asked, it's only during the expansion of B<int>::type_name that the error arises.
Why is the public inheritance of A by B ignored in this context? (If that's what's happening.)
template<typename T>
class A{
protected:
int member;
public:
using type_name = T;
};
template<typename T>
class B: public A<T>{
decltype(A<T>::member) another_member;
};
template<typename T,
typename P=typename T::type_name>
void foo(){}
// Force the instantiation of foo
void bar(){
foo<B<int>>();
}
| They'er not. Use B<T>::member.
The trouble comes from, in decltype(member) the compiler imminently notices that member isn't in scope; however, in decltype(A<T>::member) the compiler can't tell that the member is protected until template expansion. Leading to a (mostly) unrelated stack of template expansion information in the error.
Since B<T> is not a friend of A<T> it can't access its protected members through its name; but instead should access them though its qualified name of B<T>::member.
|
70,150,720 | 70,158,525 | Deduce field width from data type in std::format | I'm experimenting with the new C++ 2020 std::format function. I would like to represent the output with a width deduced from its type. Currently I have this line:
std::wstring wstr = std::format( L"{0:#0{1}x}", ::GetLastError(), sizeof( ::GetLastError() ) * 2 );
This results in the value L"0x000002".
Is # supposed to count the 0x as part of the width? (If I remove it, I get 8 nibbles as expected)
Is there a better way of formulating this format string, without sizeof thing?
|
Is # supposed to count the 0x as part of the width? (If I remove it, I get 8 nibbles as expected)
Yes. There is an example in [format.string.std]/13 which illustrates this. The whole string is 6 characters, including the 0x:
string s2 = format("{:#06x}", 0xa); // value of s2 is "0x000a"
This is similar to what printf does.
Is there a better way of formulating this format string, without sizeof thing?
If this is something you want to do often, then you can create your own type and define its formatting internally so that you just write:
std::wstring wstr = std::format( L"{}", PrettyHex{::GetLastError()});
But that's just moving where the sizeof happens - you still need to manually provide it somewhere, there's no shortcut here.
|
70,151,000 | 70,151,415 | Data type sizes in C++ and VB.NET | I am working on developing an application in VB.NET which uses a third party DLL for which the documentation is for C++. For the data type conversions, I was using two pages:
https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/
I was looking up the size in the C++ page and the equivalent size for VB.NET; e.g. int is 4 bytes in C++ so the corresponding VB.NET would be INT32 or Integer.
However, that was giving me unexpected results.
I then noticed that C++ long int is given as 8 bytes with values of -2,147,483,648 to 2,147,483,647 while VB.NET long is also given as 8 bytes with a data type of INT64 but the values are shown as -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807.
Also, the sizes for C++ int (4 bytes) and long (8 bytes) are different but the ranges are the same.
Why the two (wildly) differing ranges for an 8 byte variable? Is one of the pages wrong?
| Check this: https://learn.microsoft.com/en-gb/cpp/cpp/data-type-ranges?view=msvc-170
Long is 4 bytes. The vb.net page is correct, the C++ one is not.
|
70,151,455 | 70,195,744 | How to get more debug info for C++ std::ofstream writing to device? | Good day, I am trying to debug this C++ code which interacts with XDMA device:
#include <fstream>
#include <iostream>
#include <unistd.h>
int main()
{
std::ofstream output_;
const char* output_name = "/dev/xdma/card0/h2c0";
output_.exceptions(std::ios::failbit | std::ios::badbit);
output_.rdbuf()->pubsetbuf(nullptr, 0);
output_.open(output_name, std::ios::binary | std::ios::out);
std::streamoff offset = 0x1e00000;
output_.seekp(offset, std::ios::beg);
const char buf[1] = "";
std::streamsize size = 1;
auto pos = output_.tellp();
output_.write(buf, size); // <--- IOSTREAM ERROR
output_.seekp(pos + size, std::ios::beg);
return 0;
}
But this program fails on output_.write(buf, size); - with quite a vague error message:
terminate called after throwing an instance of 'std::__ios_failure'
what(): basic_ios::clear: iostream error
Aborted (core dumped)
And, if I wrap this output_.write(buf, size); in a try & catch block:
try {
output_.write(buf, size);
}
catch (std::system_error& e) {
std::cerr << e.code().message() << "(" << e.code().value() << ")\n";
return 1;
}
it changes to iostream error(1). This doesn't tell a failure reason... I know for sure that I can write to 0x1e00000 offset, because the alternative C code is working flawlessly. So the error is in C++ code or library. How to get more debug info?
| Although I didn't succeed in getting more debug info, the solution was to downgrade the XDMA driver, which provides /dev/xdma/card0/h2c0 device, from v2017.1.47 to the older v2017.0.45 version (which needed a custom patch to work on new OS). Unfortunately these new drivers are really buggy...
|
70,151,546 | 70,169,736 | exe file is not running in Release folder | My project IDE: Visual Studio 2019, Qt 5.15.0.
I'm trying to launch the application by the project_name.exe file of the release build, but nothing happens.
The project_name.exe file of Debug mode is running well.
The project is running well also in IDE in both Debug and Release modes.
I added Qt Bin directory to the PATH.
I tried windeployqt command but it didn't help.
I copied to Release folder all the dll files the application depends on, according to the build output and Dependencies tool, but then I couldn't run it neither from the exe file nor from the IDE (there are no any compilation errors or error messages when I'm trying to run it).
What is missing for running the exe file from Release folder?
| The following steps finally solved my problem:
Copy the qml folder from the project directory into Release folder (it has to be
near the exe file).
In Release folder launch Command prompt and write: windeployqt project_name.exe,
this step must come after having qml files for getting the whole needed deployment
files by windeployqt command.
Copy from your system the following dlls into Release folder: opengl32.dll,
libcrypto-1_1-x64.dll.
For a VM with no Visual Studio installed there are some more dlls to copy.
|
70,151,957 | 70,152,012 | What is the purpose of "int[]" here: "std::void_t<int[static_cast<Int>(-1) < static_cast<Int>(0)]>;" | This is from an example from a tutorial on std::enable_if.
Here is more context:
// handle signed types
template<typename Int>
auto incr1(Int& target, Int amount)
-> std::void_t<int[static_cast<Int>(-1) < static_cast<Int>(0)]>;
From
Shouldn't std::void_t be accepting a type as template argument?
What is the purpose of int[] in this context?
| If static_cast<Int>(-1) < static_cast<Int>(0) yields true, int[static_cast<Int>(-1) < static_cast<Int>(0)] leads to int[1] (true could be converted to int (and then std::size_t) implicitly with value 1), which is an array type.
If static_cast<Int>(-1) < static_cast<Int>(0) yields false, int[static_cast<Int>(-1) < static_cast<Int>(0)] leads to int[0] (false could be converted to int (and then std::size_t) implicitly with value 0), which is an invalid array type and SFINAE would discard the specialization from the overload set. (The size of array must be greater than zero (unless using in new[]-expression)).
|
70,151,963 | 70,152,209 | The question is about printing digits of two digit number n, I'm encountering a runtime error | Given a two-digit number n, print both the digits of the number.
Input Format:
The first line indicating the number of test cases T.
Next T lines will each contain a single number ni.
Output Format:
T lines each containing two digits of the number ni separated by space.
Constraints
1 <= T <= 100000
10 <= ni <= 99
Error: Runtime Error (SIGSEGV)
I'm not able to pinpoint, where the problem is in the code as it is working fine for a two numbers while it gives the runtime error for 4 or more numbers.
Is there another way of doing this problem other than using for loop twice?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
int arr[t];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>arr[i];
}
int c;
int b;
for(int i=0;i<t;i++)
{
c=(arr[i]/10);
if(c!=0)
{
b=arr[i]%(c*10);
}
else
{
b=arr[i];
}
cout<<c<<" "<<b<<endl;
}
return 0;
}
| Fist, you declare t, but do not initialize it, so it is uninitialized. Trying to use the value leads to undefined behavior.
Second, VLA is not valid C++, see here. You have to use std::vector instead.
Third, you don't need to use an int.
So, you should do:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int t{};
std::cin >> t;
std::vector<std::string> arr(t);
for(int i = 0; i < t; i++)
{
std::cin >> arr[i];
}
for(const auto &i : arr)
{
std::cout << i[0] << ' ' << i[1] << '\n';
}
}
|
70,152,329 | 70,153,113 | Thread separated random int generation in C++ | I need to genetate three .txt files filled with random int, calling the generate function in sepatared threads.
The problem is that as a result I have the same values in every .txt files.
A function that gererates and writes values:
void generateMoves(int limit, std::string outputPath) {
//open fstream
std::ofstream fout;
fout.open(outputPath);
if (!fout.is_open()) {
std::cout << "Error reading " << outputPath << " file. Exiting..." << std::endl;
exit(1);
}
static thread_local std::mt19937 generator;
std::uniform_int_distribution<int> distribution(1, 3);
//generating & writing moves
for (int i = 0; i < limit; i++) {
int value;
value = distribution(generator);
fout << value << std::endl;
}
fout.close();
}
I call threads like this from main():
int limit = 1000;
std::thread player1(generateMoves, limit, "player1.txt");
std::thread player2(generateMoves, limit, "player2.txt");
std::thread player3(generateMoves, limit, "player3.txt");
player1.join();
player2.join();
player3.join();
So, how do I separate int generation correctly?
Edit: Following the comment below, I putted diffent seed into each thread and everything works fine now. The random generation looks like this now:
// put different *s* into each thread
srand(s);
//generating & writing
for (int i = 0; i < limit; i++) {
int value;
value = rand() % 3 + 1;
fout << value << std::endl;
}
| As the comments state, all your generators have been created from the same default seed. It suffices to give each generator a different seed:
std::random_device rd1;
static thread_local std::mt19937 generator(rd1());
This uses the (very slow) std::random_device, but only to generate a unique seed for the mt generator.
|
70,152,360 | 70,152,792 | Is there a fast way to get the index of bit which equal 1 in a binary value? | I want to get the index which equals to 1 in binary format, now I use codes like this:
inline static uint8_t the_index(uint32_t val){
return uint8_t(log(val & ((~val) + 1))/log(2));
}
I want to know if there are other ways to achieve the same target? Is there any possible to use bit operation to solve this problem?
I do this to iterater a value and build some operations which depends on the position iterated, the pesudo codes like this:
while (temp) {
auto cur_index = the_index(temp);
auto window = ((1 << i) - 1) << cur_index;
if (((temp & window) ^ window) == 0) {
//....do something
}
temp &= temp - 1;
}
| There is a standard function for this:
auto cur_index = std::countr_zero(temp);
On my system, this compiled down to:
xor eax, eax
tzcnt eax, edi
Note that this function successfully counts the zero bits from right until first one bit whether the input has exactly one set bit or not.
|
70,152,364 | 70,152,403 | Why do designated initializers zero-initialize the data members? | Below is from cppref of Designated initializers:
struct A { int x; int y; int z; };
A b{.x = 1, .z = 2}; // ok, b.y initialized to 0
By default, all fundamental types are default-initialized rather than zero-initialized in C++.
Why do designated initializers zero-initialize the data members?
| b.y will be initialized from an empty initializer list, as the effect, zero-initialized to 0.
For a non-union aggregate, elements for which a designated initializer is not provided are initialized the same as described above for when the number of initializer clauses is less than the number of members (default member initializers where provided, empty list-initialization otherwise):
struct A {
string str;
int n = 42;
int m = -1;
};
A{.m=21} // Initializes str with {}, which calls the default constructor
// then initializes n with = 42
// then initializes m with = 21
From the standard, [dcl.init.aggr]/5:
For a non-union aggregate, each element that is not an explicitly
initialized element is initialized as follows:
(5.1) If the element has a default member initializer ([class.mem]), the element is initialized from that initializer.
(5.2) Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list ([dcl.init.list]).
(5.3) Otherwise, the program is ill-formed.
|
70,152,465 | 70,152,532 | Unexpected behavior concatenating string | I am trying to concatenate two strings in C++11 and I am often getting an unexpected behavior.
First, I have a function that converts any type to string :
template <class T>
static inline const char * toStr(T arg) {
stringstream ss;
ss << arg;
return (ss.str()).c_str();
}
Then, I use this function like this :
string measure_name;
for (unsigned long j = 0; j < 1280; j++) {
measure_name = string("ADC_") + toStr(j);
cout << measure_name << endl;
}
Everything goes well untill I reach a 4 digit number (> 999) :
my variable measure_name often equals to "ADC_ADC_"... and it happens randomly. I did some research and found nothing about this strange behavior.
For your information, this issue is fixed if toStr returns a string and not a const char *.
Also, if I try to print the returned value, I never see it equal to "ADC_ADC_", so I believe the real issue comes from the concatenating instruction :
string measure_name;
for (unsigned long j = 0; j < 1280; j++) {
const char* tmp = toStr(j);
if (!strcmp(toStr(j), "ADC_ADC_"))
cout << "bug" << endl; //never happens
measure_name = string("ADC_") + tmp; //problem comes from here
cout << measure_name << endl;
}
I just wanted to understand what I am doing wrong there... I know I am using very old C++ but it should work anyway.
Thank's for your help.
| Here
return (ss.str()).c_str();
You are returning a pointer to the buffer of a temporary std::string (returned from str()). The pointer returned from the function is useless for the caller, because the std::string it points to is already gone.
A pointer is just a pointer. If you want a string, return a std::string. If you want to return a const char* then you need to store the string somewhere and manage its lifetime.
std::string does mangage the lifetime of a character array, so just do:
template <class T>
static inline std::string toStr(T arg) {
stringstream ss;
ss << arg;
return ss.str();
}
If someone needs a c-array of char they can still call c_str (and use it as long as the std::string is still alive).
Instead of your toStr consider to use std::to_string.
|
70,152,931 | 70,153,001 | How to set a string to an optional string value? | Due to some constraint in the program(C++), I have a case where I am assigning an optional string to a string variable, which give the following error:
error: no match for ‘operator=’ ...
The piece of code is something like:
void blah(std::experimental::optional<std::string> foo, // more parameters)
{
std::string bar;
if(foo)
{
bar = foo; //error
}
// more code
}
Attempts:
I tried to convert the types to match by using:
bar = static_cast<std::string>(foo);
which ended up showing this error:
error: no matching function for call to ‘std::basic_string<char>::basic_string(std::experimental::optional<std::basic_string<char> >&)’
I am wondering:
Is there a way to handle this case?
Or else it is a design limitation and I have to use some other approach instead of assigning a optional string to a normal string?
| You have several ways:
/*const*/std::string bar = foo.value_or("some default value");
std::string bar;
if (foo) {
bar = *foo;
}
std::string bar;
if (foo) {
bar = foo.value();
}
|
70,153,546 | 70,154,006 | Variable not set inside __attribute__((constructor)) or global static variable reset after __attribute__((constructor)) invoked | I have a std::vector which need to filled with some random values when library is loaded. but I see it is been reset after library is loaded. Is it because of global and static
Library code:
static std::vector<uint8_t> g_randomNr{};
__attribute__((constructor)) void generateRandomNrAtStart(void)
{
static bool firstLoad = false;
g_randomNr.clear();
if (!firstLoad) {
firstLoad = true;
std::cout << "Library is loaded and generating first random number ...\n";
}
std::cout << "Generating random number ...\n";
for (int i = 0; i < 20; i++) {
g_randomNr.push_back(i);
}
std::cout << "Random number generated with length of " << g_randomNr.size() << "\n";
}
void getRandomNr(std::vector<uint8_t>& randomNr)
{
randomNr = g_randomNr;
}
Main code:
int main()
{
std::vector<uint8_t> randomNr{};
getRandomNr(randomNr);
std::cout << randomNr.size() << "\n";
return 0;
}
Output:
Library is loaded and generating first random number ...
Generating random number ...
Random number generated with length of 20
0
In the above output I expect 20 in cout main function but I receive empty vector
| Another option is to control the order of the vector initialization and constructor call with priorities:
__attribute__((init_priority(101))) static std::vector<uint8_t> g_randomNr{};
__attribute__((constructor(102))) void generateRandomNrAtStart() { ... }
Live demo: https://godbolt.org/z/bh9zj9cE3
Possibly OT to the problem: Note that using I/O (as std::cout in your case) in a constructor can suffer from the very same problem. See, e.g., gcc linker extension __attribute__((constructor)) causes crash in main().
|
70,154,749 | 70,154,870 | I can't access to the protected member of my base class | I am new at programming using c++ and having some troubles creating my constructors & objects.
How can I access to my protected members like int p_iID in the Fahrzeug class?
I have to access them for both of my objects seperately.
I would be so happy if you could help me out with this.
class Fahrzeug {
private:
protected:
string p_sName;
int p_iID;
double p_dMaxGeschwindigkeit;
double p_dGesamtStrecke;
double p_dGesamtZeit;
double p_dZeit;
public:
virtual void vAusgeben(Fahrzeug* pFahrzeug1,Fahrzeug* pFahrzeug2);
virtual void vKopf();
virtual void vSimulieren(Fahrzeug *pFahrzeug, Fahrzeug *pFahrzeug2);
class PKW;
class PKW: public Fahrzeug{
PKW(const int p_iMaxID, string p_sName, double p_dMaxGeschwindigkeit, double p_dGesamtStrecke) {
p_iID = p_iMaxID;
this->p_sName = p_sName;
this->p_dMaxGeschwindigkeit = (p_dMaxGeschwindigkeit < 0) ? 0 : p_dMaxGeschwindigkeit;
this->p_dGesamtStrecke = p_dGesamtStrecke;
}
void vAusgeben(PKW pkw1, PKW pkw2) {
cout << "\n";
PKW pkw1;
PKW pkw2;
pkw1.vKopf();
cout << setw(5) << left << pkw1.p_iID<< " " << setw(10) <<pkw1.p_sName << setw(8) << " " << setw(15) << showpoint << pkw1.p_dMaxGeschwindigkeit << setw(3) << " " << pkw1.p_dGesamtStrecke; //Here I have the issue with pkw1.p_sName
cout << "\n";
cout << setw(5) << left << pkw2.p_iID << " " << setw(10) << pkw2.p_sName << setw(8) << " " << setw(15) << showpoint << pkw2.p_dMaxGeschwindigkeit << setw(3) << " " << pkw2.p_dGesamtStrecke;
cout << "\n";
}
}
| void vAusgeben(PKW pkw1, PKW pkw2) {
You probably don't want to pass your PKW objects by value (or expect object slicing). Pass const references instead:
void vAusgeben(const PKW& pkw1, const PKW& pkw2) {
Also, why are you shadowing your 2 parameters with these local variables?
PKW pkw1; // ???
PKW pkw2; // ???
|
70,155,129 | 70,156,087 | Vector of structs containing allocation pointers is failing to destruct | In my project I use a class for paged memory allocation.
This class uses a struct to store all of its allocations:
enum PageStatus : uint_fast8_t { //!< possible use stati of an allocated page
PAGE_STATUS_INVALID = 0b00,
PAGE_STATUS_FREE = 0b01, //!< the page is free
PAGE_STATUS_USED = 0b10, //!< the page is (partially) used
};
struct PhysicalPage { //!< represents a page that has been allocated
char* pData; //!< pointer to the allocation
PageStatus status; //!< status of the allocation
};
These PhysicalPages are stored in a vector std::vector<PhysicalPage> physicalAllocations {};.
During runtime pages are added to the vector and some may be removed. During the removal the last element is popped and the memory is returned using delete page.pData. However a problem occurs when the allocator class reaches end of life and gets deallocated from the stack. When pyhsicalAllocations's vector destructor is called it tries to destruct not only the elements themself but also the reserved memory (which the vector keeps as a buffer for when the size is changed). That causes invalid memory pointers to be deleted, stopping program execution:
double free or corruption (!prev)
Signal: SIGABRT (Aborted)
It's probably also worth mentioning that allocations are done in chunks larger than pages, which means that only one in every x pointers are actually valid allocations. All other pointers are just offsets from the actual memory locations.
To prevent the error from occurring I tried:
deleting manually (this is a bit overcomplicated due to chunked allocation)
for (size_t i = physicalAllocations.size(); 0 < i; i -= 1 << allocationChunkSize) {
delete physicalAllocations[i - (1 << allocationChunkSize)].pData;
for (size_t a = 0; a < 1 << allocationChunkSize; a++)
physicalAllocations.pop_back();
}
clearing the vector
physicalAllocations.clear();
swapping for a clear vector
std::vector<PhysicalPage>(0).swap(physicalAllocations);
of which none worked.
I've been working on this problem for a lot longer that I would like to admit and your help is very much appreciated. Thanks!
| std::shared_ptr<char[]> pData and its aliasing constructor (8) might help. (that might even allow to get rid of PageStatus).
It would look something like:
constexpr std::size_t page_size = 6;
struct PhysicalPage {
std::shared_ptr<char[]> pData;
};
int main()
{
std::vector<PhysicalPage> pages;
{
std::shared_ptr<char[]> big_alloc = std::unique_ptr<char[]>(new char[42]{"hello world. 4 8 15 16 23 42"});
for (std::size_t i = 0; i != 42 / page_size; ++i) {
pages.push_back(PhysicalPage{std::shared_ptr<char[]>{big_alloc, big_alloc.get() + i * page_size}});
}
}
pages.erase(pages.begin());
pages.erase(pages.begin() + 2);
for (auto& p : pages) {
std::cout << std::string_view(p.pData.get(), page_size) << std::endl;
}
}
Demo
|
70,155,168 | 70,155,250 | Why my code is giving Time Limit Exceeded? | Today while solving a question on leetcode, I applied dfs on a directed graph which runs on O(N) time, but my code is giving TLE, so after trying too many time I checked on comments and there was a accepted code which also runs on O(N). So now I am confused as why my code is not getting accepted and giving time limit exceeded.
My code:-
public:
int ans=INT_MIN;
vector<vector<int>> gr;
void dfs(int head, int time, vector<int> inform){
if(gr[head].size()==0) {ans=max(ans,time);return;}
for(auto next:gr[head]){
dfs(next, inform[head]+time, inform);
}
}
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
gr.resize(n);
for(int i=0 ; i<n ; i++){
if(manager[i]!=-1) gr[manager[i]].push_back(i);
}
dfs(headID,0, informTime);
return ans;
}
One of accepted code:-
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
int res = 0;
for (int i = 0; i < n; ++i)
res = max(res, dfs(i, manager, informTime));
return res;
}
int dfs(int i, vector<int>& manager, vector<int>& informTime) {
if (manager[i] != -1) {
informTime[i] += dfs(manager[i], manager, informTime);
manager[i] = -1;
}
return informTime[i];
}
If anyone needs question link:-
https://leetcode.com/problems/time-needed-to-inform-all-employees/
| In your dfs() function, you pass inform by value, which means the compiler makes a copy of inform every time you call the function, not the inform itself.
You should pass by reference instead.
void dfs(int head, int time, vector<int> &inform)
|
70,155,255 | 70,155,661 | Print method for variadic template pairs in C++ | I want to achieve something like:
export_vars("path/to/file.dat", {"variable_name", obj}, {"another_variable", 2});
where obj can be any type as long as it has an << overload - the idea is to write to an ofstream later on. I have tried (for an initializer_list of pairs):
void
export_vars(const std::string& path, std::initializer_list<std::pair<std::string, std::any>> args)
{
for (auto& [name, var] : args)
std::cout << name << ": " << var << std::endl;
}
but std::any cannot be << without knowing the underlying type. Can it maybe be achieved using variadic templates and parameter pack expansion? I also tried something like:
template <class... Args>
void
export_vars(const std::string& path, Args... args)
{
(std::cout << ... << args.first << args.second) << std::endl;
}
but that's obviously wrong. Any suggestions?
| {..} has no type, and so disallows most deduction.
Several work arounds:
Change call to use std::pair explicitly:
template <typename ... Pairs>
void export_vars(const std::string&, const Pairs&... args)
{
((std::cout << args.first << ": " << args.second << std::endl), ...);
}
int main()
{
export_vars("unused", std::pair{"int", 42}, std::pair{"cstring", "toto"});
}
Demo
Don't use template:
void export_vars(const std::string&,
const std::initializer_list<std::pair<std::string, Streamable>>& args)
{
for (const auto& [name, value] : args) {
std::cout << name << ": " << value << std::endl;
}
}
int main()
{
export_vars("unused", {{"int", 42}, {"cstring", "toto"}});
}
with Streamable using type-erasure, possibly something like:
class Streamable
{
struct IStreamable
{
virtual ~IStreamable() = default;
virtual void print(std::ostream&) = 0;
};
template <typename T>
struct StreamableT : IStreamable
{
StreamableT(T t) : data(std::forward<T>(t)) {}
virtual void print(std::ostream& os) { os << data; }
T data;
};
std::unique_ptr<IStreamable> ptr;
public:
template <typename T>
// Possibly some concepts/SFINAE as requires(is_streamable<T>)
Streamable(T&& t) : ptr{std::make_unique<StreamableT<std::decay_t<T>>>(t)} {}
friend std::ostream& operator << (std::ostream& os, const Streamable& streamable)
{
streamable.ptr->print(os);
return os;
}
};
Demo
|
70,155,379 | 70,155,448 | Template argument deduction fails on C++14 | I was trying to compile this code but it fails on C++14 while it works on C++17
#include <cstdio>
#include <utility>
template <typename F>
struct S {
explicit S(F&& fn): fn(std::move(fn)) {}
F fn;
~S() { fn(); }
};
int main(){
S obj([]() noexcept {
std::printf("Foo\n");
});
}
I see that in C++17 the constructor of S has been invoked as
call S<main::{lambda()#1}>::S(main::{lambda()#1}&&)
which indicates that the compiler deduced the template argument. Is there a way to get this code compiling in C++14 other than doing something as follows?
auto fn = []() noexcept {
std::printf("Foo\n");
};
S<decltype(fn)> obj(std::move(fn));
| Class template argument deduction (CTAD) was only introduced in C++17 . You can deduce the argument with a function:
template <typename F>
S<F> make_S(F&& fn) { return S<F>{std::forward<F>(fn)}; }
int main(){
auto obj = make_S([]() noexcept {
std::printf("Foo\n");
});
}
|
70,155,743 | 70,158,391 | How to use Vec2w in Opencv Python | I have this part of code working in C++
Mat mapFrame5(Size(321,262), CV_16UC2);
for (int y = 0; y < mapFrame5.rows; y++) {
for (int x = 0; x < mapFrame5.cols; x++) {
mapFrame5.at<Vec2w>(y, x) = Vec2w(y, x);
cout<<mapFrame5.at<Vec2w>(y,x);
}
}
I have a hard time finding if there is equivalent of this expression in Python:
mapFrame5.at<Vec2w>(y, x) = Vec2w(y, x);
I tried following as suggested:
testArr2 = np.zeros([262,321], np.uint16)
y,yy = 0,0
byteCount = 0
while yy < 262:
x,xx = 0,0
while xx < 321:
testArr2[yy,xx] = [yy,xx]
xx+=1
x+=1
byteCount+=1
yy+=1
y+=1
But it gives me only this error:
builtins.TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'
For clearence I'm trying to save y,x values to little endian binary file.
Example:
y = 0
0 0 0 1 0 2 0 3 ... 0 320
y = 261
261 0 261 1 261 2 ... 261 320
C++ file gives me exacly 336408 bytes
| The naive approach would be to just transcribe the algorithm to Python:
def gen_grid_1(rows, cols):
result = np.zeros((rows, cols, 2), np.uint16)
for r in range(rows):
for c in range(cols):
result[r,c,:] = [r, c]
return result
Example output for 3 rows and 5 columns:
[[[0 0]
[0 1]
[0 2]
[0 3]
[0 4]]
[[1 0]
[1 1]
[1 2]
[1 3]
[1 4]]
[[2 0]
[2 1]
[2 2]
[2 3]
[2 4]]]
However, this approach has a serious drawback -- it will be very slow, due to Python interpreter overhead -- for your example 321x262 array, this takes almost 1 second to complete.
A better approach is to restate the goal of the algorithm, and reimplement using optimized functions provided by Numpy.
What we want to generate is a 2 channel array of 16-bit unsigned integers, where the first channel of each element holds its row index, and the second channel holds the column index.
This sounds very close to what the numpy.meshgrid function does: "Return coordinate matrices from coordinate vectors."
The only catch is that it returns 2 individual arrays. We can simply use numpy.dstack to combine them into one with the channels in desired order.
def gen_grid_2(rows, cols):
cc, rr = np.meshgrid(np.arange(cols, dtype=np.uint16), np.arange(rows, dtype=np.uint16))
return np.dstack([rr,cc])
The output of this function is identical to the first, but it runs in approx. 2 milliseconds (i.e. ~500x faster than the naive approach).
Full script with timing comparisons:
import numpy as np
ROWS = 262
COLS = 321
def gen_grid_1(rows, cols):
result = np.zeros((rows, cols, 2), np.uint16)
for r in range(rows):
for c in range(cols):
result[r,c,:] = [r, c]
return result
def gen_grid_2(rows, cols):
cc, rr = np.meshgrid(np.arange(cols, dtype=np.uint16), np.arange(rows, dtype=np.uint16))
return np.dstack([rr,cc])
assert(np.array_equal(gen_grid_1(ROWS, COLS), gen_grid_2(ROWS, COLS)))
import timeit
print(timeit.timeit('r1 = gen_grid_1(ROWS, COLS)'
, number=10
, setup="from __main__ import gen_grid_1, ROWS, COLS"))
print(timeit.timeit('r1 = gen_grid_2(ROWS, COLS)'
, number=10
, setup="from __main__ import gen_grid_2, ROWS, COLS"))
|
70,156,026 | 70,156,680 | C++ Template method return ref to private map value where value's type is parent of T | I have a problem blowing my mind actually, and a challenge for someone, could you help me with that ? :
class UItemEntity : public UObject
{
GENERATE_BODY()
public:
template<typename T=FItemComponent>
T& GetComponent()
{
auto Result = Components[TYPE_ID(T)];
T Comp = reinterpret_cast<T>(Result);
return Comp;
}
private:
/** Map from Component's type ID to one of their instance associated to this entity. */
TMap<const char*, FItemComponent> Components;
}
(It's Unreal c++ code but still c++ :P)
Example of usage :
struct FTestComponent : public FItemComponent { }
UItemEntity* Item;
FTestComponent& Comp = Item->GetComponent<FTestComponent>();
I cannot figure out how to cast the value retrieved from the map... I tried static, dynamic and reinterpret cast but none succeeded.
Here is the kind of error I have :
ItemEntity.h: [C2440] 'reinterpret_cast': cannot convert from 'ValueType' to 'T'
It might be an architecture problem, but I don't know how to work around :/ And I really need a GetComponent on this ItemEntity.
Thanks !
EDIT :
With the help of @Frank, I finally succeed in, there was some Unreal stuff to take into account.
Here it is :
class UItemEntity : public UObject
{
GENERATE_BODY()
public:
template<typename T=FItemComponent>
T& GetComponent()
{
const bool IsItemComponentType = std::is_base_of_v<FItemComponent, T>;
check(IsItemComponentType);
FItemComponent* ItemComp = *Components.Find(TYPE_ID(T));
return Cast<T>(ItemComp);
}
private:
/** Map from Component's type ID to one of their instance associated to this entity. */
TMap<const char*, FItemComponent*> Components;
}
| There may be some Unreal-specific shenanigans at play that I'm not aware of, but in general-purpose C++ code, it would look like this:
class UItemEntity : public UObject
{
GENERATE_BODY()
public:
template<typename T>
T& GetComponent()
{
static_assert(std::is_base_of_v<FItemComponent, T>);
return *static_cast<T*>(Components.at(TYPE_ID(T)).get());
}
private:
/** Map from Component's type ID to one of their instance associated to this entity. */
TMap<const char*, std::unique_ptr<FItemComponent>> Components;
}
Explanation:
Elements are stored as pointers since different types can be stored in it.
at() is used because there is nothing the function can return if the entry is missing.
static_cast<> lets the compiler known that the casting from base to derived is intentional.
The pointer is dereferenced into a reference with *.
I replaced the default template parameter with a static_assert(), according to the discussion in the comments.
You may want to use std::shared_ptr, std::weak_ptr, std::reference_wrapper or even a raw pointer instead of std::unique_ptr depending on the circumstances. However, it's hard to tell which is the correct one without some more context, so I used the baseline unique_ptr for this example.
|
70,156,721 | 70,156,767 | Can C++ deduce argument type from default value? | I tried to write this function with a default template argument:
template<typename A, typename B>
void func(int i1, int i2, A a, B b = 123){
...
}
In my mind I can call it like this: func(1, 2, 3) and compiler should deduce type B as int from default value, but I get no instance of overloaded function.
Is it incorrect C++ construction and compiler can't deduce type in this case?
| The type of a template parameter in a function can't be deduced from a default argument. As shown in the example on cppreference.com:
Type template parameter cannot be deduced from the type of a function
default argument:
template<typename T> void f(T = 5, T = 7);
void g()
{
f(1); // OK: calls f<int>(1, 7)
f(); // error: cannot deduce T
f<int>(); // OK: calls f<int>(5, 7)
}
However, you can specify a default argument for the template parameter:
template<typename A, typename B = int>
void func(int i1, int i2, A a, B b = 123){
...
}
|
70,156,751 | 70,158,665 | counting number of elements less than X in a BST | I had implemented a BST for a multiset using the C++ code below, whereas each node contains the number of occurrence num of each distinct number data, and I try to find the number of elements less than certain value x, using the order function below.
It works, however, inefficient in terms of execution time.
Is there any method with better time complexity?
struct Node {
int data;
int height;
int num;
Node *left;
Node *right;
};
int order(Node *n, int x) {
int sum = 0;
if (n != NULL) {
if (n->data < x) {
sum += n->num;
sum += order(n->right, x);
}
sum += order(n->left, x);
}
return sum;
}
| You can bring the algorithm down to O(logN) time by storing in each node the number of elements in the subtree of which it is the root. Then you'd only have to recurse on one of the two children of each node (go left if x < node->data, right if x > node->data), which if the tree is balanced only takes logarithmic time.
struct Node {
int data;
int height;
int num;
int size; // numer of elements in the subtree starting at this node
Node *left;
Node *right;
};
int order(Node *n, int x) {
if(n == NULL) return 0;
// elements less than n->data make up the whole left subtree
if (x == n->data) {
return n->left ? n->left->size : 0;
}
// even smaller? just recurse left
else if (x < n->data) {
return order(n->left, x);
}
// bigger? take the whole left subtree and part of the right one
else {
return (n->left ? n->left->size : 0) + order(n->right, x);
}
}
Of course, now you have to keep track of the size, but this can be done very efficiently when updating the tree: simply recalculate the size (n->left->size + n->right->size + 1) of each modified node in an insertion or deletion.
|
70,156,844 | 70,156,983 | Cpp/ C++ unique Pointer on objects access functions of that class | How do I access functions via a unique pointer pointing on an object of that class
struct foo
{
foo(int);
void getY();
};
int main()
{
foo f1(1);
f1.getY();
std::unique_ptr<foo> ptr1 = make_unique<foo>(2);
*ptr1.getY(); // Error
};
foo has a constructor with an int as argument,getY() just prints out that int value.
Obviously foo f1(1); f1.getY(); works but idk how to access getY() over the pointer. unique_ptr<foo> ptr1 = make_unique<foo>(2); *ptr1.getY();
was my initial idea, but it doesn't work.
| The problem is that due to operator precedence when you wrote *ptr1.getY();, it was equivalent to writing:
*(ptr1.getY());
So this means you're trying to call a member function named getY on the smart pointer ptr1 but since ptr1 has no member function called getY you get the error.
To solve this you should write:
( *ptr1 ).getY();//works now
This time you're specifically asking/grouping *ptr together and then calling the member function getY on the resulting object . And since the resulting object is of type foo which has a member function getY, this works.
|
70,156,906 | 70,157,082 | Is there a way to get the index of an array struct in its function without parameters? | As the title says and without any additional parameters in Request() while keeping it clean. Below is an example:
struct CPerson
{
void Request();
}
void CPerson::Request()
{
// get index
/* EXAMPLES
serverinfo* info;
server.GetInfo(&info, index);
cout << info.username << "\n";
*/
}
CPerson person[64];
int main()
{
for (int i = 0; i < 64; i++)
person[i].Request(); // i = current index
return 0;
}
edit: fixed title
| In this specific case, as long as you can guarantee that CPerson is only ever stored in this array, you can use std::distance() to get the index, since this happens to be a valid iterator into the array.
It's effectively the same thing as just doing this - person, but standard library implementations can (and often do) have additional safety nets in debug builds at no performance cost for release builds.
Even with that additional safety, manual error checking to validate the assumption that this is part of person is still a good idea. For this, you'll want to use std::less (as opposed to the relational operators), as it's guaranteed to be globally valid even for pointers that are not inside the array.
// C++11 and up.
#include <iterator>
#include <stdexcept>
struct CPerson
{
void Request();
};
CPerson person[64];
void CPerson::Request()
{
// possibly an assert() instead...
if(std::less<CPerson*>{}(this, std::begin(person)) ||
!std::less<CPerson*>{}(this, std::end(person))) {
throw std::out_of_range("not part of person");
}
std::size_t index = std::distance(std::begin(person), this);
}
In C++20, you can be cleanly more generic about it, which will let person be any contiguous range, like std::vector for example:
// C++20 and up.
#include <ranges>
#include <stdexcept>
#include <vector>
struct CPerson
{
std::size_t Index() const;
void Request();
};
CPerson person[64];
// Or possibly
// std::vector<CPerson> person;
std::size_t CPerson::Index() const
{
static_assert(std::ranges::contiguous_range<decltype(person)>);
const CPerson* person_b = std::to_address(std::ranges::begin(person));
const CPerson* person_e = std::to_address(std::ranges::end(person));
if(std::less{}(this, person_b) ||
!std::less{}(this, person_e)) {
throw std::out_of_range("not part of person");
}
return std::distance(person_b, this);
}
void CPerson::Request() {
auto i = Index();
}
|
70,157,208 | 70,157,232 | Why PyCallable_Check() returns 0 on global class instances? | Rigth now I'm working on embedding python into a larger C++ application. Despite I'm not a python specialist, I understand that with the builtin PyCallable_Check() I can check if a python object is actually callable. From What is a "callable"? I found that it depends on an available __call__ method within classes or on types that have a non null tp_call member.
Now whats bothering me is that if I get a object reference (in C++) to a specific global instance of some class (within the python script), PyCallable_Check() gives me 0 as return when checking this reference, even when I'm actually able to call it. And since this is possible I would suppose having a tp_call member here (since I've got no __call__ method in my example).
So what am I missing? Why am I getting 0 as return?
Example C++ snippet:
//...
PyObject* pModule = PyImport_Import( PyUnicode_DecodeFSDefault("testfile") );
PyObject* pGlobalObj = PyObject_GetAttrString( pModule, "globalObj" );
int ok = PyCallable_Check(pGlobalObj)
if( !ok )
{
std::cerr << "Not a callable?!" << std::endl;
std::cerr << "PyCallable_Check() gives: " << ok << std::endl;
}
//call class method anyway...
PyObject* pValue = PyObject_CallMethod( pGlobalObj , "add", "(ii)", 45, 55 );
std::cout << "Global object result: " << PyLong_AsLong(pValue) << std::endl;
//...
with following testfile.py:
class TestClass:
def add(self, a, b):
return a + b
globalObj = TestClass()
which gives:
>> Not a callable?!
>> PyCallable_Check() gives: 0
>> Global object result: 100
| That's not a callable. You may be misunderstanding what "callable" means.
If globalObj were callable, you would be able to do globalObj(), perhaps with some appropriate arguments between the parentheses. You can't.
|
70,157,682 | 70,157,737 | How to pass a C++ Template instance to a function? | How can I pass any object of an templated class to another function in C++11?
In the snippet below passInObj does not compile because it complains about Printer&. I want to pass in any Printer it does not matter which template T I have used.
How can I do this and why does the solution below not work?
#include <iostream>
#include <vector>
template <typename T>
class Printer {
public:
Printer(const T& tl) : t(tl) {}
void print() const {
for (auto x : t) {
std::cout << x << std::endl;
}
}
const T &t;
};
// THIS LINE DOES NOT COMPILE
void passInObj(const Printer& p) {
p.print();
}
int main() {
std::vector<std::string> vec;
vec.push_back("ABC");
Printer<std::vector<std::string>> printer(vec);
printer.print();
passInObj(p);
return 0;
}
|
How can I do this
You need to make it into a function template:
template <class T>
void passInObj(const Printer<T>& p) {
p.print();
}
Demo
and why does the solution below not work?
Because Printer is not a type, it's only a template. For passInObj to work with any Printer<T>, you need to make the function into a function template so that it'll be instantiated for every Printer<T> which is used to call it.
|
70,157,934 | 70,158,133 | Pass in unique pointer for inherited class to constructor with unique pointer for base class? | Is it possible to do the following: I have an inherited class B from base class A. I want to create a constructor for a method that takes in a unique pointer to class A but still accept unique pointers to class B, similar to pointer polymorphism.
void Validate(unique_ptr<A> obj) {obj->execute();}
...
unique_ptr<B> obj2;
Validate(obj2);
This doesn't seem to work as I've written it (I get a No matching constructor for initialization error), but I wonder if this is still possible?
| Your issue doesn't really have anything to do with polymorphism, but rather how unique_ptr<> works in general.
void Validate(unique_ptr<A> obj) means that the function will take ownership of the passed object. So, assuming that this is what the function is meant to do, you need to handoff said ownership as you call it.
In the code you posted, you would do this by moving the existing std::unique_ptr<>. This will ultimately (as in not by the call to std::move() itself, but the handoff as a whole) null-out the original pointer. That's the whole point of unique_ptr<> after all: There can only be one of them pointing at a given object.
void Validate(unique_ptr<A> obj) {obj->execute();}
...
unique_ptr<B> obj2;
Validate(std::move(obj2));
// obj2 is now null.
By extension, if Validate() is not meant to take ownership of obj, then it should not accept a unique_ptr<> in the first place. Instead, it should accept either a reference or a raw pointer depending on whether nullptr is an expected valid value:
Ideally:
void Validate(A& obj) {
obj.execute();
}
...
unique_ptr<B> obj2;
Validate(*obj2);
Alternatively:
void Validate(A* obj) {
if(obj) {
obj->execute();
}
}
...
unique_ptr<B> obj2;
Validate(obj2.get());
|
70,158,738 | 70,163,046 | Creating a QListIterator over a temporary object? | Currently I'm doing some code reviews and stumbled on the following construct:
QVariantMap argumentMap = QJsonDocument::fromJson(" ... JSON-String ... ", &error).toVariant().toMap();
...
QListIterator<QVariant> keyIterator( argumentMap["key"].toList() );
while ( keyIterator.hasNext() ) ...
My first feeling was that the iterator is faulty here, as toList() returns a QVariantList by value resulting in a temporary object.
So the Ctor is defined as QListIterator(const QList<T> &list) and we found this [1]: "It is an official C++ feature to extend the life time of a temporary object to the life time of the const reference which refers to it." But first my argument was that life time of the const reference to the list is bound to the Ctor.
So I tried to dig deeper into the definition of QListIterator [2]:
Q_DECLARE_SEQUENTIAL_ITERATOR(List)
#define Q_DECLARE_SEQUENTIAL_ITERATOR(C) \
\
template <class T> \
class Q##C##Iterator \
{ \
typedef typename Q##C<T>::const_iterator const_iterator; \
Q##C<T> c; \
const_iterator i; \
public: \
inline Q##C##Iterator(const Q##C<T> &container) \
: c(container), i(c.constBegin()) {} \
Now, I'm really confused! :) It seems that with the c member the Iterator holds it's own local copy of the list. So finally, I would say this usage is absolutely valid. Could someone please confirm this?
Plus, this construct is used all over the application and apparently never caused any problems.
Short addendum:
I found also this here [3]: "If you want to iterate over these using an STL iterator, you should always take a copy of the container and iterate over the copy. For example:"
// WRONG
QList<int>::const_iterator i;
for (i = splitter->sizes().begin(); i != splitter->sizes().end(); ++i)
First I thought this is the exact same problem, but on a second thought I would now say that the problem here is that begin() and end() are called on different copies of the list. Correct?
[1] https://blog.galowicz.de/2016/03/23/const_reference_to_temporary_object/
[2] https://code.woboq.org/qt5/qtbase/src/corelib/tools/qiterator.h.html
[3] https://doc.qt.io/qt-5/containers.html#stl-style-iterators
| The QListIterator should be fine, since it takes a copy of the list.
What you are referring to by the lifetime extension of temporaries is this:
{
auto const & myRef = foo.bar(); // returns by value so it returns a temporary
// you would expect the temporary to be gone now
// and myRef thus being a dangling reference, but it is not!
myRef.doSomething(); // perfectly fine
}
// now that myRef is out of scope also the temporary is destroyed
See here for a description of lifetimes.
However that is not relevant in this case because this mechanism can not extend the lifetime of a temporary to the lifetime of an object but only to the lifetime of a reference.
And yes, the last example is wrong for exactly the reason you gave: Comparing iterators to different (temporary) objects.
|
70,159,251 | 70,176,499 | Jinja2cpp valueMap param multiple items 'no matching function for call' error | I have build jinja2cpp from code. compiled libraries and everything.
int main() {
string source = R"(
My name is {{myName}}
)";
jinja2::Template tpl;
jinja2::ValuesMap params {{"myName", "Mehmet"}};
tpl.Load(source);
string result = tpl.RenderAsString(params).value();
cout << result;
return 0;
}
console output: My name is Mehmet
But when I tried to compile code snippet.(simplified version of enum2StringConvertor in https://github.com/jinja2cpp/Jinja2Cpp/wiki). It is compile
int main() {
string source = R"(
{% for user in users %}
{{user}}
{% endfor %}
)";
jinja2::Template tpl;
jinja2::ValuesMap params {{"users", {"John", "Joe"}}}; //<<<<---THIS IS WRONG SOMEHOW
tpl.Load(source);
string result = tpl.RenderAsString(params).value();
cout << result;
return 0;
}
console output:
18:54:24 **** Incremental Build of configuration Debug for project jinjaRender ****
make all
Building file: ../src/jinjaRender.cpp
Invoking: GCC C++ Compiler
g++ -I"/home/mehmet/eclipse-workspace/jinjaRender/include" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/jinjaRender.d" -MT"src/jinjaRender.o" -o "src/jinjaRender.o" "../src/jinjaRender.cpp"
../src/jinjaRender.cpp: In function ‘int main()’:
../src/jinjaRender.cpp:31:57: error: no matching function for call to ‘jinja2::ValuesMap::ValuesMap(<brace-enclosed initializer list>)’
31 | jinja2::ValuesMap params {{"users", {"John", "Joe"}}};
| ^
In file included from /usr/include/c++/9/unordered_map:47,
from /home/mehmet/eclipse-workspace/jinjaRender/include/jinja2cpp/value.h:12,
from /home/mehmet/eclipse-workspace/jinjaRender/include/jinja2cpp/error_info.h:5,
from /home/mehmet/eclipse-workspace/jinjaRender/include/jinja2cpp/template.h:5,
from ../src/jinjaRender.cpp:2:
/usr/include/c++/9/bits/unordered_map.h:151:7: note: candidate: ‘std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map(std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type, const hasher&, const key_equal&, const allocator_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = jinja2::Value; _Hash = std::hash<std::__cxx11::basic_string<char> >; _Pred = std::equal_to<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, jinja2::Value> >; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type = long unsigned int; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::hasher = std::hash<std::__cxx11::basic_string<char> >; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::key_equal = std::equal_to<std::__cxx11::basic_string<char> >; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::allocator_type = std::allocator<std::pair<const std::__cxx11::basic_string<char>, jinja2::Value> >]’
151 | unordered_map(size_type __n,
Could you help me? Why this happens?. How to compile this simple program :) Appreciated
| This works:
jinja2::ValuesMap params {{"users", jinja2::ValuesList({"John", "Joe"})}};
|
70,159,423 | 70,159,654 | forward with remove_reference in template function parameter type | This page states the following:
Given that we have the following factory template function:
template<typename T, typename Arg>
shared_ptr<T> factory(Arg&& arg)
{
return shared_ptr<T>(new T(forward<Arg>(arg)));
}
One can choose among any of the two forward implementations:
forward implementation using remove_reference
template<class S>
S&& forward(typename remove_reference<S>::type& a) noexcept
{
return static_cast<S&&>(a);
}
forward implementation without remove_reference
template<class S>
S&& forward(S& a) noexcept
{
return static_cast<S&&>(a);
}
In the tutorial, it's mentioned that:
If you want to dig a little deeper for extra credit, ask yourself this
question: why is the remove_reference in the definition of
std::forward needed? The answer is, it is not really needed at all. If
you use just S& instead of remove_reference::type& in the defintion
of std::forward, you can repeat the case distinction above to convince
yourself that perfect forwarding still works just fine. However, it
works fine only as long as we explicitly specify Arg as the template
argument of std::forward. The purpose of the remove_reference in the
definition of std::forward is to force us to do so.
Why does using remove_reference forces us to specify Arg as the template arg, are there any concrete examples where the difference is illustrated? The code appears to be the same since in both instances of forward, the type is derived from the template argument. I am also new to c++ so sorry if i am missing something obvious here.
|
Why does using remove_reference forces us to specify Arg as the
template arg
Because having a nested type remove_reference<S>::type as an argument makes a non-deducible context.
This applies for any nested type. For example, if you have
template< class T>
struct Identity
{
using type = T;
};
template< class T> void foo(T&){}
template< class T> void bar(typename Identity<T>::type&){}
then
int x;
foo(x);
bar<int>(x);
will compile, but
int x;
bar(x);
will not.
|
70,159,945 | 70,160,181 | [C++][ QT ] is not meant to be copied. Pass it by move instead | I am a beginner in C++. And I don't understand this error. I just need you to explain me.
I try to show a .sqlite database in a QTableview. The problem come from:
model->setQuery(*qry);
I want to use a function called setQuery but in first argument, I set an object with *QSqlQuery type. And this error show up.
ERROR Pics
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlDatabase>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QSqlDatabase DB;
QSqlQueryModel* model;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
DB = QSqlDatabase::addDatabase("QSQLITE");
DB.setDatabaseName("Prices.sqlite");
if (DB.open()) {
qDebug() << "Open";
model = new QSqlQueryModel();
QSqlQuery* qry = new QSqlQuery(DB);
qry->prepare("SELECT * FROM Prices");
qry->exec();
model->setQuery(*qry);
ui->tableView->setModel(model);
qDebug() << "Rows: " << model->rowCount();
DB.close();
}
else {
qDebug() << "Failed connection";
}
}
| They want you to move the object behind qry into the function.
The shortest change would be to replace
model->setQuery(*qry);
with
model->setQuery(std::move(*qry));
delete qry;
You don't need to use new/delete in this case though. Just using automatic storage duration works:
QSqlQuery qry(DB);
qry.prepare("SELECT * FROM Prices");
qry.exec();
model->setQuery(std::move(qry));
Then you don't have to worry about forgetting to delete it.
Alternatively, since the QSqlQuery object is not used anywhere else, it might be best to chose the other overload for setQuery like this:
model = new QSqlQueryModel();
model->setQuery("SELECT * FROM Prices", DB);
ui->tableView->setModel(model);
|
70,160,138 | 70,161,667 | Unresolved External Symbol LNK2019 CMake | I have here a class called engine and im trying to use, but when i include it i get LNK2019 error. Im running Visual Studio 2019 x86_64 compiler. Any ideas what could be wrong?
I have constructor and destructor defined in cpp file.
#pragma once
namespace NRD {
const int SCREEN_WIDTH(1280);
const int SCREEN_HEIGHT(720);
class Engine {
public:
Engine();
Engine(const Engine&) = delete;
Engine& operator=(const Engine&) = delete;
~Engine();
static Engine& Ref() {
static Engine reference;
return reference;
}
};
static Engine& Core = Engine::Ref();
}
Here is my cpp file:
#include "nrdengine/engine.h"
#include "nrdengine/service_locator.h"
#include "platform/glfw_window.h"
#include <iostream>
namespace NRD {
Engine::Engine() {
std::cout << "Initializing window!" << std::endl;
ServiceLocator::Provide(new CustomWindow());
}
Engine::~Engine() {
ServiceLocator::GetWindow()->DestroyWindow();
}
}
[build] main.obj : error LNK2019: unresolved external symbol "public: __cdecl NRD::Engine::Engine(void)" (??0Engine@NRD@@QEAA@XZ) referenced in function "public: static class NRD::Engine & __cdecl NRD::Engine::Ref(void)" (?Ref@Engine@NRD@@SAAEAV12@XZ) [C:\Users\Dawid\Desktop\NRD-Engine\build\nrdengine_cpp_application.vcxproj]
[build] main.obj : error LNK2019: unresolved external symbol "public: __cdecl NRD::Engine::~Engine(void)" (??1Engine@NRD@@QEAA@XZ) referenced in function "void __cdecl `public: static class Engine::Ref & __cdecl NRD::Engine::Ref(void)'::`2'::`dynamic atexit destructor for 'reference''(void)" (??__Freference@?1??Ref@Engine@NRD@@SAAEAV12@XZ@YAXXZ) [C:\Users\Dawid\Desktop\NRD-Engine\build\nrdengine_cpp_application.vcxproj]
[build] C:\Users\Dawid\Desktop\NRD-Engine\build\Debug\nrdengine_cpp_application.exe : fatal error LNK1120: 2 unresolved externals [C:\Users\Dawid\Desktop\NRD-Engine\build\nrdengine_cpp_application.vcxproj]
I have two CMakeList files (one for Engine project, one for App)
APP:
cmake_minimum_required(VERSION 3.5)
project(nrdengine_cpp_application VERSION 0.0.1 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
add_subdirectory(external/engine)
file(GLOB_RECURSE SOURCE_FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/*.c
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp)
#nrdengine_cpp_application.exe
add_executable(nrdengine_cpp_application ${SOURCE_FILES})
target_link_libraries(nrdengine_cpp_application PUBLIC nrdengine_cpp_engine)
target_include_directories(nrdengine_cpp_application PUBLIC nrdengine_cpp_engine)
ENGINE:
cmake_minimum_required(VERSION 3.5)
project(nrdengine_cpp_engine VERSION 0.0.1 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 17)
#add external libs
#find_package(OpenGL REQUIRED)
# install python and Jinja2
set(GLAD_SOURCES_DIR "${PROJECT_SOURCE_DIR}/external/glad")
add_subdirectory("${GLAD_SOURCES_DIR}/cmake" glad_cmake)
add_subdirectory(external/glfw)
add_subdirectory(external/glm)
add_subdirectory(external/assimp)
file(GLOB_RECURSE SOURCE_FILES
${CMAKE_SOURCE_DIR}/src/*.c
${CMAKE_SOURCE_DIR}/src/*.cpp)
glad_add_library(glad_gl_core_mx_31 REPRODUCIBLE MX API gl:core=3.1)
add_library(nrdengine_cpp_engine ${SOURCE_FILES})
target_include_directories(nrdengine_cpp_engine
PUBLIC
$<INSTALL_INTERFACE:include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
glm
PRIVATE
glfw
assimp
)
target_link_libraries(${PROJECT_NAME}
PUBLIC
glm
PRIVATE
glad_gl_core_mx_31
glfw
assimp
)```
| I'm kinda guessing since your question is kinda hard to answer since it could be a lot of things. But here is my inference.
It's not recommended to glob your source files like you are doing here.
file(GLOB_RECURSE SOURCE_FILES
${CMAKE_SOURCE_DIR}/src/*.c
${CMAKE_SOURCE_DIR}/src/*.cpp)
NOTE: My suggestion requires 3.13 or higher version of CMake.
This causes lots of issues and might be the cause of your problems. Please see this post by one of the CMake maintainers on how to add source files to your project.
https://crascit.com/2016/01/31/enhanced-source-file-handling-with-target_sources/
TLDR:
Make a CMakeLists.txt in your src/ directory like so.
target_sources(foobar PRIVATE
engine.cpp
engine.h
)
And make sure to call add_subdirectory(src) to process that new CMakeLists.txt
If you are interested in why globbing in build systems in general is bad. I can provide links.
|
70,160,171 | 70,160,325 | Read binary data from PLY file using Qt | Im trying to read data from this file:
Which contains both ascii text and float numbers stored in binary. I'm trying to read it by doing the following:
QTextStream in(file);
QString line;
line = in.readLine();
while (!line.startsWith(QString("element vertex"))) {
line = in.readLine();
}
point_count = line.split(QString(" ")).last().toInt();
qDebug() << "PC: " << point_count;
while (line != "end_header") {
line = in.readLine();
}
QDataStream* stream = new QDataStream(file);
stream->skipRawData(in.pos());
stream->setFloatingPointPrecision(QDataStream::SinglePrecision);
float number;
(*stream) >> number;
qDebug() << "Float: " << number;
But I read -1.98117e+13, which I guess it is wrong, what am I doing wrong?
| The default byte order for QDataStream is big endian; change it to little endian:
stream->setByteOrder(QDataStream::LittleEndian)
|
70,161,258 | 70,161,302 | Width and setfill('-') in cpp | I am new to C++ and am wondering if there is a more elegant way to print out the following:
Celsius Kelvin Fahrenheit Reaumur
-------------------------------------
I guess you could just do
cout << "Celsius Kelvin Fahrenheit Reaumur" << endl << "-------------------------------------";
But it doesn't look good. In Ada you could do "Width". Is there a similiar operator in cpp? And can you not just do setfill('-') and the amount of '-' you want to print out?
Any help is greatly appreciated
| Here are two other ways to produce this line:
std::cout << "-------------------------------------\n";
std::setfill + std::setw:
#include <iomanip>
std::cout << std::setfill('-') << std::setw(38) << '\n';
Using a std::string:
#include <string>
std::cout << std::string(37, '-') << '\n';
Demo
|
70,161,402 | 70,161,839 | Multilingual C++ program | How can I add multilanguage support to a C++ program? I want to let the user to choose between 2 languages when opening the app. What's the simplest way without any external libraries?
| Replying to my comment,
"You could make a dictionary where it's key is an enum representing a word, then the values could be an array of structures containing the language and actual string in that language. Example: (pseudo code) dictionary: - WORD1_ENUM => structure[LANGUAGE1_ENUM, WORD_IN_LANGUAGE1], structure[LANGUAGE2_ENUM, WORD_IN_LANGUAGE2]",
you could make a dictionary that retrieves your world based on the selected language.
#include <initializer_list>
#include <string>
#include <vector>
#include <iostream>
enum STRINGS
{
HELLO_WORLD,
GOODBYE_WORLD
};
#define SELECTED_LANGUAGE SLOVENIAN
#define NOT_FOUND_STR "Not Found"
enum LANGUAGE
{
ENGLISH,
SLOVENIAN
};
struct DICTIONARY_VAL
{
LANGUAGE lang;
std::string text;
};
struct DICTIONARY_BLOCK_t{
STRINGS key;
std::vector<DICTIONARY_VAL> values;
};
class DICTIONARY_t
{
private:
std::vector<DICTIONARY_BLOCK_t> data;
public:
DICTIONARY_t (std::initializer_list<DICTIONARY_BLOCK_t> var)
{
for (DICTIONARY_BLOCK_t val : var)
{
data.push_back(val);
}
}
std::string get_value(STRINGS key, LANGUAGE lang)
{
std::string l_ret = NOT_FOUND_STR;
for (uint32_t i = 0; i < data.size() ; i++)
{
if (data[i].key == key)
{
for (uint32_t j = 0; j < data[i].values.size(); j++)
{
if (data[i].values[j].lang == lang)
{
l_ret = data[i].values[j].text;
break;
}
}
break;
}
}
return l_ret;
}
};
DICTIONARY_t dict =
{
{HELLO_WORLD, { {ENGLISH, "Hello World"}, {SLOVENIAN, "Zivjo svet" } }},
{GOODBYE_WORLD, { {ENGLISH, "Goodbye World"}, {SLOVENIAN, "Nasvidenje svet"} }}
};
int main()
{
LANGUAGE selected_language;
std::cout << "Select your lanugage\n0.) ENGLISH\n1.) Slovenian" << std::endl;
int tmp;
std::cin >> tmp;
selected_language = (LANGUAGE) tmp;
std::cout << dict.get_value(HELLO_WORLD, selected_language) << std::endl;
return 0;
}
|
70,161,555 | 70,161,666 | How properly use SetMenuItemBitmaps to replace the default bitmap on a menu item? | I'm trying to change the default bitmap on a menu item. Unfortunately, I'm not getting it to work.
The documentation of SetMenuItemBitmaps() states that I should use the GetSystemMetrics() function with the SM_CXMENUCHECK and SM_CYMENUCHECK values to retrieve the default bitmap dimensions. I adjusted the .bmp file to these values, but it is still not working.
I probably have misunderstood something about the SetMenuItemBitmaps() function.
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
SetMenuItemBitmaps(GetMenu(hWnd), ID_RED, MF_BYCOMMAND, LoadBitmap(hInst, L"red.bmp"), LoadBitmap(hInst, L"red.bmp"));
return 0;
}
[...]
}
The menu item with the ID_RED id, whose bitmap I want to change:
| You need the HMENU handle of the menu that the red item directly belongs to. You are using the top-level HMENU, but red is a child item of the sub-menu of the color item, which is a child item of the sub-menu of the Menu item, which is a child item of the top-level menu.
Once you have the top-level HMENU, use GetSubMenu() or GetMenuItemInfo() to get the HMENU of the sub-menu for the Menu item, then use that handle to get the HMENU of the sub-menu for the color item, and then finally use that handle to set the bitmaps for the red item.
Also, you are not checking whether LoadBitmap() is returning NULL or not. Even if it is not, you are responsible for destroying the bitmaps when you are done using them. So, even if this code worked, you would be leaking resources.
|
70,161,557 | 70,162,881 | Bubble sort in double linked list | void sortTrain(TrainCar* head, bool ascending)
{
TrainCar* current = head;
int count = 1;
int size = (getlength(head));
if (ascending == 1)
{
for(int i = 0; i < size-1; i++)
{
while(current->next)
{
if((current->load) > ((current->next)->load))
{
swapCar(head,count,count+1);
}
count++;
current = current->next;
}
}
}
if (ascending == 0)
{
for(int i = 0; i < size-1; i++)
{
while(current->next)
{
if((current->load) < ((current->next)->load))
{
swapCar(head,count,count+1);
}
count++;
current = current->next;
}
}
}
}
Anyone helps me to fix the problem?
I don't know how to improve it.
Or any other code can do the same result?
Ascending when bool ascending is true,
otherwise, do descending.
| The main error in the code you posted is that you are not resetting current and count after each iteration of the outer loop, i.e. try the following:
// ...
if (ascending == 1)
{
for (int i = 0; i < size-1; i++)
{
TrainCar* current = head;
int count = 0;
while (current->next)
{
if ((current->load) > ((current->next)->load))
{
swapCar(head, count, count + 1);
}
count++;
current = current->next;
}
}
}
// ...
The above should work if swapCar uses zero-based indices (I also changed it such that count is initialized to zero not one : don't ever use 1-based indices in C or C++; it is just confusing to do so).
However, it is a bad design to implement swapCar as taking indices. Each call to swapCar is going to execute in O(n) time, if you know what that means. You already have current and current->next sitting there: just swap their load values, then you don't even need to maintain a count variable at all.
|
70,161,571 | 70,161,766 | Calculating color histogram of framebuffer inside compute shader | As the title suggests, I am rendering a scene onto a framebuffer and I am trying to extract the color histogram from that framebuffer inside a compute shader. I am totally new to using compute shaders and the lack of tutorials/examples/keywords has overwhelmed me.
In particular, I am struggling to properly set up the input and output images of the compute shader. Here's what I have:
computeShaderProgram = loadComputeShader("test.computeshader");
int bin_size = 1;
int num_bins = 256 / bin_size;
tex_w = 1024;
tex_h = 768;
GLuint renderFBO, renderTexture;
GLuint tex_output;
//defining output image that will contain the histogram
glGenTextures(1, &tex_output);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_output);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R16, num_bins, 3, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
glBindImageTexture(0, tex_output, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_R16UI);
//defining the framebuffer the scene will be rendered on
glGenFramebuffers(1, &renderFBO);
glGenTextures(1, &renderTexture);
glBindTexture(GL_TEXTURE_2D, renderTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, W_WIDTH, W_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindFramebuffer(GL_FRAMEBUFFER, renderFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTexture, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
In the main loop I draw a simple square onto the framebuffer and attempt to pass the framebuffer as input image to the compute shader:
glBindFramebuffer(GL_FRAMEBUFFER, renderFBO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glUseProgram(computeShaderProgram);
//use as input the drawn framebuffer
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderFBO);
//use as output a pre-defined texture image
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, tex_output);
//run compute shader
glDispatchCompute((GLuint)tex_w, (GLuint)tex_h, 1);
GLuint *outBuffer = new GLuint[num_bins * 3];
glGetTexImage(GL_TEXTURE_2D, 0, GL_R16, GL_UNSIGNED_INT, outBuffer);
Finally, inside the compute shader I have:
#version 450
layout(local_size_x = 1, local_size_y = 1) in;
layout(rgba32f, binding = 0) uniform readonly image2D img_input;
layout(r16ui, binding = 1) uniform writeonly image2D img_output;
void main() {
// grabbing pixel value from input image
vec4 pixel_color = imageLoad(img_input, ivec2(gl_GlobalInvocationID.xy));
vec3 rgb = round(pixel_color.rgb * 255);
ivec2 r = ivec2(rgb.r, 0);
ivec2 g = ivec2(rgb.g, 1);
ivec2 b = ivec2(rgb.b, 2);
imageAtomicAdd(img_output, r, 1);
imageAtomicAdd(img_output, g, 1);
imageAtomicAdd(img_output, b, 1);
}
I defined the output as a 2d texture image of size N x 3 where N is the number of bins and the 3 accounts for the individual color components. Inside the shader I grab a pixel value from the input image, scale it into the 0-255 range and increment the appropriate location in the histogram.
I cannot verify that this works as intended because the compute shader produces compilation errors, namely:
can't apply layout(r16ui) to image type "image2D"
unable to find compatible overloaded function "imageAtomicAdd(struct image2D1x16_bindless, ivec2, int)"
EDIT: after changing to r32ui the previous error now becomes: qualified actual parameter #1 cannot be converted to less qualified parameter ("im")
How can I properly configure my compute shader?
Is my process correct (at least in theory) and if not, why?
| As for your questions:
can't apply layout(r16ui) to image type "image2D"
r16ui can only be applied to unsigned image types, thus you should use uimage2D.
unable to find compatible overloaded function ...
The spec explicitly says that atomic operations can only by applied to 32-bit types (r32i, r32ui, or r32f). Thus you must use a 32-bit texture instead.
Your have other issues in your code too.
glBindTexture(GL_TEXTURE_2D, renderFBO);
You cannot bind an FBO to a texture. You should instead bind the texture that backs the FBO (renderTexture).
Also, you intend to bind a texture to an image uniform rather than a sampler, thus you must use glBindImageTexture or glBindImageTextures rather than glBindTexture. With the later you can bind both images in one call:
GLuint images[] = { renderTexture, tex_output };
glBindImageTextures(0, 2, images);
Your img_output uniform is marked as writeonly. However the atomic image functions expect an unqualified uniform. So remove the writeonly.
You can find all the above information in the OpenGL and GLSL specs, freely accessible from the OpenGL registry.
|
70,161,858 | 70,161,920 | string_view Vs const char* performance | Is a std::string_view parameter better than a const char* one in the code below?
void func( const std::string_view str )
{
std::istringstream iss( str.data( ) ); // str is passed to the ctor of istringstream
std::size_t pos { };
int num { std::stoi( str.data( ), &pos, 10 ) }; // and here it's passed to std::stoi
}
int main()
{
std::array<char, 20> buffer { };
std::cin.getline( buffer.data( ), 20 );
func( buffer.data( ) );
}
Both std::istringstream ctor and std::stoi require a const std::string& as their parameter. But I pass them a std::string_view object using its data() member function. Is this bad practice? Should I revert back to const char*?
|
But I pass them a std::string_view object using its data() member function. Is this bad practice
Yes, this is a bad practice. It's bad primarily because a string view doesn't necessarily point to a string that is null terminated. In case it doesn't, passing data() into a function that requires null termination will result in undefined behaviour.
Secondarily, there are cases where knowing the length of the string beforehand is more efficient. The length is known since it's stored in the string view. When you use data() only as an argument, you're not providing the known size to the function.
Use this instead: std::istringstream iss(std::string{str});
Should I revert back to const char*?
I see no good reason for doing so in this case.
|
70,162,888 | 70,162,958 | unexpected behavior with template function overloading | So i have the following snippet which compiles correctly:
template<typename _Tp, typename _Up = _Tp&&>
_Up
__declval(long);
//template<typename _Tp>
// _Tp
// __declval(char);
template<typename _Tp>
auto declval() noexcept -> decltype(__declval<_Tp>(0));
int main()
{
declval<int>;
return 0;
}
and i have this one, which for some reason it doesn't:
template<typename _Tp, typename _Up = _Tp&&>
_Up
__declval(long);
template<typename _Tp>
_Tp
__declval(char);
//but if we change char to int it works
template<typename _Tp>
auto declval() noexcept -> decltype(__declval<_Tp>(0));
int main()
{
declval<int>;
return 0;
}
The error i get with the second snippet according to clang:
:26:5: error: reference to overloaded function could not be
resolved; did you mean to call it?
But when i replace the __declval(char) with __declval(int) the error disappears. I've been scratching my head for some time now, any clues about the underlying cause of this issue?
| You are running into effectively the same problem as the following, simpler and equally broken, program:
void foo(long) {}
void foo(char) {}
int main() {
foo(0);
}
The error is a lot clearer here though:
:5:5: error: call to 'foo' is ambiguous
The issue is that 0, being an int, is equally valid as a char as it is as a long. In both cases, an implicit conversion is required. Since neither is preferable to the other, the call is ambiguous.
There are 3 ways to fix this:
Make sure there is only one overload that is implicitly callable from an int. That's how the original snippet works.
Provide an overload that does not need an implicit conversion for the parameter used at the callsite. This is what using __declval(int) does.
Use a long literal instead of an int one at the callsite. So that __declval(long) is called without the need for an implicit conversion.
auto declval() noexcept -> decltype(__declval<_Tp>(0L));
|
70,163,517 | 70,165,479 | Integrating a 2D Array into a Calendar Printing Program | I've decided to start learning to code on my own from a C++ textbook and one of the challenges is to create a program that prints the calendar of a given year, in this style for each month:
-------------January-------------
Sun Mon Tue Wed Thu Fri Sat
1 2
3 4 5 6 7 8 9
10 11 12 13 14 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
I have the whole program written out here in Microsoft Visual Studio, but another one of the challenges is to then convert the data from the two 1D arrays from the getMonthName and dayNumber function into one function with a 2D array that gathers both the month name and the day number, using this array:
// the first number is the month and second number is the last day of the month.
int yearly[12][2] =
{{1,31},{2,28},{3,31},{4,30},{5,31},{6,30},{7,31},{8,31},{9,30},{10,31},{11,30},{12,31}};
The textbook doesn't explain 2D arrays very well, but I know the basics. I just don't know how to go about referencing the contents of the array. Can I assign all the "month number" values of the array to a variable, like I have here for the variable monthNumber, and just go from there? If someone could perhaps provide an example on how one would do this, I'd greatly appreciate it. I'm trying to absorb as much information as I can, so if you could explain how your example works as well, I'd be over the moon.
#include <iomanip>
#include <string>
#include <iostream>
using namespace std;
int dayNumber(int day, int month, int year)
{
static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1,
4, 6, 2, 4 };
year -= month < 3;
return (year + year / 4 - year / 100 +
year / 400 + t[month - 1] + day) % 7;
}
string getMonthName(int monthNumber)
{
string months[] = { "January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"};
return (months[monthNumber]);
}
//number of days in month
int numberOfDays(int monthNumber, int year)
{
// january
if (monthNumber == 0)
return (31);
// february
if (monthNumber == 1)
return (28);
// march
if (monthNumber == 2)
return (31);
// april
if (monthNumber == 3)
return (30);
// may
if (monthNumber == 4)
return (31);
// june
if (monthNumber == 5)
return (30);
// july
if (monthNumber == 6)
return (31);
// august
if (monthNumber == 7)
return (31);
// september
if (monthNumber == 8)
return (30);
// october
if (monthNumber == 9)
return (31);
// november
if (monthNumber == 10)
return (30);
// december
if (monthNumber == 11)
return (31);
}
// display calendar function
void printCalendar(int year)
{
printf (" Calendar - 2021", year);
int days;
// day from 0 - 6
int current = dayNumber(1, 1, year);
for (int i = 0; i < 12; i++)
{
days = numberOfDays(i, year);
// current month display
printf("\n ------------%s-------------\n",
getMonthName(i).c_str());
//columns
printf(" Sun Mon Tue Wed Thu Fri Sat\n");
// spaces
int k;
for (k = 0; k < current; k++)
printf(" ");
for (int j = 1; j <= days; j++)
{
printf("%5d", j);
if (++k > 6)
{
k = 0;
printf("\n");
}
}
if (k)
printf("\n");
current = k;
}
return;
}
// main function
int main()
{
int year = 2021;
printCalendar(year);
return (0);
}
Please let me know if you need any more info, I'll be happy to provide more.
| I declared a global variable int yearly[12][2];
snippet line 90:
for (int i = 0; i < 12; i++)
{
days = numberOfDays(i, year);
yearly[i][0] = i; //month
yearly[i][1] = days;//days
... ...
The for loop is executed 12 times, and each i corresponds to a month.
Yearly [i][0] is the month and yearly [i][1] is the days of the month.
What a 2D array looks like:
column
Row 0 [0][1]
1 [0][1]
2 [0][1]
... ...
11[0][1]
Example of printing a 2D array:
for (int Row= 0; Row< 12; Row++)
{
std::cout << "{";
for (int column= 0; column< 2; column++)
{
std::cout << yearly[Row][column]<<",";
}
std::cout << "}"<<std::endl;
}
|
70,163,538 | 70,164,024 | Does accessing two different members of the same object need synchronization? | If we have an object with two data members A, and B; Do we need any form of synchronization while accessing the two members from two different threads running in parallel? How about if the object was a global variable, versus the object was a heap object, accessed with a pointer to its address?
Edit:
Each thread reads and writes into only one distinct member, a one-to-one association, the number of threads is equal to the number of data members, and threads access them distinctly, until they finish and join the main thread.
| The keywords you are looking for is memory model.
Non-bitfield members are distinct memory locations; there is no race condition from reading/writing different members.
A write in one thread and access in another of the same memory location is a potential conflict. Unless certain requirements are upheld (like happens before) this is a race condition, and your program has UB (undefined behaviour).
But access (read or write) to distinct members that are not bitfields won't trigger this.
The actual rules are more complex; not all bitfields share a memory location, for example.
|
70,163,749 | 70,163,783 | How to add a period at the end of the sequence in stead of a comma? | This is my code:
#include <iostream>
using namespace std;
int main() {
int fib[10];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < 10; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
for (int i = 0; i < 10; i++) {
cout << fib[i] << ", ";
}
return 0;
}
And this is the output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
But I want to replace the comma after 34 with a period. How would I do that?
| Change the print for loop to:
for (int i = 0; i < 10; i++) {
cout << fib[i] << (i < (10 - 1) ? ", " : ".");
}
|
70,163,753 | 70,164,476 | erase rows and colums of a 2D vector, when a condition is achieved in another single vector? | I have a matrix (vector of vector), in other words, 2D vector (6 X 6) elements <double>, and after I have a vector with 6 elements <int>. the vector with ints has only "0" and "1". Then, I am looking for a way to remove a row and column of the 2D vector when a "0" is found in the vector (1D) of ints. This time is only 6 X 6 but later on, will be around 100 X 100.
What I've done is use iterators, and I successfully remove the rows but now I don't know how to tackle the columns.
This is my code.
#include <iostream>
#include <vector>
#include <iomanip>
int main() {
std::vector <int> boundaryConditions = { 0,1,1,1,0,0 };
std::vector <std::vector<double>> matrix = { {1.46371e+07, 1.46371e+07, -1.46371e+07, -1.46371e+07, 0, 0},
{1.46371e+07, 5.60371e+07, -1.46371e+07, -1.46371e+07, 0, -4.14e+07},
{-1.46371e+07, -1.46371e+07, 5.60371e+07, 1.46371e+07, -4.14e+07, 0},
{-1.46371e+07, -1.46371e+07, 1.46371e+07, 1.46371e+07, 0, 0},
{0, 0, -4.14e+07, 0, 4.14e+07, 0},
{0, -4.14e+07, 0, 0, 0, 4.14e+07}};
int i = 0;
std::vector<int>::iterator it = boundaryConditions.begin();
while (it != boundaryConditions.end())
{
if (*it == 0)
{
it = boundaryConditions.erase(it);
matrix.erase(matrix.begin() + i);
}
else
{
it++;
i++;
}
}
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
std::cout << matrix[i][j] << std::setw(15);
}
std::cout << "\n";
}
system("pause>0");
}
| You can create a new matrix after you've removed the rows.
std::vector<std::vector<double>> removeColumns(const std::vector<int>& boundaryConditions,
const std::vector<std::vector<double>>& matrix)
{
std::vector<std::vector<double>> returnValue(matrix.size());
size_t curRow = 0;
size_t curCol = 0;
for (auto& v : returnValue)
{
for (size_t curCol = 0; curCol < matrix[0].size(); ++curCol)
{
if (boundaryConditions[curCol] == 1)
v.push_back(matrix[curRow][curCol]);
}
++curRow;
}
return returnValue;
}
Then you would call it like this, given that you have already removed the rows from matrix:
matrix = removeColumns({0,1,1,1,0,0}, matrix);
Here is a Live Example.
If you want an in-place solution, here is an example:
void removeColumns(const std::vector<int>& boundaryConditions, std::vector<std::vector<double>>& matrix)
{
size_t curCol = 0;
for (size_t i = 0; i < boundaryConditions.size(); ++i)
{
if (boundaryConditions[i] == 0)
{
for (auto& v : matrix)
v.erase(v.begin() + curCol);
}
else
++curCol;
}
}
Then it would be called like this:
removeColumns({0,1,1,1,0,0}, matrix);
Here is a Live Example
Another solution, if feasible for you, is to mark each entry to erase with a value, maybe std::numeric_limits<double>::max(). Then in a second pass, use erase/remove idiom, thus reducing the number of erase calls needed.
Here is an example:
void removeColumns(const std::vector<int>& boundaryConditions,
std::vector<std::vector<double>>& matrix)
{
// Mark the entries to delete
for (size_t i = 0; i < boundaryConditions.size(); ++i)
{
if (boundaryConditions[i] == 0)
std::for_each(matrix.begin(), matrix.end(),[&](std::vector<double>& vect)
{ vect[i] = std::numeric_limits<double>::max(); });
}
// One pass through the matrix to remove the marked entries.
for (auto& v : matrix)
v.erase(std::remove(v.begin(), v.end(), std::numeric_limits<double>::max()), v.end());
}
Here is a Live Example
Note that std::remove doesn't really remove anything, thus doesn't incur the penalty of an actual erase.
The single erase call erases an entire range, not just single values, thus has the potential to be faster than the first in-place solution given (but you have to time them, I can't guarantee which is faster).
|
70,163,859 | 70,164,010 | Declaring an object as extern | I am trying to declare an object as extern because I want a thread to be able to access and update it from a different file. But I get the following error message when I try to compile my code:
In file included from main.cpp:1:
dialog.h:43:6: error: storage class specified for ‘temperatureValue’
43 | extern QLabel *temperatureValue;
| ^~~~~~
dialog.h:44:6: error: storage class specified for ‘humidityValue’
44 | extern QLabel *humidityValue;
| ^~~~~~
dialog.h:45:6: error: storage class specified for ‘CO2Value’
45 | extern QLabel *CO2Value;
| ^~~~~~
dialog.h:46:6: error: storage class specified for ‘lightingValue’
46 | extern QLabel *lightingValue;
| ^~~~~~
dialog.h:47:6: error: storage class specified for ‘letterGrade’
47 | extern QLabel *letterGrade;
Here is the header file where I am declaring my extern objects. Why am I getting this error and how should I be declaring the objects so I can use them globally?
#ifndef DIALOG_H
#define DIALOG_H
#include <iostream>
#include <string>
#include <QLabel>
#include <QDialog>
#include <QtWidgets>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QGroupBox>
#include <QtCore>
#include <QtGui>
#include <QtCharts>
#include <QChart>
#include <QChartView>
#include <QDate>
#include <QTime>
#include <QDateTime>
#include <QFile>
#include <QString>
#include <QStringList>
#include <QTextStream>
#include <QLineSeries>
#include <QIODevice>
#include <QDir>
#include <Qt>
#include <QDateTimeAxis>
#include <QValueAxis>
#include <QComboBox>
#include <QBarSeries>
#include <QFileSystemWatcher>
namespace MainWindow
{
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
// create update graph functions
private slots:
void delayUpdateChart();
void updateChart();
void changePet();
void expandGraph();
private:
//Create the layouts that will make up the GUI
QGridLayout *mainLayout;
QGridLayout *leftLayout;
QVBoxLayout *centerLayout;
QVBoxLayout *rightLayout;
QWidget *leftWidget;
QWidget *centerWidget;
QWidget *rightWidget;
//Create all the labels that will be used to display environmental information
QLabel *temperatureLabel;
QLabel *humidityLabel;
QLabel *CO2Label;
QLabel *lightingLabel;
extern QLabel *temperatureValue;
extern QLabel *humidityValue;
extern QLabel *CO2Value;
extern QLabel *lightingValue;
extern QLabel *letterGrade;
QLabel *petName;
//Create widgets that contain the labels
QWidget *temperatureWidget;
QWidget *humidityWidget;
QWidget *CO2Widget;
QWidget *lightingWidget;
// Create file watcher for data
QFileSystemWatcher *fileWatcher;
// Create chart
QChartView *chartview;
// Create chart type selection
QComboBox *typeComboBox;
QComboBox *rangeComboBox;
// Create pet selection
QComboBox *petSelector;
// Create expand graph check box
QCheckBox *graphCheckBox;
void leftVerticalLayout();
void centerVerticalLayout();
void rightVerticalLayout();
void readLastLine();
// Create helper functions for the graph
QLineSeries* getLineSeries(std::string filename, int typeInd, int rangeInd);
QDateTimeAxis* getDTAxis();
QValueAxis* getValueAxis(std::string label);
};
}
#endif // DIALOG_H
| extern a class member is not allowed, If we can do that, for instances of a class type, compiler don't know which address to resolve while linking. you can do like this:
//A.h
#ifndef _A_H_
#define _A_H_
struct A{
int value;
};
extern A a;
#endif
//A.cpp
#include "A.h"
A a;
//main.cpp
#include <iostream>
#include "A.h"
int main() {
std::cout<<a.value<<std::endl;
}
In your codes, extern Dialog's intance instead of its members.
|
70,164,128 | 70,164,223 | array + n shifting in c++ memory behavior | I am going through a cpp course and the instructor used the following notation to get a subarray of the current array
void f(int arr[], int len) {
if (len == 0)
return;
f(arr + 1, len - 1); // arr + 1 takes a subarray
...
}
I wanted to understand how the arr+1 notation works with regards to memory. Arrays are passed by reference, but when you arr + 1 is a copy of the array from the provided offset created, or does it simply advance some pointer and no extra memory is used?
| array is pass by pointer when you call in function
see this
|
70,164,289 | 70,165,446 | Is there a way to detect when a key is pressed only once? (not held down) | I have been looking for ways to detect when a key has been pressed but only once, but the only things I can find are GetAsyncKeyState and GetKeyState. I am making a rhythm game for fun and I use a while(true) statement to get everything done. Is there anyway to detect when a key is pressed once? (I'm also using GLFW if that helps)
| You could store the state of the previous key presses, if it was not pressed in the last frame and is now, that would mean that the key is held down.
Here's an example with the LMB:
bool previousMouseState = false;
if (GetKeyState(VK_LBUTTON) < 0) {
if (!prevMouseState) {
previousMouseState = true;
//Mouse clicked.
}
} else previousMouseState = false;
|
70,164,618 | 70,170,879 | C++ typed variables using struct | In C++ I want to create a typed variable that won't accidentally be used or converted to some other type. What I've come up with is:
struct DId {
uint32_t v;
DId (uint32_t i = 0)
{
v = i;
}
};
struct TId {
uint32_t v;
TId (uint32_t i = 0)
{
v = i;
}
};
This seems to work, though sometimes I need to directly access the value, but are there any other methods I really should define? Does it use any extra resources at run time? (I could use preprocesser commands to switch it out with a "using TId = uint32_t" if not in debug mode, though that would mean extra work whenever I need to directly access the value.)
Or is there some better approach that I just haven't noticed?
| You may make the structure templated so that it can be used at multiple places and define a typecast operator.
template<typename T>
struct Id {
T v;
Id (T i = T{}) { v = i; }. // Ideally not required
operator T () { return v; } // optional to allow conversion to T
};
using DId = Id<uint32_t>;
Your code as it is also fine. Above way is for better utilization and avoid repetition.
|
70,164,978 | 70,165,070 | No naming conflict from two functions in global namespace (C++)? | I created two files, Linkage.cpp and External.cpp.
Linkage.cpp:
#include <iostream>
void Log(int x = 5)
{
std::cout << x << "\n";
}
int main()
{
Log();
return 0;
}
External.cpp:
#include <iostream>
void Log(const char* message)
{
std::cout << message << "\n";
}
Why am I not getting a linker error? Both these functions are defined in the global namespace, so there should be naming conflicts as with variables.
|
Why am I not getting a linker error?
When you wrote
void Log(int x = 5)//this means that the function named Log can be called without passing
//any argument because you have provided a default argument which will be
//used in case you don't provide/pass any argument
{
//..other code here
{
The above means that the function named Log can be called without passing any argument because you have provided a default argument which will be used in case you don't provide/pass any argument.
Next when you wrote
void Log(const char* message)//this means that this versoin of the function named Log will be called only if you pass an argument of type `char*` .
{
std::cout << message << "\n";
}
The above means that this verion of the function named Log will be called only if you pass an argument of type char* .
Now when your wrote:
Log();
The first version which has a default argument will be used because you haven't provided any argument and so the first version can be used(since it is viable) and because the second version which must take an argument is not viable.
|
70,165,120 | 70,165,158 | Does a mutex lock itself, or the memory positions in question? | Let's say we've got a global variable, and a global non-member function.
int GlobalVariable = 0;
void GlobalFunction();
and we have
std::mutex MutexObject;
then inside one of the threads, we have this block of code:
{
std::lock_guard<std::mutex> lock(MutexObject);
GlobalVairable++;
GlobalFunction()
}
now, inside another thread running in parallel, what happens if we do thing like this:
{
//std::lock_guard<std::mutex> lock(MutexObject);
GlobalVairable++;
GlobalFunction()
}
So the question is, does a mutex lock only itself from getting owned while being owned by another thread, not caring in the process about what is being tried to be accessed in the critical code? or does the compiler, or in run-time, the OS actually designate the memory location being accessed in the critical code as blocked for now by MutexObject?
My guess is the former, but I need to hear from an experienced programmer; Thanks for taking the time to read my question.
| It’s the former. There’s no relationship between the mutex and the objects you’re protecting with the mutex. (In general, it's not possible for the compiler to deduce exactly which objects a given block of code will modify.) The magic behind the mutex comes entirely from the temporal ordering guarantees it makes: that everything the thread does before releasing the mutex is visible to the next thread after it’s grabbed the mutex. But the two threads both need to actively use the mutex for that to happen.
A system which actually cares about what memory locations a thread has accessed and modified, and builds safely on top of that, is “transactional memory”. It’s not widely used.
|
70,165,418 | 70,174,424 | Nested call of consteval functions with a reference argument | The following program
template<class T>
consteval auto foo(const T&) {
return 0;
}
template<class T>
consteval auto bar(const T& t) {
auto n = foo(t);
return n;
}
int main() {
static_assert(foo("abc") == 0);
static_assert(bar("abc") == 0);
}
is built fine in GCC, but Clang rejects it with the messages:
error: call to consteval function 'foo<char[4]>' is not a constant expression
note: in instantiation of function template specialization 'bar<char[4]>' requested here
static_assert(bar("abc") == 0);
note: function parameter 't' with unknown value cannot be used in a constant expression
auto n = foo(t);
Demo: https://gcc.godbolt.org/z/M6GPnYdqb
Is it some bug in Clang?
| This is a clang bug. gcc and msvc are correct to accept it.
There are two relevant rules in question:
All immediate invocations must be constant expressions. This comes from [expr.const]/13:
An expression or conversion is in an immediate function context if it is potentially evaluated and either:
its innermost enclosing non-block scope is a function parameter scope of an immediate function, or
its enclosing statement is enclosed ([stmt.pre]) by the compound-statement of a consteval if statement ([stmt.if]).
An expression or conversion is an immediate invocation if it is a potentially-evaluated explicit or implicit invocation of an immediate function and is not in an immediate function context. An immediate invocation shall be a constant expression.
And touching an unknown reference is not allowed in constant expressions (this is [expr.const]/5.13):
An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following: [...]
an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
it is usable in constant expressions or
its lifetime began within the evaluation of E;
For more on this latter rule, see my post on the the constexpr array size problem and my proposal to resolve this (hopefully for C++23).
Okay, back to the problem. foo is obviously fine, it doesn't do anything.
In bar, we call foo(t). This is not a constant expression (because t is an unknown reference), but we are in an immediate function context (because bar is consteval), so it doesn't matter that foo(t) is not a constant expression. All that matters is that bar("abc") is a constant expression (since that is an immediate invocation), and there's no rule we're violating there. It is pretty subtle, but the reference t here does have its lifetime begin within the evaluation of E -- since E here is the call bar("abc"), not the call foo(t).
If you mark bar constexpr instead of consteval, then the foo(t) call inside of it becomes an immediate invocation, and now the fact that it is not a constant expression is relevant. All three compilers correctly reject in this case.
|
70,165,937 | 70,174,335 | How to get function return values into ROS topic msg to be published | I'm a beginner when it comes to working with ROS.
Currently working in Melodic, outside of the catkin workspace. ie: not using catkin
My goal is to create a topic that contains an x and y value, then to update those values from the return value of my path prediction function, which returns a std::vector<Eigen::Vector2f> containing the x and y values.
this is what my code looks like:
ros::NodeHangle nh;
ros::Publisher topic_pub = nh.advertise<geometry_msgs::Point>("mytopic/path", 1000);
int counter=0;
ros::Rate rate(10);
while (ros::ok()) {
geometry_msgs::Point msg;
msg.data = engine.getPathFunction();
topic_pub.publish(msg);
rate.sleep();
}
The line where I set msg.data = engine.getPathFunction(); , returns an error of course.
The return type of getPathFunction() is std::vectorEigen::Vector2f ... with x and y values for the path.
What's the best way to handle this conversion and get those x and y values into msg?
Is this something ROS can handle? If not, is there another library useful for conversions?
Should I just write my own function? If so, what should that function look like in this example?
| The best, and only, way to handle this conversion is to do it manually. A Point message has fields for (x,y,z) so you'll need to simply assign those values yourself. Another thing to note is that a Point msg doesn't have a .data field like std_msgs do.
geometry_msgs::Point msg;
std::vector<Eigen::Vector2f> tmp_vec = engine.getPathFunction();
msg.x = tmp_vec[0]; //Assumes x here
msg.y = tmp_vec[1]; //Assumes y here
topic_pub.publish(msg);
|
70,166,420 | 70,166,590 | Writing a video with H.264 in OpenCV with High profile from a high profile mp4 file | I have High profile mp4 video i am using opencv to overlay some text inside but output.mp4 is writing in simple profile format. is there a way to write it in high profile
I am using opencv 3.4.16 latest
Devlopment platform is: Windows C++ VS2019
VideoWriter videocc(destFile, VideoWriter::fourcc('M', 'P', '4', 'V'), fps, cv::Size(width, height));
I have tried X264 , H264 ,AVC1 in fourcc, But not writing in high profile
Is there a way or sample available to generate high profile output video format
please find the following attachment for main profile coded problem
| You would need to pass parameters through OpenCV, to ffmpeg and libx264.
As far as I can tell from official documentation, OpenCV doesn't support that.
However, the source contains access to the environment variable OPENCV_FFMPEG_WRITER_OPTIONS
You should be able to pass parameters like you would give them to ffmpeg, except the syntax is a little weird (semicolon between key and value, pipe between pairs).
Here is some talk of such facilities:
https://github.com/opencv/opencv/issues/6342
https://github.com/opencv/opencv/pull/9292
You should pass avc1 as fourcc. AFAIK that's the fourcc defined by standards. It does not however guarantee that you get libx264, only that you get some encoder for AVC.
I've opened an issue for this. Documentation issues are always a nice way for newbies to get their feet wet contributing to an open source project.
|
70,166,715 | 70,166,958 | Why casting of function pointers not working as it is for the primitive types? | int* b = new int(40);
int c = *(int *)b;
The above cast is working fine.
But similar casting is not working for function pointers
void abc(int a){
cout<<a<<endl;
}
std::function<void(int)> callback = *(std::function<void(int)>*)abc; // this cast is not working
What is wrong in the above piece of code?
| You cast b to the same type that it already has. This results in a static cast, which doesn't change the value. The type of b is int* and you cast to int*.
You cast abc to an entirely different type. And since the target type is unrelated, this resulst in a reinterpret cast, and accessing the pointed object through the reinterpreted pointer (which is a problem since it points to a function and not an object at all) results in undefined behaviour. The type of abc is void(int) which is a function type and it implicitly decays to void(*)(int) which is a pointer to function type. You cast it to std::function<void(int)>* which is a pointer to object type, where the object type is of the class type that was instantiated from the class template std::function.
What is wrong in the above piece of code?
Using C style cast is wrong. Don't do it.
Reinterpret casting pointer to an unrelated type is wrong. std::function<...>* is not a pointer to function. std::function is not a function. It's a class template for a function wrapper.
|
70,166,739 | 70,167,497 | Confustion about Android NDK libc++ libc++_shared, libstdc++ | I am getting very confused trying to build a simple C++ library using Android NDK 23 (23.1.7779620). I am using CMake and this is a very simple program:
# CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(mf)
add_library(mf lib.cpp)
// lib.hpp
#pragma once
#include <string>
std::string foo(std::string);
// lib.cpp
#include "lib.hpp"
std::string foo(std::string str) {
return std::string{"test"} + str;
}
This is the command line to build:
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DANDROID_STL=c++_shared -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-29 -DCMAKE_TOOLCHAIN_FILE=${ANDROID_NDK}/build/cmake/android.toolchain.cmake ..
cmake --build . -v
The first problem is that I was expecting to link against libc++.so and not libc++_shared.so. What is the difference between them? I read this article. But still is not explained the difference betweend libc++ and libc++_shared
The second problem is even worst, it seems I am using libstdc++!
The 3rd point, I was thinking that the c++ implementation of clang was under the namespace std::__1 but I cannot find anything like that.
I know libc++_shared is used because of this command:
$ readelf -d libmf.so
Dynamic section at offset 0x76e0 contains 26 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libm.so]
0x0000000000000001 (NEEDED) Shared library: [libc++_shared.so]
0x0000000000000001 (NEEDED) Shared library: [libdl.so]
0x0000000000000001 (NEEDED) Shared library: [libc.so]
0x000000000000000e (SONAME) Library soname: [libmf.so]
Running nm it seem I am using symbols from libstdc++:
$ nm -gDC libmf.so | grep '__ndk1'
0000000000003af0 T foo(std::__ndk1::basic_string<char, std::__ndk1::char_traits<char>, std::__ndk1::allocator<char> >)
U std::__ndk1::basic_string<char, std::__ndk1::char_traits<char>, std::__ndk1::allocator<char> >::append(char const*, unsigned long)
$ nm -gDC libmf.so | grep '__1'
$
Update
In this post is explained the difference between libc++.so and libc++_shared.so
| By passing -DANDROID_STL=c++_shared to the CMake invocation you explicitly asked for the shared runtime as opposed to the default runtime.
As explained in the documentation, the rules are simple:
if all your native code is in a single library, use the static libc++ (the default) such that unused code can be removed and you have the smallest possible application package.
As soon as you include an extra library – either because you include a precompiled library from somewhere else or you include an Android AAR file that happens to include native code – you must switch to the shared runtime.
The rationale for the rules is simple: the C++ runtime has certain global data structures that must be initialized once and must only exist once in memory. If you were accidentally to load two libraries that both link the C++ runtime statically, you have (for instance) two conflicting memory allocators.
This will result in crashes when you free or delete memory allocated by the other library, or if you pass a C++ STL object like std::string across library boundaries.
For completeness, in older NDKs libstdc++ (the GNU C++ runtime) was also included in the NDK, but as of NDK r18 that is no longer the case.
|
70,167,025 | 70,167,171 | Integer overflow and underflow in C++ | Can anyone please explain why this happens ?? :
int a = 2147483647;
cout <<"Product = " << a * a << endl; // output = 1 (why?)
int b = -2147483648;
cout <<"Product = " << b * b << endl; // output = 0 (why?)
Also when we write the similar for 'short' , the compiler takes the product as integer type despite the variables being initialized as of short type, like:
short x = 32767;
cout <<"Product = " << x * x << endl; // Product = 1073676289
short y = -32768;
cout <<"Product = " << y * y << endl;// Product = 1073741824
| Part 1: Intuition, without consulting references
Let's try to use some intuition, or reasonable assumptions, regarding why these results can make sense.
Basically, this is about what physical integer variables can represent - which isn't the entire infinite set of all integers, but rather the range -2^31 ... 2^31 - 1 (for a 32-bit integer, which is likely what you have; but always check to make sure, e.g. using sizeof().)
Now, if
a = 2^31 - 1
then
a*a = (2^31 - 1)^2 = 2^62 - 2*2^31 + 1 = 2^62 - 2^32 + 1
as an ideal integer, and ignoring the physical representation. When placing the result an integer with 32 bits, a reasonable guess would be that any result the CPU gives you will be equivalent, modulo 2^31 or 2^32, to the ideal result:
(2^62 - 2^32 + 1) mod 2^32
= (2^62 mod 2^32) - (2^32 mod 2^32) + (1 mod 2^32)
= 1 mod 2^32
which is what you're getting.
For b, you have:
b = -2147483648 = -2^31
and
b*b = 2^62
which is equivalent to 0, modulo either 2^31 or 2^32.
Part 2: What the language mandates
While our intuition does give a reasonable explanation of the results, it's usually also useful to consider the "official" answer. In our case, I'm quoting from cppreference.com (which is not official language standard, but close enough):
When signed integer arithmetic operation overflows (the result does
not fit in the result type), the behavior is undefined: it may wrap
around according to the rules of the representation (typically 2's
complement), it may trap on some platforms or due to compiler options
(e.g. -ftrapv in GCC and Clang), or may be completely optimized out by
the compiler.
So actually, you're not guaranteed to get those values on a different compiler, different compiler version, different machine or even on repeat compilation of the same code! You could actually get 1234 and 5678 as the results and you couldn't complain. Or your program could crash. Or anything else could happen! See:
Undefined, unspecified and implementation-defined behavior
About the second part of your question (regarding the shorts) - this is due to integer promotion:
The arguments of the following arithmetic operators undergo implicit
conversions for the purpose of obtaining the common real type, which
is the type in which the calculation is performed:
binary arithmetic *, /, %, +, -
...
Integer promotion is the implicit conversion of a value of any integer type with rank less or equal to rank of int or of a bit field of type ...short [other types here] to the value of type int or unsigned int
Part 3: Practical bottom line
Take care to avoid computing values exceeding std::numeric_limits<T>::max(): Use a larger type to begin with, or check for excessively high values (e.g. ensure both values are lower than 2^16 in absolute value, and otherwise apply some special handling).
|
70,167,284 | 70,178,175 | boost::log with multi-process | I have asked a question about how to use boost::log in multi-process
How to use Boost::log not to rewrite the log file?
That answer can solve most part of the problem. But in some rare case, when one process is writing log and another process is starting to write log,
13548:Tue Nov 30 17:33:41 2021
12592:Tue Nov 30 17:33:41 2021
13548:Tue Nov 30 17:33:41 2021
12592:Tue Nov 30 17:33:4572:Tue Nov 30 17:33:41 2021
17196:Tue Nov 30 17:33:41 2021
8572:Tue Nov 30 17:33:41 2021
17196:Tue Nov 30 17:33:41 2021
8572:Tue Nov 30 17:33:41 2021
The fourth line 17:33:4(1 2021) the rear part was erased with (8)572:Tue Nov which was written by the other process.
How do I prevent this?
| Boost.Log does not synchronize multiple processes writing to the same file. You must have a single process that writes logs to the file, while other processes passing their log records to the writer. There are multiple ways to achieve this. For example, you can pass your logs to a syslog service or writing your own log writer process. In the latter case, you can use inter-process queue to pass log messages between processes.
Alternatively, you can write your own sink backend that will perform synchronization when writing to a shared file. However, I suspect the performance will be lower than having a single log writer process.
|
70,167,531 | 70,176,161 | I2C communication between RP2040 and adxl357 accelerometer ( C/C++ SDK ) | I need to communicate via I2C to the adxl357 accelerometer and a few questions have arisen.
Looking at the RP2040 sdk documentation I see that there is a special method to send data to a certain address, such as i2c_write_blocking(). Its arguments include a 7-bit address and the data to be sent. My question is, since the accelerometer needs a Read/Write bit, is it still possible to use this function? Or should I go to the alternative i2c_write_raw_blocking()?
Also, I don't understand the notation of the Read / Write bit, it is reported with R/#W, would that mean that 1 is Read while 0 is write?
Thanks in advance for the help.
| I2C addresses have 7 bits: these are sent in the high 7 bits of an 8-bit byte, and remaining bit (the least significant bit) is set to 1 for read, 0 for write.
The reason the documentation says it wants a 7-bit address is because it is telling you that the write function will left-shift the address by one and add a 1, and the read function function will left-shift the address by one and add a 0.
If it didn't tell you this you might pre-shift the address yourself, which would be wrong.
|
70,168,411 | 70,168,500 | Can I make use on templates when implementing different interfaces in the same way? | I have many interfaces for different listeners, the all look like this:
class ListenerA
{
public:
virtual void
onEventA(const EventA&) = 0;
};
class ListenerB
{
public:
virtual void
onEventB(const EventB&) = 0;
};
When testing, I always end up just collecting those events in a std::vector for analyzing them afterwards in a specific test suite. Those event collectors all look the same like this one for example:
class EventACollector : public ListenerA
{
public:
const auto&
events() const
{
return m_events;
}
private:
void
onEventA(const EventA& event) override
{
m_events.emplace_back(event);
}
std::vector<EventA> m_events;
};
Is there a way to template an EventTCollector, so that I do not have to write it every time? Given that the virtual function name does change for every listeners?
| C++ does not have introspection, so you cannot find the virtual function in ListenerA. The other parts can go in a templated base class, but the override you'll need to define manually.
Modern C++ would use a std::function<void(EventA)> instead of a named interface, but that won't help you as a user of that old interface.
|
70,169,500 | 70,234,600 | Automatically know if a GCC/Clang warning comes from Wall or Wextra? | I wonder if there's some clever, automatic way of knowing if a particular compiler warning (e.g. -Wunused-parameter) comes from the group -Wall, -Wextra, or another group, for both GCC and Clang.
Use case: we want to enable:
-Wall -Wextra -pedantic
However, some of the pedantic warnings are unapplicable to us and we want to disable them, example:
-Wall -Wextra -pedantic -Wno-c++20-designator
Now, we want to be 100% sure that we are not disabling anything from -Wall nor -Wextra. How do we ensure that -Wc++20-designator is not part of either? Of course one can go and check the documentation, but this is a tedious process when you have many such warnings or when you upgrade the compiler and get new warnings.
Our use case to ensure that all -Wall, -Wextra warnings will always be active, regardless of the disabled warnings from -pedantic.
Thanks!
| There's no specific command to get a direct answer to the question "which warning group does a given warning come from?", but it's possible to infer this information automatically by querying the compiler which warnings are enabled and checking if the warning we are interested in is part of the list of enabled warnings.
This is done as follows:
GCC: gcc -Q -Wall --help=warnings | grep enabled | grep unused-parameter (credits to @dratenik).
Clang: this functionality is not baked into the compiler, unlike GCC, so we need to use the diagtool tool: diagtool show-enabled -Wall foo.cpp | grep unused-parameter.
Bonus:
Unrelated to the original question but related to the original use case: to be sure that all of Wall and Wextra are enabled, regardless of which warnings are disabled, the solution (only works for Clang) is to put Wall Wextra at the very end:
clang -Wno-unused-parameter -Wall -Wextra
In this case, if we accidentally disable the unused-parameter warning, Wall will be applied after, re-enabling the warning.
|
70,169,887 | 70,169,973 | Ending a while loop in command prompt | This is an excerpt from the Competitive Programmer's Handbook by Antti Laaksonen:
If the amount of data is unknown, the following loop is useful:
while (cin >> x) {
// code
}
This loop reads elements from the input one after another, until
there is no more data available in the input.
My question is how do we end such a loop in the command prompt, where the prompt takes one input at a time? By pressing enter, the prompt asks for new input and not terminating the input.
Edit: I have tried using ctrl + D/Z but I am getting this:
| In order for that loop to end, cin needs to enter a failed state. That will cause it to evaluate to false and stop the loop. You have a couple ways you can do that. First is to send bad input, which will cause cin to fail and end the loop. Since you are excepting integers, you could just input a letter and that will cause it to break.
Another option is to send the EOF (end of file) signal to cin You can do that using ctrl+D (windows) or ctrl+Z (linux) and the pressing enter. cin will stop reading once it sees it has reachged the EOF and it will enter a failed state and cause the loop to end.
It should be noted that with both of these options that if you want to use cin again after you do this you will need to call clear() to remove the error flags and if you entered bad input, you will need to use ignore() to remove the bad input from the stream.
|
70,170,160 | 70,170,420 | template class derived from `const` specialized version | I've stumbled upon this code (simplified version here):
template<typename T>
class SmartPtr;
template<typename T>
struct SmartPtr<const T>
{
const T& operator*() const { return *_ptr; }
const T* operator->() const { return _ptr; }
const T* _ptr;
// more member data and functions here
// ...
};
template<typename T>
struct SmartPtr : public SmartPtr<const T>
{
T& operator*() const { return *const_cast<T*>(_ptr); }
T* operator->() const { return const_cast<T*>(_ptr); }
};
It's the first time I see a template class derived like this. Can anyone help me understand what one can achieve using this? To me it seems the general version behaves the same as the specialization if instantiated with a const T and the specialization is not necessary. Am I missing something?
| The general behaviour of SmartPtr<T> and SmartPtr<const T> is indeed identical and no specialization would have been needed simply to handle const and non-const versions of T.
However, the answer to your question lies in that this construction allows for implicit conversion from SmartPtr<T> to SmartPtr<const T>.
For instance, a function defined for SmartPtr<const foo> can be called with a SmartPtr<foo> as well, and thus you don't need two overloads to handle both cases:
void HandleFoo(SmartPtr<foo> ptr);
void HandleConstFoo(SmartPtr<const foo> ptr);
void dotask()
{
SmartPtr<foo> fooptr = new foo ...;
...
HandleFoo(fooptr);
HandleConstFoo(fooptr); // implicit conversion
}
Simply defining a single class SmartPtr<T> does not allow for implicit conversion from SmartPtr<T> to SmartPtr<const T>.
For implicit conversion between different types you would normally add extra member functions, but in this case for the same class from non-const to const you would run into problems.
A specialization with a const T base class is one of the ways to avoid those problems.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.