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 |
|---|---|---|---|---|
71,459,542 | 71,459,621 | Different results on different compilers c++(vector copying) | I need to implement a simple version of schedule for monthly tasks. For example payment of electricity bills, subscription fees for communications, etc. I want to implement a set of the following operations:
ADD(i,s) - assign a case with name s to day i of the current month.
DUMP(i) - Display all tasks scheduled for day i of the current month.
NEXT - Go to the to-do list for the new month. When this command is executed, instead of the current (old) to-do list for the current month, a (new) to-do list for the next month is created and becomes active: all tasks from the old to-do list are copied to the new list. After executing this command, the new to-do list and the next month become the current month, and work with the old to-do list is stopped. When moving to a new month, you need to pay attention to the different number of days in months:
if the next month has more days than the current one, the "additional" days must be left empty (not containing cases);
if the next month has fewer days than the current one, cases from all "extra" days must be moved to the last day of the next month.
Here is my code:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
//q - number of operations.
//day - on which day to plan operation.
//to_do - what exactly to do on some day.
//operation - which kind of operation to perform.
const vector<int>day_mon = {31,28,31,30,31,30,31,31,30,31,30,31};
//m_ind - month index
int c_ind = 0;
int n_ind = 0;
int q,day;
int days_diff;
string operation;
string to_do;
//vector of the current month and next month
vector<vector<string> > current_month(31);
vector<vector<string> > next_month;
cin >> q;
//for q operations:
for(int i = 0;i< q;i++){
cin >> operation;
if(operation == "NEXT"){
//change next_month index
if(c_ind == 11){
n_ind = 0;
} else{
n_ind +=1;
}
next_month.resize(day_mon[n_ind]);
copy(current_month.begin(),current_month.begin() + day_mon[n_ind],next_month.begin());
days_diff = day_mon[c_ind] - day_mon[n_ind];
//if next month has less days as current month, write days into the last day
//of the next months
if(days_diff > 0){
for(int i = 0; i < days_diff;i++){
next_month[day_mon[n_ind]-1].insert(end(next_month[day_mon[n_ind]-1]), begin(current_month[day_mon[n_ind]+i]), end(current_month[day_mon[n_ind]+i]));
}
}
current_month.clear();
c_ind +=1;
current_month.resize(next_month.size());
current_month = next_month;
next_month.clear();
} else if(operation == "ADD"){
cin >> day >> to_do;
current_month[day-1].push_back(to_do);
} else if(operation == "DUMP"){
cin >> day;
cout << current_month[day-1].size() << ' ';
for(int i = 0; i < current_month[day-1].size(); i++){
cout << current_month[day-1][i] << ' ';
}
cout << endl;
}
}
return 0;
}
I have tested program by following inputs:
12
ADD 5 Salary
ADD 31 Walk
ADD 30 WalkPreparations
NEXT
DUMP 5
DUMP 28
NEXT
DUMP 31
DUMP 30
DUMP 28
ADD 28 Payment
DUMP 28
and on my compiler I got correct result:
1 Salary
2 WalkPreparations Walk
0
0
2 WalkPreparations Walk
3 WalkPreparations Walk Payment
but on other compiler I hot incorrect results:
1 Salary
2 WalkPreparations Walk
1 Salary
1
2 WalkPreparations Walk
3 WalkPreparations Walk Payment
Can you help me to find my mistake?
| Look here
copy(current_month.begin(), current_month.begin() + day_mon[n_ind], next_month.begin());
What happens when current_month has 28 days and the next month has 31 days - ie day_mon[n_ind] = 31
|
71,459,815 | 71,459,994 | C++ Program Printing 0 When Numbers Too Large | I'm trying to write a program that prints the factorial of a number:
#include <iostream>
using namespace std;
int main() {
int ans,fact=1, number;
cin>>number;
for (int i=1; i<=number; i++) {
fact = fact*i;
}
ans = fact%998244353;
cout <<ans<<endl;
return 0;
}
When I try to input the number 250, the program returns 0, but when I try to print a smaller number like 4, it returns the right number. Does anyone know why this occurs and how to fix this? Thanks.
| Some hints for doing math in a finite field or ring while avoiding overflow.
Mathematically is true that:
(a*b)%c == ((a%c)*(b%c))%c
and also:
(a+b)%c == ((a%c)+(b%c))%c
But in the case a*b or a+b will overflow, you have to use the righthand expression because it is less likely to overflow.
|
71,459,975 | 71,460,093 | C++ MSVC '=' unable to resolve function overload | I have an API which I'm able to register multiple function pointer as callbacks. However I need to track additional data when a callback is called (in this example an index). What I want to do is generate a bunch of methods at compile which holds this additional data. My code is the following:
#include <iostream>
#include <vector>
#include <sstream>
#include <array>
// API function format
typedef void ( *Function )( const std::string& msg );
// My function accepting the API interface + an additional index
void callback( const size_t index, const std::string& msg ) {
std::cout << "(" << index << "): " << msg << std::endl;
}
// Wrapper for my function in API format generating the index
template <size_t METHOD_INDEX>
void wrapper( const std::string& msg ) {
return callback( METHOD_INDEX, msg );
}
// Constexpr Array which should be built on compile time, containing all wrappers
template <size_t SIZE>
struct Array {
constexpr Array() : arr() {
for ( auto i = 0; i < SIZE; ++i ) {
arr[ i ] = wrapper<i>; // Error at this line
}
}
size_t size() const {
return SIZE;
}
void ( *arr[ SIZE ] )( const std::string& );
};
int main() {
static constexpr auto wrappers = Array<5>();
// Emulating registering wrapper functions at the API
const auto NUM_CALLBACKS = 5;
std::vector<Function> apiCallbacks( NUM_CALLBACKS );
for ( auto i = 0; i < NUM_CALLBACKS; ++i ) {
apiCallbacks[ i ] = wrappers.arr[ i ];
}
// Emulating API is calling registered functions
for ( auto i = 0; i < NUM_CALLBACKS; ++i ) {
apiCallbacks[ i ]( "Test" );
}
}
At the line marked in the source code the compiler (MSVC x64 16.8) throws an error:
main.cpp(25,1): error C2563: mismatch in formal parameter list
main.cpp(23): message : while compiling class template member function 'Array<5>::Array(void)'
main.cpp(37): message : see reference to class template instantiation 'Array<5>' being compiled
main.cpp(25,1): error C2568: '=': unable to resolve function overload
main.cpp(25,1): message : could be 'void wrapper(const std::string &)'
I wasn't able to figure out yet
why the compiler throws an error?
how to fix that code?
Can someone answer me that 2 questions and explain the problem?
Thanks in advance
| The problem is the use of variable i as template parameter. The proper approach is to use integer sequence which provides a pack of compile-time constants that can be used as template parameters:
#include <iostream>
#include <vector>
#include <sstream>
#include <array>
#include <utility>
#include <cstddef>
// API function format
typedef void ( *Function )( const std::string& msg );
// My function accepting the API interface + an additional index
void callback( const size_t index, const std::string& msg ) {
std::cout << "(" << index << "): " << msg << std::endl;
}
// Wrapper for my function in API format generating the index
template <size_t METHOD_INDEX>
void wrapper( const std::string& msg ) {
return callback( METHOD_INDEX, msg );
}
template <::std::size_t... x_index>
constexpr auto make_wrappers_impl(::std::index_sequence<x_index...>)
{
return ::std::array<Function, sizeof...(x_index)>{&wrapper<x_index>...};
}
template <::std::size_t x_size>
constexpr auto make_wrappers(void)
{
return make_wrappers_impl(::std::make_index_sequence<x_size>());
}
int main() {
static constexpr auto wrappers{make_wrappers<5>()};
// Emulating registering wrapper functions at the API
const auto NUM_CALLBACKS = 5;
std::vector<Function> apiCallbacks( NUM_CALLBACKS );
for ( auto i = 0; i < NUM_CALLBACKS; ++i ) {
apiCallbacks[ i ] = wrappers[ i ];
}
// Emulating API is calling registered functions
for ( auto i = 0; i < NUM_CALLBACKS; ++i ) {
apiCallbacks[ i ]( "Test" );
}
}
online compiler
|
71,460,068 | 71,460,291 | How do I print out the value that make magic square? | I have tried this code that I found online and it worked, but I want it to print out which number makes magic square. In this case it is 83, so instead of cout<<"Magic Square", how do I change it to show 83 instead?
Thank you in advance.
# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))
using namespace std;
// Returns true if mat[][] is magic
// square, else returns false.
bool isMagicSquare(int mat[][3])
{
int n = my_sizeof(mat)/my_sizeof(mat[0]);
// calculate the sum of
// the prime diagonal
int i=0,j=0;
// sumd1 and sumd2 are the sum of the two diagonals
int sumd1 = 0, sumd2=0;
for (i = 0; i < n; i++)
{
// (i, i) is the diagonal from top-left -> bottom-right
// (i, n - i - 1) is the diagonal from top-right -> bottom-left
sumd1 += mat[i][i];
sumd2 += mat[i][n-1-i];
}
// if the two diagonal sums are unequal then it is not a magic square
if(sumd1!=sumd2)
return false;
// For sums of Rows
for (i = 0; i < n; i++) {
int rowSum = 0, colSum = 0;
for (j = 0; j < n; j++)
{
rowSum += mat[i][j];
colSum += mat[j][i];
}
if (rowSum != colSum || colSum != sumd1)
return false;
}
return true;
}
// driver program to
// test above function
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
cout << "Magic Square";
else
cout << "Not a magic Square";
return 0;
}
As per suggested, I have tried to change it to:
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
else
cout << "Not a magic Square";
return 0;
}
But it showed the whole array instead of the correct index in the array. I am sorry, I am somewhat new at the whole thing.
The result is showing up as:
1 5 6
8 2 7
3 4 9
Did I changed it in the wrong place? Or is there any further reading that I should read. Any helps would be appreciate.
The result that I am expecting is
83
as it is the number in the index that is the magic number.
| If the given square is a magic square, that means when isMagicSquare(mat) is true, then iterate through the given square and print each of the values.
To do that, you'll have to learn how to print a 2D array.
In your case, you can do like below:
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
Please check the below resources to learn more about 2D array:
How to print 2D Arrays in C++
Two Dimensional Array in C++
Multidimensional Arrays in C / C++
|
71,460,170 | 71,465,701 | Audio samples to musical note detection issue | I'm trying to setup a pipeline allowing me to detect musical notes from audio samples, but the input layer where I identify the frequency content of the samples does not land on the expected values. In the example below I...
build what I expect to be a 440Hz (A4) sine wave in the FFTW input buffer
apply the Hamming window function
lookup the first half the output bins to find the 4 top values and their frequency
void GenerateSinWave(fftw_complex* outputArray, int N, double frequency, double samplingRate)
{
double sampleDurationSeconds = 1.0 / samplingRate;
for (int i = 0; i < N; ++i)
{
double sampleTime = i * sampleDurationSeconds;
outputArray[i][0] = sin(M_2_PI * frequency * sampleTime);
}
}
void HammingWindow(fftw_complex* array, int N)
{
static const double a0 = 25.0 / 46.0;
static const double a1 = 1 - a0;
for (int i = 0; i < N; ++i)
array[i][0] *= a0 - a1 * cos((M_2_PI * i) / N);
}
int main()
{
const int N = 4096;
double samplingRate = 44100;
double A4Frequency = 440;
fftw_complex in[N] = { 0 };
fftw_complex out[N] = { 0 };
fftw_plan plan = fftw_plan_dft_1d(N, 0, 0, FFTW_FORWARD, FFTW_ESTIMATE);
GenerateSinWave(in, N, A4Frequency, samplingRate);
HammingWindow(in, N);
fftw_execute_dft(plan, in, out);
// Find the 4 top values
double binHzRange = samplingRate / N;
for (int i = 0; i < 4; ++i)
{
double maxValue = 0;
int maxBin = 0;
for (int bin = 0; bin < (N/2); ++bin)
{
if (out[bin][0] > maxValue)
{
maxValue = out[bin][0];
maxBin = bin;
}
}
out[maxBin][0] = 0; // remove value for next pass
double binMidFreq = (maxBin * binHzRange) + (binHzRange / 2);
std::cout << (i + 1) << " -> Freq: " << binMidFreq << " Hz - Value: " << maxValue << "\n";
}
fftw_destroy_plan(plan);
}
I was expecting something close to 440 or lower/higher harmonics, however the results are far from that:
1 -> Freq: 48.4497Hz - Value: 110.263
2 -> Freq: 59.2163Hz - Value: 19.2777
3 -> Freq: 69.9829Hz - Value: 5.68717
4 -> Freq: 80.7495Hz - Value: 2.97571
This flow is mostly inspired by this other SO answer. I feel that my lack of knowledge about signal processing might be in cause! My sin wave generation and window function seem to be ok, but audio analysis and FFTW are full of mysteries...
Any insight about how to improve my usage of FFTW, approach signal processing or simply write better code is appreciated!
EDIT: fixed integer division leading to Hamming a0 parameter always being 0. Results changed a little, but still far of the expected 440 Hz
| I think you've misunderstood the M_2_PI constant in your GenerateSinWave function. M_2_PI is defined as 2.0 / PI.
You should be using 2 * M_PI instead.
This mistake will mean that your generated signal has a frequency of only around 45 Hz. This should be close to the output frequencies you are seeing.
The same constant needs correcting in your HammingWindow function too.
|
71,460,334 | 71,460,451 | How can I make sure only one thread performs IO from a file? | Here's my use case (using C++): I have a multithreaded environment performing operations on data structures written on disk. There are M files. The workflow is:
Thread reads from file into a data structure
Operations on the data structure are performed
The data structure is inserted in cache
Last recently used element is written on file
Cache insertions and deletions are thread-safe already. However, I have no idea how to parallelize writes and reads, ie if Thread 1 is reading from File 1, then Thread 2 can read from File 2. Of course Thread 2 should not read from File 1. If I simply insert a mutex, the whole section is locked and only one thread can read at the same time. What is the most efficient way to make sure only one thread reads from one file, but multiple files are read at the same time?
edit: code is something like this
for element in elements
file = element.txt
data = file.read()
cache.insert(data)
| Put file name in an std::map as a key. Then add mutex pointer as a value. Then whenever a thread has a file name to work on, it locks using the mutex and a lock guard.
{
lock_guard<mutex> lg (*mapping[filename] );
compute(filename);
}
As OS has its own file cache, it would be good to use read-lock to let multiple threads read a file concurrently and still lock against writing by a unique lock.
|
71,460,427 | 71,460,638 | Why do these lambda captured values have different types? | Two int variables, one a reference, when captured by lambdas, differ in type in MSVC's c++20. Why?
Scott's technique to determine type at compile time produces expected results for c++14 and 17 but not for c++20. However, it seems this odd difference occurs in other compiles for earlier versions too.
Specifically, two ints, one a reference, when captured by either value or reference produce differing types. int and int &. Yet earlier versions produces expected types. When captured by value both were typed int. When captured by reference both were int &.
// Scott Meyer's compile time Type Deduction technique
template<typename T>
class TD;
int main()
{
int i{ 1 };
int& ri = i;
[i, ri]() mutable {
TD<decltype(i)> WhatAmI1; // c++14, c++17 TD<int>, c++20 TD<int>
TD<decltype(ri)> WhatAmI2; // c++14, c++17 TD<int>, c++20 TD<int &>
}();
[&i, &ri]() mutable {
TD<decltype(i)> WhatAmI3; // c++14, c++17 TD<int&>, c++20 TD<int>
TD<decltype(ri)> WhatAmI4; // c++14, c++17 TD<int&>, c++20 TD<int &>
}();
}
Exploring this further, the code produced is as expected and is the same for both captured values and captured references.
int main()
{
int i{ 1 };
int& ri = i;
[i, ri]() mutable {
i += 2;
ri += 3;
}();
[&i, &ri]() {
i += 2;
ri += 3;
}();
}
[i, ri]() mutable {
i += 2;
00007FF7F506187F 48 8B 85 E0 00 00 00 mov rax,qword ptr [this]
00007FF7F5061886 8B 00 mov eax,dword ptr [rax]
00007FF7F5061888 83 C0 02 add eax,2
00007FF7F506188B 48 8B 8D E0 00 00 00 mov rcx,qword ptr [this]
00007FF7F5061892 89 01 mov dword ptr [rcx],eax
ri += 3;
00007FF7F5061894 48 8B 85 E0 00 00 00 mov rax,qword ptr [this]
00007FF7F506189B 8B 40 04 mov eax,dword ptr [rax+4]
00007FF7F506189E 83 C0 03 add eax,3
00007FF7F50618A1 48 8B 8D E0 00 00 00 mov rcx,qword ptr [this]
00007FF7F50618A8 89 41 04 mov dword ptr [rcx+4],eax
[&i, &ri]() {
i += 2;
00007FF7F506190F 48 8B 85 E0 00 00 00 mov rax,qword ptr [this]
00007FF7F5061916 48 8B 00 mov rax,qword ptr [rax]
00007FF7F5061919 8B 00 mov eax,dword ptr [rax]
00007FF7F506191B 83 C0 02 add eax,2
00007FF7F506191E 48 8B 8D E0 00 00 00 mov rcx,qword ptr [this]
00007FF7F5061925 48 8B 09 mov rcx,qword ptr [rcx]
00007FF7F5061928 89 01 mov dword ptr [rcx],eax
ri += 3;
00007FF7F506192A 48 8B 85 E0 00 00 00 mov rax,qword ptr [this]
00007FF7F5061931 48 8B 40 08 mov rax,qword ptr [rax+8]
00007FF7F5061935 8B 00 mov eax,dword ptr [rax]
00007FF7F5061937 83 C0 03 add eax,3
00007FF7F506193A 48 8B 8D E0 00 00 00 mov rcx,qword ptr [this]
00007FF7F5061941 48 8B 49 08 mov rcx,qword ptr [rcx+8]
00007FF7F5061945 89 01 mov dword ptr [rcx],eax
}();
Link to compiler explorer https://godbolt.org/z/oe9KPcWWv
| The behavior of Clang, GCC and MSVC in C++20 mode is correct for all standard versions supporting lambdas. decltype(i) and decltype(ri) yield the type of the named variables. It is not rewritten to refer to the members of the closure object, as would be the case for decltype((ri)). (see e.g. [expr.prim.lambda.capture]/14 in C++17 draft N4659 handling this specifically)
Apparently MSVC's default behavior for standard modes before C++20 is non-conforming in how lambdas are handled. According to the documentation the flag /Zc:lambda must be given to handle lambdas standard-conforming. With this option MSVC produces the same result as in C++20 mode for C++17 and C++14 mode as well.
See for example this bug report which was closed as not-a-bug with instruction to use this flag. Also note that it doesn't seem to be included in /permissive-.
|
71,460,531 | 71,460,571 | How to check invalid address/deleted pointer? | I'm pretty new to c++ and I'm stuck at this problem.
I append a struct pointer(Bar*) to a vector and that struct have a pointer class member(Foo*).
struct Bar
{
const int var{ 0 };
Foo* m_foo{ nullptr };
};
std::vector<Bar*> list;
int main()
{
Bar* p_Bar = new Bar;
p_Bar->m_foo = new Foo;
list.emplace_back(p_Bar);
}
I have a thread that checks validity of these pointers. Once I delete those pointers, vector element should exist and I should check whether both pointers are valid or not.
When any of them is invalid, I should erase that vector element(after check I mean).
Here's my try:
#include <iostream>
#include <vector>
#include <thread>
class Foo
{
public:
Foo() {};
const int var{ 5 };
};
struct Bar
{
const int var{ 0 };
Foo* m_foo{ nullptr };
};
std::vector<Bar*> list;
bool _check = true;
void Check()
{
while (_check)
{
for (int c = 0; c < (int)list.size(); c++)
{
Bar* p = list[c];
if (p)
{
if (p->m_foo)
{
std::cout << "m_foo->var:" << p->m_foo->var << "\nEnter anything to delete the element: ";
}
else
{
std::cout << "m_foo was nullptr";
}
}
else
{
std::cout << "Element was invalid";
}
}
std::this_thread::sleep_for(std::chrono::duration(std::chrono::seconds(2)));
}
}
int main()
{
Bar* p_Bar = new Bar;
p_Bar->m_foo = new Foo;
list.emplace_back(p_Bar);
std::thread thread1(Check);
thread1.detach();
std::string t;
std::cin >> t;
if (list[0]->m_foo)
delete list[0]->m_foo;
if (list[0])
delete list[0];
list.clear();
std::cin >> t;
_check = false;
return 0;
}
To check whether the pointer was deleted or not, I should use NULL or nullptr which actually means 0.
But once the pointer is deleted, the address will be something like this 0xFFFFFFFFFFFFFFFF and IDE will throw this kind of exception:
Exception thrown: read access violation.
p->m_foo was 0xFFFFFFFFFFFFFFFF.
How to check whether the pointer's deleted/pointer's address is valid or not?
|
How to check whether the pointer's deleted/pointer's address is valid or not?
It isn't possible to check whether a pointer is valid or invalid. If a pointer is valid or null, then you can check which one it is. If a pointer is invalid, then the result of the comparison will be unspecified.
Besides comparing an invalid pointer, your program has another bug: You're deleting in one thread, and accessing the pointer in another without synchronising the operations. Similarly, you're accessing the elements of the vector while its elements are removed in another thread. The behaviour of the program is undefined.
P.S. Avoid owning bare pointers.
|
71,460,632 | 71,461,062 | variadic template function (to delete number of dynamically allocated variables) | I don't get exactly if I am doing the right thing
template<typename ...AllVArgs>
auto dealloc_all(AllVArgs &..._AllVArgs) -> void {
(((std::cout << "\nin dealloc_all function " << &_AllVArgs), ...) << " ");
((delete _AllVArgs), ...);
((_AllVArgs), ...) = nullptr;
}
I allocated 2 struct and try to free them by using the variadic template function
struct a {
int x;
}
a *v1 = new a();
a *v2 = new a();
std::cout << "\nin a function " << &v1<< " " << &v2;
//address output = 0x1dce9ff588 0x1dce9ff580
dealloc_all(v1, v2);
I just wanted to know if I successfully free the allocated memory. btw these are the output it gives me, and I think there's no problem with it?
in a function 0xa4b89ff5c8 0xa4b89ff5c0
in dealloc_all function 0xa4b89ff5c8
in dealloc_all function 0xa4b89ff5c0
|
just wanted to know if I successfully free the allocated memory.
Yes: with
((delete _AllVArgs), ...);
you correctly free all the allocated memory
I don't get exactly if I am doing the right thing
Not completely: with
((_AllVArgs), ...) = nullptr;
you set to null pointer only the last argument of your function. If you want to set to null pointer all arguments, you have to rewrite your folding as follows
((_AllVArgs = nullptr), ...);
To verify what I say, I've rewritten your code as follows
#include <vector>
#include <iostream>
struct a
{ ~a() { std::cout << "deleting a" << std::endl; } };
template <typename ... Args>
auto dealloc_all (Args & ... as)
{
std::cout << "before delete" << std::endl;
((delete as), ...);
std::cout << "after delete" << std::endl;
((as), ...) = nullptr;
}
int main()
{
a *v1 = new a();
a *v2 = new a();
std::cout << "\nbefore function " << v1<< " " << v2 << std::endl;
dealloc_all(v1, v2);
std::cout << "\nafter function " << v1<< " " << v2 << std::endl;
}
so you can see that "deleting a" is written two times between "before delete" and "after delete"; so the destructor (called when you delete an allocated object) is called for every as... object.
But you can also see something as
after function 0x55b20b759eb0 0
printing the values of v1 and v2 (observe: I print the values of the pointers, not the addresses); if you want
after function 0 0
you have to change
((as), ...) = nullptr;
to
((as = nullptr), ...);
|
71,460,936 | 71,461,287 | Merge two Linked List In c++ without using inbuilt sort method | You are given two linked lists the thing is that one of them is sorted and the other isn't the task is that you have to merge them and sort their value while comparing during execution not sorting both linked lists separately and also without using any inbuilt method from c++ template library.
I have attempted the question by myself but it isn't working. I think it is approaching an infinite loop condition in the if condition!
This is what I have done:
#include <iostream>
using namespace std;
struct Student {
int id;
Student *next = NULL;
};
Student *first = NULL;
Student *last = NULL;
Student *first2 = NULL;
Student *last2 = NULL;
void display(Student *k);
void insert_end(Student *k);
void merge();
int main() {
int exit = 1;
do {
cout << "11.Display, 12.Insert, 3.Merge\n";
cout << "21.Display, 22.Insert, 0:exit\n";
cin >> exit;
switch (exit) {
case 11:
display(first);
break;
case 12:
insert_end(last);
break;
case 3:
// first = mergeTwoLists(first, first2);
//merge();
Student* SortedMerge(Student* a, Student* b);
break;
case 21:
display(first2);
break;
case 22:
insert_end(last2);
break;
default:
cout << "WRONG\n";
break;
}
} while (exit != 0);
return 0;
}
void display(Student *k) {
Student *p = k;
while (p != NULL) {
cout << "ID: " << p->id << "\n";
p = p->next;
}
}
void insert_end(Student *k) {
cout << "This is the function of insert_end \n";
Student *current = new Student;
cout << "Enter ID: ";
cin >> current->id;
if (k == NULL) {
if (k == last) {
first = last = current;
} else {
first2 = last2 = current;
}
} else {
if (k == last) {
last->next = current;
last = current;
} else {
last2->next = current;
last2 = current;
}
}
}
void merge() {
Student *p1 = first;
Student *p2 = first2;
while (p1 != NULL) {
p2 = first2;
while (p2->next != NULL) {
if (p1->id <= p2->id) {
Student *curr = p2;
curr->next = p1->next;
p1->next = curr;
}
p2 = p2->next;
}
p1 = p1->next;
}
}
What could be the possible optimized solution?
| You need at first to rewrite the function insert_end. Initially the both pointers last and last2 are null pointers
Student *first = NULL;
Student *last = NULL;
Student *first2 = NULL;
Student *last2 = NULL;
So if the user will decide at first to fill the second list then due to this if statement
if (k == NULL) {
if (k == last) {
first = last = current;
} else {
first2 = last2 = current;
}
}
the function will insert a new node in the first list instead of the second list.
The function merge is also wrong. For starters it changes neither first nor first2 and neither last and last2.
If the if statement
if (p1->id <= p2->id) {
Student *curr = p2;
curr->next = p1->next;
p1->next = curr;
}
gives the control then the data member next of the pointer p2 is changed due to these lines
Student *curr = p2;
curr->next = p1->next;
that is the data member next of the pointer of the second list points to the node of the first list.
But then after the if statement
p2 = p2->next;
the pointer p2 points to a node in the first list instead of pointing to a node in the second list.
To make the life easier you need to define one more structure as for example
struct List
{
struct Student *first;
struct Student *last;
};
and define the functions for pointers of this structure type.
|
71,461,032 | 71,461,072 | Why does this pointer behave differently between g++ and visual studio 2022's compiler? | Edit: my question was relating to the difference between compilers but I was just mislead to think there was different behavior when really both compilers were showing the expected "undefined behavior"
I know that using the static keyword here would be good for the building_num integer, but I don't understand why the value prints correctly when compiling with g++, I would think the integer value should be erased after the assign_building_num function terminates
With visual studio's compiler I see the behavior I assume, where it doesn't print out 400, it prints out some random number (in this case it is always 32759 for some reason)
#include <iostream>
#include <string>
using namespace std;
class building {
int* ptr_building_num;
public:
void set_building_num(int* num_ptr) {
ptr_building_num = num_ptr;
}
void print_building() {
cout << *ptr_building_num << flush;
}
};
void assign_building_num(building* building_ptr) {
//int* ptr_to_building_num = nullptr;
int building_num = 400;
int* ptr_to_building_num = &building_num;
building_ptr->set_building_num(ptr_to_building_num);
}
int main() {
building* ptr_to_some_building = nullptr;
ptr_to_some_building = new building;
assign_building_num(ptr_to_some_building);
ptr_to_some_building->print_building();
return 0;
}
| Variables declared in a scope (in this case, the scope for building_num is the body of the function assign_ building_num) cease to exist once the scope exits.
You are taking the address of an integer that only has a short lifetime, and retaining its address after the object has been destroyed.
Reading from a pointer to a destroyed object is Undefined Behavior, so both compilers are correct.
The integer whose address that your building object holds must live at least as long as the building object itself.
EDIT:
Since a question Undefined Behavior came up, here's what cppreference says about it, for completeness:
undefined behavior - there are no restrictions on the behavior of the
program. Examples of undefined behavior are data races, memory
accesses outside of array bounds, signed integer overflow, null
pointer dereference, more than one modifications of the same scalar in
an expression without any intermediate sequence point (until
C++11)that is unsequenced (since C++11), access to an object through a
pointer of a different type, etc. Compilers are not required to
diagnose undefined behavior (although many simple situations are
diagnosed), and the compiled program is not required to do anything
meaningful.
|
71,461,570 | 71,462,065 | Printing an element from an octree with cout alters the content? | I tried creating an octree in c++. Seems to work fairly well, but when I print the content of the tree it returns an access violation error. Running this in debug will print two different numbers, although the content should not have been changed. Here is the printout:
2
11
32762
From what digging I have done it seems like the cout statement ends up mutating the octree object. I don't see why this should happen. If my approach is faulty, then why does it work in the first .get statement?
Here is my code:
#include <iostream>
typedef unsigned int uint;
template <typename T>
class OcTree {
struct Node {
Node* parent;
uint depth;
Node* children[8];
T* data;
Node(Node* parent, uint depth, uint max_depth) : parent{parent}, depth{depth} {
for (int i=0; i<8; i++) {
children[i] = nullptr;
}
if (depth == max_depth) {
data = new T[8];
for (int i=0; i<8; i++) {
data[i] = T(); //Initialize data to default values
}
} else {
data = nullptr;
}
}
~Node() {
delete[] data;
}
};
uint max_depth;
Node root;
static uint make_subindex_from_index(uint x, uint y, uint z, uint depth) {
uint mask = 1 << depth;
uint x_bit, y_bit, z_bit;
x_bit = x & mask;
y_bit = y & mask;
z_bit = z & mask;
return compose_subindex(x_bit, y_bit, z_bit);
}
static uint compose_subindex(uint x_bit, uint y_bit, uint z_bit) {
uint out = 0;
if (x_bit) out += 4;
if (y_bit) out += 2;
if (z_bit) out += 1;
return out;
}
public:
OcTree(uint max_depth) : max_depth{max_depth}, root{Node(nullptr, 0, max_depth)} {}
uint get_range() {
return (uint)1 << max_depth;
}
void insert(uint x, uint y, uint z, T item) {
Node* current_node = &root;
uint subindex;
for (uint d = 0; d < max_depth; d++) {
subindex = make_subindex_from_index(x, y, z, d);
if (current_node->children[subindex] == nullptr) { //If the next node doesn't exist yet
Node new_node = Node(current_node, d+1, max_depth); //Make it
current_node->children[subindex] = &new_node;
}
current_node = current_node->children[subindex];
}
subindex = make_subindex_from_index(x, y, z, max_depth);
current_node->data[subindex] = item;
}
T get(uint x, uint y, uint z) {
Node* current_node = &root;
uint subindex;
for (uint d = 0; d < max_depth; d++) {
subindex = make_subindex_from_index(x, y, z, d);
if (current_node->children[subindex] == nullptr) {
std::cout << "Item does not exist!";
throw -1;
}
current_node = current_node->children[subindex];
}
subindex = make_subindex_from_index(x, y, z, max_depth);
return current_node->data[subindex];
}
};
//Temporary for testing purposes
int main() {
OcTree<int> test_tree = OcTree<int>(1);
std::cout << test_tree.get_range() << "\n";
test_tree.insert(0, 1, 2, 11);
std::cout << test_tree.get(0, 1, 2) << "\n";
std::cout << test_tree.get(0, 1, 2) << "\n";
}
| The specific error is here
Node new_node = Node(current_node, d+1, max_depth); //Make it
current_node->children[subindex] = &new_node;
'new_node' is a local variable and it will get destroyed once this function exits. You cannot store its address, its meaningless. UB.
You need
Node *new_node = new Node(current_node, d+1, max_depth); //Make it
current_node->children[subindex] = new_node;
Ie allocate it on the heap. Now you will have to deal with delete ing it once you are done with it.
You would be so so much better off if you learned to use
std::vector for you arrays of things (like children)
std::shared_ptr or std::unique_ptr instead of raw pointers
these 2 things will take care of a lot of issues for you
|
71,461,594 | 71,461,606 | Error defining const static member of class if the class has template | I have the following code in a .h file:
class Test1 {
struct A1 {
int x;
};
static const A1 a1;
};
template <class T>
class Test2 {
struct A2 {
int x;
};
static const A2 a2;
};
and I define values for both a1 and a2 in a .cpp file:
const Test1::A1 Test1::a1 = { 5 };
template<class T>
const Test2<T>::A2 Test2<T>::a2 = { 5 };
The odd thing is that for Test1 everything works, but for Test2 I get the following error in the last line of the .cpp file:
Error C2061 syntax error: identifier 'A2'
The only difference between Test1 and Test2 is that Test2 has a template. Why is this a problem, and how can I fix it? Also, this works as well:
test.h
struct A3 {
int x;
};
template <class T>
class Test3 {
static const A3 a3;
};
test.cpp
template<class T>
const A3 Test3<T>::a3 = { 5 };
So the problem is with using a struct defined in a templated class, but I can't find out what exactly is the problem.
(I'm compiling with c++14.)
| The fix is suggested by a compiler, just be more careful in reading the compiler messages.
<source>(17): warning C4346: 'A2': dependent name is not a type
<source>(17): note: prefix with 'typename' to indicate a type
<source>(17): error C2061: syntax error: identifier 'A2'
<source>(17): error C2143: syntax error: missing ';' before '{'
<source>(17): error C2447: '{': missing function header (old-style formal list?)
Or
<source>:17:7: error: missing 'typename' prior to dependent type name 'Test2<T>::A2'
const Test2<T>::A2 Test2<T>::a2 = { 5 };
^~~~~~~~~~~~
typename
1 error generated.
That means the correct code:
template<class T>
const typename Test2<T>::A2 Test2<T>::a2 = { 5 };
Read more: Why do we need typename here?.
|
71,462,073 | 71,462,123 | How to replace std::bind with lambda within steady_timer::async_wait | Live On Coliru
#include <iostream>
#include <boost/asio.hpp>
#include <functional>
class printer
{
public:
printer(boost::asio::io_context& io)
: timer_(io, boost::asio::chrono::seconds(1))
{
timer_.async_wait(std::bind(&printer::print, this));
// timer_.async_wait([this]() {
// print();
// });
}
void print()
{
std::cout << "hello world" << std::endl;
}
private:
boost::asio::steady_timer timer_;
};
int main()
{
boost::asio::io_context io;
printer p(io);
io.run();
return 0;
}
I tried to replace the following line:
timer_.async_wait(std::bind(&printer::print, this));
with
timer_.async_wait([this]() {
print();
});
But it failed and the compiler reports the following errors:
main.cpp: In constructor 'printer::printer(boost::asio::io_context&)':
main.cpp:12:22: error: no matching function for call to 'boost::asio::basic_waitable_timer<std::chrono::_V2::steady_clock>::async_wait(printer::printer(boost::asio::io_context&)::<lambda()>)'
12 | timer_.async_wait([this]() {
| ~~~~~~~~~~~~~~~~~^~~~~~~~~~~
13 | print();
| ~~~~~~~~
14 | });
| ~~
Question> What is the correct way to rewrite the std::bind with lambda expression?
Thank you
| Your lambda doesn't have the required signature.
Based the boost documentation, the callback takes a const boost::system::error_code& argument. std::bind lets you be a bit looser in the function signature (Why std::bind can be assigned to argument-mismatched std::function?), but lambdas need to be an exact match.
The following code seems to work for me
timer_.async_wait([this](auto const &ec) {
print();
});
|
71,462,164 | 71,481,189 | boost::iostreams::mapped_file_source opens a file that has CJK filename | Assume we have code like this:
boost::iostreams::mapped_file_source dev(paFileName.u8string().c_str());
where paFileName is a std::filesystem::path object.
On Windows, the internal character in std::filesystem::path is wchar_t, but boost::iostreams::mapped_file_source seems to only accept variant width character string. Therefore, we convert the fixed width wchar_t string to a variant width char string with method u8string.
The problem is that the conversion apparently causes the ctor of boost::iostreams::mapped_file_source unable to find the file in the filesystem, and the ctor will throw a boost::wrapexcept<std::ios_base::failure[abi:cxx11]> that says "failed opening file: The system cannot find the file specified."
How to fix this problem? Any suggestions? Thanks.
| According to the message of the compile-time error:
C:/msys64/mingw64/include/boost/iostreams/detail/path.hpp:138:5: note: declared private here
138 | path(const std::wstring&);
| ^~~~
Somehow Boost.Iostreams tried to convert the std::filesystem::path into a boost::iostreams::details::path but failed, because the conversion ctor that accepts the wide character string is not accessible. This problem doesn't happen on Linux, because the filesystem on Linux usually uses UTF-8 char strings as filenames. In contrast, on Windows the filenames are usually UTF-16 wchar_t strings.
My workaround is to avoid the conversion ctor mentioned above to be called. I gave a boost::filesystem::wpath instead of the original std::filesystem::path to Boost.Iostreams, hoping that the Boost version wpath is more acceptable to Boost.Iostreams.
boost::iostreams::stream<boost::iostreams::mapped_file_source> fin(
boost::filesystem::wpath(static_cast<std::wstring>(paFileName))
);
And it works.
|
71,463,199 | 71,463,275 | Returning const char* from funciton | I have this function, where I'm trying to return a const char*, but when I try to output the returned value, I get garbage value;
virtual const char* what() const noexcept
{
std::stringstream s;
if(m_id > -1)
s << m_message << " with id " << m_id << " does not exist";
else
s << m_message << " with name " << m_name << " does not exist";
//until now it works fine
std::string tmp = s.str();
const char* temp = tmp.c_str();
return temp; //after I execute this command, the value is deleted.
}
when I try to print:
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
I get this (different every time..) :
▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌╢Pⁿש▌'
What am I doing wrong?
| You are returning a pointer to the internal char data of a local std::string object that is destroyed when the function exits, thus the returned pointer is left dangling, pointing at invalid memory. Trying to access the data afterwards is undefined behavior.
Normally, you would have two choices to fix that:
return a std::string instead of a char* pointer.
allocate the char data dynamically, and then make the caller free it when done using it.
However, in this case, you are overriding the std::exception::what() method, so neither of those options are viable. What you will have to do instead is store your char data in a std::string member of your derived class, and then you can return a char* pointer to its data, eg:
private:
std::string m_what;
myException::myException(...)
{
...
std::stringstream s;
if (m_id > -1)
s << m_message << " with id " << m_id << " does not exist";
else
s << m_message << " with name " << m_name << " does not exist";
m_what = s.str();
}
virtual const char* what() const noexcept
{
return m_what.c_str();
}
If you derive your exception class from std::runtime_error instead of std::exception directly, this is already handled for you. std::runtime_error takes a string in its constructor, and overrides what() to return that string's data.
|
71,463,257 | 71,465,776 | Developing Windows Software on Linux | I am making software for windows that uses things like windows api and I really do not like developing on windows.
Is there a way to develop software on Linux, for Windows, preferably without virtual machines as my computer is not very powerful, I am using C/C++.
| There is probably no universal answer to this.
This is how I develop software on Linux that is used mainly on Windows:
I use the Qt framework which abstracts away all platform-dependent details in my case.
I use MinGW-w64 to cross-compile. It works very well with CMake-based projects and the excellent binaries from Martchus, which also have great support for static builds.
I use Wine for testing. However during development I can test and debug the Linux binary. A luxury due to Qt abstraction that fits my needs.
|
71,463,657 | 71,464,231 | C++: Pass string literal or variable to function | I have a function f that takes a string as input. I usually want to provide a string literal, e.g., f("hello"). However, I want to implement another function g that builds upon f:
std::string f(const std::string&& x) {
return x + " world";
}
std::string g(const std::string&& x) {
std::string res = f(x); // problem: rvalue reference to std::string cannot bind to lvalue of type std::string
res += "!";
return res;
}
int main() {
std::string res_a = f("hello");
std::string res_b = g("world");
return 0;
}
How can I achieve this in C++11/14 in a way that I can use f with string literals as well as variables?
| The traditional way to take a read-only parameter is by const lvalue reference.
std::string f(const std::string& x)
This rule of thumb applies to many types, not just std::string. The primary exceptions are types that are not bigger than a pointer (e.g. a char).
It's rather unusual for a function to have a const rvalue reference. As you discovered, that adds difficulty when trying to pass a variable as the argument. A non-const rvalue reference has value, but a const rvalue reference is inferior to a const lvaue reference in most cases. See also Do rvalue references to const have any use?
|
71,463,785 | 71,463,833 | Why is this code not producing expected output? | #include<iostream>
using namespace std;
#define sp ' '
std::ostream& nl(std::ostream os)
{
return os << '\n';
}
int main()
{
cout << 1 << sp << 2 << nl;
cout << 3 << sp << 4 << sp;
cin.get();
cout << 5 << sp << 6 << nl;
cin.get();
cout << 7 << sp << 8;
return 0;
}
I'm testing out my own stream manipulator that adds newline but doesn't flush.
I'm expecting no output until the end of program, since cout is supposed to only flush at the end of the program without endl. And also I'm expecting output to be
1 2
3 4
// newline added here and cin.get() executed adding another newline
5 6
// newline added here and cin.get() executed adding another newline
7 8
But instead I'm getting this.
1 2007818983 4 // cin.get() executed here in this line
5 600781898 //cin.get() executed here again
7 8
Why is that? And during debugging in Visual Studio 2019, is there any way to view what cout's, cin's or any stream's buffer in the debugger to find out what's going on?
| The problem is in nl function. you have to pass ostream by reference. Have a look at this code
// Pass by Ref
std::ostream& nl(std::ostream& os){
os << '\n';
return os;
}
|
71,464,671 | 71,464,883 | Input basic_ostream in the template | Why don't use ttt::focus_pocus() and is used without ()? What is the rule and why does it work here?
#include <iostream>
namespace ttt
{
template<class CharT, class Traits>
std::basic_ostream<CharT, Traits>& focus_pocus(std::basic_ostream<CharT, Traits> &os)
{
return os << "focus pocus";
}
};
int main()
{
std::cout << ttt::focus_pocus << std::endl; <--- here
}
DEMO
| The << operator is overloaded to accept functions with the same signature as the focus_pocus function in your example [1]. That is the reason why you don't call the function and don't need () brackets.
This overload is present, to allow outputtable objects like e.g. std::endl to manipulate the output stream and for example flush it after writing a newline character. In your special case, you could just as well have written a function that returned a string.
[1]: https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt
|
71,464,736 | 71,783,973 | How to attach Visual Studio to Unity in order to debug a native dll? | I have a native dll which is used by a project in Unity 2019.4.35f1. Since the logic in the dll is complicated I would like to be able to debug it.
From the main answer here
https://answers.unity.com/questions/30620/how-to-debug-c-dll-code.html
I was able to log debug from inside the dll.
From the answer from this thread by Tomas1856, a Unity Technologies superuser, I get that the only way to really debug the native dll code line by line is to attach a debugger to the executable.
https://forum.unity.com/threads/how-to-step-into-a-native-c-dll-in-visual-studio.413387/
The problem is that I am not able to.
I have the dll Visual Studio 2019 project. It is build in debug mode. It's pdb file is here. I have tried changing many project settings from advices I have read on the internet including on stackoverflow. But still when I press the play button in Unity and press the Attach to Process in Visual Studio the breakpoints I have put in the dll code all turn white with an error message "The breakpoint will not be hit. No symbols have been loaded for this document".
I am attaching to the Unity.exe process. I have tried changing the output path for the dll and the pdb.
I am pretty sure I am missing something obvious.
Can someone provide any guidance, please?
| After a month I have accidently found the reason. Error Pause was activated. I have logged an error so the Game has paused which makes it impossible to attach to the Unity process. I hope this helps anyone.
|
71,465,026 | 71,466,332 | Modern c++ while dealing with legacy code owning raw pointers: unique_ptr VS "softer" GSL owner<T*> | I would like to figure out pro and contra of different ways to deal with the issue of owning and not-owning raw pointers mixed up, within the pre-C++11 OOP framework that I am using. My role "as framework user" is basically to implement a dozen of abstract classes among the huge class hierarchy provided by the framework. This framework (and the "user code examples" from which I start):
extensively create objects in the heap via factories/singletons or explicit new, and most of these objects are managed by the framework but others are users' responsibility - and you have to inspect the examples user code and cross-check the thick user manual to be sure which
examples suggests to embed other classes in your implementation classes always via pointer (which you create in constructors in the proper way and, if you are the owner, delete in destructor)
all interrelation between classes is via pointer, I mean that most of the methods takes non-owning raw pointers as parameter to the objects that they have to use.
In MY user code I want to achieve the following GOALS in order of priority:
Clearly mark which member pointer is an owning pointer, so that I do not have to go through the manual every time that I read again a piece a code
Have a safer code
Have a simpler/more readable/more maintainable code
I consider the following options for all member objects of my implementation classes:
A) all owning raw pointers (clearly detectable by the delete in the destructor but also always cross-checked with the user guide) replaced with unique_ptr.
PRO I achieve all (1), (2) and (3), as e.g. I kick out the trivial destructor, etc
CONTRA I have to add .get() at every call of the framework methods (plus sometimes some .reset() when initlization cannot happen in-class/in-initializer-list), which at least at the first glance looks weird, but maybe one has just to get used to.
B) the "softer" approach of the "Guideline Support Library" owner<T*> "tag".
PRO at least I achieve (1), without diverging too much from the "framework guidelines".
CONTRA I give up with (2) and (3). Further developments will inherit further on this legacy
C) why should I have pointers at all, and not just embed the object inside??? I should get the exact PRO and CONTRA as option (A) - just & to add instead of .get() -, right???
Of course the approach departs more substantially from what the framework suggests.
This is what I have found so far, any further overlooked details (especially warnings) or suggestions are really welcome.
|
A) all owning raw pointers (clearly detectable by the delete in the destructor but also always cross-checked with the user guide) replaced with unique_ptr.
CONTRA I have to add .get() at every call of the framework methods (plus sometimes some .reset() when initlization cannot happen in-class/in-initializer-list), which at least at the first glance looks weird, but maybe one has just to get used to.
I would definitely recommend this approach. If you are bothered by the get and reset calls, you can define your own wrapper that has implicit conversions. Less safe, still better than the old state. Something like this:
template<class T>
struct owned
{
std::unique_ptr<T> ptr;
/*implicit*/ owned(T* ptr=nullptr) noexcept
: ptr(ptr)
{}
/* implicit */ operator T*() const noexcept
{ return ptr.get(); }
};
C) why should I have pointers at all, and not just embed the object inside??? I should get the exact PRO and CONTRA as option (A) - just & to add instead of .get() -, right???
Of course the approach departs more substantially from what the framework suggests
There is a good chance that you can't do this if your framework uses opaque pointers as compilation firewalls.
Another risk is that if you hand out pointers to these objects and then move the objects around, you create dangling pointers. Note that the objects created by the framework might themselves be self-referential or their own constructor/factory might have borrowed references to the object.
A well-written framework should either deal with those cases in copy constructors or deny use of those (making them private if this is pre C++11). That is something you have to check for yourself.
|
71,465,484 | 71,471,871 | Is there a proper way to receive input from console in UTF-8 encoding? | When getting input from std::cin in windows, the input is apparently always in the encoding windows-1252 (the default for the host machine in my case) despite all the configurations made, that apparently only affect to the output. Is there a proper way to capture input in windows in UTF-8 encoding?
For instance, let's check out this program:
#include <iostream>
int main(int argc, char* argv[])
{
std::cin.imbue(locale("es_ES.UTF-8"));
std::cout.imbue(locale("es_ES.UTF-8"));
std::cout << "ñeñeñe> ";
std::string in;
std::getline( std::cin, in );
std::cout << in;
}
I've compiled it using visual studio 2022 in a windows machine with spanish locale. The source code is in UTF-8. When executing the resulting program (windows powershell session, after executing chcp 65001 to set the default encoding to UTF-8), I see the following:
PS C:\> .\test_program.exe
ñeñeñe> ñeñeñe
e e e
The first "ñeñeñe" is correct: it display correctly the "ñ" caracter to the output console. So far, so good. The user input is echoed back to the console correctly: another good point. But! when it turns to send back the encoded string to the ouput, the "ñ" caracter is substituted by an empty space.
When debugging this program, I see that the variable "in" have captured the input in an encoding that it is not utf-8: for the "ñ" it use only one character, whereas in utf-8 that caracter must consume two. The conclusion is that the input is not affect for the chcp command. Is something I doing wrong?
UPDATE
Somebody have asked me to see what happens when changing to wcout/wcin:
std::wcout << u"ñeñeñe> ";
std::wstring in;
std::getline(std::wcin, in);
std::wcout << in;
Behaviour:
PS C:\> .\test.exe
0,000,7FF,6D1,B76,E30ñeñeñe
e e e
Other try (setting the string as L"ñeñeñe"):
ñeñeñe> ñeñeñe
e e e
Leaving it as is:
std::wcout << "ñeñeñe> ";
Result is:
eee>
| This is the closest to the solution I've found so far:
int main(int argc, char* argv[])
{
_setmode(_fileno(stdout), _O_WTEXT);
_setmode(_fileno(stdin), _O_WTEXT);
std::wcout << L"ñeñeñe";
std::wstring in;
std::getline(std::wcin, in);
std::wcout << in;
return 0;
}
The solution depicted here went in the right direction. Problem: both stdin and stdout should be in the same configuration, because the echo of the console rewrites the input. The problem is the writing of the string with \uXXXX codes.... I am guessing how to overcome that or using #define's to overcome and clarify the text literals
|
71,466,444 | 71,466,774 | C++ class as namespace for static values | Is there anyway to have the same API from namespace with a class
Exemple for namespace :
namespace Direction
{
static const vec3 up = vec3(0, 1, 0);
}
// in code
{
vec3 v = Direction::up;
}
whereas using a class I have to use a method
class Color : public vec4
{
// class stuff //
static Color black() {return Color(0, 0, 0, 1);}
}
// in code
{
Color c = Color::black();
}
I want to be able to use Color c = Color::black; with Color being a class and black being defined in header. Is there any way to do it ?
EDIT : an other way to put it around is :
Why does this gives me "incomplete type not allowed" and "a member of 'const Color' cannot have and in-class initializer"
class Color : public glm::vec4
{
public:
explicit Color(const float r, const float g, const float b, const float a = 1.0f)
: glm::vec4(r, g, b, a) {}
static const Color a = Color(1, 1, 1, 0); // error
}
| try this
class Color
{
public:
Color(int x, int y, int z, int t)
{}
const static Color BLACK;
};
const Color Color::BLACK{1,2,3,4};
int main()
{
Color c = Color::BLACK;
}
I tested at https://godbolt.org/z/4oP55jTMK
|
71,466,707 | 71,510,692 | C++ container without C++ standard lib | In the context of embedded software I want to make a std::vector-like container.
Vector has both size and capacity, which means vector has allocated capacity*sizeof(T) bytes, but only size entries are constructed.
An example
vector<string> v;
v.reserve(100)
v.resize(10)
v[9] gives a valid string , but v[10] gives a valid allocated memory portion of uninitialized data, so any string method will have an undefined behaviour, like v[10]= string(), if string& operator(const string& rhs) tries to destroy *this.
How can I build an object in a given memory address just using C++ compiler without including <new> or any other C++ standard include files?
UPDATE
Can I write a custom implementation of placement new operator and make final executable independant from libstdc++.so?
I don't want static linking against libstdc++.a either.
|
How can I build an object in a given memory address just using C++ compiler without including or any other C++ standard include files?
You have to read your compiler documentation and/or source code and related libraries and find out what is needed for that particular compiler with particular options used by you to allow this particular compiler with this particular configuration to work with placement new. I.e. if you can't use portability features like header files, you have to provide the compiler with your own non-portable replacement of header files.
For example, the following should be fine for gcc x86_64:
inline void* operator new(unsigned long, void* __p) { return __p; }
inline void operator delete(void*, void*) { }
struct A {};
int main() {
alignas(A) char buf[sizeof(A)];
struct A *a = new (buf) A;
a->~A();
::operator delete(buf, a);
}
make final executable independant from libstdc++.so?
In the same way, compiling against LLVM libc++ makes the executable independent of GNU libstdc++. Provide your own implementation of needed functions in libstdc++ and link with them.
Placement new are inline empty functions on gcc. They use no symbols from the shared library.
|
71,466,931 | 71,468,126 | Hash Function for a 7 digits int | I'm new to hash tables and functions, so I apologize in advance if I got anything wrong.
I'm trying to create a hash table in C++ for a list of about 100k entries comprised of a 7 digit number.
The thing is, I got stuck while trying to figure out what hash function to use.
When using %100000 I got ~65k unique keys, while there are ~90k unique entries. Which means that about 1/3 of the data will have collisions.
Is this a good hash function to use? Or is there a better function to use in that case in order to have less collisions?
What size should my table be?
Thanks again!
Edit-
The entries are numbers between 1 and 2 mil.
Is it possible to use the number itself as the key? Or should keys for hash table always start at 0?
| The standard library comes with two types internally using a hash table: std::unordered_map and std::unordered_set.
As your key type is an integral type you get a hash table pretty conveniently by std::unordered_map<YourIdType, YourDataType. You can easily access the data via theMap[someId], but be aware that if the key is not found a new object is created! If that's not desired you'd rather use theMap.find(someId), which returns an iterator.
The drawback, though, is that you store the id twice then (internally as a std::pair<YourIdType, YourDataType>). You can avoid that by using a std::unordered_set. To be able to do so, though, you need to specialise std::hash and std::equal_to for your type:
namespace std // you are not allowed to add to – with exception of specialisations
{
template<>
struct hash<YourDataType>
{
size_t operator()(YourDataType const& object) const
{
return hash<YourIdType>()(object.id);
}
};
// analogously equal_to with appropriate comparisons, possibly by
// comparing the object's addresses
Alternatively you can provide a custom hasher type (with C++20 that can even be a lambda packed into decltype) to the set as second template parameter and just implement operator== for your object type, or provide a custom equality comparer type if you need it to compare differently than the operator, maybe like:
// C++20 required:
using YourMapType = std::set
<
YourDataType,
decltype
(
[](YourDataType const& object)
{ return std::hash<YourIdType>()(object.id); }
),
decltype
(
[](YourDataType const& o1, YourDataType const& o2)
{ return &o1 == &o2; } // TODO: comparisons as you need!
)
>;
// alternatively create custom types with appropriate operator() implementations
Drawback here is – apart from additional complexity for the specialisations – that you cannot lookup objects by the id only, instead you need a complete object of your data type.
So which one is more appropriate/suitable? That depends on your concrete requirements...
|
71,467,220 | 71,467,301 | How to concatenate the preprocessor constant and a literal string in cout | I started to learn c++, and when I tried to cout a macro it prints the value in the console but when I tried to cout the macro with another string literal, it raises an error.
#include <iostream>
using namespace std;
#define PI 3.14;
int main()
{
cout<<"Value of PI: " << PI;
cout<<"Value of PI: " << PI << endl;
}
First-line inside the main function works perfectly, but the second line raises an error while compiling.
Error:
error: expected primary-expression before '<<' token
cout<<"Value of PI: " <<PI<<endl;
What am I doing wrong here?
| The problem is that you have a semicolon at the end of the macro.
This line
cout<<"Value of PI: " << PI << endl;
then becomes:
cout<<"Value of PI: " << 3.14; << endl;
// ^
So, just remove the ; at the end of the macro:
#define PI 3.14
You could also use a proper constant instead of a macro (which is usually preferred):
inline constexpr double PI = 3.14;
or use the mathematical constants library part that was added in C++20:
#include <numbers>
int main() {
std::cout<<"Value of PI: " << std::numbers::pi << '\n';
}
|
71,467,245 | 71,467,292 | Passing pre-processor flags that contain special characters [c++17, g++] | I am trying to assign a value to a const char* by using a pre-processor flag in the following way.
#include <iostream>
#define ST(A...) #A
#define STR(A) ST(A)
const char* output = STR(FLAG);
int main() {
std::cout << output;
}
This approach works well, unless FLAG contains some special characters. When I attempt to build the above with
g++ .\Main.cpp -std=c++17 -DFLAG="a,b!c)d}e-f"
I get this in the error log. It doesn't like the special characters.
<command-line>: error: expected ',' or ';' before 'd'
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
| ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
6 | const char* output = STR(FLAG);
| ^~~~
<command-line>: error: expected declaration before '}' token
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
6 | const char* output = STR(FLAG);
| ^~~~
<command-line>: error: 'e' does not name a type
.\Main.cpp:4:19: note: in definition of macro 'STR'
4 | #define STR(A) ST(A)
| ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
6 | const char* output = STR(FLAG);
|
The desired output of the program would be a,b!c)d}e-f.
Is there any (sane) way to obtain this functionality using pre-processor flags, or something similar?
| You don't have to use stringification macros when FLAG is a string:
-std=c++17 -DFLAG="\"a,b!c)d}e-f\""
Live Demo
|
71,467,348 | 71,467,403 | Reusing String in C++ in function | As someone whose main language has been Python so far, I have a problem with string reuse.
Here's an example code (simplified):
void function(std::string &basicString)
{
std::cout << "Function print: " << &basicString << "\n";
}
int main()
{
std::vector<std::string> x_files;
/*
Does sth, x_files contains some strings
*/
for (std::vector<std::string>::size_type i = 0; i != x_files.size(); i++) {
std::string temp = x_files[i];
std::cout << temp << "\n";
function(temp);
}
return 0;
}
The thing is, as a result I'd like to have this:
my_string
Function print: my_string
Instead, I get this:
my_string
Function print: 0x7cd2346eaf1827cd
0x7cd2346eaf1827cd - not exactly what I get every time, but an example.
| std::cout << "Function print: " << &basicString << "\n";
Here you use unary & operator, which is an address-of operator, in other words it gives you a pointer. And since this is not a char pointer, std::cout prints the pointer value, in other words a memory address, as hex.
Solution is simple, remove &:
std::cout << "Function print: " << basicString << "\n";
Perhaps you're getting confused about pointers, because if instead of reference you used a pointer, you'd do this:
void function(std::string *basicString)
{
std::cout << "Function print: " << *basicString << "\n";
}
Pointers and references are quite similar, but they are not the same, including this difference in how they are declared and used.
Finally, you probably want to pass a const reference:
void function(const std::string &basicString)
You should always use const with a reference parameter, unless you intend to modify the original.
|
71,467,429 | 71,469,469 | Link dll against static build of QuaZip using Qt5.12 in VS2017 | I'm trying to link a .dll against a static builld of QuaZip library to get rid of the quazip.dll dependency at runtine. Since I've ran into a dependency conflict at production because a customer is using other third party applications in the same process where my .dll is uncluded, which are also using the quazip.dll but a legacy version.
My steps were first to statically compile the zlib dependency as instructed in other posts with the ZLIB_WINAPI flag. Then I compiled QuaZip also with the appropriate ZLIB_WINAPI flag and QUAZIP_STATIC. As zlib.h I have used QtZlib/zlib.h header like in this post recommended. In my .dll project I've also tried to set all the mentioned flags (QUAZIP_STATIC seems to be necessary). Now when I try to compile my .dll I get the following errors
1>quazip.lib(zip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__z_deflate@8" in Funktion "_zipCloseFileInZipRaw64@16".
1>quazip.lib(zip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__z_deflateEnd@4" in Funktion "_zipCloseFileInZipRaw64@16".
1>quazip.lib(zip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__z_crc32@12" in Funktion "_zipWriteInFileInZip@12".
1>quazip.lib(unzip.obj) : error LNK2001: Nicht aufgelöstes externes Symbol "__imp__z_crc32@12".
1>quazip.lib(zip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "_imp__z_deflateInit2@32" in Funktion "_zipOpenNewFileInZip4_64@76".
1>quazip.lib(zip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__z_get_crc_table@0" in Funktion "_zipOpenNewFileInZip4_64@76".
1>quazip.lib(unzip.obj) : error LNK2001: Nicht aufgelöstes externes Symbol "__imp__z_get_crc_table@0".
1>quazip.lib(unzip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__z_inflate@8" in Funktion "_unzReadCurrentFile@12".
1>quazip.lib(unzip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "__imp__z_inflateEnd@4" in Funktion "_unzCloseCurrentFile@4".
1>quazip.lib(unzip.obj) : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol "_imp__z_inflateInit2@16" in Funktion "_unzOpenCurrentFile3@20".
All projects have been build with the /MT flag.
This is my linker command line
/OUT:"builds\qt5\dll\release\.dll" /MANIFEST /NXCOMPAT /PDB:"builds\qt5\dll\release\.pdb" /DYNAMICBASE "qtmain.lib" "Qt5Core.lib" "Qt5Gui.lib" "Qt5Widgets.lib" "Qt5Sql.lib" "Qt5Network.lib" "Qt5PrintSupport.lib" "qwt.lib" "sloperatecppapi.lib" "slgfw.lib" "slgfwwidget.lib" "slcap.lib" "sltrc.lib" "sltrp.lib" "slhmiutilitieslib.lib" "slaesvcadapter.lib" "slfsfilesvcadapter.lib" "sltraceadapter.lib" "slarchiveadapter.lib" "slmd.lib" "slgfwmanager.lib" "slcncversioninfo.lib" "quazip.lib" "setupapi.lib" "wsock32.lib" "ws2_32.lib" "ucrt.lib" "vcruntime.lib" "msvcrt.lib" "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib" "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib" /DLL /MACHINE:X86 /SAFESEH /INCREMENTAL:NO /PGD:"builds\qt5\dll\release<myapplication>.pgd" /SUBSYSTEM:WINDOWS /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /ManifestFile:"builds\qt5\dll\release<myapplication>.dll.intermediate.manifest" /ERRORREPORT:PROMPT /NOLOGO /LIBPATH:"S:\hmisl\lib" /LIBPATH:"S:\hmisl\siemens\sinumerik\hmi\osal\ace\lib" /LIBPATH:"S:\hmisl\siemens\sinumerik\hmi\osal\qt\lib" /LIBPATH:".\include\qt5\qwt\lib" /LIBPATH:".\include\qt5\quazip\lib" /LIBPATH:".\include\qt5\modbus\lib" /LIBPATH:".\include\qt5\qtsingleapplication\lib\release" /TLBID:1
I would be grateful for any new tip, because I've been trying this for almost a week now and I'm running out of ideas.
| Ok, three days of agony and I have the solution. I recompiled the zlib, this time not using the provided project file in \contrib\vstudio\vc14, but generating my own with CMake. Then QuaZip linked against it with the flag QUAZIP_STATIC. I then set this flag in my project, which uses QuaZip and linked it against the built quazip.lib and its dependency zlibstatic.lib. Now the library is built into my .dll statically and I no longer have to supply the quazip.dll that caused the conflict.
|
71,467,718 | 71,468,004 | How do I fix this for loop problem in C++? | I have this for loop problem in my c++ program. When i try to run it it's all working fine but there is a small problem in the "Enter name:" loop. The "Enter name:" outputs 5 times but the first "Enter name:" is not recognized as part of the loop but instead the 6th empty line before the last "Enter name:" loop is recognized as one but it does not have a "Enter name:" in it, it is just an empty line with no words but the program recognized it as part of the loop not the one in the very first line with the "Enter name:". Can someone help me to fix and recognize the first line with the "Enter name:" as part of the loop and not recognize the 6th line of the program as part of the loop.
This is my code for my c++ program:
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
char names[5][20],t[20];
int i,j;
for ( int i = 0; i < 5; i++ )
{
cout << "Enter name: ";
cin.getline( names[i], 20 );
}
{
cout<<" ";
cin>>names[i];
}
for(i=1; i<5; i++)
{
for(j=1; j<5; j++)
{
if(strcmp(names[j-1], names[j])>0)
{
strcpy(t, names[j-1]);
strcpy(names[j-1], names[j]);
strcpy(names[j], t);
}
}
}
cout<<"\n Names Sorted in Alphabetical Order : \n\n";
for(i=0; i<5; i++)
{
cout<<" ";
cout<<names[i]<<"\n";
}
return 0;
}
| There are 2 problems with your code:
Mistake 1
The variable i is uninitialized and you're using that uninitialized variable when you wrote:
cin>>names[i]; //this is undefined behavior since `i` is uninitialized
which leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Mistake 2
You have an unnecessary block(given below) in your code:
{
cout<<" ";
cin>>names[i];
}
The above block does not belong to any for loops and is completely unnecessary. You should remove the above shown block.
Additionally, you need to take care of the fact that you must not go out of bounds of any of the array in your program. For example, say if you have an array named arr of length 5 then you can safely access elements: arr[0],arr[1],arr[2],arr[3] and arr[4]. But if we try to access arr[5] then it will lead to undefined behavior.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
71,468,108 | 71,471,278 | DocuSign integration from desktop application | I am trying to implement document signing with the DocuSign API in our Windows desktop application built in VC++.
Our application is built with unmanaged code without using .net. I tried the supported languages, C++ is not available so I tried C# that is web interface which I can't use inside my application.
How can I use the DocuSign API in an unmanaged c++ application?
| You can use the Microsoft open-source REST API C++ SDK
https://github.com/microsoft/cpprestsdk
"
C++ Rest SDK
The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services."
You will still need to get an integration key and set it up for authentication, maybe use JWT since it's a desktop app.
|
71,468,470 | 71,469,669 | Use thread with shared memory | I have an exe that writes data to shared memory than i read data from shared memory, i want to use std::thread when copy shared memory to different memory because writer exe does not stop writing.
When i use std::thread for copying shared memory,i pass memory structure as parameter than memory structure will be null in thread function, but when use the function normally, function memory structure will be as i expect. am i missed something or std::thread not useable for shared memory ?
struct Foo {
imgHeader imgHeader;
uint8_t imgBuf[12441600];
}
void memCpyFunc(uint8_t buf[12441600], std::list<uint8_t*>& bufferList) {
uint8_t* ImgBuffer = new uint8_t[12441600];
memcpy(ImgBuffer, buf, 12441600);
bufferList.push_back(ImgBuffer);
}
int main(){
Foo* foo;
shmid = shmget(SHM_KEY, sizeof(Foo), 0666 | IPC_CREAT);
foo = (Foo*)shmat(shmid, NULL, 0);
std::list<uint8_t*> bufferList;
memCpyFunc(foo->imgBuf, bufferList); //It works
std::thread thread(&memCpyFunc, foo->imgBuf, std::ref(bufferList)); //Segmantation Fault
//foo->imgBuf error: Cannot access memory at address 0x7ffff03b3078
thread.detach();
if (shmdt(foo) == -1) {
perror("shmdt");
}
}
I simply want to copy data from shared memory to different memory with thread.
| Okay, there are some problems with your code as written. First, main is almost certainly going to quit before the thread gets a chance to run. But even if this isn't main but is something else (and thus your program isn't trying to quit), then bufferList is going out of scope before your thread runs.
This is a time when Francois might be right about using thread->join(), although I normally disagree with him about that. There are times to detach and times to use join.
Are you sure the error is about the shared memory and not about bufferList?
I'd do this. First, I'd change the detach to a join, and then I'd stick debug statements in the function you're calling. The code should work as long as main doesn't return too fast.
|
71,468,722 | 71,488,391 | reverse_iterator weird behavior with 2D arrays | I have a 2D array. It's perfectly okay to iterate the rows in forward order, but when I do it in reverse, it doesn't work. I cannot figure out why.
I'm using MSVC v143 and the C++20 standard.
int arr[3][4];
for (int counter = 0, i = 0; i != 3; ++i) {
for (int j = 0; j != 4; ++j) {
arr[i][j] = counter++;
}
}
std::for_each(std::begin(arr), std::end(arr), [](auto const& row) {
for (auto const& i: row) {
fmt::print("{} ", i);
}
fmt::print("\n");
});
std::for_each(std::rbegin(arr), std::rend(arr), [](auto const& row) {
for (auto const& i: row) {
fmt::print("{} ", i);
}
fmt::print("\n");
});
The output for the first for_each is fine:
0 1 2 3
4 5 6 7
8 9 10 11
Yet the second one is garbage:
-424412040 251 -858993460 -858993460
-424412056 251 -858993460 -858993460
-424412072 251 -858993460 -858993460
When I print their addresses up I couldn't understand it:
<Row addr=0xfbe6b3fc58/>
0 1 2 3
<Row addr=0xfbe6b3fc68/>
4 5 6 7
<Row addr=0xfbe6b3fc78/>
8 9 10 11
<Row addr=0xfbe6b3fb98/>
-424412040 251 -858993460 -858993460
<Row addr=0xfbe6b3fb98/>
-424412056 251 -858993460 -858993460
<Row addr=0xfbe6b3fb98/>
-424412072 251 -858993460 -858993460
What is happening here?
| This is very likely a code generation bug of MSVC related to pointers to multidimensional arrays: The std::reverse_iterator::operator*() hidden in the range-based loop is essentially doing a *--p, where p is a pointer type to an int[4] pointing to the end of the array. Decrementing and dereferencing in a single statement causes MSVC to load the address of the local variable p instead of the address of the previous element pointed to by the decremented p, essentially resulting in the address of the local variable p being returned.
You can observe the problem better in the following standalone example (https://godbolt.org/z/x9q5M74Md):
#include <iostream>
using Int4 = int[4]; // To avoid the awkward pointer-to-array syntax
int arr[3][4] = {};
Int4 & test1()
{
Int4 * p = arr;
Int4 * pP1 = p + 1;
// Works correctly
--pP1;
Int4 & deref = *pP1;
return deref;
}
Int4 & test2()
{
Int4 * p = arr;
Int4 * pP1 = p + 1;
// msvc incorrectly stores the address of the local variable pP1 (i.e. &pP1) in deref
Int4 & deref = *--pP1;
return deref;
}
int main()
{
std::cout << "arr = 0x" << &arr[0][0] << std::endl;
std::cout << "test1 = 0x" << &test1() << std::endl; // Works
std::cout << "test2 = 0x" << &test2() << std::endl; // Bad
}
In this example, &test1() correctly prints the address of the first element of arr. But &test2() actually prints the address of the local variable test2::pP1, i.e. it prints &test2::pP1. MSVC even warns that test2() returns the address of the local variable pP1 (C4172).
clang and gcc work fine. Versions before MSVC v19.23 also compile the code correctly.
Looking at the assembly output, clang and gcc emit the same code for test1() and test2(). But MSVC is doing:
; test1()
mov rax, QWORD PTR pP1$[rsp]
mov QWORD PTR deref$[rsp], rax
; test2()
lea rax, QWORD PTR pP1$[rsp]
mov QWORD PTR deref$[rsp], rax
Notice the lea instead of the mov statement, meaning that test2() loads the address of pP1.
MSVC seems to get confused somehow by pointers to multidimensional array.
|
71,469,730 | 71,469,948 | How to initialize all fields of a big class with two different fields in standard C++ | I have a very big class with a bunch of members, and I want to initialize them with a given specific value.The code below is the most naive implementation, but I don't like it since it's inelegant and hard to maintain because I have to list all the members in the constructor.
struct I_Dont_Like_This_Approach {
int foo;
long bar;
unsigned baz;
int a;
int b;
int c;
int d;
SomeStruct and_so_on;
/*...*/
public:
explicit I_Dont_Like_This_Approach(int i) : foo(i), bar(i), baz(i), a(i), b(i), c(i), d(i), and_so_on(i) /*...*/ {}
};
I thought of an alternative implementation using templates.
template <int N>
struct MyBigClass {
int foo{N};
long bar{N};
unsigned baz{N};
int a{N};
int b{N};
int c{N};
int d{N};
SomeStruct and_so_on{N};
/*...*/
};
but I'm not sure if the code below is safe.
MyBigClass<1> all_one;
MyBigClass<2> all_two;
/* Is the following reinterpret_cast safe? */
all_one = reinterpret_cast<decltype(all_one) &>(all_two);
Does the C++ specification have any guarantees about the data layout compatibility of such templated structs? Or is there a more reasonable implementation? (in standard C++, and don't use macros)
| I would argue that the first one is much more maintainable, with the right warnings enabled (and a modern compiler), you will see if your initializer list gets out of sync with the class fields at compile time.
As to your alternative.. you're using templates as compiler arguments, which is not what they're meant to be. That brings a whole slew of issues:
instantiated templates get copied in memory, making your executable larger. Though in this case, I'm hoping your compiler is smart enough to see that the field structure is the same and treat it as one type.
your code now works only with constant literal integers, no more run-time variables.
there is indeed no guarantee that the memory structure of those two classes is the same. You can disable optimizations in most compilers (like pack, alignment, etc), but that comes at the cost of disabling optimizations, which isn't actually necessary except to support your specific code.
And related to the last one, if you ever need to consider whether this is ever going to break, you're heading down a very dark road. I mean any sane person can tell you it will "probably work", but the fact that you have no guarantees in the language that pretty much popularized memory corruption and buffer overflows should terrify you. Write constructors.
|
71,469,748 | 71,470,010 | Move object from local variable to std::shared_ptr | Please note that with the words "object" and "move" in the title, I do not mean the C++-specific concepts of what an object is and what it means to move an object.
I have a local variable of a pretty simple struct type where I accumulate some values read from a config file.
struct Foo
{
std::string name;
float someValue;
int someStuff;
};
// This stores the current settings
std::shared_ptr<Foo> currentFooSetting;
void readSettings()
{
Foo f;
f.name = ...;
f.someValue = ...;
f.someStuff = ...;
if (everythingIsOk)
{
//TODO:
//Delete the old object pointed to by currentFooSetting (if it's not pointed to by any other shared_ptr, of course)
//Allocate some new memory to put f into... or maybe reuse *currentFooSetting if it's now free idc.
//Copy f to the new memory location
//
}
}
If everything is OK, I want to move f onto the heap and have currentFooSetting point to that.
How do I do that?
It seems I could do this:
std::shared_ptr<Foo> newFooSetting = std::make_shared<Foo>();
*newFooSetting = f;
currentFooSetting = newFooSetting;
(Using a local variable to better emphasize the separation between the allocation, copying, and replacing.)
But even after reading through https://en.cppreference.com/w/cpp/memory/shared_ptr and https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared I have no idea whether that's "the way" of doing this.
| How about
if (currentFooSetting) {
*currentFooSetting = f;
} else {
currentFooSetting = std::make_shared<Foo>(f);
}
this sort-of ensures that you have just one shared pointer, and once it is created, its value is changed on update. Alternately, if existing holders-of-the-shared-pointer should keep their values, just assign a new one:
currentFooSetting = std::make_shared<Foo>(f);
This will "fork" the views of current settings -- holders-of-a-shared-pointer keep the old one with old values, but functions that newly share the pointer get the new value.
Which makes more sense depends on your design (which is what Ted Lyngmo asks in a comment). Both code snippets assume your Foo class has suitable (copy) constructors.
|
71,470,625 | 71,471,149 | const object as a data member vs normal variable | I was trying to make a Container class that will be using an object of a class Comparator which will be passed through the template.
So I am doing something like:
template<typename T>
class Container{
const T c;
};
struct Comparator{
public:
bool operator()(const int a, const int b)const{
return a < b;
}
};
int main(){
Container<Comparator> container;
return 0;
}
When I am trying to compile this code I am getting the following error:
e.cpp:28:27: error: uninitialized const member in 'class Container<Comparator>'
28 | Container<Comparator> container;
| ^~~~~~~~~
e.cpp:16:13: note: 'const Comparator Container<Comparator>::c' should be initialized
16 | const T c;
|
To get rid of this error what I did is just added a default constructor in the Comparator class:
struct Comparator{
public:
Comparator(){
}
bool operator()(const int a, const int b)const{
return a < b;
}
};
But the weird thing I observed is that when I am making a const object of the class Comparator as a normal variable (not the data member of any class) I am not getting any kind of error.
struct Comparator{
public:
bool operator()(const int a, const int b)const{
return a < b;
}
};
int main(){
const Comparator comp;
return 0;
}
So my question is why I am getting errors when making a const object of the Comparator type within a class and not when making a normal const object of the same type?
| If no initializer is given for the const Comparator variable it must be const-default-constructible. But your class Comparator is const-default-constructible because it has no non-static data members. For actual rules determining that see [dlc.init.general]/7.
This is not only the requirement for such a variable, but also the requirement to not cause the implicit default constructor to be deleted if a class has an analogues non-static member without initializer, see [class.default.ctor]/2.4.
So your original code should compile. MSVC does compile it, but GCC and Clang do not.
The relevant requirement for the class members was however changed to the referenced wording with a defect report: CWG 2394. Before that it required the member to have a user-provided default constructor, which is a stronger requirement than being const-default-constructible and which is exactly what you did add to make it work.
According to both the Clang implementation status page and the GCC implementation status page the status of their implementation of the DR is unknown.
|
71,471,136 | 71,471,420 | why pointer variable inside private class can't point to outside variable of class | #include<iostream>
#include <string>
using namespace std;
class Human
{
private:
int *age;
string *name;
public:
Human(string p_name, int value)
{
*name = p_name;
*age = value;
cout <<"Name of Person is "<<*name <<" and age is "<<*age<<endl;
}
~Human()
{
delete name;
delete age;
cout<<"Destructor release all memory So now name is "<<*name << " and age is "<<*age<<endl;
}
void display()
{
cout << "The name is "<<*name <<" and age is "<<*age<<endl;
}
};
int main()
{
int age = 24;
string name = "CODY";
Human cody(name,age);
cody.display();
}
It is not printing anything.... What is happening can somebody explain it please.... Is it due to I implemented pointer variable incorrectly...Why is it incorrect please tell me then and what will be the alternative solution
|
why pointer variable inside private class can't point to outside variable of class
The premise of your question is faulty. A private member variable can point to outside of the class.
Human(string p_name, int value)
{
*name = p_name;
*age = value;
You didn't initialise the pointers, so indirecting through them results in undefined behaviour. Don't do this.
cout << "The name is "<<*name <<" and age is "<<*age<<endl;
Here, you indirect through the invalid pointers and the behaviour of the program is undefined.
delete name;
delete age;
cout<<"Destructor release all memory So now name is "<<*name << " and age is "<<*age<<endl;
Even if the pointers weren't invalid, it would be wrong to delete them. You didn't create any objects with allocating new, so there is nothing to delete. Deleting the pointers that weren't returned by allocating new will result in undefined behaviour. Don't do this.
Furthermore, even if delete had been valid, that would invalidate the pointers, and the successive indirection through the newly invalidated pointers in the cout statement would result in undefined behaviour. Don't do this either.
Solution: Remove the delete lines.
A solution where the class points to variables outside of the class: In order to refer to an object outside of a function, you need to use indirection. You can use a pointer parameters for example, and initialise the members to point to the same objects:
Human(string* p_name, int* value)
: name(p_name), age(value)
{}
// example usage:
Human cody(&name, &age);
Note that storing pointers in members is precarious because you must be aware of the relative lifetimes of the pointed objects, and the object containing the pointers. You must be sure that the pointers don't outlive the pointed objects.
Considering the problems of the referential design of your class, I urge you to consider using values instead. This would likely be more useful class in general:
struct Human {
std::string name;
int age;
void display()
{
std::cout
<< "The name is "
<< name
<< " and age is "
<< age
<< '\n';
}
};
int main()
{
Human cody {
.name="CODY",
.age=24,
};
cody.display();
}
|
71,471,142 | 71,490,226 | How can I make my container compatible with boost::range? | I'm rolling a custom, standard-like container and I'd like to have it compatible with the boost::range library.
So far it works with all the STL algorithms and it also satisfies the following:
BOOST_CONCEPT_ASSERT((boost::InputIterator<my_container::const_iterator>));
BOOST_CONCEPT_ASSERT((boost::Container<my_container>));
But when I try to use it in this context:
auto r = c | boost::adaptors::indexed();
It seems to be missing some templated metadata. The errors are something like
error: no type named 'type' in boost::range::iterator<my_container, void>
>> typename range_iterator<SinglePassRange>::type
Is there a similar concept assert I can use to help me complete the missing implementation for my type? Or maybe even an article explaining how to make a container boost::range compatible? I'm assuming I do not need to actually include boost types in my implementation, since the STL obviously doesn't.
Any help greatly appreciated! :-)
Edit: minimal(ish) example
#include <catch2/catch.hpp>
#include <boost/concept_check.hpp>
#include <boost/concept/assert.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <algorithm>
SCENARIO("container")
{
class my_container
{
public:
class const_iterator
{
public:
using value_type = const int;
using pointer = const int*;
using reference = const int&;
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
const_iterator() = default;
bool operator==(const_iterator other) const noexcept { return d == other.d; }
bool operator!=(const_iterator other) const noexcept { return !(*this == other); }
reference operator*() const { return *d; }
pointer operator->() const { return d; }
const_iterator& operator++() { ++d; return *this; }
const_iterator operator++(int) { return d++; }
private:
friend my_container;
const_iterator(const int* p) : d(p) {}
const int* d{nullptr};
};
using value_type = int;
using const_reference = const int&;
using const_pointer = const int*;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
my_container() : data({0, 1, 2, 3, 4}) {}
const_iterator begin() const { return const_iterator(data.data()); }
const_iterator end() const { return const_iterator(data.data() + 5); }
size_type size() const { return 5; }
size_type max_size() const { return 5; }
bool empty() const { return false; }
private:
std::array<int, 5> data;
};
BOOST_CONCEPT_ASSERT((boost::InputIterator<my_container::const_iterator>));
BOOST_CONCEPT_ASSERT((boost::Container<my_container>));
GIVEN("a container") {
my_container container;
WHEN("use std::algorithms") {
auto itr = std::find(container.begin(), container.end(), 3);
THEN("element is found") {
CHECK(itr != container.end());
}
}
WHEN("use boost range") {
// wont compile
auto r = container | boost::adaptors::indexed();
}
}
}
| You need iterator as well as const_iterator. Try:
using iterator = const_iterator;
|
71,471,386 | 71,472,638 | OpenGL Alpha Channel not affective | Trying to make objects that fade over time in openGL.
I am doing this by decreasing the value of the Alpha in the color I am using to draw the object. But this does not seem to have any effect on the object, it still draws it as solid.
I have simplified the code to simply drawing three rectangles. Each rectangle is drawn with the same color but a different alpha value.
#include <GLUT/glut.h>
#include <stdlib.h>
void display(void)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// Set the color to red, with alpha at 100%
float f1[] = {1.0, 0, 0, 1.0};
glColor4fv(f1);
glRecti(10, 10, 110, 110);
// Set the color to red, with alpha at 50%
float f2[] = {1.0, 0, 0, 0.5};
glColor4fv(f2);
glRecti(120, 10, 220, 110);
// Set the color to red, with alpha at 20%
float f3[] = {1.0, 0, 0, 0.2};
glColor4fv(f3);
glRecti(230, 10, 330, 110);
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);␣
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 5000.0);
gluLookAt(0, 0, 500, 0, 0, 0, 0, 100, 0);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
}
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_ALPHA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(1200, 1200);
int id = glutCreateWindow(argv[0]);
// Set up call back
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
glutDestroyWindow(id);
}
The code that does the display is all in display(). I have included all the other functions openGL functions I use as I am probably not setting something up correctly.
| You need to enable blending and set an appropriate blend function (see Blending). To run an OpenGL instruction, you need an OpenGL Context. The context is create when the OpenGL window is created with glutCreateWindow. Therefore you must add the instructions after glutCreateWindow.
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_ALPHA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(1200, 1200);
int id = glutCreateWindow(argv[0]);
//
// After the window has been created set the window
// To enable the alpha part of the color.
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
// DONE
// Set up call back
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
glutDestroyWindow(id);
}
|
71,471,684 | 71,471,919 | Why does a C++ mathematical operation accept a letter as an input and output a number? | I'm brand new to c++, so maybe this is a stupid question, but I coded a very simple temperature conversion program. It looks like this:
#include <iostream>
int main() {
double tempf;
double tempc;
// Ask the user
std::cout << "Enter the temperature in Fahrenheit: ";
std::cin >> tempf;
// Conversion
tempc = (tempf - 32) / 1.8;
// Print Output
std::cout << "The temp is " << tempc << " degrees Celsius.\n";
}
This compiles and runs fine when I enter an integer/float as an input. However, out of curiosity, I tried entering a letter, expecting to get an error or a failure of some kind. Instead, after compiling, I get this output:
$ g++ temperature.cpp -o temp
$ ./temp
Enter the temperature in Fahrenheit: abc
The temp is -17.7778 degrees Celsius.
Can someone tell me where the executable is getting the output -17.7778 from? This seems like an arbitrary number, not a mathematical output.
| "However, out of curiosity, I tried entering a letter, expecting to get an error or a failure of some kind."
By default, std::cin reports errors by setting internal error bits that must be checked manually. One mechanism is to use the good() member function to check for any error bits. Another is to use the bool conversion operator which does the same thing, it will convert to true is no error bits are set, otherwise it converts to false.
Example :
if(!std::cin) {
std::cout << "Input error!";
return;
}
When std::cin fails, it will assign the value 0 to the variable.
From cppreference.com :
If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set.
When you provide the input "abc" the expression std::cin >> tempf; will fail to read anything, assign 0 to tempf and set a fail bit. Then, during tempc = (tempf - 32) / 1.8; the value calculated will be (0.0 - 32) / 1.8 which is approximately -17.7778 which is the result you observe.
You can change the default behavior to throw an exception on failure by using the exceptions member function. But beware that if other parts of your project use std::cin and don't expect this change it can disrupt their error handling scheme which may rely on checking error bits.
The example provided by cppreference.com for this example :
#include <iostream>
#include <fstream>
int main()
{
int ivalue;
try {
std::ifstream in("in.txt");
in.exceptions(std::ifstream::failbit); // may throw
in >> ivalue; // may throw
} catch (const std::ios_base::failure& fail) {
// handle exception here
std::cout << fail.what() << '\n';
}
}
|
71,472,463 | 71,482,486 | VLC huge buffering times over rtp for local H264 stream | I'm outputting an H264 stream, encoded by my application using ffmpeg. I can display it using ffplay, but when trying to view the stream in VLC, I only get the first frame, or it looks like that's the case.
The messages output shows that it is "buffering", taking around a minute to get to 100% when the frame updates.
When using ffplay, the latency is about 50-100ms at worst.
I am sending to rtp://127.0.0.1:6666?pkt_size=1316 with the format rtp_mpegts.
I am new to this and it's highly likely I haven't set the frame up completely correctly. The process is (minus declarations and error checking)
codec_name = "libx264";
codec = avcodec_find_encoder_by_name(codec_name.c_str());
context = avcodec_alloc_context3(codec);
pkt = av_packet_alloc();
context->bit_rate = 5 * Mega;
context->width = info.DisplayWidth;
context->height = info.DisplayHeight;
context->time_base = { 1, FPS };
context->framerate = { FPS, 1 };
context->gop_size = 100;
context->max_b_frames = 1;
context->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec->id == AV_CODEC_ID_H264)
{
check_ret("set option: preset", av_opt_set(context->priv_data, "preset", "fast", 0));
check_ret("set option: tune", av_opt_set(context->priv_data, "tune", "zerolatency", 0));
check_ret("set option: profile", av_opt_set(context->priv_data, "profile", "baseline", 0));
}
check_ret("open codec", avcodec_open2(context, codec, NULL));
// setup the stream
fmt = (AVOutputFormat*)av_guess_format("rtp_mpegts", NULL, NULL);
avformat_alloc_output_context2(&avfctx, fmt, fmt->name,
"rtp://127.0.0.1:6666?pkt_size=1316");
avio_open(&avfctx->pb, avfctx->url, AVIO_FLAG_WRITE);
AVStream* stream = avformat_new_stream(avfctx, codec);
avcodec_parameters_from_context(stream->codecpar, context);
stream->time_base.num = 1;
stream->time_base.den = FPS;
avformat_write_header(avfctx, NULL);
// then the encoding (in an output loop)
<not shown: get frame from swapchain, sws_scale from rgba to yuv>
yuvFrame->pts = i++; // i is incremented every frame
avcodec_send_frame(enc_ctx, yuvFrame);
while (ret >= 0) {
ret = avcodec_receive_packet(enc_ctx, pkt);
//ret = av_interleaved_write_frame(avfctx, pkt); was using this, don't seem to need it
ret = av_write_frame(avfctx, pkt);
av_packet_unref(pkt);
}
The VLC output looks like this:
main debug: using hw decoder module "d3d11va"
avcodec info: Using D3D11VA (NVIDIA GeForce RTX 2080 Super with Max-Q Design, vendor 10de(NVIDIA), device 1e93, revision a1) for hardware decoding
qt debug: Logical video size: 1280x720
main debug: resized to 1280x720
main debug: VoutDisplayEvent 'resize' 1280x720
main debug: Received first picture
main debug: Buffering 1%
main debug: Buffering 2%
main debug: Buffering 3%
main debug: auto hiding mouse cursor
main debug: Buffering 4%
main debug: Buffering 5%
main debug: Buffering 6%
main debug: Buffering 7%
main debug: Buffering 8%
main debug: Buffering 9%
main debug: Buffering 10%
main debug: auto hiding mouse cursor
main debug: Buffering 11%
rtp warning: 1 packet(s) lost
rtp warning: 1 packet(s) lost
rtp warning: 1 packet(s) lost
ts warning: discontinuity received 0x3 instead of 0xd (pid=256)
ts warning: discontinuity received 0x5 instead of 0xf (pid=256)
ts warning: discontinuity received 0x1 instead of 0xb (pid=256)
main debug: Buffering 12%
main debug: Buffering 13%
main debug: Buffering 14%
main debug: Buffering 15%
main debug: Buffering 16%
main debug: Buffering 17%
main debug: Buffering 18%
main debug: auto hiding mouse cursor
main debug: Buffering 19%
main debug: Buffering 20%
| The problem with my approach above was that it was based on the ffmpeg example encode_video.c with some bits for stream output borrowed from google.
Thanks to @rotem I started putting together a standalone executable and stumbled on the example muxing.c in the ffmpeg examples.
This let me find the steps I was missing: set the stream index on the packet, and rescale the time:
av_packet_rescale_ts(pkt, context->time_base, stream->time_base);
pkt->stream_index = stream->index;
int ret = av_interleaved_write_frame(avfctx, pkt);
|
71,472,475 | 71,473,401 | How to create make not visible range so when user clicks near point, the point will be chosen | I have a set of vector points, with each click on my window I add pair to the vector. I want to add an invisible radius on my point which will help me to detect if a point was clicked. The point is basically 1 pixel in size so the user is not able to click on it directly. How can I achieve this? Do I need to use any math formulas for this?
std::vector<QPoint> pointSet;
void MyWindow::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
x0 = event->x();
y0 = event->y();
QPoint data;
data.setX(x0);
data.setY(y0);
pointSet.push_back(data);
}
//I want to be able to do it like below
if(event->button() == Qt::RightButton)
{
//if(pointClicked) { cout << "point with x,y clicked"; }
}
update();
}
| If I understand your question correctly, you just need to run through your vector and check if any of the saved points are within a range of the clicked point. So something like this should work:
if (event->button() == Qt::RightButton)
{
int radius = <something>
QRectF range(event->x() - radius, event->y() - radius, radius * 2, radius * 2);
for (auto &p in pointSet)
{
if (range.contains(p))
{
cout << "point with" << p.x() << "," << p.y() << "clicked";
break;
}
}
}
|
71,474,096 | 71,474,786 | What must I do for visual studio 2017 to use the natstepfilter file to avoid stepping into std library functions and class methods? | First, I am testing this capability by editing the default.natstepfilter file on purpose. I realize that there is a just my code feature built into visual studio now and an associated compiler setting /JMC. However I have a legacy project that is built using the older VS2013 tools still so I can't use the newer just my code feature to avoid stepping into STL and other library functions. Therefore I have setup a simple hello world example to figure out how to use the technique described in these next two articles.
Having read these two articles, the filters are slightly different. I have tried both ways with and without escaping the colon character but neither seems to work.
https://blog.wholetomato.com/2020/08/18/prevent-debugger-from-stepping-into-unwanted-functions-in-visual-studio/
https://www.asawicki.info/news_1486_how_to_make_visual_studio_debugger_not_step_into_stl.html
Consider this code. When stepping into printGreeting that takes the c-string I do not want to step into c_str() method of std::string, but I have to click f-11 to step into printGreeting so this is my test case for verifying that the change to default.natstepfilter works.
I've tried these two lines recommended by the aforementioned sites but neither seems to have an effect. I don't think the escape of the colon is needed but that is how one example showed it.
<Function><Name>std::.+ </Name><Action>NoStepInto</Action>
<Function><Name>std\:\:.* </Name><Action>NoStepInto</Action>
Here is the sample code.
#include "pch.h"
#include <iostream>
using namespace std;
void printGreeting(const char* greeting) {
std::cout << greeting << std::endl;
}
int main()
{
std::string greeting("Hello World!\n");
printGreeting(greeting.c_str());
}
I have also tried restarting visual studio 2017 after editing the .natstepfilter which had no effect. The debugger still steps into the constructor of std::string and the c_str() method.
| I think I solved my own issue by starting over and creating a new file with the .natstepfilter extension. I can't prove that a mistake in the file was the problem because the previous files I tried were changed or deleted already. However I am fairly confident that there was an error in my edited .natstepfilter file. I was able to reproduce the problem again by purposefully inserting an error. In my original post my xml sample entries were wrong. It was missing the trailing tag . It's possible when I copy and pasted examples from a browser window that I didn't copy the entire line or that I copied something extra. It's also possible that I didn't copy and paste correctly from my edited file into the original question. When the file contains an error, it will silently fail to be loaded. I couldn't find a diagnostic output anywhere that showed the problem loading that file.
I also learned from the Microsoft documentation that you can create a new .natstepfilter file with any name that you like instead of modifying the default so prefer that approach to avoid introducing an error into the original. Here is the content of the file I created which did work for me.
<?xml version="1.0" encoding="utf-8"?>
<StepFilter xmlns="http://schemas.microsoft.com/vstudio/debugger/natstepfilter/2010">
<Function><Name>std::.*</Name><Action>NoStepInto</Action></Function>
</StepFilter>
Moreover you can put these files in your %USERPROFILE%\Documents\Visual Studio 2017\Visualizers directory so that you do not have to add a file to a system installation directory. I did have to manually create the Visualizers directory and then create the file. You can add multiple files with the extension if you'd like to organize the entries across multiple files.
|
71,474,612 | 71,513,890 | WebView2 AddScriptToExecuteOnDocumentCreated - How to wait for completion in C++? | In a C++ (MFC) app using WebView2, I can't find a way to simply wait until the script passed to AddScriptToExecuteOnDocumentCreated() is ready. My ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler() is just never called if I add some waiting code (e.g. WaitForSingleObject()) after calling AddScriptToExecuteOnDocumentCreated().
Without the wait, the ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler() is reached and I can see it's invoked on the message thread. Then, obviously, if I have to make the UI (i.e. message thread) wait, it can't work.
Does someone know how we're supposed to use this properly?
Doc:
https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2?view=webview2-1.0.1150.38#addscripttoexecuteondocumentcreated
| Ok, I found a solution to my problem. Although I could make it work using the old dirty MFC message pumping trick (which I really don't like), I could finally refactor some code and call the navigate from the handler directly. Pretty simple. Thanks for your replies.
auto res = webView->AddScriptToExecuteOnDocumentCreated(L"Some script", Microsoft::WRL::Callback<ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler>( [](HRESULT error, PCWSTR id)->HRESULT { // call Navigate here return S_OK; }).Get());
|
71,474,982 | 71,475,029 | Why can't I return std::getline's as-if-boolean result? | A standard idiom is
while(std::getline(ifstream, str))
...
So if that works, why can't I say
bool getval(std::string &val)
{
...
std::ifstream infile(filename);
...
return std::getline(infile, val);
}
g++ says "cannot convert 'std::basic_istream<char>' to 'bool' in return".
Is the Boolean context of a return statement in a bool-valued function somehow different from the Boolean context of while(), such that the magic conversion that std::basic_istream performs in one context doesn't work in the other?
Addendum: There's apparently some version and perhaps language standard dependency here. I got the aforementioned error with g++ 8.3.0. But I don't get it with gcc 4.6.3, or LLVM (clang) 9.0.0.
| The boolean conversion operator for std::basic_istream is explicit. This means that instances of the type will not implicitly become a bool but can be converted to one explicitly, for instance by typing bool(infile).
Explicit boolean conversion operators are considered for conditional statements, i.e. the expression parts of if, while etc. More info about contextual conversions here.
However, a return statement will not consider the explicit conversion operators or constructors. So you have to explicitly convert that to a boolean for a return.
|
71,475,054 | 71,475,104 | Structured bindings in Python | C++17 introduced the new structured bindings syntax:
std::pair<int, int> p = {1, 2};
auto [a, b] = p;
Is there something similar in python3? I was thinking of using the "splat" operator to bind class variables to a list, which can be unpacked and assigned to multiple variables like such:
class pair:
def __init__(self, first, second):
self.first = first
self.second = second
...
p = pair(1, 2)
a, b = *p
Is this possible? And if so, how would I go by implementing this to work for my own classes?
A tuple in Python works as a simple solution to this problem. However, built in types don't give much flexibility in implementing other class methods.
| Yes, you can use __iter__ method since iterators can be unpacked too:
class pair:
def __init__(self, first, second):
self.first = first
self.second = second
def __iter__(self):
# Use tuple's iterator since it is the closest to our use case.
return iter((self.first, self.second))
|
71,475,844 | 71,476,733 | Understand the usage of timeout in beast::tcp_stream? | Reference:
https://www.boost.org/doc/libs/1_78_0/libs/beast/example/websocket/client/async/websocket_client_async.cpp
https://www.boost.org/doc/libs/1_78_0/libs/beast/doc/html/beast/using_io/timeouts.html
https://www.boost.org/doc/libs/1_78_0/libs/beast/doc/html/beast/ref/boost__beast__tcp_stream.html
void on_resolve(beast::error_code ec, tcp::resolver::results_type results)
{
if(ec) return fail(ec, "resolve");
// Set the timeout for the operation
beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(30));
// Make the connection on the IP address we get from a lookup
beast::get_lowest_layer(ws_).async_connect(
results, beast::bind_front_handler(
&session::on_connect, shared_from_this()));
}
void on_connect(beast::error_code ec, tcp::resolver::results_type::endpoint_type ep)
{
if(ec) return fail(ec, "connect");
// Turn off the timeout on the tcp_stream, because
// the websocket stream has its own timeout system.
// beast::get_lowest_layer(ws_).expires_never(); // Note: do NOT call this line for this question!!!
...
host_ += ':' + std::to_string(ep.port());
// Perform the websocket handshake
ws_.async_handshake(host_, "/",
beast::bind_front_handler(&session::on_handshake, shared_from_this()));
}
Question 1>
Will the timeout of beast::tcp_stream continue to work after a previous asynchronous operation finishes on time?
For example,
In above example, the timeout will expire after 30 seconds. If async_connect doesn't finish within 30 seconds, session::on_connect will receive an error::timeout as the value of ec. Let's assume the async_connect takes 10 seconds,
can I assume that async_handshake needs to finish within 20(i.e. 30-10) seconds otherwise a error::timeout will be sent to session::on_handshake? I infer to this idea based on the comments within on_connect function(i.e.
Turn off the timeout on the tcp_stream
). In other words, a timeout will only be turned off after it finishes the specified expiration period or is disabled by expires_never. Is my understanding correct?
Question 2> Also I want to know what a good pattern I should use for timeout in both async_calling and async_callback functions.
When we call an async_calling operation:
void func_async_calling()
{
// set some timeout here(i.e. XXXX seconds)
Step 1> beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(XXXX));
Step 2> ws_.async_operation(..., func_async_callback, )
Step 3> beast::get_lowest_layer(ws_).expires_never();
}
When we define a async_callback handle for an asynchronous operation:
void func_async_callback()
{
Step 1>Either call
// Disable the timeout for the next logical operation.
beast::get_lowest_layer(ws_).expires_never();
or
// Enable a new timeout
beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(YYYY));
Step 2> call another asynchronous function
Step 3> beast::get_lowest_layer(ws_).expires_never();
}
Does this make sense?
Thank you
| Question 1
Yes that's correct. The linked page has the confirmation:
// The timer is still running. If we don't want the next
// operation to time out 30 seconds relative to the previous
// call to `expires_after`, we need to turn it off before
// starting another asynchronous operation.
stream.expires_never();
Question 2
That looks fine. The only subtleties I can think of are
often, because of Thread Safety often the initiation as well as the completion happen on the same (implicit) strand.
If that's the case, then in your completion handler example, the expires_never(); would be redundant.
If the completion handler is not on the same strand, you want to actively avoid touching the expiry, because that would be a data race
An alternative pattern is to set the expiry only once for a lengthier episode (e.g. an multi-message conversation between client/server). Obviously in this pattern, nobody would touch the expiry after initial setting. This seems pretty obvious, but I thought I'd mention it before someone casts this pattern in stone to never think about it again.
Always do what you need, prefer simple code. I think your basic understanding of the feature is right. (No wonder, this documentation is a piece of art).
|
71,476,045 | 71,476,195 | c++ pointer segfaults without compiler warning, works when previously assigned | I have a difficulties understanding pointers and how/when they fail. So I made a tiny program which creates a pointer, assigns a value to it and then prints that value. Compiles fine with both gcc and clang and does not give any warnings when using the -Wall switch. Why does it segfault and why does it not segfault when I assign a different value to the pointer first? I thought I had initialized the pointer to somewhere. When I just declare the pointer without initialization, then I rightfully get a compiler warning. However, here I do not get a compiler warning, but it still segfaults.
#include<iostream>
int main(){
int *b = (int*) 12; //pointer gets initialized, so it points to somewhere
//int a = 13; //works fine when uncommenting this and the next line
//b = &a;
*b = 11;
std::cout << "*b = " << *b << "\n";
return 0;
}
| A pointer is a variable that save a memory address.
You "can" have any memory address in your pointer, but trying to read from memory space outside of where your application are allowed to read, will trigger the OS to kill you application with a segfault error.
If you allow me the metaphor:
You can write on a paper the address of any person in your country. But if you try to enter that house without permission, you most probably will get stopped by the police.
Back to code:
int *b = (int*) 123; // ok, you can save what you want.
std::cout << *b << std::endl; // SEGFAULT: you are not allowed to read at 123.
When you uncomment the two lines of code:
int a = 13;
b = &a;
Basically, b is not any-more pointing to that forbidden 123 address, but to the address of a. a is in your own code, and it memory is not forbidden to you, so accessing *b after this is allowed.
Reading at any hard-coded address is not forbidden by C++ (in fact it is useful in some situations), but your OS may not allow you to mess with that memory.
On the other hand, the compiler is able to detect a variable being used without initialization, and can warn this case. This has nothing to do with raw pointers.
|
71,476,058 | 71,476,218 | Bazel doesn't exit after build when called from CMake (ExternalProject_Add) | I am trying to build an external project that uses Bazel as its build system from CMake with Ninja. I am doing this by using ExternalProject_Add
ExternalProject_Add(bazel_proj
SOURCE_DIR "${bazel_proj_DIR}"
CONFIGURE_COMMAND :
CONFIGURE_HANDLED_BY_BUILD ON
BUILD_COMMAND bazel build //:install
INSTALL_COMMAND bazel run //:install
BUILD_IN_SOURCE ON
BUILD_ALWAYS ON
USES_TERMINAL_BUILD ON
USES_TERMINAL_INSTALL ON
LOG_BUILD ON
LOG_INSTALL ON
LOG_OUTPUT_ON_FAILURE ON
LOG_MERGED_STDOUTERR ON
INACTIVITY_TIMEOUT 10
)
I tried to add --worker_quit_after_build to the build command but it did not help. Bazel uses the linux-sandbox spawn strategy by default.
The only way to work around this is to stop the build with CTRL+C and start over so it goes to the install step the next time!
I also could not make CMake print the progress report of Bazel to the terminal. That might be related.
| Bazel has a client/server model, where the server stays around for subsequent incremental builds. So this might be due to the server staying around. Try using the --batch startup flag, which tells bazel not to use this client/server model:
bazel --batch build //:install
https://bazel.build/docs/user-manual#batch
Note that bazel run //:install will also start the server. You could add --batch there as well, but it will probably be a bit slow because Bazel will reanalyze the build. You could possibly instead run the install program directly, which will be something like bazel-bin/install (depends on what the //:install target actually builds).
|
71,476,403 | 71,489,578 | Why does GetPointCount of a GraphicsPath always return 0? | I am trying to learn the gdiplus windows API, and in particular how to use GraphicsPath to get points from different shapes. I noticed that I could never get anything to appear from microsoft's example code, so I tried to see how many points were actually in a GraphicsPath like this:
#include <windows.h>
#include <gdiplus.h>
#include <iostream>
//use gdiplus library when compiling
#pragma comment( lib, "gdiplus" )
using namespace Gdiplus;
VOID GetPointCountExample()
{
// Create a path that has one ellipse and one line.
GraphicsPath path;
path.AddLine(220, 120, 300, 160);
// Find out how many data points are stored in the path.
int count = path.GetPointCount();
std::cout << count << std::endl;
}
int main()
{
GetPointCountExample();
}
This always returned a count of 0. Why is this?
I have tried compiling with mingw-64 and Visual Studio with the same result.
I also tried printing out the Gdiplus::Status returned from this:
GraphicsPath path;
int stat = path.StartFigure();
std::cout << stat << std::endl;
Which printed a status of 2, "InvalidParameter" even though StartFigure doesn't take parameters.
| Ahh read more documentation and found this: The GdiplusStartup function initializes Windows GDI+. Call GdiplusStartup before making any other GDI+ calls
https://learn.microsoft.com/en-us/windows/win32/api/Gdiplusinit/nf-gdiplusinit-gdiplusstartup
This code works:
#include <windows.h>
#include <gdiplus.h>
#include <iostream>
//use gdiplus library when compiling
#pragma comment( lib, "gdiplus" )
using namespace Gdiplus;
VOID GetPointCountExample()
{
// Create a path that has one ellipse and one line.
GraphicsPath path;
path.AddLine(0, 0, 0, 1);
// Find out how many data points are stored in the path.
int count = path.GetPointCount();
std::cout << count << std::endl;
}
int main()
{
//Must call GdiplusStartup before making any GDI+ calls
//https://learn.microsoft.com/en-us/windows/win32/api/Gdiplusinit/nf-gdiplusinit-gdiplusstartup
ULONG_PTR token;
GdiplusStartupInput input;
input.GdiplusVersion = 1;
input.SuppressBackgroundThread = false;
GdiplusStartup(&token, &input, NULL);
GetPointCountExample();
//Shutdown GDI+ when finished using
GdiplusShutdown(token);
}
|
71,476,428 | 71,476,624 | C++ unusual use of placement new into NULL | In the following C++98 statement:
multiThreadService[nextBuffer] = new (NULL) MultiThreadService(binder);
Would it be correct to say:
this is "placement new",
the object will be created (at NULL, somehow?) and thrown away, and
multiThreadService[nextBuffer] will now be NULL?
I was also told this could be UB - is that the case?
| First, it is not necessarily calling the global non-allocating placement-new operator new overload void* operator new(std::size_t size, void* ptr) (What is commonly meant by "placement new".)
Because the new-expression is not qualified as ::new, it may prefer an in-class overload of operator new if a suitable one exists and furthermore the type of NULL is not void*, but either std::nullptr_t or an integral type (the former not being possible in C++98). Therefore there are some potential alternative results of overload resolution even in the global case.
Searching the project for operator new overloads one can find at least one possible candidate at https://github.com/aneto0/MARTe2/blob/master/Source/Core/BareMetal/L2Objects/CLASSREGISTER.h#L85, which seems to return a valid pointer even if the placement argument (second function argument) is a null pointer.
If the selected overload is really the global non-allocating placement-new operator new, then it was basically a noop in C++98 resulting in a null pointer. new expressions were required to not do any initialization if operator new returns a null pointer.
However this was changed with CWG 1748 and now the behavior is undefined if the global non-allocating placement-new operator new returns a null pointer value. This may have been considered a defect against C++98 as well (I don't know), in which case -std=c++98 will not prevent the undefined behavior on a current compiler.
|
71,476,653 | 71,480,150 | What is a pattern to ensure that every derived class (including derived classes of the immediate derived class) implement a method? | I have a base class and a number of generations of descendants (derived classes):
class Base{
public:
virtual void myFunc() = 0;
}
class Derived : public Base{
//This class needs to implement myFunc()
}
class Derived2 : public Derived{
//How to force this class to implement its version of myFunc(), and force it to call Derived::myFunc as well ?
}
class Derived3 : public Derived2{
//.....should implement its own myFunc and call Derived2's mynFunc()...
}
class Derived4 : public Derived3{
//.....should implement its own myFunc and call Derived3's mynFunc()...
}
Is there a pattern to ensure:
That each derived class (regardless of whether it is an immediate descendant of the base class, or a descendant of a descendant of the base class), implement its version of myFunc?
That each derived class calls its immediate parent class myFunc?
EDIT: The pattern that comes to mind to me is Decorator pattern, but wondering if there is some better way or variation.
| I propose the following solution:
#include <iostream>
template <class BaseClass>
class RequireMyFunc: public BaseClass
{
public:
virtual void myFunc() = 0; // declaration to force write implementation
protected:
void callBaseClassMyFunc() override
{
BaseClass::callBaseClassMyFunc();
BaseClass::myFunc();
}
};
class Base{
public:
void func()
{
callBaseClassMyFunc();
//myFunc();
}
virtual void myFunc(){};
protected:
Base(){}
virtual void callBaseClassMyFunc(){};
};
class Derived : public RequireMyFunc<Base>{
public:
void myFunc() override
{
std::cout << "Derived" << std::endl;
}
};
class Derived2 : public RequireMyFunc<Derived>{
public:
void myFunc() override
{
std::cout << "Derived2" << std::endl;
}
};
class Derived3 : public RequireMyFunc<Derived2>{
public:
void myFunc() override
{
std::cout << "Derived3" << std::endl;
}
};
int main()
{
Base* d = new Derived();
d->func(); // prints "Derived" (invokes only Derived::myFunc)
Base* d2 = new Derived2();
d2->func(); // prints "Derived" and "Derived2", i.e. invokes Derived::myFunc and Derived2::myFunc
Base* d3 = new Derived3();
d3->func(); // prints "Derived", "Derived2" and "Derived3"
d->myFunc(); // prints "Derived"
d2->myFunc(); // prints only "Derived2"
d3->myFunc(); // prints only "Derived3"
// Base* b = new Base(); -- cannot create because of protected constructor
//b->myFunc(); // prints nothing
}
|
71,476,758 | 71,480,105 | How to create a wrapper or intermediate layer to access a class, without exposing it? | I use a third party engine, that has a class "Sprite". My classes use sprite, and call its methods.
There is a probability that "Sprite" will be replaced in the future by some other game engine. I would like to have a layer between my class, and Sprite, so that it is easy to swap out Sprite in future.
I figure there are at least two ways to do this:
Implement a wrapper class that has a bridge method for every method in sprite, and that my code uses to access the sprite.
For Example:
Wrapper{
private:
Sprite* foo;
public:
void method1(){
foo->method1();
}
int method2(){
return foo->method2();
}
}
The downside with this approach is that there is a lot of work to write a method for each method in Sprite, even though all it is doing is just calling the method and returning whatever result. It is also a lot of maintenance work each time there is a change in sprite.
Alternative 2 : Some kind of magic by overloading the -> operator.
struct LoggingFoo : public Sprite {
void log() const { } //Just a method for logging.Doesn't matter.
Foo const *operator -> () const { log(); return this; }
Foo *operator -> () { log(); return this; }
};
Not very sure of all the things to keep in mind with this option ? For example, what happens to class methods ? Does it make sense to publicly inherit Sprite for this use case ?
Note: In practice, there is no object that is intended to inherit from Sprite in my code.
EDIT:
What would be the most concise way to create the wrapper, yet expose all public member variables and functions? For example, not having to specify each and every variable and function to expose ?
| You just need to create a Wrapper class that publicly inherits from Sprite and use it. It automatically fully inherits all the methods and variables of the Sprite class in the Wrapper class with the same level of visibility:
class Sprite
{
public:
void foo(){};
void bar(){};
int mode = 0;
};
class Wrapper : public Sprite
{
};
int main()
{
Wrapper w;
w.foo();
w.mode = 5;
w.bar();
}
If in the future you switch to another library, you will inherit Wrapper from the new class and implement only removed or changed methods:
class NewSprite
{
public:
void foo(){}; // same interface
void new_bar(int mode){};
};
class Wrapper : public NewSprite
{
public:
void bar() // wrap new method
{
new_bar(mode);
}
int mode = 0;
};
But a better approach would be to build a higher-level Wrapper interface so that when you completely change the library API, you don't have to rewrite every method:
class Wrapper
{
public:
void do_operation() // high-level interface
{
s_.foo();
s_.mode = 5;
s_.bar();
}
protected:
Sprite s_;
};
class Wrapper
{
public:
void do_operation() // high-level interface
{
s_.foo();
mode = 5;
s_.new_bar(mode);
}
int mode = 0;
protected:
NewSprite s_;
};
int main()
{
Wrapper w;
w.do_operation();
}
|
71,476,864 | 71,477,050 | Why r-value is not copied, when it passed to function by value? | I have the following code:
struct Foo {
Foo() = default;
Foo(const Foo&) { std::cout << "Copy" << std::endl; }
Foo(Foo&&) noexcept { std::cout << "Move" << std::endl; }
};
struct Bar {
Bar(Foo foo) : foo(std::move(foo)) {}
Foo foo;
};
int main() {
Foo foo;
std::cout << "Pass l-value:" << std::endl;
Bar barL(foo);
std::cout << "Pass r-value:" << std::endl;
Bar barR({});
}
It prints the following:
Pass l-value:
Copy
Move
Pass r-value:
Move
How compiler understands that it may not copy r-value?
| The {} in your second call isn't just an rvalue, it's a prvalue: a pure rvalue. Prvalues don't act like objects so much as they do instructions for initializing an object. Prvalues only get materialized under certain circumstances. Those being primarily when they're used to initialize an object or when bound to a reference.
So when you call Bar barR({}), there's no need to copy (or move) the prvalue that you passed in, because it never gets materialized. Instead, the {} is used to directly initialize the foo parameter of Bar's constructor.
Note: Everything I wrote in this answer is valid for C++17 and later. Prior standards didn't have the prvalue materialization/mandatory copy elision rules yet.
|
71,477,234 | 71,477,745 | How do I fix this Expected Expression Error? | I am trying to write a code for a project, and in my if else statements I want to put that the SWI is greater than or equal to 305 and less than or equal to 395. How would I place those limitations in the code? I tried using <= and >=, but I do not think the placement is correct, and I am confused on how to fix it.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double T,SWI,W;
cout << "HELLO USER, PLEASE ENTER THE TEMPERATURE AND WIND SPPED TO PREDICT WEATHER FORECAST";
cin >> T, W;
SWI = 150*log10(T-49)+0.41*W+125*W/T;
if (SWI < 305);{
cout << "There is a low risk of severe thunderstorms.\n";
cout << "However, still remain indoors and keep dry until the storm passes\n";
}else if (SWI >= 305,SWI <= 395); {
cout<< "Severe thunderstorms possible.\n";
cout << "Please remain indoors and expect turbulant winds.\n";
}else if(SWI > 395);{
cout << "Severe thunderstorms imminent.\n";
cout << "Stay off the roads and avoid any tall trees, possibility of tornadoes suspected.\n";
}
return 0;
} // end program
| There are too many syntactic errors. Corrected version below.
also you might need to consider a check on T. It must be >49 else the log function gets a -ve input.
#include <iostream>
#include <cmath>
int main()
{
using namespace std;
double T,SWI,W;
cout << "HELLO USER, PLEASE ENTER THE TEMPERATURE AND WIND SPEED TO PREDICT WEATHER FORECAST";
cin >> T;
cin >> W;
SWI = (150*log10(T-49))+(0.41*W)+(125*W/T);
if (SWI < 305){
cout << "There is a low risk of severe thunderstorms.\n";
cout << "However, still remain indoors and keep dry until the storm passes\n";
}else if (SWI <= 395) {
cout<< "Severe thunderstorms possible.\n";
cout << "Please remain indoors and expect turbulent winds.\n";
}else {
cout << "Severe thunderstorms imminent.\n";
cout << "Stay off the roads and avoid any tall trees, possibility of tornadoes suspected.\n";
}
return 0;
} // end program
|
71,477,428 | 71,477,611 | C++, Nothing in the output | I am new to C++ and coded my first main.cpp but I got an error, not exactly an error, it is a logical error, I guess because I wrote the following code:
#include <iostream> // including the iostream
using namespace std; // using the std namespace
int main() { // starting the main function
cout << "Hello World!" << endl; // My favorite line of code in all the of languages
return 0; // returning 0 to stop the function execution
}
In the terminal I expected
C:\Users\DELL\Desktop> g++ main.cpp
Hello World!
C:\Users\DELL\Desktop>
But it is just showing:
C:\Users\DELL\Desktop> g++ main.cpp
C:\Users\DELL\Desktop>
No output is coming, but when I try in Code::Blocks, it is working just fine! In vscode terminal, the same problem but when I run the file, it is working again! Why is it not working? I tried it in Command Prompt, installed the Windows Terminal, and tried it in that also (keeping the terminal as Command Prompt, cause I don't know what PowerShell is and how to use it) but any method is not working.
Please tell me what to do, I am new to c++ and know only some things amount it.
| The command g++ main.cpp creates the file a.out or a.exe. After that file is created you need to run it by the command ./a.out on Linux and Mac or a.exe on Windows.
|
71,478,077 | 71,478,455 | boolean check behaving unexpectedly when returning value | #include <iostream>
#include <string>
bool is_favorite(std::string word)
{
int isTrueCounter = 0;
std::cout << "\nisTrueCounter: " << isTrueCounter;
if (isTrueCounter == word.length())
{
return true;
}
else {
for (int i = 0; i < word.length(); i++)
{
if (word[i] == 'a' || word[i] == 'A')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'c' || word[i] == 'C')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else {
if (word[i] == 'd' || word[i] == 'D')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'e' || word[i] == 'E')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'f' || word[i] == 'F')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
}
}
}
}
}
} //for
}
std::cout << "\nisTrueCounter: " << isTrueCounter;
}
int main()
{
std::string favWord;
std::cout << "Please input your word: ";
std::cin >> favWord;
std::cout << "\nFavWord Length: " << favWord.length();
if (is_favorite(favWord) == true)
{
std::cout << "\nThis is a favorite word!";
}
else
{
std::cout << "\nThis is NOT a favorite word!";
}
}
Here is my code, I am attempting to pass a string into a boolean function that will return true if all criteria is met by the string passed. The qualifications for a "passing" word is that it contains ONLY the letters a-f (of either case) so words like AaAa or Cafe or Bad should pass, but after trial and error, even words that I know should pass are failing and I feel like I am keeping track of the letters' qualifications properly, by incrementing on a variable (isTrueCounter) to count if all the characters in the string are qualifying characters, but even when the function should be returning true, the false case displays. What am I doing wrong? What am I not seeing? When I run this code it will display the variables to help keep track of when stuff is being added to the holder variables but even when all the numbers are right the false case displays.
| You didn't return anything, you can do this in many way. For example from your code, return false immediatly after condition is not true (not in a-f).
bool is_favorite(std::string word)
{
int isTrueCounter = 0;
std::cout << "\nisTrueCounter: " << isTrueCounter;
if (isTrueCounter == word.length())
{
return true;
}
else {
for (int i = 0; i < word.length(); i++)
{
if (word[i] == 'a' || word[i] == 'A')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'c' || word[i] == 'C')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else {
if (word[i] == 'd' || word[i] == 'D')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'e' || word[i] == 'E')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'f' || word[i] == 'F')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
} else { //add this else clause
return false;
}
}
}
}
}
}
} //for
}
std::cout << "\nisTrueCounter: " << isTrueCounter;
}
But some of your code can improve.
1.I don't know why you add these lines. This will never true unless word.length() is 0.
if (isTrueCounter == word.length())
{
return true;
}
2.Don't split condition that can write in one if into many if, it's a bad behavior.
if (word[i] == 'a' || word[i] == 'A')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
else
{
if (word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
This is better.
if (word[i] == 'a' || word[i] == 'A' || word[i] == 'b' || word[i] == 'B')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
3.You can compare char, instead of check if word[i] == 'a'... Use > < >= <=.
if (word[i] >= 'a' && word[i] <= 'f' || word[i] >= 'A' && word[i] <= 'F')
{
isTrueCounter++;
std::cout << "\nisTrue +1 ";
}
4.string is already in iostream you don't have to import it again.
In conclusion your code can turn into this
bool is_favorite(std::string word)
{
int isTrueCounter = 0;
for (int i = 0; i < word.length(); i++)
{
if (word[i] >= 'a' && word[i] <= 'f' || word[i] >= 'A' && word[i] <= 'F') {
isTrueCounter++;
std::cout << "\nisTrue +1 ";
} else {
return false;
}
}
std::cout << "\nisTrueCounter: " << isTrueCounter;
return true;
}
|
71,478,253 | 71,487,664 | Read bitset from file using istream_iterator | I'm trying to read a text file into a vector of std::bitset-objects. The file consists of 1's and spaces (for indicating 0 or false) and I'm trying to do this by overloading the input operator>> and using istream_iterators. I start by changing the spaces in the string to 0's and then construct a bit that I push to the vector with that string. However when I print the output looks very strange and it seems that I'm reading in more elements than lines in the file (the vector of bitsets is longer than the number of lines). The code looks as follows:
template<long unsigned int N>
std::istream& operator>>(std::istream& is, std::bitset<N>& b){
std::string line;
std::getline(is,line);
for(unsigned long int i =0;i<N;++i){line[i]==' '? line[i]='0':'1';};
std::cout << line << std::endl;
b = std::bitset<N>(line);
return is;
}
int main(){
const unsigned long int N = 40;
std::ifstream file("activities.txt");
std::istream_iterator<std::bitset<N>> begin(file),end;
std::vector<std::bitset<N>> bits;
for(auto it = begin;it!=end;++it){
bits.push_back(*it);
}
for(auto bit: bits){ std::cout << bit << std::endl;}
}
I succeeded in doing the same thing without using the istream_iterator and the overloading of operator>> but I'm just trying to figure out why this way is not working.
| Interesting question.
The reaon, why this happens is that the std::bitsethas already an overwritten extraction operator >>. Please see here. You can read that this behaves like a formatted input function. So, it will read until the next white space and then stop. It will end reading, if we have an "end of file" or until it hits the length of the defined std::bitset.
Accidently you have spaces in your source file, which will act as separator for this formatted input function, and will not lead to any problem.
Actually, you should see a lot of "bitsets" in your std::vector, all consisting of many leading '0'es at the beginning and a few '1's with different length at the end.
That is the result of reading many '1' islands and padding the string on the left with '0's, so that the final bitset has 40 characters.
If you want C++ to call your function, you would need to open the std-namespace. While it could be done, this is strongly discouraged, except for template specializations. See:
NOT recommended:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <bitset>
#include <vector>
constexpr unsigned long int N = 40;
namespace std {
template<long unsigned int N>
std::istream& operator>>(std::istream& is, std::bitset<N>& b) {
std::string line;
std::getline(is, line);
for (unsigned long int i = 0; i < N; ++i) { line[i] == ' ' ? line[i] = '0' : '1'; };
std::cout << line << std::endl;
b = std::bitset<N>(line);
return is;
}
}
int main() {
std::ifstream file("activities.txt");
std::istream_iterator<std::bitset<N>> begin(file), end;
std::vector<std::bitset<N>> bits;
for (auto it = begin; it != end; ++it) {
bits.push_back(*it);
}
for (auto& bit : bits) { std::cout << bit << std::endl; }
}
This could basically work. But, should not be used. And, additionally, in my opinion there is a semantic bug in the for loop of the >>-operator, by comparing with "N" and not with "line.length()", which would be better. Because, if a line containes more than 40 characters, the spaces will not be converted, stay at ' ' (space) and lead to an exception for invalid input.
Correcting that (in any case, longer strings in a line will be truncated) and using the allowed template specialization in the "std" namespace, you coud write:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <bitset>
#include <vector>
constexpr unsigned long int N = 40;
namespace std {
template<>
std::istream& operator>>(std::istream& is, std::bitset<N>& b) {
std::string line;
std::getline(is, line);
for (unsigned long int i = 0; i < line.length(); ++i) { line[i] == ' ' ? line[i] = '0' : '1'; };
//std::cout << line << std::endl;
b = std::bitset<N>(line);
return is;
}
}
int main() {
std::ifstream file("activities.txt");
std::istream_iterator<std::bitset<N>> begin(file), end;
std::vector<std::bitset<N>> bits;
for (auto it = begin; it != end; ++it) {
bits.push_back(*it);
}
for (auto& bit : bits) { std::cout << bit << std::endl; }
}
This would work.
You can make your life even simpler by taking advantage of std::bitsets constructor number 3 which can interprete the spaces a 0es.
And, please use the std::vectors range constructor (number 5).
With that, the code will be even simpler:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <bitset>
#include <vector>
constexpr unsigned long int N = 40;
namespace std {
template<>
std::istream& operator>>(std::istream& is, std::bitset<N>& b) {
std::string line;
std::getline(is, line);
b = std::bitset<N>(line, 0, N, ' ', '1');
return is;
}
}
int main() {
std::ifstream file("activities.txt");
std::vector<std::bitset<N>> bits(std::istream_iterator<std::bitset<N>>(file), {});
for (auto& bit : bits) { std::cout << bit << std::endl; }
}
|
71,478,720 | 71,480,227 | how to override operator== in inheritance without being limited to base class? | struct Data
{
std::string Info; // Object Info
virtual bool operator==(Data& b)
{
return this->Info == b.Info;
}
};
struct Data1: public Data
{
int ID;
virtual bool operator==(Data1& b) override // overrides the bool operator==(Data& b) base function
{
return (this->Info == b.Info) && (this->ID);
}
};
The above code won't compile, I am wandering if it is possible to do so?
I would like my virtual operator function not be class bound.
In other words, maybe something like a template virtual (doesn't exist). I have tried template but of course virtual cannot be paired with template.
struct Data
{
std::string Info; // Object Info
template <class T>
virtual bool operator==(T& b)
{
return this->Info == b.Info; // something along the line
}
};
struct Data1: public Data
{
int ID;
virtual bool operator==(Data1& b) override // overrides the bool operator==(Data& b) base function
{
return (this->Info == b.Info) && (this->ID);
}
};
| As a rule, objects of different types can't be equal to each other.
That being the case, for your case, you may be able to get at least reasonably sane results with code on this general order:
struct base {
std::string info;
virtual ~base() = default;
virtual bool cmp(base const& other) const {
return info == other.info;
}
};
struct derived1 : public base {
int i = 0;
bool cmp(base const& other) const override
{
try {
derived1 const& d = dynamic_cast<derived1 const&>(other);
return info == d.info && i == d.i;
}
catch(...) { return false; }
}
};
bool operator==(base const &a, base const &b) {
return a.cmp(b) && b.cmp(a);
}
The logic here may not be obvious. Instead of overloading == as a virtual member function, we do the overload as a free function. And the free function does two comparisons, once in each order.
We do that to deal with a case like:
base b;
derived1 d;
if (b == d) std::cout << "oops: shouldn't be equal\n";
If we had overloaded operator== as a member function, it would tell us that the two objects are equal, which is almost certainly not desired. It does that because the code is equivalent to: if (b.operator==(d)), which uses the base class comparison operator. Since a reference to the base can refer to an object of derived type, that works, and just compares the base class parts of the two objects, ignoring the fact that one is really a derived object, so the two can't be equal.
With the code the way it's written above, we use both b.operator==(d) and d.operator==(b), so if one of b or d is an object of derived type, then we'll only get a true result if the other is also of the (same) derived type. Any attempt at mixing objects of base and derived type will yield false.
So that does what I think you're asking for. But I'm a long ways from excited about this code even at best. First of all, if comparisons are expensive, it'll get pretty slow, since it does each comparison twice. Second, the code is fragile and difficult to maintain--at the very least, it requires a fairly detailed comment about why it's written the way it is, and why simpler, more obvious code won't work reliably.
Bottom line: yes it works (at least as I perceive what you want), but no I don't like or recommend it.
|
71,479,264 | 71,479,390 | CPP Enums as template flags | I'm trying to refactor an entire codebase of "std::filesystem::path path = blah; if (path.extension() == ".whatever") load_file(path) else abort/error".
Thus far, I've written my enum as a bitfield with all the file extensions I wish my application to accept, and this function in the Assets namespace:
enum class AcceptedFileExtension : uint32_t {
SCENE = BIT(0),
OBJ = BIT(1),
GLTF = BIT(2),
GLB = BIT(3),
PNG = BIT(4),
JPG = BIT(5),
TTF = BIT(6),
VERT = BIT(7),
FRAG = BIT(8),
SPV = BIT(9),
};
template <AcceptedFileExtension T>
static std::optional<std::filesystem::path> accept(const std::filesystem::path& path)
{
if (to_accepted_extension(path) == T) {
return { path };
}
return {};
}
where the template type is my enum, defined as a bitfield essentially (Each member is = 1 << n, say for example AcceptedFileExtension::PNG = 1 << 3).
I would like this function to accept logically "or"-d values as the template, e.g:
// AFE = AcceptedFileExtension
auto path_or_nothing = Assets::accept<AFE::PNG | AFE::JPG>(assets_folder_path / images);
I recently read this post on SO and tried to write my own implementation for a new API, which added the logical operators to the enum class I'd written.
However, the problem is obvious, this creates a value (?) and not a type which I can use in templates.
These are inline constexpr, and implements or, and, xor.
If I then make the enum class into a parameter for the function as an R-value (which is how the caller should use it), another issue arises:
static std::optional<std::filesystem::path> accept(const std::filesystem::path& path, AcceptedFileExtension&& afe)
{
// Does not compile, since "&" does not reduce this to bool but to AFE.
if (to_accepted_extension(path) & afe) {
return { path };
}
return {};
}
How do I move forward?
Thank you.
| You can write your own overload of operator| for your enum. E.g.
#include<cstdint>
constexpr uint32_t BIT(int i){
return static_cast<uint32_t>(1)<<i;
}
enum class AcceptedFileExtension : uint32_t {
SCENE = BIT(0),
OBJ = BIT(1),
GLTF = BIT(2),
GLB = BIT(3),
PNG = BIT(4),
JPG = BIT(5),
TTF = BIT(6),
VERT = BIT(7),
FRAG = BIT(8),
SPV = BIT(9),
};
constexpr AcceptedFileExtension operator|(
AcceptedFileExtension const& lhs,
AcceptedFileExtension const& rhs
){
return static_cast<AcceptedFileExtension>(
static_cast<uint32_t>(lhs) |
static_cast<uint32_t>(rhs)
);
}
template <AcceptedFileExtension T>
static void accept()
{
}
int main(){
accept<AcceptedFileExtension::PNG | AcceptedFileExtension::JPG>();
}
|
71,479,442 | 71,480,289 | Binding temporary to r-value reference produces error | I'm trying to write a pImpl without using a unique_ptr. I don't understand while writing something like this:
class PublicClass
{
public:
// Some stuff
PublicClass();
private:
class ImplClass;
ImplClass&& mImpl;
};
class PublicClass::ImplClass
{
public:
ImplClass() {}
};
PublicClass::PublicClass() : mImpl(ImplClass()){}
produces following compilation error
Reference member 'mImpl' binds to a temporary object whose lifetime would be shorter than the lifetime of the constructed object
while writing the following
PublicClass::PublicClass() : mImpl(std::move(ImplClass())){}
is ok. R-value references should not extend life-time of temporaries, as in first snippet?
| From class.temporary:
The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
A temporary bound to a reference member in a constructor's ctor-initializer ([class.base.init]) persists until the constructor exits.
This is applicable to both of your examples. That is, in both of your given cases you have a dangling reference. Its just that in case 2 of your example the compiler is not able to give us the appropriate error/warning.
|
71,479,736 | 71,479,912 | What is the effect of calling a virtual method by a base class pointer bound to a derived object that has been deleted | The fllowing questions are:
p->test() should not work after b is destroyed. However, the code is running without any issue, the dynamic binding still works;
when the destructor of A is defined, the dynamic binding doesnot work anymore. What is the logic behind it?
#include <iostream>
using namespace std;
struct A {
//~A() {}
virtual void test() { cout << 0 << endl; }
};
class B :public A {
void test() { cout << 1 << endl; }
};
int main() {
A* p;
{
B b;
p = &b;
}
p->test(); // the method called will be different if the destructor of A is removed
}
|
p->test() should not work after b is destroyed. However, the code is running without any issue, the dynamic binding still works;
It does not "work". p->test() invokes undefined behavior.
when the destructor of A is defined, the dynamic binding doesnot work anymore. What is the logic behind it?
There is no logic behind it, other than implementation details of the compiler you are using, because the C++ standard does not mandate what a compiler should do with code that has undefined behavior.
For more details on undefined behavior I refer you to https://en.cppreference.com/w/cpp/language/ub
Compilers cannot detect all undefined behavior, but some of it. With gcc you can try -fsanitize=address to see the issue more clearly: https://godbolt.org/z/qxTs4sxcW.
|
71,479,959 | 71,479,994 | How can an if statement change a variable, when there's no assignement operator used? | I have a dynamic queue, so I want to check if the head pointer is pointing to something. So I do this:
if (mHeadPtr = NULL)
return false;
The pointer isn't empty (which is also why it does not go into the "return false" line) before this executes, but somehow it is afterwards, and I have no idea why.
If I instead check if the variable is not empty, it works without a problem.
if (mHeadPtr != NULL)
std::cout << "yay!" << std::endl;
else
return false;
How can it be that the if statement changes the variable it's only supposed to read?
| For comparisions you should use == instead of =. By using a single = you don't compare the value of the variable but assign NULL to it.
|
71,480,646 | 71,493,732 | Does QtNetworkAuth support PKCE | I use Qt5. I did not find any documentation on how to enable PKCE when using QOAuth2AuthorizationCodeFlow.
If so, please provide the link. If there is no support, how can this feature be added to it?
I added code_challenge and code_challenge_method, but it is not enough. I don't know what the next step is.
#include <QtNetworkAuth/QtNetworkAuth>
void loginHelper()
{
auto* authFlow = new QOAuth2AuthorizationCodeFlow;
QObject::connect(authFlow, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, &QDesktopServices::openUrl);
authFlow->setScope("openid profile email mobile");
authFlow->setAuthorizationUrl(QUrl("https://accounts.XYZ.com/core/connect/authorize")); // url is changed
authFlow->setClientIdentifier("desktop.test");
authFlow->setAccessTokenUrl(QUrl("https://accounts.XYZ.com/core/connect/token")); // url is changed
authFlow->setClientIdentifierSharedKey("0323af0d-efe2-fcec-b450-72f102530a77");
authFlow->setModifyParametersFunction([=](QAbstractOAuth::Stage, QVariantMap* params)
{
params->insert("code_challenge", "1Kht0Wkyt_WvDngoM_AIOYPPOWG8lzVG1g1zk28TjSo");
params->insert("code_challenge_method", "S256");
});
auto* replyHandler = new QOAuthHttpServerReplyHandler(1234); // port number
authFlow->setReplyHandler(replyHandler);
QObject::connect(authFlow, &QOAuth2AuthorizationCodeFlow::granted, []()
{
qDebug() << "Access Granted!";
});
authFlow->grant();
}
| The next step is to set code_verifier at RequestingAccessToken stage.
auto code_verifier = (QUuid::createUuid().toString(QUuid::WithoutBraces) +
QUuid::createUuid().toString(QUuid::WithoutBraces)).toLatin1(); // 43 <= length <= 128
auto code_challenge = QCryptographicHash::hash(code_verifier, QCryptographicHash::Sha256).toBase64(
QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);
authFlow.setModifyParametersFunction([=](QAbstractOAuth::Stage stage, QVariantMap* params)
{
switch (stage)
{
case QAbstractOAuth::Stage::RequestingAuthorization:
params->insert("code_challenge", code_challenge);
params->insert("code_challenge_method", "S256");
break;
case QAbstractOAuth::Stage::RequestingAccessToken:
params->insert("code_verifier", code_verifier);
break;
}
});
|
71,480,809 | 71,484,148 | Acqrel memory order with 3 threads | Lately the more I read about memory order in C++, the more confusing it gets. Hope you can help me clarify this (for purely theoretic purposes). Suppose I have the following code:
std::atomic<int> val = { 0 };
std::atomic<bool> f1 = { false };
std::atomic<bool> f2 = { false };
void thread_1() {
f1.store(true, std::memory_order_relaxed);
int v = 0;
while (!val.compare_exchange_weak(v, v | 1,
std::memory_order_release));
}
void thread_2() {
f2.store(true, std::memory_order_relaxed);
int v = 0;
while (!val.compare_exchange_weak(v, v | 2,
std::memory_order_release));
}
void thread_3() {
auto v = val.load(std::memory_order_acquire);
if (v & 1) assert(f1.load(std::memory_order_relaxed));
if (v & 2) assert(f2.load(std::memory_order_relaxed));
}
The question is: can any of the assertions be false? On one hand, cppreference claims, std::memory_order_release forbids the reordering of both stores after exchanges in threads 1-2 and std::memory_order_acquire in thread 3 forbids both reads to be reordered before the first load. Thus, if thread 3 saw the first or the second bit set that means that the store to the corresponding boolean already happened and it has to be true.
On the other hand, thread 3 synchronizes with whoever released the value it has acquired from val. Can it happen so (in theory if not in practice) that thread 3 "acquired" the exchange "1 -> 3" by thread 2 (and therefore f2 load returns true), but not the "0 -> 1" by thread 1 (thus the first assertion fires)? This possibility makes no sense to me considering the "reordering" understanding, yet I can't find any confirmation that this cannot happen anywhere.
| Neither assertion can ever fail, thanks to ISO C++'s "release sequence" rules. This is the formalism that provides the guarantee you assumed must exist in your last paragraph.
The only stores to val are release-stores with the appropriate bits set, done after the corresponding store to f1 or f2. So if thread_3 sees a value with 1 bit set, it has definitely synchronized-with the writer that set the corresponding variable.
And crucially, they're each part of an RMW, and thus form a release-sequence that lets the acquire load in thread_3 synchronize-with both CAS writes, if it happens to see val == 3.
(Even a relaxed RMW can be part of a release-sequence, although in that case there wouldn't be a happens-before guarantee for stuff before the relaxed RMW, only for other release operations by this or other threads on this atomic variable. If thread_2 had used mo_relaxed, the assert on f2 could fail, but it still couldn't break things so the assert on f1 could ever fail. See also What does "release sequence" mean? and https://en.cppreference.com/w/cpp/atomic/memory_order)
If it helps, I think those CAS loops are fully equivalent to val.fetch_or(1, release). Definitely that's how a compiler would implement fetch_or on a machine with CAS but not an atomic OR primitive. IIRC, in the ISO C++ model, CAS failure is only a load, not an RMW. Not that it matters; a relaxed no-op RMW would still propagate a release-sequence.
(Fun fact: x86 asm lock cmpxchg is always a real RMW, even on failure, at least on paper. But it's also a full barrier, so basically irrelevant to any reasoning about weakly-ordered RMWs.)
|
71,480,912 | 71,481,059 | Same math and numbers different answers? | im writing a simple program that you give a number of days and it gives back the number of years weeks and days that equal to the numbers of days you give.
but i noticed that you can get two different answers even tho when i checked the math it makes sense in both cases .
can someone please please explain to me why the answers are different and which one is correct
#include<iostream>
using namespace std;
int main()
{
int y;
int d,w;
int Days;
cin>>d;
y=d/365;
int LessThanAYearDays = d%365;
Days=LessThanAYearDays%7;
w=LessThanAYearDays/7;
int SameDays = d%7;
cout<<"answer1 is : "<<y<<" "<<w<<" "<<Days<< "\n";
cout<<"answer2 is : "<<y<<" "<<w<<" "<<SameDays<< "\n";
return 0;
}
| There are not an exact multiple of weeks in a year, so you are displaying different things. They will be the same in years divisible by 7.
E.g. Assume that a given year starts on a Tuesday.
Days corresponds to how many days past the last Tuesday you are.
SameDays corresponds to what day you are on.
See also the distinction that std makes between a std::chrono::duration, which is a count of time, and a std::chrono::time_point, which is a count of time since a particular date.
|
71,481,244 | 71,482,525 | Protobuf Partially Copy vector into repeated filed | In this question, it is answered how a vector can be copied into a repeated field by using fMessage.mutable_samples() = {fData.begin(), fData.end()}; ( and the other direction works too ).
But how about a partial copy?
Would the below work?
std::copy(
fData.begin() + 3, fData.end() - 2,
fMessage.mutable_samples()->begin() + 3
);
In this scenario fMessage has already allocated elements in the samples field, and std::copy would overwrite the items already present in fMessage.
| I created a program to test this, and it seems that using std::copy works!
syntax = "proto3";
message messagetest{
repeated float samples = 6;
}
#include <iostream>
#include <vector>
#include "message.pb.h"
int main(){
std::vector<float> fData(10);
messagetest fMessage;
std::generate(fData.begin(),fData.end(),[&fMessage](){
static float num = 0.0;
num += 1.0;
fMessage.add_samples(0.0);
return num;
});
for(const float& f : fData)
std::cout << "[" << f << "]";
std::cout << std::endl;
std::copy(
fData.begin() + 3, fData.end() - 2,
fMessage.mutable_samples()->begin() + 3
);
for(const float& f : fMessage.samples())
std::cout << "[" << f << "]";
std::cout << std::endl;
return 0;
}
output:
[1][2][3][4][5][6][7][8][9][10]
[0][0][0][4][5][6][7][8][0][0]
|
71,481,294 | 71,493,038 | LLVM IR basic blocks meaningful names | I'm trying to have meaningful names for the basic blocks in LLVM IR. That is, instead of the name 6 for this loop header, I would like it to be something like: loop.header.6. I'm pretty sure previous llvm/opt versions had this option, but I can't seem to find it in llvm-13. The actual source code for this is probably irrelevant, but given below for completeness
$ sed -n "18,23p" main.ll
6: ; preds = %27, %1
%7 = load i32, i32* %4, align 4
%8 = load i32, i32* %3, align 4
%9 = icmp slt i32 %7, %8
br i1 %9, label %10, label %30
Source code + compilation flags:
$ cat ~/main.cpp
#include <stdio.h>
bool isPrime(int p) {
for (int i=2;i<p;i++)
for (int j=2;j<p;j++)
if (i*j == p)
return 0;
return 1; }
int main(int argc, char **argv) {
printf("%d\n", isPrime(7));
}
$ ./clang -O0 -c -emit-llvm ~/main.cpp -o main.bc
$ ./llvm-dis ./main.bc -o main.ll
| The value names are only added by a frontend (clang) if it is compiled in debug mode / with assertions enabled.
Note that the names might become misleading after optimizations, etc.
|
71,482,152 | 71,482,520 | why can't bind be turned into function? | the problem is that IDE says the bind cannot be turn into function pointer.
Fudge<int> obj(1);
std::function<void(std::vector<int>&)> a = std::bind(&Fudge<int>::_pack_method, obj); //IDE warning here
where the _pack_method is declared as
template <class E>
class Fudge
{
public:
Fudge() = delete;
Fudge(int i) {};
void _pack_method(std::vector<E>& frames) {return;};
}
| Your problem here is you are not accounting for the function parameter of _pack_method. You need to tell bind how to fully bind with the function and you don't do that, you only give it the object to call the function on and not the vector parameter that it takes. To fix this, you either need to provide the vector you want to pass to the member function like
std::bind(&Fudge<int>::_pack_method, obj, my_vector);
or you need to use a placeholder to tell bind that that the function object that is created needs to take in parameter in order for it to work. That would look like
std::bind(&Fudge<int>::_pack_method, obj, std::placeholders::_1);
Instead of using bind, you could use a lambda expression which I find to be more explicit in denoting what is going on. That would look like:
auto a = [&obj](std::vector<int>& var){ obj._pack_method(var); };
|
71,482,195 | 71,709,945 | Can we assume std::is_default_constructible<T> and std::is_constructible<T> to be equal? | Pretty short question here:
Will std::is_default_constructible<T> and std::is_constructible<T> give the same result?
And what about to the new concepts std::default_initializable and std::constructible_from.
It might be important to know the distinctions when making templated factory or emplace functions.
| So I finally got to reading the specification. Here's what I found:
20.15.4.3 is_default_constructible<T>:
As pointed out by @Raymon Chen in the comments: true precisely when is_constructible<T> holds true.
18.4.11 constructible_from<T>:
Is defined in term of is_constructible<T>, but also poses the additional requirement destructible<T>.
18.4.12 default_initializable<T>:
Is defined in term of constructible_from<T>, but also requires T{} to be well-formed. Defining a variable of type T must be possible too; I.e. the statement T var{}; should be well-formed.
Source: N4861 Working Draft, Standard for Programming
Language C++
|
71,482,327 | 71,482,771 | Implementing Binary Semaphore using atomic<int> | I have written this code to demonstrate Binary Semaphore using only atomic .
1 thread producer will push 100 elements in the queue initially.
later threads 2 and 3 which is the consumer will run in parallel to consume this queue.
The issue is: I can see the same data/element print by both the threads
BinarySemaphore.cpp
std::queue<int> buffer;
int s_data = 1;
struct Semaphore
{
Semaphore():s_(1)
{
}
void wait()
{
while( s_.load() == 0); //you will keep waiting here until s_ becomes 1
s_.fetch_sub(1);
}
void signal()
{
s_.fetch_add(1);
}
private :
std::atomic<int> s_ ;
};
Semaphore s;
void producer()
{
while(s_data <= 100)
{
s.wait();
// critical section starts
{
std::ostringstream oss;
oss << "Consumer pushing data " << s_data <<endl;
cout << oss.str();
buffer.push(s_data++);
}
// critical section ends
s.signal();
}
}
void consumer()
{
while (1)
{
s.wait();
// critical section starts
if (!buffer.empty())
{
int top = buffer.front();
buffer.pop();
std::ostringstream oss;
oss << "consumer thread id= " << this_thread::get_id() << " reading data = " << top << endl;
cout << oss.str();
}
// critical section ends
s.signal();
}
}
int main()
{
Semaphore s;
std::thread prod(producer);
prod.join();
std::thread cons1(consumer);
std::thread cons2(consumer);
cons1.join();
cons2.join();
}
| If you need to do more then one action on atomic you need check consistency if data was not changed. Other wise you will have a "gap" as point out in other answer.
There is a compare_exchange which should be used for that:
void wait()
{
auto oldValue = s_.load();
while (oldValue == 0 || !s_.compare_exchange_strong(oldValue, oldValue - 1))
oldValue = s_.load();
}
Now if oldValue is out of date oldValue will be updated and new check will be performed (new iteration of loop) and in next iteration condition will be checked again.
|
71,482,623 | 71,483,437 | std::cin not working correcly with large numbers | I found a strange behavior of std::cin (using VS 17 under Win 10): when a large number is entered, the number that std::cin is reading is close but different.
Is there any kind of approximation done with large numbers ?
How to get the exact same large number than entered ?
double n(0);
cout << "Enter a number > 0 (0 to exit): ";
cin.clear(); // does not help !
cin >> n; // enter 2361235441021745907775
printf("Selected number %.0f \n", n); // 2361235441021746151424 is processed ?.
Output
Enter a number > 0 (0 to exit):
2361235441021745907775
Selected number 2361235441021746151424
| You need to learn about number of significant digits. A double can hold very large values, but it will only handle so many digits. Do a search for C++ doubles significant digits and read any of the 400 web pages that talk about it.
If you need more digits than that, you need to use something other than double. If you know it's an integer, not floating point, you can use long long int which is at least 8 bytes and can hold 2^63-1. If you know it's a positive number, you can make it unsigned long long int and you get the range 0 to at least 18,446,744,073,709,551,615 (2^64-1).
If you need even more digits, you need to find a library that supports arbitrarily long integers. A google for c++ arbitrary precision integer will give you some guidance.
|
71,482,792 | 71,482,929 | C++ abi compatability without pimpl using abstract class | Suppose I have a class B_Impl which inherits and implements a pure abstract class B (not containing any data-fields).
Suppose class A uses B_Impl via B* only.
If I add a field to B_Impl.h (clearly, not included by A), will ABI compatability be preserved?
I thought, that it will not be preserved, -- after reading https://wiki.qt.io/D-Pointer.
But I can see in my app that after changing B_Impl.h, the object file for class A is not regenerated and everything still works great.
Maybe, this is because in my app A and B are part of the same app and B is not a library called by A? Or is it because vtable is located as the very first field in the memory always and adding another field to B_Impl.h (which is "beneath" B) does not change the fact that vtable is the first field? Or is this stuff somehow corrected by the linker rather than by re-generating A-object-file?
Honestly, I am a bit confused here:
Is this ABI problem is only about libraries?
How can I modulate the situation in my app (where A uses B not as a library) when I call B* and get some seg-fault by changing B_Impl.h, (i.e. by ignoring the Pimpl principle, suggested in the article), and not re-generating A-object-file?
Or is it true that if I use a class via interface B* I can change its B_Impl.h as much as I could by adding new fields etc. and not being afraid that I will have to re-compile A that uses B directly in the same app or re-compile C that uses B as a call to a shared library? Thank you for attention!
|
If I add a field to B_Impl.h (clearly, not included by A), will ABI compatability be preserved?
Yes. If a translation unit doesn't include the definition of B_Impl, then changes to B_Impl won't affect the compatibility.
The interface compatibility - whether it is API or ABI - matters only when the interface is used. In your example, the interface of B is used; not the interface of B_Impl.
Is this ABI problem is only about libraries?
Whether B_Impl is in a library or not shouldn't matter.
|
71,482,810 | 71,528,374 | using cmake, build a visual studio project with dependencies, being able to debug also into the dependencies | I have a C++ project source code with several dependencies (C++ packages, compiled libs and source).
I need to create a CMake file which will generate the Visual Studio solution and projects files in such a way that if I put a break point in one of the dependencies source code, the execution of the main project in debug mode would break and debug at that break point in the dependency.
Any suggestion is highly appreciated.
[EDIT]
If I use the packages, with the provided ...config.cmake files, the source files are not included in the generated project.
If I generate the MS projects individually and use include_external_msproject to put them together in a solution, I have the source code, but it is executed from somewhere else (binaries), so my breakpoints are ignored.
On the other hand, there is overlap from duplicated targets, like DOCUMENTATION for example, which come from each dependency, if I want to use add_subdirectory to add the deps to the main project
| I ended up modifying the dependencies so that they implement unique target names for documentation, but if built individually to create the original named target: DOCUMENTATION.
doxygen_add_docs(DOCUMENTATION_${PROJECT_NAME}
doc
src/component
)
if (NOT (TARGET DOCUMENTATION))
add_custom_target(DOCUMENTATION COMMENT "workaround for multi-dependencies project")
add_dependencies(DOCUMENTATION DOCUMENTATION_${PROJECT_NAME})
endif()
|
71,482,828 | 71,497,693 | Crash when calling interrupt() on a boost::thread, which has another boost::thread | I'm getting a crash when calling interrupt() on an outer boost::thread, which runs an inner boost::thread, which is connected to a thread_guard. It's not crashing when calling join() manually on the inner thread.
Crash:
terminate called after throwing an instance of 'boost::thread_interrupted'
Source:
https://gist.github.com/elsamuko/6e178c37fa2cf8742cb6bf512f2ff866
#include <iostream>
#include <thread>
#include <boost/thread/thread.hpp>
#include <boost/thread/thread_guard.hpp>
#define LOG( A ) std::cout << A << std::endl;
void double_interrupt() {
boost::thread outer([] {
boost::thread inner([]{
while(true) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
LOG("Interrupting inner");
boost::thread_guard<boost::join_if_joinable> guard(inner); // crashes
// inner.join(); // works
}
});
LOG("Interrupting outer");
outer.interrupt();
outer.join();
}
int main(int argc, char* argv[]) {
LOG("Start");
double_interrupt();
LOG("End");
return 0;
}
Compile & Run:
http://coliru.stacked-crooked.com/a/46c512bf9a385fff
I'm running on Ubuntu 18.04. with g++ 7.5.0 and got the latest boost 1.78.0.
I opened this issue on github, too: https://github.com/boostorg/thread/issues/366
| I got a solution. The problem was, that the join() of the thread_guard waits for the inner thread with a condition_variable::wait(). condition_variable::wait() itself checks, if it's interruptible and throws an exception.
The solution is to use a custom thread_guard with disable_interruption:
#include <iostream>
#include <thread>
#include <boost/thread.hpp>
#include <boost/thread/thread_guard.hpp>
#define LOG( A ) std::cout << A << std::endl;
void work() {
size_t sum = 0;
for(int i = 0; i < 1E7; ++i) { sum += 1; }
LOG("work: " << sum);
}
// helper struct to interrupt a boost::thread within a boost::thread
struct non_interruptable_interrupt_and_join_if_joinable {
template <class Thread>
void operator()(Thread& t) {
if(t.joinable()) {
boost::this_thread::disable_interruption di;
t.interrupt();
t.join();
}
}
};
void double_interrupt() {
boost::thread outer([] {
boost::thread inner([] {
while(true) {
boost::this_thread::interruption_point();
work();
}
});
{
boost::thread_guard<non_interruptable_interrupt_and_join_if_joinable> guard(inner);
LOG("Interrupting inner");
}
});
LOG("Interrupting outer");
outer.interrupt();
outer.join();
}
int main() {
LOG("Start");
double_interrupt();
LOG("End");
}
Run here:
http://coliru.stacked-crooked.com/a/a365e40a2bd574cc
|
71,483,146 | 71,511,497 | How can I know which file called the function? cpp | I'm trying to understand a program(Moveit!) connected with many other files.
The program runs fine without any problem, but I want to know which function(from a different directory) calls the function I'm interested in.
Since there are so many directories and functions of the same name, I can't just simply track them easily.
So far, I've just tracked the caller function by manually opening all other files.
Can I know how to track down the caller function(or file)?
For example, I've attached a code below that which caller function and file location I want to know.
bool ompl_interface::ModelBasedPlanningContext::solve(planning_interface::MotionPlanResponse& res) { ... }
| Thank you guys!
The program I've been using(ROS Moveit!) had a built-in gdb debugger and I could find the log file which showed all the directories .cpp file launched.
This might not be applied to all for sure, but below is just an example of the location of the log file for my case.
~/.ros/log/cf90466c-a51d-11ec-b5e0-7085c253edd4/rosout.log
|
71,483,341 | 71,484,219 | SWIG - OverflowError when methods have enum typed arguments | I have a C++ code base which uses SWIG to generate Python 3 interfaces.
I had a problem where I couldn't convert enum values into large enough types. This was solved with good help.
Now I have a new problem that relates to the other one. Methods that take the corrected enum values as arguments are throwing an OverflowError when the largest enum values are passed in as an argument.
I was wondering if there is a generic way to solve this using the typemap function (like the way with the enum objects). To identify all methods that take the enum constants as arguments. Or do I need to define an in typemap for each of the enum types?
What I have tried, and works, is including this in the .i file:
%include "typemaps.i"
%apply unsigned long long { doom::Bar::FooPresence };
But it would be great if there was a "catch all" kind of thing, like with the constcode typemap.
The code necessary to reproduce the current behavior:
bar.h
namespace doom
{
class Bar
{
public:
struct FooIdent
{
enum Ident
{
UnknownFoo = 0,
KnownFoo = 1,
MainFoo = 2,
SecondaryFoo = 3
};
};
enum FooPresence
{
Boo = 0x0,
Foo1 = 0x8000000000ULL,
Foo2 = 0x4000000000ULL,
Foo3 = 0x2000000000ULL,
FooWithA1 = 0x1000000000ULL,
FooWithA2 = 0x0800000000ULL,
FooWithA3 = 0x0400000000ULL,
FooWithA4 = 0x0200000000ULL,
FooWithB1 = 0x0100000000ULL,
FooWithB2 = 0x0080000000,
FooWithB3 = 0x0040000000
};
Bar();
void setVesODee( int ves, doom::Bar::FooPresence pr );
void setVesOGoo( int goo, doom::Bar::FooIdent::Ident ide );
int doSomething();
private:
int m_vdee;
int m_vgoo;
};
} // namespace doom
bar.cpp
#include "bar.h"
#include <iostream>
namespace doom
{
Bar::Bar()
{
m_vdee = 0;
m_vgoo = 0;
}
void Bar::setVesODee( int ves, doom::Bar::FooPresence pr ) {
m_vdee = static_cast< doom::Bar::FooPresence >( ves & pr );
}
void Bar::setVesOGoo( int goo, doom::Bar::FooIdent::Ident ide ) {
m_vgoo = static_cast< doom::Bar::FooIdent::Ident >( goo & ide );
}
int Bar::doSomething() {
return m_vgoo + m_vdee;
}
} // namespace doom
int main() {
doom::Bar b = doom::Bar();
b.setVesODee(3, doom::Bar::FooWithB2);
b.setVesOGoo(4, doom::Bar::FooIdent::MainFoo);
int c = b.doSomething();
std::cout << c << std::endl;
return 0;
}
bar.i
%module bar
%feature ("flatnested");
%{
#define SWIG
#include "bar.h"
#define SWIG_PYTHON_STRICT_BYTE_CHAR
%}
%typemap(constcode) int %{
SWIG_Python_SetConstant(d, "$symname", PyLong_FromLongLong(static_cast<long long>($1)));
%}
%rename("Bar_%s", %$isnested) "";
%include "bar.h"
test_bar.py
import bar
b = bar.Bar()
b.setVesODee(10, bar.Bar.Foo1)
build-and-test.sh
#!/bin/bash
set -e
echo "Cleanup..."
rm -rf __pycache__
rm -f _bar.so bar.o bar_wrap.*
echo "Building..."
swig -python -c++ -py3 -debug-tmsearch bar.i
g++ -fPIC -c $(pkg-config --cflags --libs python3) bar.cpp bar_wrap.cxx
g++ -shared -o _bar.so bar.o bar_wrap.o
echo "Testing..."
python3 test_bar.py
output
Traceback (most recent call last):
File "test_bar.py", line 15, in <module>
b.setVesODee(10, bar.Bar.Foo1)
File "/workspace/ctmp/bar.py", line 83, in setVesODee
return _bar.Bar_setVesODee(self, ves, pr)
OverflowError: in method 'Bar_setVesODee', argument 3 of type 'doom::Bar::FooPresence'
| SWIGTYPE is the default type match when a type-specific match is not found. You can use the following to apply to all enumerations:
%apply unsigned long long { enum SWIGTYPE };
See 13.3.3 Default typemap matching rules in the SWIG documentation.
Example:
test.i
%module test
%typemap(constcode) int %{SWIG_Python_SetConstant(d, "$1",PyLong_FromLongLong(static_cast<long long>($1)));%}
%apply unsigned long long { enum SWIGTYPE };
%{
#include <iostream>
%}
%inline %{
enum FooPresence : unsigned long long
{
Foo1 = 0x8000000000ULL,
};
void func(FooPresence x) {
std::cout << std::hex << static_cast<unsigned long long>(x) << std::dec << std::endl;
}
%}
Demo:
>>> import test
>>> test.func(test.Foo1)
8000000000
|
71,483,904 | 72,156,301 | Escape sequences for char8_t and unsigned char | Trying to use escape sequences to construct a char8_t string (to not rely on file/compiler encoding), I got issue with MSVC.
I wonder if it is a bug, or if it is implemention dependent.
Is there a workaround?
constexpr char8_t s1[] = u8"\xe3\x82\xb3 \xe3\x83\xb3 \xe3\x83\x8b \xe3\x83\x81 \xe3\x83\x8f";
constexpr unsigned char s2[] = "\xe3\x82\xb3 \xe3\x83\xb3 \xe3\x83\x8b \xe3\x83\x81 \xe3\x83\x8f";
//constexpr char8_t s3[] = u8"コ ン ニ チ ハ";
static_assert(std::equal(std::begin(s1), std::end(s1),
std::begin(s2), std::end(s2))); // Fail on msvc
Demo
Note:
Final goal is to replace std::filesystem::u8path(s2) (std::filesystem::u8path is deprecated since C++20) by std::filesystem::path(s1);
| This is a bug in MSVC that I expect to be fixed at some point during Microsoft's implementation of C++23.
Historically, numeric escape sequences in character and string literals were not well specified in the C++ standard and this lead to a number of core issues. These issues were addressed by P2029; a paper adopted for C++23 in November of 2020. The reported MSVC bug (along with an additional one related to non-encodeable characters) is discussed in the "Implementation impact" section of the paper.
As mentioned by other commenters, use of universal-character-names (UCNs) like \u1234 would be the preferred solution to avoid a dependency on source file encoding.
|
71,484,271 | 71,485,268 | C++: insert element into std::map<MyStruct> where MyStruct can only be aggregate initialized and contains const unique pointers | Here is what I am trying to do and what I have tried:
#include <memory>
#include <map>
#include <string>
using namespace std;
struct MyStruct {
const unique_ptr<int> a;
const unique_ptr<int> b;
};
int main() {
auto a = make_unique<int>(7);
auto b = make_unique<int>(5);
map<string, MyStruct> myMap;
myMap["ab"] = { move(a), move(b) }; // nope
myMap.insert("ab", { move(a), move(b) }); // nope
myMap.emplace("ab", { move(a), move(b) }); // nope
myMap.try_emplace("ab", { move(a), move(b) }); // nope
// EDIT 1:
myMap.emplace(piecewise_construct,
forward_as_tuple("ab"),
forward_as_tuple(move(a), move(b))
); // nope
// EDIT 2:
// works in C++20 as there is now a standard ctor for MyStruct:
myMap.try_emplace("ab", move(a), move(b));
return 0;
}
I understand why none of this works but is there any way to insert an element into myMap without modifying MyStruct?
| Both
myMap.emplace(piecewise_construct,
forward_as_tuple("ab"),
forward_as_tuple(move(a), move(b))
);
and
myMap.try_emplace("ab", move(a), move(b));
should work in C++20. You need to construct the pair in-place, because it will be non-copyable and non-movable due to MyStruct. This leaves only the emplace family of member functions. Using a braced initializer list in emplace can never work because emplace only forwards arguments, but wouldn't be able to deduce types for arguments.
Before C++20, these member functions also won't work, because they internally use direct-initialization with parentheses. MyStruct however has no constructor matching the two arguments. In C++20 parenthesized initializers can also do aggregate initialization and that will work, since MyStruct is an aggregate.
I don't think there is any possibility to add an element to the map before C++20 without change of MyStruct or adding an implicit conversion for it, because it can only be aggregate-initialized, but must be emplace constructed which doesn't support aggregate-initialization.
The only the exception to that should be default initialization. For example
myMap.emplace(piecewise_construct,
forward_as_tuple("ab"),
forward_as_tuple()
);
should work also before C++20, because MyStruct is default-constructible.
An implicit conversion could be added to do aggregate initialization, for example:
struct A {
std::unique_ptr<int> a;
std::unique_ptr<int> b;
operator MyStruct() && {
return {std::move(a), std::move(b)};
}
};
//...
myMap.emplace("ab", A{ std::move(a), std::move(b) });
This will probably work in C++17 mode on compilers, although it is technically not correct as mandatory copy elision doesn't apply to initialization by conversion operator. See CWG 2327.
As for changes of MyStruct: In particular the two examples quoted above should also work pre-C++20 if you add a matching constructor:
struct MyStruct {
MyStruct(std::unique_ptr<int> a_, std::unique_ptr<int> b_) : a(std::move(a_)), b(std::move(b_)) { }
const std::unique_ptr<int> a;
const std::unique_ptr<int> b;
};
|
71,484,680 | 71,505,403 | Match a set of unicode characters with ctre-unicode | Say, I have a string
char8_t text[] = u8"• test\n - two\n •• three\n-• four\n";
I would like to substitute any number of consecutive blank characters, -, or • with just a single space. I tried the following:
char8_t* b = text + std::size(text)-1;
for (char8_t* r = text;;) {
auto m = ctre::search<u8R"([\s\-•]+)">(r,b);
if (!m) break;
char8_t* w = m.begin();
r = m.end();
if (r==b) {
b = w;
break;
}
*w++ = ' ';
if (w!=r) {
memmove(w,r,b-r);
b -= r-w;
r = w;
}
}
*b = '\0';
cout << ((char*)text) << endl;
But this results in
• test two •• three • four
I'm including <ctre-unicode.hpp> from Hana's GitHub repo.
Is this a bug or the intended behavior?
At first, I thought that maybe the problem is with putting a • inside [], because maybe [] only accepts single-byte characters and escape sequences, but I get the same output with (?:[\s\-]|•)+ as with the original [\s\-•]+. And \P{L}+ results in, what I'm assuming is, removal of only some of the bytes comprising the • characters:
� test two � � three � four
Here's a godbolt link.
| I opened an issue in the github repo and the author replied.
The Unicode mode of operation is implemented internally by using ctre::utf8_iterator. But in the current implementation, the use of utf8_iterator is triggered only if the search function receives std::u8string_view as the argument. In the current implementation, a pair of char8_t* does not make search use utf8_iterator.
This is why the Unicode example in the readme and Ted Lyngmo's answer both work in utf8 mode, but my original code works in byte mode.
|
71,484,705 | 71,484,840 | C++: Why I can change the assignment of reference on my computer? | I am new to C++, and I am studying the concept of reference.
I have studied the fact that a reference should not be assigned to something else once defined and initialized, the description of reference on C++ primer states that once you have bound a reference to an object, then you can't change the object which the reference is bounded to.
I am confused by this statement. I tried the following code on my computer, the compiler didn't report neither warnings nor errors.
int a = 2;
int b = 4;
int &ref = a;
cout << "ref = " << ref << endl;
ref = b;
cout << "ref = " << ref << endl;
On my computer, the compilation passes, and outputs were printed, one is 2, the other is 4, there's no problem at all.
I am confused by this concept of reference, is it the condition that we SHOULD NOT change the object which the reference is bounded to, or we CANNOT change the object which the reference is bounded to?
P.S. Even the page 58 on C++ primer also demonstrates the example where the reference refers to new object, and the book says it's ok to do that. Like this:
int i = 42;
int *p;
int *&r = p;
r = &i; // isn't this changing r to an new object?
*r = 0;
|
then you can't change the object which the reference is bounded to.
I am confused by this statement
The statement tries to say, that the reference cannot be modified to refer to another object. The object that is referred can be modified.
When left hand operand of assignment is a reference, you are indirecting through the reference, and assigning the value of the referred object.
ref = b;
ref still refers to the object named by a. That object is modified by this assignment. After the assignment, the value of a is 4.
r = &i; // isn't this changing r to an new object?
r still refers to the object named by p. That object is modified by this assignment. After the assignment, p points to i.
|
71,485,000 | 71,486,808 | NTP timestamps using std::chrono | I'm trying to represent NTP timestamps (including the NTP epoch) in C++ using std::chrono. Therefore, I decided to use a 64-bit unsigned int (unsigned long long) for the ticks and divide it such that the lowest 28-bit represent the fraction of a second (accepting trunction of 4 bits in comparison to the original standard timestamps), the next 32-bit represent the seconds of an epoch and the highest 4-bit represent the epoch. This means that every tick takes 1 / (2^28 - 1) seconds.
I now have the following simple implementation:
#include <chrono>
/**
* Implements a custom C++11 clock starting at 1 Jan 1900 UTC with a tick duration of 2^(-28) seconds.
*/
class NTPClock
{
public:
static constexpr bool is_steady = false;
static constexpr unsigned int era_bits = 4; // epoch uses 4 bits
static constexpr unsigned int fractional_bits = 32-era_bits; // fraction uses 28 bits
static constexpr unsigned int seconds_bits = 32; // second uses 32 bits
using duration = std::chrono::duration<unsigned long long, std::ratio<1, (1<<fractional_bits)-1>>;
using rep = typename duration::rep;
using period = typename duration::period;
using time_point = std::chrono::time_point<NTPClock>;
/**
* Return the current time of this. Note that the implementation is based on the assumption
* that the system clock starts at 1 Jan 1970, which is not defined with C++11 but seems to be a
* standard in most compilers.
*
* @return The current time as represented by an NTP timestamp
*/
static time_point now() noexcept
{
return time_point
(
std::chrono::duration_cast<duration>(std::chrono::system_clock::now().time_since_epoch())
+ std::chrono::duration_cast<duration>(std::chrono::hours(24*25567)) // 25567 days have passed between 1 Jan 1900 and 1 Jan 1970
);
};
}
Unfortunately, a simple test reveals this does not work as expected:
#include <chrono>
#include <iostream>
#include <catch2/catch.hpp>
#include "NTPClock.h"
using namespace std::chrono;
TEST_CASE("NTPClock_now")
{
auto ntp_dur = NTPClock::now().time_since_epoch();
auto sys_dur = system_clock::now().time_since_epoch();
std::cout << duration_cast<hours>(ntp_dur) << std::endl;
std::cout << ntp_dur << std::endl;
std::cout << duration_cast<hours>(sys_dur) << std::endl;
std::cout << sys_dur << std::endl;
REQUIRE(duration_cast<hours>(ntp_dur)-duration_cast<hours>(sys_dur) == hours(24*25567));
}
Output:
613612h
592974797620267184[1/268435455]s
457599h
16473577714886015[1/10000000]s
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PackageTest.exe is a Catch v2.11.1 host application.
Run with -? for options
-------------------------------------------------------------------------------
NTPClock_now
-------------------------------------------------------------------------------
D:\Repos\...\TestNTPClock.cpp(10)
...............................................................................
D:\Repos\...\TestNTPClock.cpp(18): FAILED:
REQUIRE( duration_cast<hours>(ntp_dur)-duration_cast<hours>(sys_dur) == hours(24*25567) )
with expansion:
156013h == 613608h
===============================================================================
test cases: 1 | 1 failed
assertions: 1 | 1 failed
I also removed the offset of 25567 days in NTPClock::now asserting equality without success. I'm not sure what is going wrong here. Can anybody help?
| Your tick period: 1/268'435'455 is unfortunately both extremely fine and also doesn't lend itself to much of a reduced fraction when your desired conversions are used (i.e. between system_clock::duration and NTPClock::duration. This is leading to internal overflow of your unsigned long long NTPClock::rep.
For example, on Windows the system_clock tick period is 1/10,000,000 seconds. The current value of now() is around 1.6 x 1016. To convert this to NTPClock::duration you have to compute 1.6 x 1016 times 53,687,091/2,000,000. The first step in that is the value times the numerator of the conversion factor which is about 8 x 1023, which overflows unsigned long long.
There's a couple of ways to overcome this overflow, and both involve using at least an intermediate representation with a larger range. One could use a 128 bit integral type, but I don't believe that is available on Windows, except perhaps by a 3rd party library. long double is another option. This might look like:
static time_point now() noexcept
{
using imd = std::chrono::duration<long double, period>;
return time_point
(
std::chrono::duration_cast<duration>(imd{std::chrono::system_clock::now().time_since_epoch()
+ std::chrono::hours(24*25567)})
);
};
That is, perform the offset shift with no conversion (system_clock::duration units), then convert that to the intermediate representation imd which has a long double rep, and the same period as NTPClock. This will use long double to compute 1.6 x 1016 times 53,687,091/2,000,000. Then finally duration_cast that to NTPClock::duration. This final duration_cast will end up doing nothing but casting long double to unsigned long long as the conversion factor is simply 1/1.
Another way to accomplish the same thing is:
static time_point now() noexcept
{
return time_point
(
std::chrono::duration_cast<duration>(std::chrono::system_clock::now().time_since_epoch()
+ std::chrono::hours(24*25567)*1.0L)
);
};
This takes advantage of the fact that you can multiply any duration by 1, but with alternate units and the result will have a rep with the common_type of the two arguments, but otherwise have the same value. I.e. std::chrono::hours(24*25567)*1.0L is a long double-based hours. And that long double carries through the rest of the computation until the duration_cast brings it back to NTPClock::duration.
This second way is simpler to write, but code reviewers may not understand the significance of the *1.0L, at least until it becomes a more common idiom.
|
71,485,418 | 71,485,835 | runtime error: member access within null pointer of type 'ListNode' - Clone a linked list | I am trying to clone a linked list in reverse order.
ListNode* cloneList(ListNode* head) {
ListNode *prev = new ListNode(head->val);
head = head->next;
while (head != NULL)
{
ListNode *p = new ListNode(head->val, prev);
head = head->next;
prev = p;
}
return prev;
}
The definition of ListNode is as follows :
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
But i am getting this runtime error : member access within null pointer of type 'ListNode'.
Am i making some mistake in creating or initialising the node? Please explain.
| It is unusual for a clone method to return a new list in reverse order, but OK, if that is your actual requirement.
As stated in comments, the code you have shown does not account for the possibility of the list being empty (ie, when head is nullptr), eg:
ListNode* cloneList(ListNode* head) {
if (!head) return nullptr; // <-- add this
...
}
If head is not nullptr and points to a valid ListNode, and the list is properly null-terminated, then your code works just fine.
Online Demo
However, it can be simplified a bit, eg:
ListNode* cloneList(ListNode* head) {
ListNode *newHead = nullptr;
while (head) {
newHead = new ListNode(head->val, newHead);
head = head->next;
}
return newHead;
}
Online Demo
|
71,485,543 | 71,486,824 | Where does MFC get the Automation IDs from? | I am about to add automatic GUI tests to an MFC application (created with Visual Studio 2019). It seems as AutomationId is something that could be useful when identifying various child windows in the application.
When I examined the application using Microsoft’s tool “Visual UIA Verify” I noticed that most of the child windows in the application have AutomationIds.
My concern is that they might not be unique if I have multiple instances of a window class and that the IDs may change over time.
My questions are
Where do the AutomationIds come from?
Can I change them?
Can I rely on them being constant?
| Automation IDs are obtained from UIA (User Interface Accessibility), you should generally be able to count on them being the same from run-to-run of the same program, but note that a new version may or may not be "the same".
From the UIA documentation:
Identifies the AutomationId property, which is a string containing the UI Automation identifier (ID) for the automation element.
When it is available, the AutomationId of an element must be the same in any instance of the application, regardless of the local language. The value should be unique among sibling elements, but not necessarily unique across the entire desktop. For example, multiple instances of an application, or multiple folder views in Microsoft Windows Explorer, can contain elements with the same AutomationId property, such as "SystemMenuBar".
Although support for AutomationId is always recommended for better automated testing support, this property is not mandatory. Where it is supported, AutomationId is useful for creating a test automation script that runs regardless of the UI language. Clients should make no assumptions regarding the AutomationId values exposed by other applications. AutomationId is not guaranteed to be stable across different releases or builds of an application.
|
71,486,284 | 71,502,376 | parquet_cpp StreamWriter not writing anything to file | Hey guys I am using the parquet_cpp's StreamWriter, but the output file is not empty. Even the header was not written, as the file was a 4-byte file.
std::shared_ptr<::arrow::io::FileOutputStream> outfile_{""};
std::string outputFilePath_ = "/tmp/part.0.parquet";
PARQUET_ASSIGN_OR_THROW(
outfile_,
::arrow::io::FileOutputStream::Open(outputFilePath_)
)
// build column names
parquet::schema::NodeVector columnNames_{};
columnNames_.push_back(
parquet::schema::PrimitiveNode::Make(
"Time", parquet::Repetition::REQUIRED, parquet::Type::INT64, parquet::ConvertedType::UINT_64
)
);
columnNames_.push_back(
parquet::schema::PrimitiveNode::Make(
"Value", parquet::Repetition::REQUIRED, parquet::Type::INT64, parquet::ConvertedType::UINT_64
)
);
auto schema = std::static_pointer_cast<parquet::schema::GroupNode>(
parquet::schema::GroupNode::Make("schema", parquet::Repetition::REQUIRED, columnNames_)
);
parquet::WriterProperties::Builder builder;
parquet::StreamWriter os_ = parquet::StreamWriter {parquet::ParquetFileWriter::Open(outfile_, schema, builder.build())};
// Start writing to os_, would be in a callback function
os_ << std::uint64_t{5} << std::uint64_t{59} << parquet::EndRow;
I seem to be missing something trivial for the column names and data to be written out, but I could not find anything online. Thank you.
| Yeah. The RowGroup must be flushed too. So all I need is to have:
os_.EndRowGroup();
While the data is written out, the parquet file's footer is corrupted and could not be read. I posted a question HERE on this writing out footer issue.
|
71,486,418 | 71,486,592 | Bubble sort a pack of cards | I have taken myself down a rabbit hole that I do not know how to get out of, I have created a deck of random cards. However, I now need to sort them firstly by suit then by rank in the order of my enum's. Firstly I can't figure out how to get elements from within the vector and within the enum, so I can compare them, secondly, I suspect this links to the first I'm not sure how to swap them, finally it would be nice to have a function for the bubble sort that I can call twice to first-order them by suit and then call again to order by card.
Here are the libraries:
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
using std::vector;
These are the structs and enum's:
enum Rank { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }; // aspects of the card
enum Suit { HEARTS, CLUBS, DIAMONDS, SPADES }; // suits of the card
struct Card { //Card data numbers
Rank rank;
Suit suit;
};
struct Deck { // defines a card
vector<Card> cards; // All the cards
int size = 5; // Max deck size
};
This is what generates a random card deck:
void initialize(Deck& deck, string stdno) {
for (int count=0; count < deck.size; count++) { //creates a deck of cards
Card card;
string rcardstr = stdno.substr(rand() % 8, 1) + stdno.substr(rand() % 8, 1);
int rcard = stoi(rcardstr) % 52;
card.suit = static_cast<Suit>(rcard / 13); //cast between the enumerator and the value
card.rank = static_cast<Rank>(1 + rcard % 13);
deck.cards.push_back(card); //Adds the card to the deck of cards
}
}
This is my feeble attempts of a bubble sort before I realized my first two problems:
void bubble_sort(Deck& deck ){
bool swapp = true;
while (swapp) {
swapp = false;
for (int i=0; i < deck.size; i++) {
if (deck.rank[0]
}
}
}
...And finally my main function:
int main() {
string stdno="14398132";
Deck my_deck;
initialize(my_deck, stdno);
}
If someone would be willing to give me a few minutes of their time to explain where I need to look/what I need to learn I would be incredibly grateful and make sure to give the same time back to the community once I've become better at c++.
| The way to access the members of the deck is to write:
deck.cards[i].rank
or
deck.cards[i].suit
You have multiple options for sorting.
Simply write two functions:
void bubble_sort_by_rank(Deck& deck ){
bool swapp = true;
while (swapp) {
swapp = false;
for (int i=0; i < deck.cards.size()-1; i++) {
if (deck.cards[i+1].rank > deck.cards[i].rank){
//...
}
}
}
}
and
void bubble_sort_by_suit(Deck& deck ){
bool swapp = true;
while (swapp) {
swapp = false;
for (int i=0; i < deck.cards.size()-1; i++) {
if (deck.cards[i+1].suit > deck.cards[i].suit){
//...
}
}
}
}
Write one bubble sort function, but take the sort criteria as a parameter (which can be enum).
Write a single bubble sort function, but compare each card first by suit and if they were equal, then compare them by rank or just overload the operator< for your Card class as suggested in the comments. This is probably the preferred method and more efficient.
If you don't insist on using bubble sort, you can just use std::sort with a lambda function that compares your cards first by suit then by rank.
For swapping you should be able to use std::swap or write a simple template function yourself:
template <class T>
void swap(T& x,T& y)
{
T temp;
temp=x;
x=y;
y=temp;
}
|
71,486,792 | 71,486,861 | no match for 'operator+' (operand types are 'std::basic_string<char>' and 'double') c++ | double vitesse();
string description();
string toString()
{
return nom + " : " + description() + "\nvitesse : " + vitesse() + ", poids : " + poids;
}
this code is part of class I'm testing, and whene i try to compile it the error in the title pops up return nom + " : " + description() + "\nvitesse : " + vitesse() + ", poids : " + poids; in this line and i can't understand why?
| It's because the function vitesse() returns a double value, which can't be concatenated as-is with strings. I believe if you replace vitesse() in the return value with to_string(vitesse()), it would work.
|
71,486,864 | 71,487,375 | boost::graph: How to remove in-edges of a previously removed vertex? | I created the simplest directed graph possible using boost::graph, and added 2 vertices that are mutually connected via 2 edges.
After removing the first vertex, the second vertex still has an out-edge that points to the previously removed vertex.
boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::directedS,
boost::no_property,
boost::no_property
> graph;
// add 2 vertices and connect them
auto v0 = boost::add_vertex(graph);
auto v1 = boost::add_vertex(graph);
boost::add_edge(v0, v1, graph);
boost::add_edge(v1, v0, graph);
// remove the first vertex
boost::remove_vertex(v0, graph);
// iterate over vertices and print their out_degree.
auto [begin, end] = boost::vertices(graph);
for (auto vertex_itr = begin; vertex_itr != end; ++vertex_itr)
{
auto vertex_descriptor = *vertex_itr;
auto out_degree = boost::out_degree(vertex_descriptor, graph);
std::cout << out_degree << '\n'; // this prints 1
}
To my understanding, my graph is in a sort of "invalid state" where an edge points to a non exiting vertex.
From further examining, it seems as if the "dangling edge" has become an edge with source == target. This makes me even more confused as to why boost::graph decided to leave this edge and even go to the trouble of making it cyclic.
Questions:
How do I fix this?
How do I remove the in edges of a vertex?
Does it make more sense to use a bidirectional graph in this situation?
Also, I couldn't find anything on the docs regarding this behavior, so I would appreciate if someone could point me to the right place.
| The implementation isn't "going through the trouble" - it's just doing anything, because you didn't satisfy the pre-conditions:
void remove_vertex(vertex_descriptor u, adjacency_list& g)
Remove vertex u from the vertex set of the graph. It is assumed that there are no edges to or from vertex u when it is removed. One way to make sure of this is to invoke clear_vertex() beforehand.
I repro-ed your issue slightly more briefly: Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <iostream>
int main() {
boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> g(2);
add_edge(0, 1, g);
add_edge(1, 0, g);
print_graph(g, std::cout << "--- Before: ");
remove_vertex(0, g); // remove the first vertex
print_graph(g, std::cout << "--- After: ");
// iterate over vertices and print their out_degree.
for (auto [it, end] = boost::vertices(g); it != end; ++it)
std::cout << out_degree(*it, g) << "\n"; // this prints 1
}
Prints
--- Before: 0 --> 1
1 --> 0
--- After: 0 --> 0
1
Fixing It
Let's simply do as the docs say:
clear_vertex(0, g); // clear edges
remove_vertex(0, g); // remove the first vertex
Now it works: Live On Coliru, printing:
--- Before: 0 --> 1
1 --> 0
--- After: 0 -->
0
BONUS
For more elegance:
// iterate over vertices and print their out_degree.
for (auto v : boost::make_iterator_range(vertices(g)))
std::cout << v << " out_degree: " << out_degree(v, g) << "\n";
|
71,486,992 | 71,501,520 | gnuplot visual studio invalid command error in console | This is the following code I have for plotting a series of random points in gnuplot. I have no errors in gnuplot-iostream header.
#include <iostream>
#include <vector>
#include <random>
#include <numeric>
#include "gnuplot-iostream.h"
int main() {
Gnuplot gp("\"C:\\Program Files\\gnuplot\\bin\\gnuplot.exe\"");
std::random_device rd;
std::mt19937 mt(rd());
std::normal_distribution<double> normdist(0., 1.);
std::vector<double> v0, v1;
for (int i = 0; i < 1000; i++) {
v0.push_back(normdist(mt));
v1.push_back(normdist(mt));
}
std::partial_sum(v0.begin(), v0.end(), v0.begin());
std::partial_sum(v1.begin(), v1.end(), v1.begin());
gp << "set title 'graph of two random lines'\n";
gp << "plot '-' with lines title v0,"
<< "'-' with lins title 'v1'\n";
gp.send(v0);
gp.send(v1);
std::cin.get();
}
In console I am getting the following output:
gnuplot> -7.293891473275246
^
line 1001: invalid command
gnuplot> -6.2938345608263884
^
line 1001: invalid command
Thank you very much for assisting. I am new to gnuplot and appreciate it!
| For debugging I used 5 points instead of 1000, so it was easier to see the first error:
line 6: undefined variable: v0
It turns out that the title of the first plot must be quoted:
gp << "plot '-' with lines title 'v0',"
There is also a typo in the second one, it must be lines instead of lins:
<< "'-' with lines title 'v1'\n";
|
71,487,302 | 71,501,314 | How to build SDL_Image from FetchContent? | I'm attempting to build a C++ program with SDL2 and SDL_Image using CMake by fetching them from their respective GitHub repositories; and it works for the most part! When I ran my code with SDL2 everything built fine, and when I added the code for SDL_Image everything compiled without a problem.
However, things break when I try to add SDL_Image. I get:
fatal error C1083: Cannot open include file: 'SDL_Image.h'
I'm confused how it compiles fine and why the same code works fine for main SDL2.
Here's the relevant part of my CMakeLists.txt:
include(FetchContent)
set(FETCHCONTENT_QUIET FALSE)
# sdl2
FetchContent_Declare(
SDL2
GIT_REPOSITORY https://github.com/libsdl-org/SDL
GIT_TAG release-2.0.20
GIT_PROGRESS TRUE
)
# sdl2_image
FetchContent_Declare(
SDL2_IMAGE
GIT_REPOSITORY https://github.com/libsdl-org/SDL_image
GIT_TAG release-2.0.5
GIT_PROGRESS TRUE
)
FetchContent_MakeAvailable(SDL2 SDL2_IMAGE)
set(SDL_LIBRARIES ${SDL_LIBRARIES} SDL2main SDL2-static SDL2_image-static)
target_include_directories("${PROJECT_NAME}" PRIVATE include)
target_link_libraries("${PROJECT_NAME}" PRIVATE ${SDL_LIBRARIES})
My build command:
cmake --build ./build --config debug --target ALL_BUILD --parallel
| There are two problems with your CMake file:
GIT_TAG release-2.0.5
If you look at the SDL_Image repo at that tag, there's no CMakeLists.txt file. That is indeed the most recent tag, though. But fortunately, according to the docs you can use a git SHA for GIT_TAG. With the most recent git SHA at the time of writing, that would look like this:
GIT_TAG 97405e74e952f51b16c315ed5715b6b9de5a8a50
The other error is that SDL2_image-static doesn't exist. You need to change that in your set(SDL_LIBRARIES ...) line to just SDL2_image.
With those two changes, I'm able to #include SDL_Image.h.
|
71,487,540 | 71,487,624 | Can access private sections in Singleton class | I wrote an singletone class as below:
class logger
{
FILE *__fp_log = NULL;
const char* __logpath;
//Constructor
logger();
static logger* __instance;
logger& operator=(const logger &) ;
logger(const logger &);
public:
~logger();
void write_file( const char* ,... );
static logger* getInstance();
};
I understand that I need to make Copy Constructor and assignment operator as private (reference here).
But still I can access them from main():
logger* log = logger::getInstance();
logger* log2 = logger::getInstance();
log = logger::getInstance();
I should get a compilation warning, any pointer why compilation is not complaining?
I am compiling using g++:
g++ .\main.cpp .\logger.cpp
| You're not performing any copying or assignment of loggers here. You're copying/assigning pointers to logger, which doesn't involve the logger object being pointed to at all.
The operation you're trying to prohibit would be something like:
logger log = *logger::getInstance(); // Dereferencing and copying to separate log object
which would try to make an unrelated instance that is a copy of the singleton instance.
Analogy: Your house is unique. No one can make an exact copy of your house (at least, it's unreasonably difficult to do so) without access to the blueprints (the constructor). But someone who has the address of your house can easily copy the address to a postcard, without affecting your house in any way. Your getInstance() method is returning a copy of the address, which you can "write" to a "postcard" (a local pointer to logger). It does not affect the "house" (the singleton logger instance) in any way. Any such copy of the address can be used to find the "house"/logger instance, but by making the constructors and assignment operator private, you've denied access to the house's blueprints (constructor/assignment), so they're limited to walking around your "house" (calling methods on the singleton logger), they can't just make a duplicate of it.
|
71,488,084 | 71,488,551 | Proper declaration of C++ private standard library type member | I'm trying to declare a priority queue as a private member so all other methods in the class can access it.
However, I am not able to get this to work with a custom lambda compare function.
Moreover, what is the recommended way of handling such situations?
This works:
private:
priority_queue<int, vector<int>, greater<int>> pq;
This does not work.
private:
static auto comp = [](int n1, int n2) {return (n1 > n2);};
priority_queue<int, vector<int>, decltype(comp)> pq;
If I want to use an STL object with a custom compare function that is accessible by all class methods, how would I do so?
| The problem here is a fairly subtle one. Before C++ 20, lambdas are not default constructible, but from C++ 20 on, they are. So looking at this:
priority_queue<int, vector<int>, decltype(comp)> pq;
we can see that pq only knows the type of your comparator and will need to instantiate that type itself. But, before C++20, it cannot because the language doesn't support it.
So, there are two solutions to this, both equally easy:
Add -std=c++20 to your compiler switches.
Change that line of code to:
priority_queue<int, vector<int>, decltype(comp)> pq { comp };
And in fact for option 2, since you are (also) initialising comp inline, you also need:
static constexpr auto comp = [] (int n1, int n2) { return n1 > n2; };
or:
static inline auto comp = [] (int n1, int n2) { return n1 > n2; };
Both of which need C++17 or later.
Now you have passed as instance of comp to priority_queue's (alternative) constructor and so it has what it needs to get the job done.
The reason that std::greater works is that it's a just a normal functor that std::priority_queue can construct an instance of when it needs to.
I would also say that it's worth reading this.
And just to round off, the nice thing about using C++ 20 is that, for one-off cases, you can do things like this:
std::priority_queue<int, std::vector<int>, decltype ([] (int n1, int n2) { return n1 > n2; })> pq;
Which keeps it all neat and tidy.
|
71,488,464 | 71,489,051 | Is way to get more colors in windows console (c++)? | Is way to get more colours in windows console (c++)?
by "more" i mean RGB colours, i have tried:
CONSOLE_SCREEN_BUFFER_INFOEX info;
info.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfoEx(hcon, &info);
info.ColorTable[0] = 0x505050;
info.ColorTable[1] = 0xcccccc;
SetConsoleScreenBufferInfoEx(hcon, &info);
SetConsoleTextAttribute(hcon, 01);
but i can use only 16 colours in one time
| From some of the documentation on the console API, specifically relating to Virtual Terminal Sequences for Extended Color:
Some virtual terminal emulators support a palette of colors greater than the 16 colors provided by the Windows Console. For these extended colors, the Windows Console will choose the nearest appropriate color from the existing 16 color table for display.
Based on this, I'd make the assumption that the Windows Console doesn't support anything more than 16 colors. If I had to guess, this is a backwards-compatibility restriction to interact with programs that assumed there were only ever 16 colors.
If you want more, you'd be best served by not using the Windows Console. If that's not possible, then you're stuck with 16 total.
|
71,489,173 | 71,546,749 | Integrate pre-compiled libraries into C++ codebase with CMake ExternalProject | I want to integrate CasADi into a CMake-based C++ codebase as an ExternalProject. For this purpose, I would like to use pre-compiled libraries because building from source is not recommended. So far, I have only managed to write the following:
ExternalProject_Add(
casadi-3.5.5
URL https://github.com/casadi/casadi/releases/download/3.5.5/casadi-linux-py39-v3.5.5-64bit.tar.gz
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
PREFIX ${CMAKE_BINARY_DIR}/external/casadi)
and I noticed that all the binaries are correctly downloaded in the specified folder. However, I do not know how to link my targets to CasADi, nor how to find the package.
| There is a natural problem with ExternalProject_Add:
ExternalProject_Add executes commands only on build.
Hence, download will not happen at the configure stage of your project which makes it difficult to use find_package, because the files cannot be found during your first configure run.
Take this CMakeLists.txt:
cmake_minimum_required(VERSION 3.21)
project(untitled)
set(CMAKE_CXX_STANDARD 17)
add_executable(untitled main.cpp)
include(ExternalProject)
ExternalProject_Add(
casadi-3.5.5
URL https://github.com/casadi/casadi/releases/download/3.5.5/casadi-linux-py39-v3.5.5-64bit.tar.gz
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
PREFIX ${CMAKE_BINARY_DIR}/external/casadi)
find_package(casadi HINTS ${CMAKE_BINARY_DIR}/external/casadi/src/casadi-3.5.5/casadi)
target_link_libraries(untitled casadi)
In order to use it you have to do the following:
Configure your project
mkdir build
cd build
cmake ..
Build (download) casadi-3.5.5
cmake --build . --target casadi-3.5.5
Reconfigure your project, because now find_package will find the needed files
cmake ..
Build your targets
cmake --build .
If you want a one step build, there are ways to get around this problem
Use FetchContent
Create a sub-cmake-project in a subfolder with all the ExternalProject_Add commands and execute the approriate build (download) steps manually in your own CMakeLists.txt via execute_process calls: https://stackoverflow.com/a/37554269/8088550
Here is an example for the second option, which might be better since FetchContent doesn't have the full functionality of ExternalProject.
main.cpp
#include <casadi/casadi.hpp>
int main()
{
casadi_printf("This works!");
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(untitled)
set(CMAKE_CXX_STANDARD 17)
# some default target
add_executable(untitled main.cpp)
# Configure and build external project
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/external)
execute_process(
COMMAND ${CMAKE_COMMAND} ${CMAKE_SOURCE_DIR}/external
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/external
)
execute_process(
COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR}/external
)
# find and link externals
find_package(casadi REQUIRED HINTS ${CMAKE_BINARY_DIR}/external/external/casadi/src/casadi-3.5.5/casadi)
target_link_libraries(untitled casadi)
external/CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(external)
include(ExternalProject)
ExternalProject_Add(
casadi-3.5.5
URL https://github.com/casadi/casadi/releases/download/3.5.5/casadi-linux-py39-v3.5.5-64bit.tar.gz
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
PREFIX ${CMAKE_BINARY_DIR}/external/casadi)
The point is to have another cmake project under external/CMakeLists.txt, which gets configured and build via execute_process calls from the main cmake project. Do note, that you can now have find_package(casadi REQUIRED ...) at configure stage, because the download will happen just before.
|
71,489,212 | 71,489,608 | Visual Studio 2019 Preprocessor definition as a result of cmd/sript | How can i make a definition as a variable from an evaluated expression? I add in my c++ project ( Visual Studio 2019 ) in the Project->Configuration Properties-> C/C++ -> Command Line /D "__MYVAL__=$(python3 .\calc.py)" but i get errors "the expression cannot be evaluated". How can i do this in visual studio 2019 preprocessor on windows?
| So this is not actually a Visual Studio thing - this is one level deeper. Welcome to the relatively unknown world of MSBuild.
MSBuild is the backend build engine for Visual Studio. It handles all the elements of the build process, and is responsible for managing and evaluating properties of the build, executing targets, finding and building dependencies, etc.
If you actually dig into the details, you'll find that Visual Studio projects are really just MSBuild scripts.
Have a look at the official documentation on properties for MSBuild. Based on what I could read, it looks like you can add C# code directly into the value of a property, and MSBuild will execute that code to perform custom actions.
If that's not enough for your purposes, you could also create a custom MSBuild task, which will allow you to run any code you like during the build process.
Once you have a property defined for what you want (we'll call it MyProperty), you can reference it on the command line via:
/D __MYVAL__=$(MyProperty)
|
71,489,412 | 71,490,265 | What exactly is the -xhost flag? | I am having trouble understanding the purpose of the -xhost flag used with icc.
On the intel website, it states:
xHost, QxHost
Tells the compiler to generate instructions for the
highest instruction set available on the compilation host processor.
I am not sure what is meant by "highest instruction set".
Also, I see something about SIMD here. If -xhost can speed up your code, why would someone choose not to use this flag?
| The -xhost flag generates the most optimal code possible, based on the capabilities of your current CPU (that is, the one in the computer you're using to do the compilation).
By "highest instruction set", it means that the compiler will automatically turn on the code-generation flags corresponding to the highest instruction set supported by your CPU. So, if your CPU only supports SSE2, then that's all that will be turned on. If it supports AVX2, then that option will be turned on. Whatever the highest instruction set extension that your CPU supports, the compiler will generate code targeting that instruction set extension.
This option is generally used when you want to build code to run on the same computer where you're building it. For example, when building a scientific algorithm that you'll run on the same computer, or when compiling your own Linux kernel.
Technically speaking, the generated binaries will run on any computer that supports at least the same instruction set extensions as the build computer, which is why the documentation talks about "the highest instruction set available on the compilation host processor".
As Peter Cordes already noted in a comment, ICC's -xhost flag is essentially equivalent to GCC and Clang's -march=native flag. Both of them tell the compiler to automatically turn on all options that match what the host CPU is capable of, generating the most optimal binary possible for the host CPU, but which will run on other CPUs, as long as they have equal or higher capabilities.
You can do exactly the same thing that -xhost is going to do by looking up the specifications for your computer's CPU and adding the corresponding code-gen options to the compiler command line. -xhost just does it for you, looking up what your host CPU supports and enabling those flags automatically, without you having to do the legwork. So, it is a convenience feature; nothing more, nothing less.
The -xhost flag can, indeed, speed up your code by taking advantage of certain instruction set extensions, but it can also result in a binary that won't work at all (on a different computer that doesn't support the same instruction set extensions as your build computer). Maybe that's not a problem for you; in that case, you'd definitely turn on the -host flag. But, in many cases, we software developers are building binaries for other people to run, and in that case, we have to be a bit more careful about exactly which CPUs we want to exclude.
It is also worth noting that Intel's compiler can actually generate a single executable with dynamic dispatching support that allows you to support two different architectures. See Sergey L.'s answer to a related question for more details.
|
71,490,067 | 71,491,023 | how do I change the way VS comment out the lines from `//` to `/**/` | In Visual Studio, I selected the lines and click "Comment out the selected lines" in the tool bar. The VS will put // in front of all selected lines. How do I change the style so that the VS put the selected lines in between /**/?
| Currently, there is no such setting you want in C++ project. You can go to Developer Community to propose this new feature and post the link in comment. In addition, Visual Studio now supports Ctrl + Shift + / to comment and uncomment.
|
71,490,470 | 71,490,485 | Reading input with varying number of ints each line in C++ | I am trying to read in user input from the console. The data is as such
3
3 100
5 100
6
9 200
6
9
Where the first line represents N, and there are 2*N entries following it. How would I decide whether a line has two int inputs or just one.
I thought about implementing getline, but that just gives me the whole line, and it gives me a string with a space in between.
Thanks
| I always use getline and parse the string myself. This gives you the most flexibility and is pretty much a requirement when you get to the point that you want to do error handling.
It's not that hard to split a string into pieces based on a common delimiter (like a space). And writing that code is good practice for you.
std::vector<std::string> splitAt(const std::string &input, const std::string &delim) {
std::vector<std::string> vec;
...
return vec;
}
Implement that, and you're golden. The rest of the problem solves itself, and you can use it over and over.
|
71,490,651 | 71,491,337 | va_arg returns different values on x86 and ARM | I'm a new developer on a team who was just given a new Macbook with an M1 Pro (ARM). The rest of my team uses Intel Macbooks (x86). I ran a test which was supposed to create a file and write to it, however, the test errored out because the file was created with incorrect permissions.
I traced it back to a wrapper function that the team uses around open, sysio::openc. It makes use of a variadic template, and intends to eventually call open in libc. Normally, _syscall(fst, args...) would be used to call libc's open. However, for reasons outside the scope of this question, there is another open in available to our test, defined in our_open.cpp below, which is called by _syscall(fst, args...). That might make things a bit confusing, but I think it provides valuable debug information.
We've narrowed down the problem to the following:
When debugging on my coworker's Intel (x86) Mac, inside our version of open, mode = va_arg(ap, int) returns 438 as expected. On my M1 Pro (ARM) Mac, mode = va_arg(ap, int) always returns 32.
Note
The same permissions issue occurs if _syscall(fst, args...) directly calls libc's version of open instead of our redefined version. I left our redefined version of open in the question because we thought it adds debugging value to be able to look into where va_arg is called.
Replacing our variadic sysio::openc wrapper with a direct call to libc's open fixes the issue and creates a file with the expected permissions.
It could have something to do with undefined behavior due to an unexpected type being passed to va_arg like from Why va_arg() produce different effects on x86_64 and arm?. However, I've experimented with things like mode_t mode = static_cast<mode_t>(va_arg(ap, int)) with no success. Also, it wouldn't explain why calling libc's open directly from _syscall(fst, args...) (avoiding our use of va_arg) still doesn't work.
<test.cpp>
const int fdOut = sysio::openc(path, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL | O_CLOEXEC, 438);
<wrapper.h>
template<IOType IOType, typename RetVal, typename... Args>
class IoWrapper
{
public:
explicit IoWrapper(RetVal syscall(Args...))
: _syscall(syscall)
{}
template<typename Arg1, typename... Ts>
RetVal operator()(Arg1 fst, Ts... args)
{
const RetVal ret = _syscall(fst, args...);
if (ret == RetVal(-1)) {
abortOnVfsError<IOType>(fst, errno);
}
return ret;
}
private:
std::function<RetVal(Args...)> _syscall;
};
template<IOType IOType, typename RetVal, typename... Args>
IoWrapper<IOType, RetVal, Args...> make_wrapper(RetVal syscall(Args...))
{
return IoWrapper<IOType, RetVal, Args...>(syscall);
}
inline auto openc = make_wrapper<IOType::read>((int (*)(const char*, int, int))::open);
<our_open.cpp>
extern "C" int open(const char* file, int flags, ...)
{
static libc_open_ptr libc_open = (libc_open_ptr)dlsym(RTLD_NEXT, "open");
int mode = 0;
if ((flags & O_CREAT)) {
va_list ap;
va_start(ap, flags);
mode = va_arg(ap, int); // Returns 438 (correct) on x86 but 32 on ARM (M1 Pro)
va_end(ap);
}
return libc_open(file, flags, mode);
}
| It is undefined behavior to call a function through a function pointer of the wrong type. In this case, open has signature int(const char*, int, ...) and is being called through a int (*)(const char*, int, int). I would say it's a miracle this code ever works on any architecture! The (IMO quite confusing, consider not using the ::) syntax (int (*)(const char*, int, int))::open is a C-style cast to int (*)(const char*, int, int) applied to ::open. C-style casts are dangerous when used with pointers and references because they suppress warnings about questionable casts. A static_cast would have errored here and a reinterpret_cast would have at least made you question your choices.
The simplest solution is probably to rely on std::function to do the adapting.
template<IOType IOType, typename RetVal, typename... Args>
class IoWrapper {
std::function<RetVal(Args...)> syscall;
public:
explicit IoWrapper(std::function<RetVal(Args...)> syscall) // function pointers are annoying anyway...
: syscall(std::move(syscall))
{}
template<typename Arg1, typename... Ts>
RetVal operator()(Arg1 fst, Ts... args) {
const RetVal ret = syscall(fst, args...);
if (ret == RetVal(-1)) {
abortOnVfsError<IOType>(fst, errno);
}
return ret;
}
};
// make_wrapper is unnecessary here because the argument types can't be inferred
inline IoWrapper<IOType::read, int, const char*, int, int> openc(open);
Note that BOTH your version of open and the standard one in the C library should have the signature int open(const char*, int, ...), hence they should either both work or both not work.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.