question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,708,068 | 69,749,258 | C/C++: Streaming MP3 | In a C++ program, I get multiple chunks of PCM data and I am currently using libmp3lame to encode this data into MP3 files. The PCM chunks are produced one after another. However, instead of waiting until the PCM data stream finished, I'd like to encode data early as possible into multiple MP3 chunks, so the client can either play or append the pieces together.
As far as I understand, MP3 files consist of frames, files can be split along frames and published in isolation. Moreover, there is no information on length needed in advance, so the format is suitable for streaming. However, when I use libmp3lame to generate MP3 files from partial data, the product cannot be interpreted by audio players after concatted together. I deactivated the bit reservoir, thus, I expect the frames to be independent.
Based on this article, I wrote a Python script that extracts and lists frames from MP3 files. I generated an MP3 file with libmp3lame by first collecting the whole PCM data and then applying libmp3lame. Then, I took the first n frames from this file and put them into another file. But the result would be unplayable as well.
How is it possible to encode only chunks of an audio, which library is suitable for this and what is the minimum size of a chunk?
| I examined the source code of lame and the file lame_main.c helped me to come to a solution. This file implements the lame command-line utility, which also can encode multiple wav files, so they can be appended to a single mp3 file without gaps.
My mistake was to initialize lame every single time I call my encode function, thus, initialize lame for each new segment. This causes short interruptions in the output mp3. Instead, initializing lame once and re-using it for subsequent calls already solved the problem. Additionally, I call lame_init_bitstream at the start of encode and use lame_set_nocap_currentindex and lame_set_nogap_total appropriately. Now, the output fragments can be combined seamlessly.
|
69,708,154 | 69,802,699 | Setting Up Neovim for C++ with CMAKE | I'm using coc for code-completion and ale for linting my c++ files, this works fine when I have all my headers and source files in the same directory, however when I have a CMake project with the typical include & src directories (for headers and .cpp files respectively) this setup fails to realize that my headers are in the include directory and so the linting and code completion dont work.
Any help in configuring my neovim setup to handle this project structure, or suggestions of different plugins which would do what I want would be much appreciated.
| Please check CMake's documentation regarding CMAKE_EXPORT_COMPILE_COMMANDS.
Here is part of my .nvimrc for example:
nnoremap <F5> :wa <bar> :set makeprg=cd\ build\ &&\ cmake\ -DCMAKE_BUILD_TYPE=debug\ -DCMAKE_EXPORT_COMPILE_COMMANDS=1\ ../view\ &&\ cmake\ --build\ . <bar> :compiler gcc <bar> :make <CR>
This generates the compile_commands.json file which is read by the various ALE Supported Languages and Tools.
|
69,708,428 | 69,708,477 | initialize array of pointer and matrix | I want to initialize array of pointer.(not a normal array) But this doesn't work.
int* arr = new int [5];
arr = {1,2,3,4,5};
Also I don't want to do it like this:(Because if the size changes I have to change the code)
arr[0] = 1; arr[1] = 2; ...
Is there an easy way to do this? what about a matrix?
int** mat = ...
mat = { {1,2} , {3,4} }
And also I don't want initialize like this: (Because when I want to pass the matrix to a function there are some limits (For example: If size changes, I have to change function defenition))
int mat[2][2] = { {1,2} , {3,4} };
| You can write for example
int* arr = new int [5] { 1, 2, 3, 4, 5 };
Or for example you could use the algorithm std::iota like
int* arr = new int [5];
std::iota( arr, arr + 5, 1 );
or some other algorithm as for example std::fill or std::generate.
If the array will be reallocated then it is much better in this case to use the standard container std::vector<int>.
(For example: If size changes, I have to change function defenition))
You can define the function as a template function where the size of an array will be a template non-type parameter.
|
69,708,571 | 69,708,780 | How to pass vector to func() and return vector[array] to main func() | int multif(std::vector<int> &catcher)
{
printf("\nThe array numbers are: ");
for (int i = 0; i < catcher.size(); i++)
{
catcher[i]*=2;
//printf("%d\t", catcher[i]);
return catcher[i];
}
}
Can someone help me to understand how to pass above catcher[i] to main func() in the form of entire array? Thanks in advance...
int main()
{
std::vector <int> varray;
while(true)
{
int input;
if (std::cin >> input)
{
varray.push_back(input);
}
else {
break;
}
}
multif(varray);
std::cout << multif << std::endl;
| Your multif() function:
int multif(std::vector<int> &catcher)
{
printf("\nThe array numbers are: ");
for (int i = 0; i < catcher.size(); i++)
{
catcher[i]*=2;
//printf("%d\t", catcher[i]);
return catcher[i];
}
}
This will double the first element of catcher and return it. I don't think that's what you want. If you want to double all the elements in your function, change that to:
void multif(std::vector<int> &catcher)
{
printf("\nThe array numbers are: ");
for (int i = 0; i < catcher.size(); i++)
{
catcher[i]*=2;
//printf("%d\t", catcher[i]);
}
}
Also, in main() , you call std::cout << multif << std::endl; which will print the memory address of multif(), which also probably not what you want.
If you want to print all the values of varray, try:
void multif(std::vector<int> &catcher)
{
printf("\nThe array numbers are: ");
for (int i = 0; i < catcher.size(); i++)
{
catcher[i]*=2;
//std::cout << catcher[i] << '\n' you can print it here, or:
}
}
int main()
{
std::vector <int> varray;
while(true)
{
int input;
if (std::cin >> input)
{
varray.push_back(input);
}
else {
break;
}
}
multif(varray);
for(const auto &i : varray) std::cout << i << '\n';
}
|
69,708,700 | 69,708,879 | Pointer to portions of array. Operations with filtered array | Following the question in Pointer to portions of array, a structure that does operations with portions of an array was proposed.
However, I am having a problem when calling functions that change entries in the matrices.
When defining operations for matrices it is standard to pass by reference. However, when I use the same structure for the filtered array I get:
error: cannot bind non-const lvalue reference of type ‘subMat&’ to an
rvalue of type ‘subMat’
Here is the code:
#include <vector>
#include <array>
#include <iostream>
// define matrix 4x4
typedef std::array<double, 16> matrix4;
// define matrix 3x3
typedef std::array<double, 9> matrix3;
struct subMat{
matrix4& matrix_;
const double& operator[](size_t index) const
{
static size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10};
return matrix_[mapping[index]];
}
double& operator[](size_t index)
{
static size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10};
return matrix_[mapping[index]];
}
subMat (matrix4& A): matrix_(A){}
};
template <typename T>
double sum_of_elements(const T& arr)
{
double res = 0;
for (int i=0;i <9; ++i) res += arr[i];
return res;
}
template <typename T>
void test(T& arr)
{
for (int i=0;i <9; ++i)
{
arr[i] = 1;
}
}
int main(int argCount, char *args[])
{
std::vector<matrix4> myBlockMatrix(5);
for (int i=0; i < myBlockMatrix.size(); i++)
{
for (int j = 0; j<myBlockMatrix[0].size(); j++)
{
myBlockMatrix[i][j] = i*j;
}
}
for (int i = 0; i<myBlockMatrix.size(); i++)
{
std::cout << sum_of_elements(subMat(myBlockMatrix[i])) << std::endl; // this owrks
}
test(subMat(myBlockMatrix[0])); // this does not work
subMat a = subMat(myBlockMatrix[0]);
test(a); // this works and changes the values in myBlockMatrix
return 0;
}
The question is: What can I do with this structure to re-use the previous functions for matrix3. Do I need to always create a new instance of subMat to do operations? Or is there a way to use subMat(myBlockMatrix[0]) inside the function argument?
| The clue is in the error message: Your test function takes an lvalue reference but the temporary subMat object constructed as the argument in the test(subMat(myBlockMatrix[0])) call is an rvalue.
The simplest fix for this is to redeclare the test function template to have a forwarding reference argument:
template <typename T>
void test(T&& arr) // forwarding reference
{
for (int i = 0; i < 9; ++i) {
arr[i] = 1;
}
}
This will allow the compiler to create versions of test that take either lvalue or rvalue references, the latter being used in the case when the argument is a temporary object.
From the linked cppreference page:
Rvalue references can be used to extend the lifetimes of temporary
objects (note, lvalue references to const can extend the lifetimes of
temporary objects too, but they are not modifiable through them).
|
69,708,765 | 69,708,978 | How can I sort a pair of vector in some given range? | I know how to sort pair of vectors using std:sort(v.begin(), v.end()); But this will sort all the pairs of the vector.
But I want to sort the vector in a specified range.
#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool sortbysecdesc(const pair<int,int> &a,const pair<int,int> &b)
{
return a.second>b.second;
}
int main(){
int n;
cin>>n;
ll a[n];
ll b[n];
vector<pair<ll, ll>> v;
vector<pair<ll, ll>>::iterator itr;
for (int i = 0; i < n; i++) {
cin>>a[i];
}
for (int i = 0; i < n; i++) {
cin>>b[i];
}
for (int i = 0; i < n; i++) {
v.push_back(make_pair(a[i],b[i]));
}
//sorting the pair in descending order with second element
sort(v.begin(), v.end(), sortbysecdesc);
for (itr=v.begin(); itr!=v.end(); itr++) {
/* Logic to be implement */
}
return 0;
}
Code explanation- Here I'm taking input 2 arrays and making a pair of vector by combining first_array[i] element with second_element[i] element.
Such as - first_array = {1, 5, 4, 9} and second_array = {2, 10, 5, 7} then the vector of pair's will be of size = 2*size_of(first/second array) and elements will be [{1, 2}, {5, 10}, {4, 5}, {9, 7}].
Then I'm sorting these pair in descending order according to second elements of pairs i.e, all elements of second array.
Now I wanna sort the vector form where second elements are equal.
eg - if the vector is [{1,6} , {4,5}, {3,5}, {8,5}, {1,1}]. Here 5 occurs three time in second element of pair so sort their first index in ascending order.
Expected result - [{1,6} , {3,5}, {4,5}, {8,5}, {1,1}]
Note - We had already sorted the second element in descending order.
| What you need is something like the following
#include <tuple>
#include <vector>
#include <iterator>
#include <algorithm>
//...
std::sort( std::begin( v ), std::end( v ),
[]( const auto &p1, const auto &p2 )
{
return std::tie( p2.second, p1.first ) < std::tie( p1.second, p2.first );
} );
Here is a demonstration program.
#include <iostream>
#include <tuple>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::pair<long long, long long>> v =
{
{1,6} , {4,5}, {3,5}, {8,5}, {1,1}
};
std::sort( std::begin( v ), std::end( v ),
[]( const auto &p1, const auto &p2 )
{
return std::tie( p2.second, p1.first ) <
std::tie( p1.second, p2.first );
} );
for ( const auto &p : v )
{
std::cout << "{ " << p.first << ", " << p.second << " } ";
}
std::cout << '\n';
return 0;
}
The program output is
{ 1, 6 } { 3, 5 } { 4, 5 } { 8, 5 } { 1, 1 }
|
69,709,284 | 69,709,574 | C++ Check if the package has been installed via Swift Package Manager and include a file | I have a set of C++ packages resolved with the Swift Package Manager and another Package Manager (let's call it PMX).
PMX cannot resolve one of the dependencies, but I have to run CI on it. Is it possible to somehow check that the package is being compiled with the SPM system and include the appropriate imports and if it's not using SPM, then just not include those headers?
Example:
#if defined(_WIN32) || defined(_WIN64) || defined(__APPLE__)
#include <MyFile.h>
#endif
I'd like to have something similar to this:
#if defined(_WIN32) || defined(_WIN64) || (defined(__APPLE__) && defined(SWIFT_PACKAGE_MANAGER))
#include <MyFile.h>
#endif
Is something like this possible?
| Found a solution, this flag exists and it's called SWIFT_PACKAGE
This solution has worked perfectly for me:
#if defined(_WIN32) || defined(_WIN64) || (defined(__APPLE__) && defined(SWIFT_PACKAGE))
#include <MyFile.h>
#endif
Blog post mentioning the issue
|
69,709,450 | 69,709,571 | Facing debugging problem when implementing doubly linked list in C++ | I am implementing a doubly linked list where each node has two pointers. One points to the next node in the list, while the other points to the previous node.
The node struct consists of an integer and a node-pointer to the next node in the list. And another pointer to the previous pointer in the list.
The class contains two node pointers: one to the head of the list, and one to the tail of the list. If the list is empty, they should both point to nullptr.
My code is
#include <iostream>
using namespace std;
struct Node
{
int value;
Node *next;
Node *tail; //previous node pointer
};
class LinkedList
{
private:
Node *head;
Node *tail;
public:
int size;
LinkedList()
{
head = nullptr;
tail = nullptr;
size = 0;
}
int length()
{
return size;
}
void append(int val)
{
if (head == nullptr)
{
head = new Node(val);
return;
}
// Iterate to end of list
Node *current;
current = head;
while (current->next != nullptr)
{
current = current->next;
}
// Link new node to end of list
current->next = new Node(val);
}
};
int main()
{
};
I am getting this error:
error: no matching constructor for initialization of 'Node'
head = new Node(val);
^ ~~~
linked_list.cpp:4:8: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'int' to 'const Node' for 1st
argument
struct Node
^
linked_list.cpp:4:8: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 1 was provided
2 errors generated.
Any advice/links about where I can read more about this topic is welcome:) Thank you in advance!
| In other to call new Node(val) where val is an int, your Node needs a constructor that takes an int as an argument.
Perhaps:
struct Node
{
int value;
Node *next;
Node *tail;
Node(int v) : value(v), next(nullptr), tail(nullptr) { }
};
|
69,709,668 | 69,709,889 | accessing struct by a pointer | Im currently experimenting with pointers and i have several questioins to my code
ps. this is just for experimenting Im not going to use this in any code
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
struct obj
{
int* IntPtr;
obj()
{
IntPtr = new int[2];
IntPtr[0] = 123;
IntPtr[1] = 456;
}
};
int main()
{
obj MyStruct;
long long int* Adress = (long long int*) & MyStruct; //pointer to a struct
//change value in struct
*(long long int*)(*Adress + sizeof(int)) = 789;
std::cout << "get value by pointer: " << (int)*(long long int*)(*Adress + sizeof(int)) << std::endl; //std::cout crashes my program
printf("get value by pointer: %d\n", (int)*(long long int*)(*Adress + sizeof(int)));
printf("get value from struct: %d\n", MyStruct.IntPtr[1]);
return 0;
}
why does std::cout crashes my program? I had to use printf function to fix this issue
can i delete IntPtr from from my main function? something like delete[] (long long int*)*Adress; and then create new ? like:
int* Itemp = new int[5];
*Adress = (long long int)Itemp;
EDIT: this was just an experiment on how to access int* IntPrt in strcut obj when it is private: i wouldnt use this method othersise.
the code even with the delete[] and new worked fine on my compiler
thanks everyone for the explanation
| Even if the syntax errors in your code were fixed, the premise of what I suspect you are trying to do would still be fundamentally flawed. Taking a pointer, converting it to a number representing a memory address, shifting it around to land on another object and accessing it this way is simply not something you are allowed to do in C++.
Compilers are allowed to, and actively do, optimize code based on the assumption that the program never does such things. So even if a program appears to be working while doing this, it could very well break when compiled with a different compiler, a different version of the same compiler, or different compilation settings on the same compiler.
So what does that mean to us as programmers? Pointers being memory addresses does not mean that we are allowed to treat them like memory addresses (with a few specific exceptions).
Pointers point to objects (reminder: even a simple int is an object). the fact that a pointer points into memory is an implementation detail; unless you are manipulating the raw bytes of the underlying storage a single byte at a time.
You must treat a pointer as either:
Not pointing at an object, in which case you can only assign, copy, or compare it.
Pointing at an object, in which case you can also dereference it with * or ->.
Pointing at an object that is part of an array, at which point, you can
also use [] or pointer arithmetic (+, -, etc...) to access other objects in the same array.
That's all.
Taking this into consideration, here's what your code should be looking like. This is mostly for reference. I know that's not what you were trying to do.
struct obj
{
int* IntPtr;
obj()
{
IntPtr = new int[2];
IntPtr[0] = 123;
IntPtr[1] = 456;
}
~obj()
{
// Btw. If you have a new, ALWAYS have a delete, even in throwaway code.
delete IntPtr[];
}
};
int main()
{
obj MyStruct;
// Get a pointer to the struct
obj* Adress = &MyStruct;
// Change value in struct via the pointer
obj->IntPtr[1] = 789;
(*obj).IntPtr[1] = 789;
std::cout << "get value by pointer: " << obj->IntPtr[1] << std::endl;
printf("get value by pointer: %d\n", obj->IntPtr[1]);
printf("get value from struct: %d\n", obj.IntPtr[1]);
}
Edit: For completeness' sake, here's code that does what I interpreted you were going for:
#include <iostream>
#include <cstdint>
#include <cassert>
struct obj {
int IntData[2];
};
int main()
{
obj MyStruct;
// Get a number containing the memory address associated with MyStruct.
// std::uintptr_t is the integer type of the same size as a pointer
std::uintptr_t AdressOfMyStruct = (std::uintptr_t)&MyStruct;
std::cout << "MyStruct lives at: " << AdressOfMyStruct << std::endl;
// Do the same thing for IntData[1]
std::uintptr_t AdressOfIntData1 = (std::uintptr_t)&MyStruct.IntData[1];
std::cout << "MyStruct.IntData[1] lives at: " << AdressOfIntData1 << std::endl;
// recalculate the address of IntData1 as an offset from MyStruct
std::uintptr_t AdressOfIntData1Calculated = AdressOfMyStruct + sizeof(int);
std::cout << "MyStruct.IntData[1] lives at (alt): " << AdressOfIntData1 << std::endl;
// Verify that IntData[1] is where we expect it to be.
assert( AdressOfIntData1Calculated == AdressOfIntData1 );
// ...Everything up to here is valid code...
// WARNING: this may looks like it works, but it is, in fact, Undefined Behavior.
int* PtrToIntData1 = reinterpret_cast<int*>(AdressOfIntData1);
*PtrToIntData1 = 789;
// WARNING: This is also undefined behavior.
std::cout << "get value by pointer: " << *PtrToIntData1 << std::endl;
// This is fine, obviously.
std::cout << "get value from struct: " << MyStruct.IntData[1] << std::endl;
return 0;
}
|
69,709,958 | 69,710,155 | Where to insert an #include when multiple files need it C++ | Let's say I have 4 source files main, aux1, aux2 and aux3, all of whom work with strings and therefore need to #include <string>.
The main one will include the 3 aux, since it will use it's functions, but none of the aux needs to include main nor any other aux.
Where should I include string and how could something like #pragma once help me with this situation?
| Headers should include what they use. Deviating from this leads to pain on the long run. Hence:
// aux1.h
#include <string>
// aux2.h
#include <string>
// aux3.h
#include <string>
// main.cpp
#include "aux1.h"
#include "aux2.h"
#include "aux3.h"
You could in principle include <string> in main before you include the other headers, then the code will compile even if the other headers do not include <string>. However, this is very fragile, because then correctness of your code depends on order of includes. The auxX.h headers should be correct independent of what other headers have already been included or not.
[...] how could something like #pragma once help me with this situation?
You should use header guards for your own headers, though <string> already has header guards and including it multiple times is a not something you need to worry about.
|
69,709,983 | 69,711,108 | Am I implementing Euler's Method correctly in C++? | I was asked to write a C or C++ program to solve the given differential equation
This must be achieved numerically using Euler method. The user should be able to enter the velocity(v), the initial value of x(0) and the final Time (T) at the beginning of the program.It should also plot the numerical solution for times 0 <t < T.
I felt like I got the program running fine, but I am having trouble implementing the Euler method correctly in the respect to the equation. Here is the program I have created. Any feedback/advise would be greatly be appreciated. Let me know if you require more information.
#include <iostream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
using namespace std;
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <array>
#include "gnuplot.cxx"
int main()
{
//establishing values
double v, x0, T, dt, number_steps;
const int max_number_steps = 100000;
int i=0;
//establishing numverical arrays
double value_t [max_number_steps];
double approx_x [max_number_steps];
//Allow users to input variables
cout<<"Enter Initial Condition"<< endl;
cout<<"Velocity(v) = ";
cin>> v;
cout<<"x0 = ";
cin >> x0;
cout<<"Final time(T) = ";
cin >> T;
cout << "number steps = ";
cin >> number_steps;
//Establishing stepside and assigning arrays
dt = T/number_steps;
value_t[0]= 0.0;
approx_x[0] = x0;
//for loop which should implement Euler's Method
for ( i= 0; i < number_steps; i++)
{
value_t [i+1] = dt*(i+1);
approx_x[i+1] = approx_x[i+1] + dt*v;
}
//Graph the plot via gnuplot
gnuplot_one_function("Velocity", "linespoints", "Time(t)", "Position(x)", value_t, approx_x, number_steps);
return 0;
}
| You have a fundamental error with the Euler method concept.
my_aprox[i + 1] = my_aprox[i] + dt*v
Remember, to calculate a new approximation you have to have "a priori" the initial value which, with the next approximation will be the next initial value an so.
|
69,710,244 | 69,713,691 | Accessing only one executable at a time to a function in .so library | I'm developing a system of executables which run together (and communicate via ROS). I have a .json configuration file which is common for all the executables and a libCommon.so which is a library of functions to read certain values from the .json. The library is linked statically to all the executables in CMakeLists.txt:
set(NAME exec1)
target_link_libraries(${NAME} ... Common)
As the system is launching, all the execs need to start one after another - something like that in bash script:
./exec1 & ./exec2
etc.
The problem
The .json parser which I use is giving me assertion errors which I found out to be symptoms of the executables running their constructors and accessing the same config file at once;
So, I have tried some stuff with a global mutex (std::mutex busy), which is declared in the header and defined in cpp of the libCommon.so. Then, it is locked on entry of every function and unlocked before return statement:
Common.h
namespace jsonFunctions
{
extern std::mutex busy;
namespace ROS
{
extern double readRosRate( configFiles::fileID configID );
}
...
}
class ConfigFile
{
public:
ConfigFile( configFiles::fileID configID )
{
configFileFstream.open( configFiles::filePaths.at( configID ) );
if( configFileFstream.is_open() )
{
parsedFile.parse( configFileFstream );
}
}
~ConfigFile()
{
configFileFstream.close();
}
public:
jsonxx::Object parsedFile;
private:
std::fstream configFileFstream;
};
Common.cpp
namespace jsonFunctions
{
std::mutex busy;
namespace ROS
{
double readRosRate( configFiles::fileID configID )
{
busy.lock();
ConfigFile* desiredConfigFile = new ConfigFile( configID );
auto rosConfig = desiredConfigFile->parsedFile.get< jsonxx::Object >( "ROS" );
delete desiredConfigFile;
busy.unlock();
return rosConfig.get< jsonxx::Number >( "rate" );
}
But this doesn't work.
How am I supposed to block the executables from accessing the config file at the same time?
| Executables live in their own memory space. They do not share memory with other executables, even if they are both using the same shared library1.
There are no interprocess mutexes in standard C++. You have to find an interprocess mutex from outside the standard.
boost has them, and most OS file system APIs can be used to create them.
Some OS APIs allow you to open files in an exclusive mode. Others rely on you created explicit locks. In some cases, this functionality may depend on the filesystem you are accessing, and even how you are accessing it.
Apparently one way to do it is to open open("unique_name.lock", O_CREAT|O_EXCL, 0777) in a specific spot you both share. Only one process can have unique_name.lock open in this way at a time.
Another is to use flock.
1 Well, read only pages are sometimes shared by some OS's between processes; like executable code. And even read-write pages can be copy-on-write shared. This kind of sharing, however, happens just "as if" it didn't happen. Also, address space layout randomization makes this optimization less useful.
|
69,710,300 | 69,713,941 | Print library value from function on display | I'm trying to print the return value(WiFi.localIP) on my display from the library ESP8266WiFi. But I'm getting an error. For the display I'm using the SSD1306 library.
The purpose of this is to print the IP adress of the ESP8266 on the display.
ERROR:
Arduino: 1.8.16 (Windows 10), Board: "LOLIN(WEMOS) D1 R2 & mini, 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
C:\Users\lauwy\Documents\Arduino\Testsketch\Project\Code\WEB\V4.2\V4.2.ino: In function 'void connectToWifi()':
V4.2:38:32: error: taking address of rvalue [-fpermissive]
38 | String ipstat = &WiFi.localIP();
| ~~~~~~~~~~~~^~
V4.2:38:19: error: conversion from 'IPAddress*' to non-scalar type 'String' requested
38 | String ipstat = &WiFi.localIP();
| ^~~~~~~~~~~~~~~
exit status 1
taking address of rvalue [-fpermissive]
CODE:
#include <Wire.h>
#include "SSD1306.h"
SSD1306 display(0x3C, D2, D5);
#include <ESP8266WiFi.h>
const char* ssid = "*****************"; //Enter network SSID
const char* password = "*****************"; //Enter network PASSWORD
WiFiServer server(80);
void connectToWifi(){
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
String ipstat = &WiFi.localIP();
display.init();
display.flipScreenVertically();
display.drawString(0, 0, ipstat);
display.display();
}
| Used toString() method from the ESP8266WiFi library (line 162-173).
String ipstat = WiFi.localIP().toString();
|
69,710,587 | 69,710,983 | C++ vector of strings into associative vector of ints | Im having trouble to convert a string vector with size of ~ 1.0000.0000 elements to an associative vector with integers.
Input:
std::vector<std::string> s {"a","b","a","a","c","d","a"};
Desired output:
std::vector<int> i {0,1,0,0,2,3,0};
I was thinking of an std::unordered_multiset as mentioned in Associative Array with Vector in C++ but i can't get it running.
The goal is to reduce the time it takes to convert c++ strings to R strings, which is so much faster if I just use numbers.
Thank you for your help!
Edit:
Thats how I tried to populate the set:
for (size_t i = 0; i < s.size(); i++)
{
set.insert(s[i]);
}
| This code will output your desired output for your given input. And it will process 1.000.000 strings of length 3 in 0.4s. So I think unordered_map is a viable choice.
#include <string>
#include <iostream>
#include <unordered_map>
#include <chrono>
#include <random>
// generator function for creating a large number of strings.
std::vector<std::string> generate_strings(const std::size_t size, const std::size_t string_length)
{
static std::random_device rd{};
static std::default_random_engine generator{ rd() };
static std::uniform_int_distribution<int> distribution{ 'a', 'z' };
std::vector<std::string> strings;
std::string s(string_length, ' ');
for (std::size_t n = 0; n < size; n++)
{
for (std::size_t m = 0; m < string_length; ++m)
{
s[m] = static_cast<char>(distribution(generator));
}
strings.emplace_back(s);
}
return strings;
}
int main()
{
std::vector<std::string> strings = generate_strings(1000000, 3);
//std::vector<std::string> strings{ "a","b","a","a","c","d","a" };
std::unordered_map<std::string, int> map;
std::vector<int> output;
// speed optimization, allocate enough room for answer
// so output doesn't have to reallocate when growing.
output.reserve(strings.size());
auto start = std::chrono::high_resolution_clock::now();
int id = 0;
for (const auto& string : strings)
{
if (map.find(string) == map.end())
{
output.push_back(id);
map.insert({ string, id });
id++;
}
else
{
output.push_back(map.at(string));
}
}
auto duration = std::chrono::high_resolution_clock::now() - start;
auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count();
auto seconds = static_cast<double>(nanoseconds) / 1.0e9;
/*
for (const auto& value : output)
{
std::cout << value << " ";
}
*/
}
|
69,711,295 | 72,350,398 | C++ execute python file using ShellExecuteA | So im trying to execute a python file (no console) using C++ shellapi.h ShellExecuteA but it wont work and return a value 42 if i do
int value = ShellExecuteA(nullptr,"open",path.c_str(),nullptr,nullptr, SW_HIDE );
and return (error 2) if i use GetLastError(); from errhandlingapi.h
here is the entire function in C++
void mainwindow::make_projectsave(){
ofstream ofFile(PATH + string("depozitdir\\info.txt"));
string line;
for(int nr = 0;nr<scazator.size();nr++){
line = column1[nr] +" "+ column2[nr] +" "+ column3[nr] + " "+ scazator[nr] +" "+ column4[nr] + "\n";
ofFile<<line;}
string dirname = std::string(namevector[2]);
string name = std::string(namevector[0]);
namevector.clear();
ofFile<< "=filename->" +name+"\n";
ofFile<< "=dir->" +dirname+"\n";
ofFile.close();
string path = PATH + "makesave.pyw";
ShellExecuteA(nullptr,"open",path.c_str(),nullptr,nullptr, SW_HIDE ); // doesnt work...
what it does it stores some info to the file info.txt and then calls the python file (which doesnt work) so it makes an excel file.
| To fix it make the file you want to execute .py , instead of .pyw
|
69,711,555 | 69,711,808 | How to get integers until \n for n number of lines | My input :
the first input is number of lines the input will contain
5
7 3 29 0
3 4 3
2 3 4 55 5
2 3
1 2 33 4 5
My issue is how can I store them in vector of vector..?
My concept..
.
.
.
cin>>n;
vector<vector<int>>vec;
while(n--)
{
vector<int>vec2;
for(**Getting input until the line**){
vec2.emplace_back(input);}
vec.emplace_back(vec2)
}
I need to implement that getting input till the line. For this I thought of getting the input as string and storing the values in vector vec2 using strtok after converting it to c_string... But I need to know whether there is any efficient way I can overcome this problem..
| Here's my suggestion, YMMV.
Read each line into a string.
Use istringstream to extract the integers from the string, into a vector.
After string is processed, push_back the vector into the outer vector.
unsigned int rows;
std::cin >> rows;
std::string text_row;
for (unsigned int i = 0U; i < rows; ++i)
{
std::getline(cin, text_row);
std::istringstream numbers_stream(text_row);
std::vector<int> row_data;
int number;
while (numbers_stream >> number)
{
row_data.push_back(number);
}
vec.push_back(row_data);
}
|
69,711,608 | 69,717,395 | Why XRecordDisableContext() is not working? | void Callback (XPointer, XRecordInterceptData *pRecord) { std::cout << "my logs\n"; }
int main ()
{
if(auto* const pDisplay = XOpenDisplay(nullptr))
{
XRecordClientSpec clients = XRecordAllClients;
auto* pRange = ::XRecordAllocRange();
pRange->device_events = XRecordRange8{KeyPress, ButtonRelease};
auto context = ::XRecordCreateContext(pDisplay, 0, &clients, 1, &pRange, 1);
::XRecordEnableContextAsync(pDisplay, context, Callback, nullptr); // use with/without `...Async()`
::XRecordDisableContext(pDisplay, context);
::XRecordFreeContext(pDisplay, context);
::XFree(pRange);
::XFlush(pDisplay);
::XSync(pDisplay, true);
}
}
I am noticing that even after XRecordDisableContext(), the Callback() continues to be invoked.
How can we disable the recording, so that the callback isn't invoked anymore?
Note:
Have taken example from this site.
Don't know how to use XRecordEnableContext(), so using XRecordEnableContextAsync(). Is that the source of problem?
| One way is to move below statement into the Callback() or some equivalent other thread. For testing purpose, I changed the code as below where after few event raised, I disable from the Callback() and it works.
::Display* pDisplay;
XRecordRange* pRange;
XRecordContext context;
#define CHECK(EVENT) if(*pDatum == EVENT) qDebug() << #EVENT
void Handle (XPointer, XRecordInterceptData *pRecord)
{
std::cout << "my logs\n";
static int i = 0;
if(++i < 10)
return;
::XRecordDisableContext(pDisplay, context);
::XRecordFreeContext(pDisplay, context);
::XFree(pRange);
::XFlush(pDisplay);
::XSync(pDisplay, true);
}
// other code same, except 3 variables are global and "Free"-up functions are not required
|
69,711,686 | 69,712,159 | Rebuild CMake target when dependency changes | There are countless similar questions on here but I can't find one that addresses exactly this issue:
I'm using to CMake to build shared libraries a and b and executable prog. prog should be linked against a but not against b. However, at the same time I want prog to be rebuilt whenever b is outdated. In practical terms, b is a compiler plugin used while building prog.
I have tried:
add_library(a a.cc)
add_library(b b.cc)
add_dependencies(a b)
add_executable(prog prog.cc)
target_link_libraries(prog PRIVATE a)
But this does not work, when b needs to be rebuilt this does not result in prog being rebuilt as well.
I have also tried:
add_library(a a.cc)
add_library(b b.cc)
target_link_libraries(a INTERFACE b)
add_executable(prog prog.cc)
target_link_libraries(prog PRIVATE a)
But this causes prog to be linked against b. Is there no way to achieve this?
| I see that generator expression do not work in OBJECT_DEPENDS context. Touché. Anyway, just do a small proxy:
cmake_minimum_required(VERSION 3.11)
project(test)
add_library(a a.cpp)
add_library(b b.cpp)
add_executable(prog prog.cpp)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/b_is_build
COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/b_is_build
DEPENDS $<TARGET_FILE:b>
)
set_source_files_properties(prog.cpp PROPERTIES
OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/b_is_build
)
Then touching b.cpp rebuilds prog:
+ touch b.cpp
+ cmake --build _build --verbose
[1/5] /usr/bin/c++ -MD -MT CMakeFiles/b.dir/b.cpp.o -MF CMakeFiles/b.dir/b.cpp.o.d -o CMakeFiles/b.dir/b.cpp.o -c /dev/shm/.1000.home.tmp.dir/b.cpp
[2/5] : && /usr/bin/cmake -E rm -f libb.a && /usr/bin/ar qc libb.a CMakeFiles/b.dir/b.cpp.o && /usr/bin/ranlib libb.a && :
[3/5] cd /dev/shm/.1000.home.tmp.dir/_build && /usr/bin/cmake -E touch /dev/shm/.1000.home.tmp.dir/_build/b_is_build
[4/5] /usr/bin/c++ -MD -MT CMakeFiles/prog.dir/prog.cpp.o -MF CMakeFiles/prog.dir/prog.cpp.o.d -o CMakeFiles/prog.dir/prog.cpp.o -c /dev/shm/.1000.home.tmp.dir/prog.cpp
[5/5] : && /usr/bin/c++ CMakeFiles/prog.dir/prog.cpp.o -o prog liba.a && :
b is a compiler plugin used while building prog
Ideally would be to tell CMake that object files depend on that plugin file, however $<TARGET_FILE does not work here.
set_source_file_properties(prog.cc PROPERTIES
OBJECT_DEPENDS $<TARGET_FILE:b>
)
Or tell CMake that that linking the resulting program depends on on the plugin, depending where exactly that plugin is used.
set_target_properties(prog PROPERTIES
LINK_DEPENDS $<TARGET_FILE:b>
)
Dependencies are modeled on files - for example executable file prog depends on file b. add_dependencies only does ordering (one is build before the other).
|
69,712,496 | 69,712,519 | Use of incomplete types in templates | Is it legal to use an incomplete type in a template if the type is complete when the template is instantiated?
As below
#include <iostream>
struct bar;
template <typename T>
struct foo {
foo(bar* b) : b(b) {
}
void frobnicate() {
b->frobnicate();
}
T val_;
bar* b;
};
struct bar {
void frobnicate() {
std::cout << "foo\n";
}
};
int main() {
bar b;
foo<int> f(&b);
f.frobnicate();
return 0;
}
Visual Studio compiles the above without complaining. GCC issues the warning invalid use of incomplete type 'struct bar' but compiles. Clang errors out with member access into incomplete type 'bar'.
| Clang is correct in reporting an error (as opposed to a warning or being silent about it), though MSVC's and GCC's behavior are also consistent with the standard. See @HolyBlackCat's answer for details on that.
The code you posted is ill-formed NDR. However, what you want to do is feasible.
You can defer the definition of template member functions the same way you would for a non-template class. Much like non-template classes, as long as these definitions requiring bar to be a complete type happen only once bar is complete, everything is fine.
The only hiccup is that you need to explicitly mark the method as inline to avoid ODR violations in multi-TU programs, since the definition will almost certainly be in a header.
#include <iostream>
struct bar;
template <typename T>
struct foo {
foo(bar* b) : b(b) {
}
inline void frobnicate();
T val_;
bar* b;
};
struct bar {
void frobnicate() {
std::cout << "foo\n";
}
};
template <typename T>
void foo<T>::frobnicate() {
b->frobnicate();
}
int main() {
bar b;
foo<int> f(&b);
f.frobnicate();
return 0;
}
|
69,712,790 | 69,712,832 | how to emplace_back (append) in vector without declaring variables..? | If number of input are given as first input.
If I need to store them in vector
I can easily do it by creating a variable and using the variable I can append it in the vector
I'm fascinated to know , is there any other way so that I need not have to use a variable..
INPUT
4
1 5 3 2
How vector take inputs
vector<int>vec;
for(int i=0;i<n;i++)
{
int x;
cin>>x; // any idea to remove using a variable here..?
vec.emplace_back(x);
}
How array takes inputs
int array[n];
for(int i=0;i<n;i++)
cin>>array[i];
| Yes, just do this:
std::cin >> vec.emplace_back();
The return type of vector::emplace_back() in C++17 is no longer void. Instead, it returns a reference to the inserted element. So vec.emplace_back() will construct an element by default and return its reference.
|
69,712,879 | 69,712,977 | Drag and Drop QTreeWidgetItem to QGraphicsView with custom data | I've a class containing a QTreeWidget, where I have some QTreeWidgetItem.
I want to drag and drop a QTreeWidgetItem into a QGraphicsScene, in order to create an object in there. The object is a rectangle with the text of the QTreeWidgetItem in there.
I was able to perform the drag and drop operation, and I've my dropEvent virtual method for handling it. It receives the drop event, but I'm not be able to retrieve information about the original QTreeWidgetItem.
This is the code that I've used to initialize the QTreeWidget:
m_nodeList = new QTreeWidget(this);
m_nodeList->setColumnCount(2);
m_nodeList->setHeaderLabels({ NameLabel, CategoryLabel });
m_nodeList->setDragEnabled(true);
m_nodeList->setDragDropMode(QAbstractItemView::DragOnly);
The dropEvent overridden method in my Scene subclass of QGraphicsScene is the following one:
void Scene::dropEvent(QGraphicsSceneDragDropEvent* event) {
event->acceptProposedAction();
for (const auto& it : event->mimeData()->formats()) {
std::string f = it.toStdString();
int i = 0;
}
std::string t = event->mimeData()->text().toStdString();
std::string on = event->mimeData()->objectName().toStdString();
}
f contains application/x-qabstractitemmodeldatalist, while other strings are empty.
How can I retrieve information about the QTreeWidgetItem that I've dragged into the QGraphicsScene?
| DND of models uses an internal Qt format so a possible solution is to use a dummymodel:
void Scene::dropEvent(QGraphicsSceneDragDropEvent* event) {
event->acceptProposedAction();
if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")){
QStandarditemmodel dummy_model;
if(dummy_model.dropMimeData(event->mimeData(), event->dropAction(), 0, 0, QModelIndex()){
QModelIndex index = dummy_model.index(0, 0);
qDebug() << index.data();
}
}
}
|
69,712,962 | 69,713,171 | Constexpr CRTP destructor | I created the constexpr version of the Curiously Recurring Template Pattern and all seem to work as expected, except the destructor who "under normal circumstances" should be marked as virtual. As I can understand, virtual is the vital enemy of constexpr.
In my example I implemented two interfaces with no data-members. Is it correct in the general case (with data-members) to let virtual ~Crtp() = default;, virtual ~FeatureNamesInterface() = default; and virtual ~FeatureValuesInterface() = default; commented out and let the compiler to define the destructors? Does this approach have a memory leak? Is it a better approach to make them protected? Any other solution that work with constexpr would be welcome!
The interface code look like this
namespace lib
{
template <typename Derived, template<typename> class CrtpType>
struct Crtp
{
//virtual ~Crtp() = default;
[[nodiscard]] Derived& child() noexcept { return static_cast<Derived&>(*this); }
[[nodiscard]] constexpr Derived const& child() const noexcept { return static_cast<const Derived&>(*this); }
private:
constexpr Crtp() = default;
friend CrtpType<Derived>;
};
template<typename Derived>
struct FeatureNamesInterface : Crtp<Derived, FeatureNamesInterface>
{
constexpr FeatureNamesInterface() = default;
//virtual ~FeatureNamesInterface() = default;
[[nodiscard]] constexpr auto& GetFeatureNames() const noexcept { return Crtp<Derived, FeatureNamesInterface>::child().GetNames(); }
};
template<typename Derived>
struct FeatureDataInterface : Crtp<Derived, FeatureDataInterface>
{
constexpr FeatureDataInterface() = default;
//virtual ~FeatureValuesInterface() = default;
[[nodiscard]] constexpr auto GetFeatureData() const { return Crtp<Derived, FeatureDataInterface>::child()(); }
};
}
And the implementation of the two sample classes look like this
namespace impl
{
class ChildOne final : public lib::FeatureNamesInterface<ChildOne>, public lib::FeatureDataInterface<ChildOne>
{
static constexpr std::array mNames{"X"sv, "Y"sv, "Z"sv};
public:
constexpr ChildOne() : FeatureNamesInterface(), FeatureDataInterface() {}
~ChildOne() = default;
[[nodiscard]] constexpr auto& GetNames() const noexcept { return mNames; }
[[nodiscard]] constexpr auto operator()() const noexcept
{
std::array<std::pair<std::string_view, double>, mNames.size()> data;
double value = 1.0;
for (std::size_t i = 0; const auto& name : mNames)
data[i++] = {name, value++};
return data;
}
};
class ChildTwo final : public lib::FeatureNamesInterface<ChildTwo>, public lib::FeatureDataInterface<ChildTwo>
{
static constexpr std::array mNames{"A"sv, "B"sv, "C"sv, "D"sv, "E"sv, "F"sv};
public:
constexpr ChildTwo() : FeatureNamesInterface(), FeatureDataInterface() {}
~ChildTwo() = default;
[[nodiscard]] constexpr auto& GetNames() const noexcept { return mNames; }
[[nodiscard]] constexpr auto operator()() const noexcept
{
std::array<std::pair<std::string_view, double>, mNames.size()> data;
double value = 4.0;
for (std::size_t i = 0; const auto& name : mNames)
data[i++] = {name, value++};
return data;
}
};
}
The full example can be found here.
|
except the destructor who "under normal circumstances" should be marked as virtual
Something is iffy here. It sounds like you are operating on the assumption that "All classes should have a virtual destructor", which is incorrect.
virtual destructors are only required if there is a possibility that a derived class might be deleted from a pointer to the base. As a matter of safety, it is also generally encouraged to systematically have a virtual destructor if the base has any other virtual methods because the resulting additional overhead is negligible, since there is already a vtable present.
On the flip side, if a class has no virtual methods, then there's generally no reason to ever hold a owning pointer to a derived object in a pointer to the base. On top of that, the virtual destructor's overhead becomes proportionally a lot larger because there would be no need for a vtable at all without it. A virtual destructor becomes likely to cause more harm than good, unless you know for sure that you will need it.
It's even more clear-cut in the case of CRTP because pointers to base CRTP types are generally never a thing in the first place since:
They only ever have one Derived class.
The base class is unusable by itself on account of the casts to the Derived class.
Is it a better approach to make them protected?
That's generally a good approach for non-polymorphic classes that are meant to be inherited. It ensures that the only thing ever calling the destructor will be a derived class's destructor, which provides a hard guarantee that destruction will never need to be virtual.
In the case of CRTP, though, it almost borders on overkill. Just leaving the destructor defaulted out is generally deemed acceptable.
|
69,713,155 | 69,713,287 | When iterating over a 2D structure, is it faster to iterate over the total length or use nested loops to iterate over the rows and columns? | I can think of two different ways to iterate over a 2d range, either using nested loops to iterate over the rows and columns separately:
for (int i = 0; i < width * height; i++) {
int x = i % width;
int y = i / width;
//Do stuff
}
or using a single for loop to iterate over the area and computing the row and column:
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//Do stuff
}
}
In my application width and height can be very large, so I need to know which one will perform better for large numbers of iterations.
| width * height might overflow. Signed integer overflow is (still) undefined behavior. i % 0 is undefined behavior. i / 0 is undefined behavior too. You can protect the first version against such problems, though in the second version none of this issues is present.
Don't do premature optimization. This:
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//Do stuff
}
}
Is simpler and more readable than the flat loop, and on top of that it is correct (irrespective of the values of height and width).
If you do care about performance, you should first write correct and tested code and then measure and profile it.
|
69,713,776 | 69,715,088 | How to tell when all instances of Thread A have finished from Thread B | I am currently making a program in C++ that simulates Waiters and Customers in a restaurant using threads. The program runs 40 Customers threads and 3 Waiters threads, with functions like this:
void *customer(void * vargp){
//depending on assigned table, call waiter 1-3 using semaphore
sem_post(&callWaiter);
//wait for waiter to respond
sem_wait(&waiterResponse);
//leave table and finish thread
}
void *waiter(void *vargp){
//this is what I'm trying to fix
while(there are still customers){ //this check has been a number of different attempts
sem_wait(&callWaiter);
sem_post(&waiterResponse);
}
}
The issue I am trying to find a solution for is that a waiter will see that a customer is still active (through a few different techniques I tried), then block waiting for the semaphore, then the customer will finish and there will be no more customers. Does anyone have ideas for how a waiter thread can check for running customers without the check going through before the last customers finish?
| With semaphores, a straightforward way would be to use sem_getvalue() on a semaphore initialized to the number of customers.
int num_customers(bool = false){
int v;
sem_getvalue(&customers, &v);
return v;
}
As customers leave, each performs sem_wait() on that semaphore. When sem_getvalue() returns 0, it means all the customers have left.
A trick would be for the last customer to wake up their waiter to let them know they have left.
//leave table and finish thread
sem_wait(&customers);
if (num_customers() == 0) sem_post(&callWaiter);
The waiters would check to see if there are any customers first before handling a customer.
while(num_customers(true) > 0){
//wait for work
sem_wait(&callWaiter);
if (num_customers(true) == 0) break;
//work
sem_post(&waiterResponse);
}
The trick of the last customer waking up the waiter has a harmless race, where multiple customers may each of them believe they are the last, and so the waiter gets multiple posts each indicating there are no more customers. Those extra posts are harmless, since the waiter is exiting anyway. However, avoiding that race can be achieved with another semaphore initialized to 1 used to let the first customer that detected no more customers be the one to wake up the waiter.
int num_customers(bool is_waiter = false){
int v;
sem_getvalue(&customers, &v);
if (is_waiter) return v;
if (v == 0) {
if (sem_trywait(&last_customer) == -1) {
assert(errno == EAGAIN);
return 1;
}
}
return v;
}
|
69,713,981 | 69,714,007 | Is there any advantage of using a range for loop rather than an iterator? | for (auto& i : just_a_vec )
Or an iterator for loop.
for (std::vector<std::string>::iterator it = just_a_vec.begin(); it < just_a_vec.end(); it++)
| Iterators predate range-based for loops, so they used to be the only of these two alternatives available. Nowadays, range-based for has mostly replaced iterators when dealing with a simple loop.
However, iterators can be used in various other contexts as well. For example, you can do std::sort(v.begin(), std::next(v.begin(), 5)) to sort the first five elements of a vector while leaving the rest of it alone.
Going back to iterating over a whole container:
If you can accomplish what you want with a range-based for, then it leads to more legible code, so they are preferable by default.
If you need iterators for some reason, such as using an algorithm that requires them, or because you need to jump ahead or back while iterating, then use those instead.
Also: In the later case, you can/should still use auto when declaring the iterator:
for(auto it = just_a_vec.begin(); it < just_a_vec.end(); it++) {
}
Edit: as asked: here's a simple, if a bit contrived, example where an iterator-based loop can still be useful:
// adds all values in the vector, but skips over twos values when encountering a 0
// e.g.: {1,2,0,4,5,2} => 5
int my_weird_accum(const std::vector<int>& data) {
int result = 0;
for(auto it = data.begin(); it != data.end(); ++it) {
auto v = *it;
result += v;
if(v == 0) {
// skip over the next two
assert(std::distance(it, data.end()) > 2);
std::advance(it, 2);
}
}
return 0;
}
|
69,714,664 | 69,719,236 | Magic Square confusion | #include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std ;
int main()
{
const int maxsize=21 ;
int magq[maxsize][maxsize] ;
int size ;
cout << "Magic Square" << endl ;
cout << "Size (odd): " ;
cin >> size ;
if( size<=0 || size>maxsize)
{
cout << "Size to big" << endl ;
exit(1) ;
}
if( 1!=size%2)
{
cout << "Not an odd nr. " << endl ;
exit(1) ;
}
for( int x=0; x<size; x++)
for( int y=0; y<size; y++)
magq[x][y] = 0 ;
// In the lecture it is said to put the nr. 1 in the first row middle column
int x=(size-1)/2 ;
int y=0 ;
magq[x][y]=1 ; //As we can clearly see here magq[x][y] for i.e size=5 is magq[2][0]
// which is not first row middle column
for( int z=2; z<=size*size; z++)
{
int xneu=(x+1)%size ; // oder: x<size-1 ? x+1 : 0
int yneu=y>0 ? y-1 : size-1 ;
if (0!=magq[xneu][yneu])
{
xneu=x ;
yneu=y+1 ;
if (yneu==size)
{
cout << "Boundary met under?!" << endl ;
yneu=0 ;
}
}
x=xneu ;
y=yneu ;
if( 0!=magq[x][y])
{
cout << "............some meaningless text!" << endl ;
cout << "Nr.: " << z << " Field: " << x << ", " << y << endl ;
exit(1) ;
}
// cout << "Feld " << x << " " << y << " Zahl " << z << endl ;
magq[x][y]=z ;
}
for( int y=0; y<size; y++)
{
for( int x=0; x<size; x++)
cout << setw(5) << magq[x][y] ;
cout << endl ;
}
int diag1=0, diag2=0 ;
for( int i=0; i<size; i++)
{
diag1 += magq[i][i] ;
diag2 += magq[i][size-1-i] ;
}
cout << "Sum: (diag1, diag2, erwartet) "
<< diag1 << " " << diag2 << " " << (size*(size*size+1))/2 << endl ;
return 0 ;
}
Can someone explain to me how is he moving in the matrix, in this exercise?
If we follow his initial notation then for n=5 (for example)
for z=2, xneu=3 and yneu=4, that is totally the reverse of the position 4,3 in which the number 2 should be stored. (Assuming that the index for rows and Column starts from 0 and ends at 4).
Can anyone explain to me, how are we moving in this program?
| This program is about creating a magic square according to the "de la Loubère" method. There is a very good explanation on Wikipedia here. Or, because I saw some German text here.
The mechanism is totally simple. Always Go up and right (take boundaries into account). If t´his place is already filled, then go one down.
The links show a step by step example.
Your confusion about the "Middle" comes from the fact that you assume array index 2 to be not the middle. But it is. Array indicess in C++ start wirth 0. So, if you have an odd number and make a integer division by 2, you will always get an even number, because the 0.5 part is truncated.
3/2=1, 5/2=2, 7/2=3 and so on. And with the example of 5, we will receive a 2 which is the middle of indeces 0,1,2,3,4.
This should answer your question.
Additionally, I will show you a different solution
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <array>
// The maximumn dimension of the magic square
constexpr size_t MaxDimension{ 21u };
// Some abbreviations for less typing work. Square will be implemented as a 2 dimensional std::array
using Square = std::array< std::array <int, MaxDimension>, MaxDimension>;
// Create a magic square following the method of "De-la-Loubère"
void createMagicSquare(Square& square, int sizeOfSquare) {
// Reset all values in the square to 0
square = {};
// Starting row and column. Set to upper middle cell
int row{}; int column{ sizeOfSquare / 2};
// This will wrap a position if it leaves the boundary of the square
auto wrap = [&sizeOfSquare](const int position) { return (position + sizeOfSquare) % sizeOfSquare; };
// Now build the magic square and fill it with all numbers
for (int runningNumber{ 1 }; runningNumber <= (sizeOfSquare * sizeOfSquare); ++runningNumber) {
// Write number into cell at current position
square[row][column] = runningNumber;
// If the upper right cell is occupied
if (square[wrap(row-1)][wrap(column+1)] != 0) {
// Then just go one rowe down
row = wrap(row + 1);
}
else {
// Next position will be upper right
row = wrap(row - 1);
column = wrap(column + 1);
}
}
}
// Output of the magic square
void display(Square& square, int sizeOfSquare)
{
constexpr int Width = 4;
std::cout << "\nThe Magic square is: \n\n";
for (int row = 0; row < sizeOfSquare; ++row) {
for (int column = 0; column < sizeOfSquare; ++column)
std::cout << std::setw(Width) << square[row][column];
std::cout << "\n\n";
}
}
int main()
{
// Give instruction what to do
std::cout << "Enter The Size of the Magic Square (odd number (<=21): ";
// Read user inpuit and make sure that it is a correct value
if (int sizeOfSquare{}; (std::cin >> sizeOfSquare) and (sizeOfSquare <= MaxDimension) and (sizeOfSquare%2)) {
// Define the empty square
Square square{};
// Fill it with magic numbers
createMagicSquare(square, sizeOfSquare);
// Show result
display(square, sizeOfSquare);
}
else std::cerr << "\nError: Wrong Input\n";
}
|
69,714,747 | 69,719,351 | Identity of unnamed enums with no enumerators | Consider a program with the following two translation units:
// TU 1
#include <typeinfo>
struct S {
enum { } x;
};
const std::type_info& ti1 = typeid(decltype(S::x));
// TU 2
#include <iostream>
#include <typeinfo>
struct S {
enum { } x;
};
extern std::type_info& ti1;
const std::type_info& ti2 = typeid(decltype(S::x));
int main() {
std::cout << (ti1 == ti2) << '\n';
}
I compiled it with GCC and Clang and in both cases the result was 1, and I'm not sure why. (GCC also warns that "ISO C++ forbids empty unnamed enum", which I don't think is true.)
[dcl.enum]/11 states that if an unnamed enumeration does not have a typedef name for linkage purposes but has at least one enumerator, then it has its first enumerator as its name for linkage purposes. These enums have no enumerators, so they have no name for linkage purposes. The same paragraph also has the following note which seems to be a natural consequence of not giving the enums names for linkage purposes:
[Note 3: Each unnamed enumeration with no enumerators is a distinct type. — end note]
Perhaps both compilers have a bug. Or, more likely, I just misunderstood the note. The note is non-normative anyway, so let's look at some normative wording.
[basic.link]/8
Two declarations of entities declare the same entity if, considering declarations of unnamed types to introduce their names for linkage purposes, if any ([dcl.typedef], [dcl.enum]), they correspond ([basic.scope.scope]), have the same target scope that is not a function or template parameter scope, and
[irrelevant]
[irrelevant]
they both declare names with external linkage.
[basic.scope.scope]/4
Two declarations correspond if they (re)introduce the same name, both declare constructors, or both declare destructors, unless [irrelevant]
It seems that, when an unnamed enum is not given a typedef name for linkage purposes, and has no enumerators, it can't be the same type as itself in a different translation unit.
So is it really just a compiler bug? One last thing I was thinking is that if the two enum types really are distinct, then the multiple definitions of S violate the one-definition rule and make the program ill-formed NDR. But I couldn't find anything in the ODR that actually says that.
| This program is well-formed and prints 1, as seen. Because S is defined identically in both translation units with external linkage, it is as if there is one definition of S ([basic.def.odr]/14) and thus only one enumeration type is defined. (In practice it is mangled based on the name S or S::x.)
This is just the same phenomenon as static local variables and lambdas being shared among the definitions of an inline function:
// foo.hh
inline int* f() {static int x; return &x;}
inline auto g(int *p) {return [p] {return p;};}
inline std::vector<decltype(g(nullptr))> v;
// bar.cc
#include"foo.hh"
void init() {v.push_back(g(f()));}
// main.cc
#include"foo.hh"
void init();
int main() {
init();
return v.front()()!=f(); // 0
}
|
69,715,426 | 69,715,501 | Can we access private members of another object within a method of a class? | #include <string>
#include <iostream>
#include <vector>
using namespace std;
class Test {
public:
int testing() {
Test t;
return t.x;
}
private:
int x = 0;
};
int main() {
Test a;
cout << a.testing() << endl;
}
I did not know I can access the private data member x of the t (the instance of Test that is not this) within the class definition of the Test. Why am I allowed to use t.x in the example code?
| Colloquially, C++'s private is "class-private" and not "object-private".
Scopes are associated with lexical elements of source code, not with run-time entities per se. Moreover, the compiled code has little to no knowledge of the logical entities in the source it was compiled from. For this reason the accessibility is enforced on the level of lexical scopes only. Within the scope of the class, any object of the class's type can have its private members accessed.
Plus, C++ wouldn't be able to work as a whole otherwise. A copy constructor or an assignment operator could not be written if the accessibility was checked on a per-object basis. Those operations need to access the members of the source object in order to initialize/overwrite the target object.
|
69,715,892 | 69,716,691 | How to replace the value of a LPTSTR? | LPTSTR in;
// ...
std::wstring wstr(in);
boost::replace_all(wstr, "in", ",");
wcscpy(in, wstr.data());
There is any other way to replace the value of a LPTSTR?
In the code, LPTSTR is a wchar_t*
| If, and only if, the replacement string is smaller/equal in length to the search string, then you can modify the contents of the input string directly.
However, if the replacement string is larger in length than the search string, then you will have to allocate a new string of larger size and copy the characters you want into it as needed.
Try something like this:
LPTSTR in = ...;
...
const int in_len = _tcslen(in);
LPTSTR in_end = in + in_len;
LPCTSTR search = ...; // _T("in")
const int search_len = _tcslen(search);
LPCTSTR replace = ...; // _T(",")
const int replace_len = _tcslen(replace);
LPTSTR p_in = _tcsstr(in, search);
if (replace_len < search_len)
{
if (p_in != NULL)
{
const int diff = search_len - replace_len;
do
{
memcpy(p_in, replace, replace_len * sizeof(TCHAR));
p_in += replace_len;
LPTSTR remaining = p_in + diff;
memmove(found, remaining, (in_end - remaining) * sizeof(TCHAR));
in_end -= diff;
}
while ((p_in = _tcsstr(p_in, search)) != NULL);
*in_end = _T('\0');
}
}
else if (replace_len == search_len)
{
while (p_in != NULL)
{
memcpy(p_in, replace, replace_len * sizeof(TCHAR));
p_in = _tcsstr(p_in + replace_len, search);
}
}
else
{
int numFound = 0;
while (p_in != NULL)
{
++numFound;
p_in = _tcsstr(p_in + search_len, search);
}
if (numFound > 0)
{
const out_len = in_len - (numFound * search_len) + (numFound * replace_len);
LPTSTR out = new TCHAR[out_len + 1];
// or whatever the caller used to allocate 'in', since
// the caller will need to free the new string later...
LPTSTR p_out = out, found;
p_in = in;
while ((found = _tcsstr(p_in, search)) != NULL)
{
if (found != p_in)
{
int tmp_len = found - p_in;
memcpy(p_out, p_in, tmp_len * sizeof(TCHAR));
p_out += tmp_len;
}
memcpy(p_out, replace, replace_len * sizeof(TCHAR));
p_out += replace_len;
p_in = found + search_len;
}
if (p_in < in_end)
{
int tmp_len = in_end - p_in;
memcpy(p_out, p_in, tmp_len * sizeof(TCHAR));
p_out += tmp_len;
}
*p_out = _T('\0');
delete[] in;
// or whatever the caller uses to free 'in'...
in = out;
}
}
See why working with raw C-style string pointers is so much harder than using C++-style string classes?
|
69,716,141 | 69,716,569 | Removing non-prime numbers from a vector | I have a simple function that "primes a list" i.e. it returns the passed vector but without all non-primes. Essentially it removes non-primes from the vector and returns the updated vector. But my function just returns the vector without the numbers 0 and 1. Assume the vector is sorted in ascending order(0, 1, 2, 3, ... ) The basic structure of my function follows:
#include<vector>
#include<algorithms>
#include "cmath.h"
.
.
.
std::vector<int> prime_list(std::vector<int> foo){
int limit_counter = 1;
const int p_limit = sqrt(foo.at(foo.size() - 1));
for(int w = 0; w < foo.size(); w++){
if(foo.at(w) <= 1)
foo.erase(foo.begin() + w);
}
for(int i : foo){
do{
if(i % limit_counter == 0)
foo.erase(std::remove(foo.begin(), foo.end(), i), foo.end());
limit_counter++;
}
while(limit_counter < p_limit);
}
return foo;
}
|
const int p_limit = sqrt(foo.at(foo.size() - 1));
This will initialize the limit once, based on the last element in the list. You have to do that for each element being test for prime.
More importantly, limit_counter should be initialized for each i
Ignoring the problem with iterators, you can fix it with this pseudo code.
std::vector<int> prime_list(std::vector<int> foo)
{
foo.erase(std::remove(foo.begin(), foo.end(), 0), foo.end());
foo.erase(std::remove(foo.begin(), foo.end(), 1), foo.end());
for (int i : foo)
{
int limit_counter = 1;
const int p_limit = static_cast<int>(sqrt(i));
do
{
if (i % limit_counter == 0)
{
//undefined behavior, this might destroy the iterator for `i`
foo.erase(std::remove(foo.begin(), foo.end(), i), foo.end());
}
limit_counter++;
} while (limit_counter < p_limit);
}
return foo;
}
For an easier and safer solution, just create a new list and add the primes to it. Or, create a duplicate list primes and go through the loop in foo
std::vector<int> prime_list(std::vector<int> &foo)
{
std::vector<int> primes = foo;
primes.erase(std::remove(primes.begin(), primes.end(), 0), primes.end());
primes.erase(std::remove(primes.begin(), primes.end(), 1), primes.end());
for (int n : foo)
for (int k = 2, limit = static_cast<int>(sqrt(n)); k <= limit; k++)
if (n % k == 0)
primes.erase(std::remove(primes.begin(), primes.end(), n), primes.end());
return primes;
}
|
69,716,199 | 69,716,249 | DPAPI output buffer memory management | I'm using CryptProtectData() and CryptUnprotectData() APIs for data encryption and decryption in my App.
Reading the API documentation, it's not clear why LocalFree() needs to be called against the output buffer after usage. The example code on that page does not invoke LocalFree(), is that a miss?
What's also missing in the documentation (the main reason for this question) is that, how is DATA_BLOB::pbData for the output managed by DPAPI? Can I manage the memory for the output buffer myself? If I can, how do I know the output buffer size of the encrypted data in advance so that I can allocate a large enough buffer for CryptProtectData() or CryptUnprotectData() to use?
Here is a code snippet on how I'm using CryptProtectData():
DATA_BLOB dataIn;
DATA_BLOB dataOut;
dataIn.pbData = (BYTE *)"Hello world";
dataIn.cbData = (DWORD)strlen((char*)pbDataInput);
if(CryptProtectData(&dataIn, NULL, NULL, NULL, NULL, 0, &dataOut))
{
printf("Encrypted data size: %d", dataOut.cbData);
// LocalFree(dataOut.pbData); // Is this needed? Why? How do I manage dataOut.pbData by myself?
}
|
Reading the API documentation, it's not clear why LocalFree() needs to be called against the output buffer after usage.
Because CryptProtectData() dynamically allocates an output buffer and gives it to you, so you need to free it when you are done using it.
The example code on that page does not invoke LocalFree(), is that a miss?
Yes.
how is DATA_BLOB::pbData for the output managed by DPAPI? Can I manage the memory for the output buffer myself?
Not with CryptProtectData(), no. You must use the buffer that it gives you.
If you want to use your own buffer, use CryptProtectMemory() instead.
If I can, how do I know the output buffer size of the encrypted data in advance so that I can allocate a large enough buffer for CryptProtectData() or CryptUnprotectData() to use?
CryptProtectData() handles that for you when it allocates the dynamic output buffer.
CryptProtectMemory() encrypts inline, using the same buffer for both input and output. So you are responsible for ensuring that the buffer is large enough to hold the output. Its documentation says:
[in] cbDataIn
Number of bytes of memory pointed to by the pData parameter to encrypt. The number of bytes must be a multiple of the CRYPTPROTECTMEMORY_BLOCK_SIZE constant defined in Wincrypt.h.
So, you would simply take the size of your input data and round it up to the next multiple of the block size.
|
69,716,519 | 69,721,844 | C++ multiindex column csv load | Multi-index column csv is
Its size is (8, 8415).
This csv file was made from pandas multi-index dataframe (python).
Its columns are [codes X financial items].
codes are
financial items are
How can I use this csv file to use its year(2014, 2015, ....) as index and codesXfinancial items as multi columns?
| What kind of output you want is unclear. There are not many libraries to imitate pandas in C++. A very messy, convoluted and inelegant way of doing it is declaring a structure and then put it into a list. Something like,
struct dataframe{
double data;
int year;
int code;
char item[]; //or you can use "string item;"
}
Make a list of this structure either by a custom class or C++ native "list" class.
If you can provide a more detailed explanation of what kind of data structure you want in the program or what do you want to do with it, I would try to provide a better solution.
|
69,716,528 | 69,728,838 | Dissapearing SDL Rects. How to update window with new additional shapes | I'm trying to update the window with a new additional rect upon key pressing, but it keeps disappearing due to SDL_RenderClear. Is it recommended to remove SDL_RenderClear?
while (!quit) {
while (SDL_PollEvent( & e) != 0) {
if (e.type == SDL_QUIT)
quit = true;
}
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(gRenderer); //if i remove this line, the new rectangle will remain there
SDL_Rect fillRect = {
0,
0,
SCREEN_WIDTH / 5 - 5,
SCREEN_HEIGHT / 5 - 5
};
SDL_SetRenderDrawColor(gRenderer, 255, 205, 51, 0xFF);
SDL_RenderFillRect(gRenderer, & fillRect);
switch (e.type) {
case SDL_KEYDOWN:
if (e.key.keysym.sym == SDLK_RIGHT) {
SDL_Rect fillRect = {
0,
200,
SCREEN_WIDTH / 5 - 5,
SCREEN_HEIGHT / 5 - 5
};
SDL_SetRenderDrawColor(gRenderer, 255, 205, 51, 0xFF);
SDL_RenderFillRect(gRenderer, & fillRect);
}
break;
}
SDL_RenderPresent(gRenderer);
}
| SDL_RenderClear() is perfectly fine and in fact you should be using it. Your problem (aka the rect disappearing) is caused by the way you handle input. SDL_KEYDOWN is an event that only occurs on the frame that you press a key for, and while you're holding it down after a short delay. What you are doing is drawing the rect if the key has been pressed on that exact frame, not if it's been pressed on any previous frames. A solution via a bool could look like this:
bool keyPressed = false;
while( !quit ) {
while( SDL_PollEvent( &e ) != 0 ) {
if( e.type == SDL_QUIT )
quit = true;
}
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gRenderer ); //if i remove this line, the new rectangle will remain there
SDL_Rect fillRect = { 0, 0, SCREEN_WIDTH / 5-5, SCREEN_HEIGHT / 5-5 };
SDL_SetRenderDrawColor( gRenderer, 255, 205, 51, 0xFF );
SDL_RenderFillRect( gRenderer, &fillRect );
if(keyPressed){
SDL_Rect fillRect = { 0, 200, SCREEN_WIDTH / 5-5, SCREEN_HEIGHT / 5-5 };
SDL_SetRenderDrawColor( gRenderer, 255, 205, 51, 0xFF );
SDL_RenderFillRect( gRenderer, &fillRect );
}
switch(e.type){
case SDL_KEYDOWN:
if(e.key.keysym.sym==SDLK_RIGHT){
keyPressed = true;
}
break;
}
SDL_RenderPresent( gRenderer );
}
Screen clearing is something that should absolutely be done in graphics, because otherwise the shapes you've drawn on previous frames will just remain there.
|
69,716,718 | 69,716,819 | how to emplace in map of(string and vector)..? | I'm not sure if it is possible to have a vector inside of a map container.
If yes, can I have the map with vector and vector?
INPUT
ONE 1 11 111 1111
TWO 22 2 2222
THREE 333 3333 3
map<string, vector<int>> mp;
How to emplace the input in the above container?
map<vector<int>, vector<int>> mp;
If this is possible to implement, how will you emplace elements here, and how can you access those elements?
| Your first case is fairly easy to implement, eg:
#include <fstream>
#include <sstream>
#include <map>
#include <vector>
#include <string>
using namespace std;
void loadFile(const string &fileName, map<string, vector<int>> &mp)
{
ifstream file(fileName.c_str());
string line;
while (getline(file, line))
{
istringstream iss(line);
string key;
if (iss >> key)
{
vector<int> &vec = mp[key];
int value;
while (iss >> value) {
vec.push_back(value);
}
}
}
}
int main()
{
map<string, vector<int>> mp;
loadFile("input.txt", mp);
// use mp as needed...
return 0;
}
|
69,717,385 | 69,725,330 | Creating DLL and using it from Excel | I have the following issue when trying to create a DLL in CPP and using it in Excel. When the argument reaches the CPP function, the value it holds changes (regardless of what it was in Excel). I am guessing somewhere it "drops", but I haven't been able to figure it out.
Here is the code:
Source.cpp
extern "C" double __stdcall my_double(double A)
{
return 2.0 * A;
}
Source.def
LIBRARY
EXPORTS
my_double
VBA Code
Declare PtrSafe Function my_double Lib "C:\MyDir\Example.dll" (ByVal A As Double) As Double
Then when I call my_double from excel, it always returns 0.0.
I attached a debug point to the function, and I can see that the value is indeed 0 when it reaches the cpp function. Any tips on how to debug this issue would be greatly appreciated!
Things I have tried so far without success:
Made sure the bits on excel and the build in CPP match (both x64).
Tried with Release mode and Debug mode.
Tried changing the VBA code with ByVal, ByRef and using neither.
Tried a simpler example using int instead of double.
I checked DUMPBIN in the DLL file I created, and it looks OK.
I was following this tutorial: https://personalpages.manchester.ac.uk/staff/Andrew.Hazel/EXCEL_C++.pdf (page 54)
| Excel will struggle to use a function declared directly from a dll entry point as it doesn't know the types of the parameters (and other things, eg how to manage the memory of the return value). The OP's method from the tutorial may have worked in the past, but not any more it seems.
Creating a VBA user-defined function (UDF) wrapper gets around this, as Excel knows how to handle and marshal parameters in this case:
Private Declare PtrSafe Function my_double Lib "C:\Users\david\source\repos\CppTests\x64\Release\DllForExcel.dll" (ByVal A As Double) As Double
Public Function MyDouble(d As Double) As Double
MyDouble = my_double(d)
End Function
Use the MyDouble() function in the spreadsheet.
The other solution is to go down the route of creating a compiled Xll (often using the Excel SDK), which has entry points to register functions and their parameters, as well as managing memory allocations.
|
69,717,728 | 69,717,786 | In C++, how do you mutate objects in containers (vector, list, unordered_map)? | Context:
New to C++ here. I have a larger project where I have a classes A, B, and C.
Class A has a field with type unordered_map<int, B>.
Class B also has fields of class C which have fields of type set.
I want to mutate the B objects in the map because I don't want the overhead associated with immutability. I have tried doing this with map.find() and map.at(), but with both methods, the mapped objects are not mutated as evidenced by the behavior of subsequent calls. I didn't try indexing with [] because class B does not have a default constructor.
According to the VSCode C++ documentation (but oddly not the online docs), the pair returned by find has a copy of the value object, which is wrong for obvious reasons.
I tried using at(), which supposedly returns a reference to the value object. This results in the same issue with find(), unfortunately.
I then tried making my map with values of *B, but later, these objects would go out of scope and I assume deallocated resulting in a segmentation fault.
So I even tried changing my map to be of type <int, int> where the value is an index into a vector, which is where I found the problem to be general to containers as opposed to just maps.
I know I can do something like map.at(i) = map.at(i).funcWithSideEffects(); but I'm not ready to accept that this is the only way to do this. For a procedural language with a concept of state (i.e. not-a-fundamentally-functional language), it seems bizarre that there would be no way to mutate a value in a map or container-type field.
Long story short and minimum example:
How can I mutate objects in a container field such as a vector?
Example:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Person
{
private:
string first;
string last;
vector<Person> children;
public:
Person(string first, string last) {
this->first = first;
this->last = last;
}
string getFirstName() {
return this->first;
}
void setFirstName(string first) {
this->first = first;
}
string getLastName() {
return this->last;
}
vector<Person> getChildren() {
return this->children;
}
void addChild(Person child) {
return children.push_back(child);
}
};
int main() {
Person p("John", "Doe");
Person child("Johnny", "Appleseed");
p.addChild(child);
Person grandchild("one", "two");
p.getChildren().at(0).addChild(grandchild);
p.getChildren().at(0).setFirstName("Mark");
cout << "Name: " << p.getFirstName() << " " << p.getLastName() << "\n";
cout << "No. Children: " << p.getChildren().size() << "\n";
cout << "Child Name: " << p.getChildren().at(0).getFirstName() << "\n";
cout << "No. Grandchildren: " << p.getChildren().at(0).getChildren().size() << "\n";
return 0;
}
Desired Output:
Name: John Doe
No. Children: 1
Child Name: Mark
No. Grandchildren: 1
Actual Output:
Name: John Doe
No. Children: 1
Child Name: Johnny
No. Grandchildren: 0
Edit:
Unfortunately, the example I created is decoupled from my original problem. Yes, the behavior that I want is that of references, which is why I was scratching my head when I used map.at(), which says it returns a reference. As described above, this is not the behavior I am observing. Leaving this solved, since I did a subpar job asking my question, and will construct a better example in a different post.
Edit 2:
Thank you to everyone who responded! I put two and two together and figured out what I was doing wrong in my map problem.
I was accessing values in my map with
B b = map.at(i);
instead of
B& b = map.at(i);
I guess the original version makes a copy instead of retaining the reference that map returns. Will make a solution post if anyone else is confused about the same thing in the future.
| You returning a copy of your child with calling
vector<Person> getChildren() {
return this->children;
}
With this, your changes are done at the returned copy only. Not in the original stored inctance.
Use a reference to it and you get the
vector<Person>& getChildren() {
return this->children;
}
with this you do the changes in the stored instance.
I you want to avoid useless data copy work, you could change
void addChild(Person& child) {
return children.push_back(child);
}
That avoids creation and deletion of instances to/from the callstack.
|
69,717,841 | 69,720,238 | lldb - passing hex value as an input while debugging | I am learning lldb from security perspective. I am trying to perform a bufferoverflow in the below sample code.
#include<stdio.h>
void return_input(void) {
char array[30];
gets(array);
printf("%s\n", array);
}
int main(){
return_input();
return 0
}
gets function is the target here.
While inside lldb console, I need to key in the long string that will override the return address. if I try a string like,
(lldb) AAAAAAA\x01\x02
They are being treated as individual characters and not hex values.
How do I pass in hex values as input while inside LLDB session? Basically, I am trying to overwrite the memory.
There are other answers where we pass the string as an argument, but i want to key in the data myself while inside the session.
Updating the lldb session.
In the below picture you can see that the hex are actually, converted into strings
Thanks.
| You are trying to enter arbitrary bytes via gets() into your variable array and beyond. This is not straight-forward and partially impossible, as the standard input stream and gets() commonly does not take all codes and filter some codes.
For example, if you want the byte 0x0D (or 0x0A, depending on your terminal) in your input, you could try to type Enter. But this key will get filtered by gets() as it thinks you have finished your input.
You can type many codes, by combinations of Ctrl and A to Z or umlauts or accented characters. But it is difficult to get exactly the sequence of codes you want.
You can try this: Prepare a sequence of characters that resemble your hex bytes in a text editor. Copy them into the console when gets() expects your input.
To see which character produces what code, consider to write a little experimental program that calls gets() and prints the received codes:
#include <stdio.h>
int main(void) {
char line[30];
gets(line);
for (int i = 0; i < sizeof line; ++i) {
printf("%d: %X\n", i, line[i]);
}
return 0;
}
Note: Please adopt a code style and stick to it. Your source is not indented at all.
|
69,718,964 | 69,719,128 | What is the meaning of this command line | g++ -fsanitize=address -std=c++17 -Wall -Wextra -Wshadow -DONPC -O2 -o %< % && ./%< < inp
Especially last part with bizzare symbol sequence
Line was taken from some .vimrc file i wanted to copy
| Lets break it down:
g++ = Your compiler
-fsanitize=address = Compiler flags which adds address sanitizing. Increasing memory usage but also useful for debugging memory issues.
-std=c++17 = Your C++ standard
-Wall -Wextra -Wshadow = Your compiler error flags
-DONPC = A compilation define for ONPC
-O2 = A mild optimization flag
-o = The name of your compiled output-file
%< = In vim this stands for the main part of your filename
% = In vim this stands for your full filename, which you are compiling
&& = Indicating a second command
./%< = Run the output-file you just created
< inp = With this as input
I hope this clears things up. For further information, I'd recommend reading up on the vim and g++ documentation. Maybe even on bash && You can find all this information in there.
|
69,719,155 | 69,719,280 | User defined type used in dynamic allocated 2d array | Let's assume that we have a simple struct
struct S {
int a;
int b;
int c;
}
Now we want to create an array of pointers (2d array 5x5):
S** arr = new S*[5];
for (int i = 0; i < 5; ++i)
arr[i] = new S[5];
My questions are:
Is it a correct way to dynamically allocate a memory for this array using new? Shouldn't we use sizeof(S) somewhere?
How would the code look like if using malloc instead of new? Is the code below correct?
S** arr = (S**)malloc(5 * sizeof(S));
for (int i = 0; i < 5; ++i)
arr[i] = (S*)malloc(5 * sizeof(S));
|
Yes, this is correct way. No, there is no need to use sizeof(S)
Your code isn't correct. Generally you shouldn't use malloc if struct S have non-trivially-copiable members, but if S satisfy that, your code should look like this:
S** arr = (S**)malloc(5 * sizeof(S*));
for (int i = 0; i < 5; ++i)
arr[i] = (S*)malloc(5 * sizeof(S));
But using malloc in C++ is considered as bad practice. And I would try to rewrite it using std::vector if you can.
And of course don't forget to clear memory with delete/free in case of using new/malloc
|
69,719,273 | 69,721,555 | Address Sanitizer with Visual C++: ignore read buffer overflows while still catching write buffer overflows | Consider the following example:
int main()
{
char* p = new char[10];
srand(p[11]); // heap buffer overflow - read
p[11] = rand(); // heap buffer overflow - write
}
I want ASan not to flag heap buffer overflow - read for now, while still flagging heap buffer overflow - write.
The reason I want this is to concentrate on more dangerous errors for now. Read overflow either crash immediately or don't have consequences, whereas write overflow may cause corruption that would trigger elsewhere later. For some small overflows, even immediate crash is excluded. So sure I'd look into read overflows too, but later.
Is there a way to accomplish this?
| There are two directions to achieve this.
1. Continue after the error is triggered
To continue after an error, -fsanitize-recover=address option should be used. From FAQ:
Q: Can AddressSanitizer continue running after reporting first error?
A: Yes it can, AddressSanitizer has recently got continue-after-error mode. This is somewhat experimental so may not yet be as reliable as default setting (and not as timely supported). Also keep in mind that errors after the first one may actually be spurious. To enable continue-after-error, compile with -fsanitize-recover=address and then run your code with ASAN_OPTIONS=halt_on_error=0.
This option is not yet supported by MSVC compiler. There's an issue to add it.
If it would have worked, a custom handler could have been installed that would inspect whether it is read or write error, ignore read error, and report write error.
2. Don't instrument read errors
As @yugr pointed out, there's -mllvm -asan-instrument-reads=false option to achieve this. But this option is also not supported by MSVC compiler.
But there's still a way to avoid compiler instrumentation in some places. It is __declspec(no_sanitize_address). So the goal could be achieved by isolating known read errors, like this:
__declspec(no_sanitize_address)
void isolate_read_heap_buffer_overflow(char* p)
{
srand(p[11]); // heap buffer overflow - read
}
int main()
{
char* p = new char[10];
isolate_read_heap_buffer_overflow(p);
p[11] = rand(); // heap buffer overflow - write
return 0;
}
Other better alternative
There's also clang-cl compiler, it is actually Clang that supports Visual C++ semantics. Visual Studio installer installs it. So if a project can be retargeted to use Clang, this would open all Address Sanitizer features usable in Clang. Unfortunately, retargeting some legacy code base may be a long task.
|
69,719,363 | 69,722,850 | HTTPSConnectionPool error when trying to install gtest with conan | I'm trying to use conan to install gtest but when I do so I have the following error:
gtest/1.11.0: Not found in local cache, looking in remotes...
gtest/1.11.0: Trying with 'conancenter'...
ERROR: HTTPSConnectionPool(host='center.conan.io', port=443): Max retries exceeded with url: /v1/ping (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)'),))
Unable to connect to conancenter=https://center.conan.io
1. Make sure the remote is reachable or,
2. Disable it by using conan remote disable,
Then try again.
However I'm not sure why it doesn't works
The package do exists ( https://conan.io/center/gtest )
And I'm also using conan to install others packages and I have no issue with them
My full conanfile looks like that:
[requires]
libcurl/7.78.0
cjson/1.7.15
gtest/1.11.0
[options]
openssl:shared=True
[generators]
cmake
Would anyone please know why I have this error?
I'm on Windows 11 with conan 1.37.0
| This error is related to deprecated certificate.
It was discussed here: https://github.com/conan-io/conan/issues/9695
To summarize, you have 2 options:
Update your Conan client to >= 1.41.0 (Best solution):
pip install -U conan
Install a new certificate (Workaround):
conan config install https://github.com/conan-io/conanclientcert.git
|
69,719,529 | 69,726,862 | C/C++ Validating Host and Peer with CURL for CloudFlare based websites | I`m working on an API behind CloudFlare and I would like to validate the connection fully for extended security. The platform I am using right now is Windows 10.
First I downloaded some CA's found on CloudFlare's website (Cloudflare_CA.pem, origin_ca_rsa_root.pem, origin_ca_ecc_root.pem) and then tried to contact the API after settings the required options in CURL:
struct curl_blob blob;
std::string cf_pem = ...;
blob.data = cf_pem.data();
blob.len = cf_pem.size();
blob.flags = CURL_BLOB_COPY;
curl_easy_setopt(pcurl, CURLOPT_CAINFO_BLOB, &blob);
/* Set the default value: strict certificate check please */
curl_easy_setopt(pcurl, CURLOPT_SSL_VERIFYPEER, 1L);
/* Set the default value: strict name check please */
curl_easy_setopt(pcurl, CURLOPT_SSL_VERIFYHOST, 2L);
All failed with PEER validation error. Then I have tested with openssl the following:
openssl s_client -connect website:443
The result was:
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Server public key is 256 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 20 (unable to get local issuer certificate)
Afterwards I found a very nice command which basically "extracts" the CA from the given website:
openssl s_client -showcerts -servername website -connect website:443 > cacert.pem
At the end I still received:
Verify return code: 20 (unable to get local issuer certificate)
However the cacert.pem was created with some content inside it. I grabbed the first certificate between then -----BEGIN CERTIFICATE-----/-----END CERTIFICATE----- and put it inside the code.
Validation succeeded and CURL did not complain anymore. However, I am unable to contact other hosts under CloudFlare which means this CA is not "ok".
So my question is, what to do? How I find the correct CA for CloudFlare?
Please advise, I`m sure other developers might face the same issue.
| As @David mentioned, it is correct that CloudFlare uses DigiCert Root CA (in general). However, as they state on their website this can change; which means if you hard code such check your software might break in future at any point.
Without further due the options are as following:
Option A
Buy an "Advanced" certificate from CloudFlare instead of the Universal one, and select your desired Root CA. This ensures (up to a point) that it will be the same and you can validate any domain using that CA (in my case I tested with DigiCert Root CA).
Option B
Use mTLS feature (mTLS is a great way to protect your API). This is preferred as a long-term solution however the downside is that you need to supply/embed the certificate private key as well in your software. You can however revoke at any point the certificate if it was compromised.
For my choice I want to also validate the CA however using the DigiCert Root CA does not work for mTLS, and it's pretty clear because on your dashboard you will see:
Review Client Certificate for CN=Cloudflare, C=US
Validity Period: 15 Years
Authority: Cloudflare Managed CA for ....
I could not find/download the root certificate for "Cloudflare Managed CA". I`m not happy with this so to ensure everything works OK I have used the "Baltimore CyberTrust Root" from here: https://baltimore-cybertrust-root.chain-demos.digicert.com/info/index.html
Now you can have mTLS with CURL with CA validation as well:
// https://baltimore-cybertrust-root.chain-demos.digicert.com/info/index.html
std::string ca_pem = ...
// mtls.cert
std::string cert = ...
// mtls.key
std::string key = ...
struct curl_blob blob;
blob.data = cert.data();
blob.len = cert.size();
blob.flags = CURL_BLOB_COPY;
curl_easy_setopt(pcurl, CURLOPT_SSLCERT_BLOB, &blob);
curl_easy_setopt(pcurl, CURLOPT_SSLCERTTYPE, "PEM");
blob.data = key.data();
blob.len = key.size();
curl_easy_setopt(pcurl, CURLOPT_SSLKEY_BLOB, &blob);
curl_easy_setopt(pcurl, CURLOPT_SSLKEYTYPE, "PEM");
blob.data = ca_pem.data();
blob.len = ca_pem.size();
curl_easy_setopt(pcurl, CURLOPT_CAINFO_BLOB, &blob);
IMPORTANT NOTES REGARDING mTLS:
Make sure you input effort to encrypt your cert/key if you embed it
inside your software.
I do not recommend you to supply your cert/key as individual files
next to your software.
Even if you encrypt your cert/key inside your software there is
always a way to get it, either via unpacking/de-onfuscabtion/de-virtualization; either
during runtime... etc. My advise is for you to immediately re-encrypt
the data or delete it from memory ASAP.
In case someone gets your cert/key, first generate a new cert/key
then update your software and afterwards revoke the existing one.
Then you should look into how someone got your cert/key and try to
mitigate the issue.
Please feel free to comment if you disagree with anything and/or/if you have some suggestions/improvements.
|
69,720,388 | 69,721,500 | Launching a bat file using CreateProcess windows API | I have written a bat file that works fine when launched from command prompt. Now I have written a small C++ program using `CreateProcess' to launch the bat file from a C++ program. The C++ program take 2 command line parameters. One is the path of the bat file to be executed and the otherone is a path to a file where the output of bat file will be written. I am launching the process as below
DWORD processflags =
CREATE_DEFAULT_ERROR_MODE
//| CREATE_NEW_CONSOLE
| CREATE_NO_WINDOW
;
//security attribute
SECURITY_ATTRIBUTES securityAttr;
securityAttr.bInheritHandle = TRUE;
securityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
securityAttr.lpSecurityDescriptor = NULL;
HANDLE fileHandleforChildProcessTowrite,fileHandleforChildProcessToRead, fileHandleforChildProcessToErr
fileHandleforChildProcessTowrite = CreateFile(logfilepath, FILE_SHARE_WRITE, 0, &securityAttr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
//STARTUP INFO
STARTUPINFO sinfo;
ZeroMemory(&sinfo, sizeof(STARTUPINFO));
sinfo.cb = sizeof(STARTUPINFO);
sinfo.dwFlags = STARTF_USESTDHANDLES;
sinfo.hStdOutput = fileHandleforChildProcessTowrite;
sinfo.hStdInput = fileHandleforChildProcessToRead;
sinfo.hStdError = fileHandleforChildProcessToErr;
if (!CreateProcess(NULL, // No module name (use command line)
command, // bat file to be run
&securityAttr,
NULL,
TRUE, // Set handle inheritance to TRUE/FALSE
processflags, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&sinfo, // Pointer to STARTUPINFO structure
&pifo) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return PROCESS_CREATION_FAILED;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
//Rest of the code follows to clean up logic to close process and file handles
The problem I face here is that when I createProcess with bInheritHandles parameter set to FALSE batch file executes fine but no bat file out output will be written to the file handle which is expected but when I set bInheritHandles parameter to TRUE bat file execution fails and I get the below warning message in the log
The process cannot access the file because it is being used by another process.
Can someone help me with this? why does bat file execution fails with bInheritHandles set to TRUE but works fine if that flag is false? I cannot share complete bat file for obvious reasons please excuse me for that.
| Using FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE for dwShareMode parameter of CreateFile API for file handles solves the problem
CreateFile(filehandlepate, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &secureAttr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
|
69,720,494 | 69,720,518 | Why using != to compare iterator in loop condition | In many examples regarding iterating over vectors, I noticed that often the not-equals operator is used to check whether the loop has reached the vector's end. Normally, I am using the lower-than operator in the loop condition. Hence, I am wondering, what is the rationale behind choosing !=?
Example:
std::vector<int> vec = {1, 2, 3, 4, 5};
for (auto iter = vec.begin(); iter != vec.end(); iter++) {
std::cout << *iter << " ";
}
| Because not all iterators support ordering but all can be compared for equality in O(1).
For example associative (ordered) containers use bidirectional iterators, which are defined as (cppreference):
template<class I>
concept bidirectional_iterator =
std::forward_iterator<I> &&
std::derived_from</*ITER_CONCEPT*/<I>, std::bidirectional_iterator_tag> &&
requires(I i) {
{ --i } -> std::same_as<I&>;
{ i-- } -> std::same_as<I>;
};
std::forward_iterator can only be dereferenced, copied, ==, and incremented.
On the other hand, random access iterator used by std::vector requires std::totally_ordered<I>. So in your case you could write iter < vec.end();, but the code will become less generic. As long as you do not increment the iterator in the loop's body, you are safe anyway.
|
69,720,667 | 69,721,174 | variadic template method to create object | I have a variadic template method inside a template class (of type T_) looking like this
template < typename T_ >
class MyContainer {
public:
...
template <typename ...A>
ulong add (A &&...args)
{
T_ t{args...};
// other stuff ...
vec.push_back(t);
// returning an ulong
}
}
So basically I'm trying to make this class adapt to whatever type T_ but since I can't know in advance which types its constructor requires, I use a variadic. I took inspiration from the emplace_back method from the stl library.
Nevertheless, I get a warning of narrowing conversion with integer types if I try to do something like this
MyContainer<SomeClassRequiringAnUlong> mc;
mc.add(2);
warning: narrowing conversion of ‘args#0’ from ‘int’ to ‘long unsigned int’ [-Wnarrowing]
So I was wondering if I can do anything about it. Is there any way to tell the method which parameters' type it is supposed to take according to the template parameter T_ (which is known when the object is created) ?
|
Is there any way to tell the method which parameters' type it is
supposed to take according to the template parameter T_ (which is
known when the object is created)?
In your case, you should use direct initialization(()) instead of list initialization({}) (to avoid unnecessary narrowing checks).
Consider the case where T is a vector<int>:
MyContainer<std::vector<int>> mc;
mc.add(3, 0);
What do you expect mc.add(3, 0) to do? In your add() function, T_ t{args...} will invoke vector<int>{3,0} and create a vector of size 2, which is obviously wrong. You should use T_ t(args...) to call the overload of vector(size_type count, const T& value) to construct a vector of size 3, just like emplace_back() does.
It is worth noting that due to P0960R3, T_ t(std::forward<Args>(args)...) can also perform aggregate initialization if T_ is aggregate.
|
69,720,877 | 69,721,484 | Read data from file and store into RAM in C++ | I'm writing a code where I have to generate a key.bin file containing 10000 keys(1 key = 16 bytes random no.), read the Key file, and store it in the RAM. Can anyone tell me how I got about it? I'm relatively new to this, so any guidance would be great.
Thanks.
| As @heap-underrun has pointed out, it is unclear if you're talking about general RAM used in PCs or some special type of memory in some other device. I will just assume that you're talking about regular RAM in PC.
When you run a program, all the variables in the program are stored in the RAM until the program terminates. So, all you need to do is to read the file in your program and store the data in a variable. Then the data will be stored in RAM till your program terminates.
https://www.cplusplus.com/doc/tutorial/files/ should be a good reference to file I/O in C++.
I will give a simple example here. Assuming your file looks like this
00001
00002
00003
...
A simple C++ code to read the file is,
#include<fstream>
using namespace std;
int main(){
int n = 10000; //number of keys in file
long double keys[n]; //because you said 16 bit number
//and long double is 16 bit
ifstream FILE;
FILE.open("key.bin"); //include full path if the file is in
//a different directory
for(int i = 0; i < n; i++){
FILE >> keys[i];
}
FILE.close();
}
Now, all the keys are in keys array. You can access the data and do whatever you want. If you are still unclear about something, put it in the comments.
|
69,721,029 | 69,724,094 | How to improve the efficiency of QVector lookup? | For some reason, I need to traverse an image many times and I need to know which pixel points I have processed.
So I use a QVector to store the location of the pixel points I have processed each time so I can use it to determine the next time I iterate.
Examples are as follows。
QVector<int> passed;
for(int n = 0; n < 10; n++) { // Multiple traversals
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
if(......) { // Meeting certain conditions
if(!passed.contains(y*width+x)) {
// do something
passed.append(y*width+x);
}
}
}
}
}
I spent a lot of time processing the passed.contains() step!
Do you know how I can optimize the search speed?
Or is there a better way to make it easier for me to determine certain pixels that have been processed?
| Use this:
QVector<bool> passed(height * width, false);
for(int n = 0; n < 10; n++) { // Multiple traversals
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
if(......) { // Meeting certain conditions
int pos = y*width+x;
if(!passed.at(pos)) {
// do something
passed[pos] = true;
}
}
}
}
}
Or maybe you can get even faster by reordering the inner conditions. It could be significantly faster if evaluation if(......) is not trivial. But you must be sure that this change does not affect your algorithm.
QVector<bool> passed(height * width, false);
for(int n = 0; n < 10; n++) { // Multiple traversals
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
int pos = y*width+x;
if(!passed.at(pos)) {
if(......) { // Meeting certain conditions
// do something
passed[pos] = true;
}
}
}
}
}
|
69,721,754 | 69,722,395 | no matching function for call to ‘std::set<unsigned int>::insert(std::size_t&) | I am working on migrating my package from ros melodic to ros noetic. while doing it I got compilation error in PCL library during cmake. The package is too big I am giving some code where error happened. Any guidance would be helpfull.
This is myfile.cpp
std::vector<bool> ignore_labels;
ignore_labels.resize(2);
ignore_labels[0] = true;
ignore_labels[1] = false;
//TODO commented that out i think we have to fix the error
ecc->setExcludeLabels(ignore_labels);
'''
and this is the PCL-1.10 library file it called at line ecc->setExcludeLabels(ignore_labels); here error occured,
'''
brief Set labels in the label cloud to exclude.
param[in] exclude_labels a vector of bools corresponding to whether or not a given label should be considered
void
setExcludeLabels (const std::vector<bool>& exclude_labels)
{
exclude_labels_ = boost::make_shared<std::set<std::uint32_t> > ();
for (std::size_t i = 0; i < exclude_labels.size (); ++i)
if (exclude_labels[i])
exclude_labels_->insert (i);
}
'''
the error is
/usr/include/pcl-1.10/pcl/segmentation/euclidean_cluster_comparator.h:256:13: error: no matching function for call to ‘std::set::insert(std::size_t&) const’
256 | exclude_labels_->insert (i);
| ^~~~~~~~~~~~~~~
In file included from /usr/include/c++/9/set:61,
| I have looked into the source code for this library, here is the issue:
The type is a typedef:
The issue is that the object itself is a shared_ptr<const std::set<std::uint32_t>>
the code you have posted is allocating the object, but also calling std::set::insert on an instance of const std::set, which does not exist because by std::set::insert modifies the state of the std::set
notice the const at the end of the compiler error: ‘std::set::insert(std::size_t&) const
it means you are trying to call a version of insert that is const, which does not exist (and cannot exist)
Here you can learn more about const-qualified methods
|
69,721,849 | 69,722,569 | return key doesn't work when i use regex in QT C++ | Hey guys I'm trying to use regex on line edit in QT but when I use my regex one function that do something when I enter the return key on keyboard doesn't work any more!
This is my regex on line edit:
QRegularExpression r("[0-9\\.\\+\\-\\=\\/\\*\n]{100}");
ui->lineEdit->setValidator(new QRegularExpressionValidator (r,this));
And this is my function test:
void MainWindow::on_lineEdit_returnPressed()
{
on_pushButton_14_clicked();
}
I also try my regex without "\n" but doesn't change any thing. When I comment the regex my function works correctly.
So any solution?
| Your regex needs to support a pattern of length one, thus, {100} quantifier should be replaced with {1,100} or even {0,100}.
Besides, you may also add \r (carriage return) char to the character set, and remove unnecessary escapes:
QRegularExpression r("^[0-9.+=/*\n\r-]{1,100}$");
I added ^ and $ anchors to make sure the regex only matches the whole string (here, line).
|
69,722,222 | 69,722,442 | How to scan an integer array | I am new to C++. I am trying to define a binary converter function and return a pointer. Then U want to display generated binary in the main function:
#include <iostream>
using namespace std;
int* binary_con(int n)
{
int i;
int binary[100];
for (i = 0; n > 0; i++)
{
binary[i] = n % 2;
n = n / 2;
}
return binary;
}
int main()
{
int n;
int* a;
cout << "Input the number:";
cin >> n;
a = binary_con(n);
while (*a)
{
cout << *a;
a++;
}
return 0;
}
But after I run my code, I got this:
Can anyone explain this to me?
| you can't return an array from a function, the way is to pass that array as an argument to the functionm using this approach:
void binary_con(int n, int *binary)
now you have access to binary array inside your function, hence you can edit it and see the changes outside of the function without returning anything.
inside your main, instead of writing a = binary_con(n);, you should write this:
binary_con(n, a);
|
69,723,008 | 69,823,599 | Error facing with range function in DPC++ | I'm new to Sycl/DPC++ language. I wrote a sample vector addition code using Unified shared memory (USM):
#include<CL/sycl.hpp>
#include<iostream>
#include<chrono>
using namespace sycl;
int main()
{
int n=100;
int i;
queue q{ };
range<1>(n);
int *a=malloc_shared<int>(n,q);
int *b=malloc_shared<int>(n,q);
int *c=malloc_shared<int>(n,q);
for(i=0;i<n;i++)
{
a[i]=i;
b[i]=n-i;
}
q.parallel_for(n,[=](auto &i){
c[i]=a[i]+b[i];
}).wait();
for(i=0;i<n;i++){
std::cout<<c[i]<<std::endl;
}
free(a,q);
free(b,q);
free(c,q);
return 0;
}
When I compile it I get the following error:
warning: parentheses were disambiguated as redundant parentheses around declaration of variable named 'n' [-Wvexing-parse]
range<1>(n);
^~~
vec_add.cpp:11:1: note: add enclosing parentheses to perform a function-style cast
range<1>(n);
^
( )
vec_add.cpp:11:9: note: remove parentheses to silence this warning
range<1>(n);
^ ~
vec_add.cpp:11:10: error: redefinition of 'n' with a different type: 'range<1>' vs 'int'
range<1>(n);
^
vec_add.cpp:8:5: note: previous definition is here
int n=100;
^
1 warning and 1 error generated.
How to fix this error?
|
error: redefinition of 'n' with a different type: 'range<1>' vs 'int'
Two variables with the same name within the same scope create confusion to the compiler, so it might be the reason for the error which you are getting. You can try defining the value of n globally say for eg: #define N 100 in this case, set
range<1>(n);
to
range<1> (N);
and use that in your code.
If you want to declare the size locally then assign another variable (r) to the range as
range<1> r (n);
Now you can directly pass the 'r' variable as a parameter to the parallel_for.
|
69,723,013 | 69,723,337 | Can different .dwo files be combined into a single one? | Background:
I have a need of the debugging information of the code in our project.
The following two approaches are available:
Compile using -g and afterwards use GNU binary utilities strip and objcopy to strip the debugging information into a separate file.
Compile using -gsplit-dwarf
Question
The second approach creates a .dwo for each translation unit in the application.
Although this would improve the linker time. But with the huge number of translation files, this would create management headache for us.
Is there a way to combine all the .dwo files into a single file per binary ?
System Info
Compiler : GCC toolchain.
OS: CentOS/RH 7/8
| The tool you're looking for is called dwp. It collects your .dwo files into a .dwp file ("DWARF package"). .dwp files can themselves be combined into larger .dwp files if needed.
It should come with non-ancient binutils packages.
|
69,723,284 | 69,738,008 | How to resolve "C2660 'SWidget::Construct': function does not take 1 arguments"? | How can I resolve
C2660 'SWidget::Construct': function does not take 1 arguments
I am trying to put a widget that displays the controls of the game.
I am new to Unreal Engine.
Error
C2660 'SWidget::Construct': function does not take 1 arguments
C:\Program Files\Epic Games\UE_4.26\Engine\Source\Runtime\SlateCore\Public\Widgets\DeclarativeSyntaxSupport.h 862
SPanelWidget.h
#pragma once
#include "SlateBasics.h"
#include "SlateExtras.h"
class SPanelWidget : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS(SPanelWidget) {}
SLATE_ARGUMENT(TWeakObjectPtr<class AControlPanel>, OwningPanel)
SLATE_END_ARGS()
void construct(const FArguments& InArgs);
TWeakObjectPtr<class AControlPanel> OwningPanel;
virtual bool SupportsKeyboardFocus() const override {return true;};
};
SPanelWidget.cpp
#include "SPanelWidget.h"
#define LOCTEXT_NAMESPACE "Panel"
void SPanelWidget::construct(const FArguments& InArgs) {
const FText TitleText = LOCTEXT("ProjectTitle","Chair Table Practice Problem");
const FMargin ContentPadding = FMargin(500.f,300.f);
ChildSlot [
SNew(SOverlay)
+ SOverlay::Slot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill) [
SNew(SImage)
.ColorAndOpacity(FColor::Black)
]
+ SOverlay::Slot()
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
.Padding(ContentPadding) [
SNew(SVerticalBox)
+SVerticalBox::Slot() [
SNew(STextBlock)
.Text(TitleText)
]
]
];
}
#undef LOCTEXT_NAMESPACE
| Need to declare Construct function with an upper case 'C'.
Credit: splodginald
|
69,723,421 | 69,723,463 | Is std::vector allowed inside std::variant union? | I'm using std::variant as a safe-type union. On https://en.cppreference.com/w/cpp/utility/variant I've read that
A variant is not permitted to hold references, arrays, or the type void.
Does it mean that std::vector isn't allowed to be hold inside std::variant? - it is kind of array, yet I can hold std::string inside my variant, what probably I could not do using simple c++ union.
I couldn't find direct answer for that (dummy) question.
|
Does it mean that std::vector isn't allowed to be hold inside std::variant?
It does not mean that. std::vector is none of references, arrays, or the type void. It is a (template for a) class type. std::variant is allowed to hold std::vector.
it is kind of array
The abstract data structure that std::vector models is a kind of an "array". But nevertheless, it isn't an array type.
yet I can hold std::string inside my variant
std::string also models an abstract data structure that is kind of an "array". In fact, the data structure is nearly identical to vector in many regards. But indeed, neither template is an array and both of them can be held in a variant.
|
69,723,539 | 69,723,689 | Undefined symbols for architecture arm64 using g++ compiler | I'm trying to get some code to work but i keep getting the same error regardless of compiler. I'm trying to overload the operators but i get errors.
I have 3 files: main.cpp, vector2d.cpp and vector2d.h
This is the error i get with the g++ compiler:
Undefined symbols for architecture arm64:
"v2d::length()", referenced from:
_main in main-c7db92.o
"v2d::v2d(v2d const&)", referenced from:
_main in main-c7db92.o
"v2d::v2d(double, double)", referenced from:
_main in main-c7db92.o
"v2d::~v2d()", referenced from:
_main in main-c7db92.o
"v2d::operator=(v2d const&)", referenced from:
_main in main-c7db92.o
"v2d::operator*(double)", referenced from:
_main in main-c7db92.o
"v2d::operator+(v2d const&)", referenced from:
_main in main-c7db92.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Here is my main.cpp
#include <iostream>
#include "vector2d.h"
using namespace std;
int main() {
// We crate some vectors with fixed values
v2d v1(3,0); //(3,0)
v2d v2(0,4);
v2d v3(3,2);
// We create v4 as vector which is like v2
v2d v4(v2);
cout << "Pythagoras holds on perpendicular triangles (a,b,c):" << endl;
cout << "a = " << v1.length();
cout << " , b = " << v2.length();
// We create a new vector v5 by combining other vectors
// This vector corresponds to the diagonal of the triangle defined by v1 and v2
v2d v5 = v1 + v2 * (-1);
cout << " , c = " << v5.length() << endl;
cout << "...but not on non-perpendicular triangles (a,b,c):" << endl;
cout << "a = " << v3.length();
cout << " , b = " << v4.length();
v5 = v3 + v4 * (-1);
cout << " , c = " << v5.length() << endl;
return 0;
}
Here is my vector2d.cpp
#include "vector2d.h"
#include <cmath>
v2d::v2d(double a, double b) {
// Write your code here
}
v2d::v2d(const v2d & v) {
// Write your code here
}
v2d::~v2d() {
// Write your code here
}
v2d & v2d::operator=(const v2d &v) {
// Write your code here
return *this;
}
v2d & v2d::operator+(const v2d &v) {
// Write your code here
return *this;
}
double v2d::operator*(const v2d &v) {
// Write your code here
return 0;
}
v2d & v2d::operator*(double k) {
// Write your code here
return *this;
}
double v2d::length() {
// Write your code here
return 0;
}
Here is my vector2d.h
#ifndef __v2d__
#define __v2d__
class v2d {
public:
// Standard constructor: builds a vector (a,b)
v2d(double a, double b);
// Copy constructor: builds a vector that is exactly as v
v2d(const v2d & v);
// Destructor
~v2d(void);
// Assignment operator: updates the vector to make it as v
v2d & operator=(const v2d &v);
// Vector addition: updates the vector by adding v
v2d & operator+(const v2d &v);
// Scalar multiplication: updates the vector by scaling by k
v2d & operator*(double k);
// Scalar product of the current vector by another vector v
double operator*(const v2d &v);
// Returns the length of a vector
double length(void);
private:
// Internal representation of a vector with just two doubles x and y
double x;
double y;
};
#endif
I am really stuck...
| My guess is that you have missed to add vector2d.cpp to your project. After adding that (with whatever build system you use) the errors should go away.
The errors indicate that the compiler tries to link the program without the symbols from that file present.
I cannot help with exactly how to add it since it is not specified in the question how the project is built, but if you would like to just compile from terminal it could be as simple as
g++ main.cpp vector2d.cpp -o program_name
## ^---- this was probably missing
|
69,724,102 | 69,735,093 | Is there a difference between Apple Clang and OpenMP-enabled Clang from Homebrew? | I want to know if there are any advantages in Apple's provided Clang compiler compared to the Clang compiler that comes with OpenMP available from Homebrew?
Will there be any performance loss if switching to OpenMP Clang (regardless of the multi-threading ability)?
I also found this old question that has no good answer
Update
I compiled the OOFEM using Apple's Clang and mainstream Clang and ran the same problem,
Apple's Clang: Real time consumed: 000h:01m:26s
Mainstream Clang: Real time consumed: 000h:01m:24s
With multi-threading enabled also the performance is similar.
One difference that I also noticed, is that Apple's Clang seems to ignore some CMake options e.g. -DOpenMP_CXX_FLAGS="-I/usr/local/opt/libomp/include" has no effect with Apple's Clang while works fine with the mainstream Clang.
|
Is there a difference?
As stated that answers itself. They're two different compilers and we don't know what Apple have done inside theirs. We do know that they don't provide OpenMP support, so that is at least one difference.
Will there be any performance loss if switching to OpenMP Clang
(regardless of the multi-threading ability)?
I doubt it, but since you're clearly measuring performance and playing with both compilers, you seem in a good position to tell us :-)
|
69,724,298 | 69,724,588 | Removing code in Release mode using macros C++ | I have some code that is used for debugging and don't want then to be in the releases.
Can I use macros to comment them out?
For example:
#include <iostream>
#define p(OwO) std::cout << OwO
#define DEBUG 1 // <---- set this to -1 in release mode
#if DEBUG == 1
#define DBUGstart
#define DBUGend
// ^ is empty when in release mode
#else
#define DBUGstart /*
#define DBUGend */
/*
IDE(and every other text editor, including Stack overflow) comments the above piece of code,
problem with testing this is my project takes a long
time to build
*/
#endif
int main() {
DBUGstart;
p("<--------------DEBUG------------->\n");
// basically commenting this line in release mode, therefore, removing it
p("DEBUG 2\n");
p("DEBUG 3\n");
DBUGend;
p("Hewwo World\n");
return 0x45;
}
For single line debugs I could easily do something like:
#include <iostream>
#define DEBUG -1 // in release mode
#define p(OwO) std::cout << OwO
#if DEBUG == 1
#define DB(line) line
#else
#define DB(line)
#endif
int main()
{
DB(p("Debug\n"));
p("Hewwo World");
return 0x45;
}
But I guess this will be a bit messy with multiple lines
I'm working with MSVC (Visual Studio 2019), if this doesn't work then is there any other way of implementing the same (for multi lines, it's pretty simple for the single lines)?
| You are making this unnecessarily complicated.
Instead of conditionally inserting C-style comments if in Release, just only insert the code if in Debug. Visual Studio defines _DEBUG by default in Debug configurations, so you can use this like the following:
#include <iostream>
int main() {
std::cout << "hello there.\n";
#ifdef _DEBUG
std::cout << "this is a debug build.\n";
#endif
}
|
69,724,441 | 69,726,345 | std::lock_guard and std::adopt_lock behaviour without locking the mutex | I have been learning about the usage of std::lock and std::lock_guard and most examples follow the pattern below:
std::lock(m1, m2);
std::lock_guard<std::mutex> guard1(m1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(m2, std::adopt_lock);
//Do something here
Then I came across an example that utilized the same pattern you would use if you were using std::unique_lock, but with lock_guard:
std::lock_guard<std::mutex> guard1(m1, std::adopt_lock);
std::lock_guard<std::mutex> guard2(m2, std::adopt_lock);
std::lock(m1, m2);
//Do something here
My question is, would this cause undefined behaviour if you use the second pattern and an exception occurs before you reach std::lock?
P.S. I am aware that C++17 introduced std::scoped_lock and that std::lock_guard is still around mainly for compatibility with older code.
| Your second example is undefined behavior; adopt_lock constructor presumes that the mutex is already held. This UB is triggered at construction, not at destruction or when an exception is thrown.
If you used unique_lock instead of scoped_lock, it has a:
unique_lock( mutex_type& m, std::defer_lock_t t ) noexcept;
constructor, which permits your std::lock use with a slight change:
std::unique_lock<std::mutex> guard1(m1, std::defer_lock);
std::unique_lock<std::mutex> guard2(m2, std::defer_lock);
std::lock(guard1, guard2);
Now, unique_lock does track if it has the lock, so there is possible memory and performance overhead; if unique_locks are local to the scope, compilers can and will optimize out that if it can prove it safe.
And if the compiler can't prove it safe, quite often it isn't safe.
|
69,724,800 | 69,724,989 | Time complexity with Big O notation for a called function | I read many resources about calculating time complexity O(n). I applied what I understand on my code.
Bellow is my code and my attempt to find time complexity.
my code:
float Euclidean_distance(int array_point_A[20], int array_point_B[20]) {
float sum = 0.0;
float w[20] = { 0.0847282, 0.0408621, 0.105036, 0.0619821, 0.0595455, 0.0416739, 0.0181147, 0.00592921,
0.040049, 0.0766054, 0.0441091, 0.0376111, 0.0124285, 0.0733558, 0.0587338, 0.0303001, 0.0579207, 0.0449221,
0.0530462, 0.0530462 };
for (int i = 0; i < 20; ++i) {
float a = array_point_A[i] - array_point_B[i];
float wieghted_distance = w[i] * (a * a);
sum += wieghted_distance;
}
return sqrt(sum);
}
int KNN_classifier(int X_train[4344][20], int Y_train[4344], int k, int data_point[20]) {
// Calculate the distance between data_point and all points.
float array_dist[4344]{};
int index_arr[4344]{}
for (int i = 0; i *< 4344; ++i) {
array_dist[i] = Euclidean_distance(X_train[i], data_point);
index_arr[i] = i;
}
Now: for function Euclidean_distanceit has 2 operations outside the loop and 3 operations inside the loop that will iterate 20 times. Thus, 2+3n then we have O(n).
Now: for function KNN_classifier. it has a loop that will iterate 4344 times. Inside the loop , there is 2 operations. so we have 2n and then O(n). // I am not sure about this solution.
This operation array_dist[i] = Euclidean_distance(X_train[i], data_point); confused me.
So, do I need to include the Euclidean_distance time complexity in my calculation. If so, I guess the time complexity will be O(n^2). But the two loops has different bounds.
Please I need help !!!
| Big-O notation only has meaning relative to one or more parameters, but you haven't described which values in your code are variable and which are constants.
As it is written, the function KNN_classifier is actually O(1) because 4344 is a fixed constand and 20 is a constant. If 20 is a constant and the size of X_train and Y_train is meant to vary as some number n then it is O(n). If the 20 constant also varies as m then it is O(n*m).
|
69,724,884 | 69,727,729 | Access violation writing location while giving value to a struct | I am trying to give a value to a 2D struct in a loop but i keep getting Access violation writing location error
My code is :
typedef struct {
int prtcls[10],numb;
} intpos;
int main(int argc, char** argv)
{
particle_t* particles;
intpos** points = new intpos*[(int)SCALE];
for (int i = 0; i < (int)SCALE; i++) {
intpos* row = new intpos[(int)SCALE - 1];
points[i] = row;
}
cudaMallocHost(&particles, sizeof(particle_t)*NUM_PARTICLES);
// Random initial positions / directions.
for (int i = 0; i < NUM_PARTICLES; i++)
{
particles[i].x =( (float)rand() / (float)RAND_MAX) * SCALE ;
particles[i].y = ((float)rand() / (float)RAND_MAX) * SCALE;
particles[i].phi = ((float)rand() / (float)RAND_MAX) * 2 * 3.14;
particles[i].flrx = floor(particles[i].x) ;
particles[i].flry = floor(particles[i].y) ;
int fx = particles[i].flrx;
int fy = particles[i].flry;
points[fx][fy].numb += 1;
int curn = points[fx][fy].numb;
points[fx][fy].prtcls[curn] = i;
}
and full error is :
0xC0000005: Access violation writing location 0x000001DEA3C7836C.
| What line? If you're using the GNU tools, gdb and a stack trace will tell you what line is crashing.
I suspect it's one of these lines:
particles[i].x =( (float)rand() / (float)RAND_MAX) * SCALE ;
points[fx][fy].numb += 1;
points[fx][fy].prtcls[curn] = i;
Are you absolutely sure all those array index values are in range?
|
69,724,991 | 69,725,074 | How to correctly define a template class return type of a template function? | What I'm trying to do is fairly simple. I have a template class PayloadResult<T> with a generic payload and in another class a template function which returns an object of such class.
class Result
{
public:
template<class TPayload>
PayloadResult<TPayload> success(TPayload payload) { return PayloadResult<TPayload>(payload); }
}
template <TPayload>
class PayloadResult
{
private:
TPayload payload_;
public:
PayloadResult(TPayload payload)
{
payload_ = payload;
}
TPayload payload()
{
return payload;
}
}
What happens is that the compiler tells me that the success function's return type is No template named 'PayloadResult'
I changed the return type signature to std::array<TPayload, 1> and it worked. What am I doing wrong? (I am a newbie in C++)
Many thanks in advance!
| Below is the corrected example. You have to forward declare the class template PayloadResult<> for using it as the return type as you did in your example. Second you did not have the keyword typename or class infront of TPayload.
//forward declare the class template PayloadResult
template <typename TPayload> class PayloadResult;
class Result
{
public:
template<class TPayload>
PayloadResult<TPayload> success(TPayload payload) { return PayloadResult<TPayload>(payload); }//now this won't give error because you have forward declared
};
//added typename
template <typename TPayload>
class PayloadResult
{
private:
TPayload payload_;
public:
PayloadResult(TPayload payload)
{
payload_ = payload;
}
TPayload payload()
{
return payload;
}
};
int main()
{
return 0;
}
|
69,725,529 | 69,725,885 | Does memory_order_relaxed respect data dependencies within the same thread? | Given:
std::atomic<uint64_t> x;
uint64_t f()
{
x.store(20, std::memory_order::memory_order_relaxed);
x.store(10, std::memory_order::memory_order_relaxed);
return x.load(std::memory_order::memory_order_relaxed);
}
Is it ever possible for f to return a value other than 10, assuming there is only one thread writing to x? This would obviously not be true for a non-atomic variable, but I don't know if relaxed is so relaxed that it will ignore data dependencies in the same thread?
| The result of the load is always 10 (assuming there is only one thread). Even a relaxed atomic variable is "stronger" than a non-atomic variable:
as with a non-atomic variable, all threads must agree on a single order in which all modifications to that variable occur,
as with a non-atomic variable, that single order is consistent with the "sequenced before" relationship, and
the implementation will guarantee that potentially concurrent accesses will somehow sort themselves out into some order that all threads will agree on (and thus satisfy requirement 1). On the other hand, in the case of a non-atomic variable, potentially concurrent accesses result in undefined behaviour.
A relaxed atomic variable can't be used to synchronize different threads with each other, unless accompanied by explicit fences. That's the sense in which it's relaxed, compared with the other memory orderings that are applicable to atomic variables.
For language lawyering, see C++20 [intro.races]/10:
An evaluation A happens before an evaluation B (or, equivalently, B happens after A) if:
A is sequenced before B, or [...]
and [intro.races]/15:
If an operation A that modifies an atomic object M happens before an operation B that modifies M, then A shall be earlier than B in the modification order of M. [Note: This requirement is known as write-write
coherence. — end note]
and [intro.races]/18:
If a side effect X on an atomic object M happens before a value computation B of M , then the evaluation B shall take its value from X or from a side effect Y that follows X in the modification order of M. [Note: This requirement is known as write-read coherence. — end note]
Thus, in your program, the store of 20 happens before the store of 10 (since it is sequenced before it) and the store of 10 happens before the load. The write-write coherence requirement guarantees that the store of 10 occurs later in the modification order of x than the store of 20. When the load occurs, it is required to take its value from the store of 10, since the store of 10 happens before it and there is no other modification that can follow the store of 10 in the modification order of x.
|
69,725,728 | 69,726,636 | g++ 10.3.0: False positive or an actual problem? | Compiling the following code with g++ 10.3 gives some fearsome warnings (see https://godbolt.org/z/excrEzjsd, too):
#include <iostream>
#include <memory>
#include <vector>
#include <cstring>
#include <boost/algorithm/clamp.hpp>
namespace demo {
template <typename T, size_t N> constexpr std::size_t array_size(T (&)[N]) { return N; }
template <std::size_t N> inline void StrCpy(std::string::value_type (&dest)[N], const std::string::value_type *src) {
std::strncpy(dest, src, N);
dest[N - 1] = 0; // make sure the terminating NUL is there
}
template <std::size_t N> inline void StrCpy(std::string::value_type (&dest)[N], const std::string &src) { StrCpy(dest, src.c_str()); }
} // namespace demo
int main() {
struct a {
int m_num_lines;
char m_lines[6][201];
};
std::vector<std::string> lines{
"Line0",
"Line1",
"Line2",
"Line3",
"Line4",
"Line5",
"Line6",
"Line7",
"Line8",
"Line9",
"Line10",
};
auto theA = std::make_shared<a>();
theA->m_num_lines = boost::algorithm::clamp(lines.size(), 0, demo::array_size(theA->m_lines));
for (auto i = 0; i < theA->m_num_lines; i++) {
demo::StrCpy(theA->m_lines[i], lines[i]);
}
for (auto i = 0; i < theA->m_num_lines; i++) {
std::cout << theA->m_lines[i] << std::endl;
}
}
I don't understand what the compiler is actually trying to say. Do I have a bug or does the compiler see ghosts? BTW: clang++ and MSVC see nothing wrong here.
The output:
g++ -Wall -pedantic -O3 gcc.cpp -o gcc-bug
In file included from /usr/include/string.h:495,
from /usr/include/c++/10/cstring:42,
from gcc.cpp:4:
In function ‘char* strncpy(char*, const char*, size_t)’,
inlined from ‘void demo::StrCpy(std::__cxx11::basic_string<char>::value_type (&)[N], const value_type*) [with long unsigned int N = 201]’ at gcc.cpp:10:17,
inlined from ‘int main()’ at gcc.cpp:14:113:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:106:34: warning: ‘char* __builtin_strncpy(char*, const char*, long unsigned int)’ forming offset [1212, 1410] is out of the bounds [0, 1212] [-Warray-bounds]
106 | return __builtin___strncpy_chk (__dest, __src, __len, __bos (__dest));
| ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In function ‘void demo::StrCpy(std::__cxx11::basic_string<char>::value_type (&)[N], const value_type*) [with long unsigned int N = 201]’,
inlined from ‘int main()’ at gcc.cpp:14:113:
gcc.cpp:11:17: warning: writing 1 byte into a region of size 0 [-Wstringop-overflow=]
11 | dest[N - 1] = 0; // make sure the terminating NUL is there
| ~~~~~~~~~~~~^~~
gcc.cpp: In function ‘int main()’:
gcc.cpp:19:14: note: at offset 206 to object ‘main()::a::m_lines’ with size 1206 declared here
19 | char m_lines[6][201];
| ^~~~~~~
| Thanks to @StoryTeller-UnslanderMonica for identifying this as a compiler bug. Adding the option -fno-peel-loops solves the problem.
|
69,725,754 | 69,725,833 | Error: no matching function for call to ‘foo::foo()’ | I have the following two files
foobar.h
#ifndef FOOBAR_H
#define FOOBAR_H
#include <cstring>
class Foo {
public:
int x;
Foo(int x);
};
class Bar {
public:
char* name;
Foo foo;
Bar(Foo foo);
};
#endif // FOOBAR_H
and foobar.cpp
#include "foobar.h"
Foo::Foo(int x) {
// Do something
}
Bar::Bar(Foo foo) {
// Do something
}
Attempting to compile these with g++ -c foobar.cpp -o foobar.o results in the following error:
foobar.cpp: In constructor ‘Bar::Bar(Foo)’:
foobar.cpp:9:17: error: no matching function for call to ‘Foo::Foo()’
Bar::Bar(Foo foo) {
^
foobar.cpp:5:1: note: candidate: ‘Foo::Foo(int)’
Foo::Foo(int x) {
^~~
foobar.cpp:5:1: note: candidate expects 1 argument, 0 provided
In file included from foobar.cpp:1:
foobar.h:5:7: note: candidate: ‘constexpr Foo::Foo(const Foo&)’
class Foo {
^~~
foobar.h:5:7: note: candidate expects 1 argument, 0 provided
foobar.h:5:7: note: candidate: ‘constexpr Foo::Foo(Foo&&)’
foobar.h:5:7: note: candidate expects 1 argument, 0 provided
As far as I understand the output of g++ is that it requires me to have a default constructor for foo. Why? I wish to pass a foo object to the constructor of bar, why would it need to invoke a default constructor anywhere? I do not want to have a no-args constructor anyways, since I NEED that x has a specific user defined value.
| You are trying to default construct a Foo here:
Bar::Bar(Foo foo) {
// the member variable `foo` would have been default constructed here
// Do something
}
But Foo doesn't have a default constructor. One possible solution would be to initialize it in the member initializer list:
Bar::Bar(Foo foo) : foo(std::move(foo)) { // now uses the move constructor instead
// Do something
}
|
69,726,022 | 69,726,398 | Parse time format "DD/MM/YYYY at hh:mm:ss" & others using std::chrono::from_stream() | I'm currently trying to parse some info about the start time of an experiment as listed in a log file. After reading in the file important info, e.g column titles, start time, time between measurements, is parsed using <regex>.
I'm trying to use the std::chrono::from_stream(...) function to parse a string with the format "DD/MM/YYYY at hh:mm:ss" into a std::chrono::time_point, example of a string:
08/03/2021 at 09:37:25
At the moment I'm attempting this using the following function which attempts to construct a duration from a provided string to parse & a string to parse it with, then converting that to a time_point so I have control over the clock used:
#include <chrono>
#include <string>
#include <sstream>
#include <iostream>
using nano = std::chrono::duration<std::uint64_t, std::nano>;
template <typename Duration>
Duration TimeFormat(const std::string& str,
const std::string& fmt,
const Duration& default_val)
{
Duration dur;
std::stringstream ss{ str };
std::chrono::from_stream(ss, fmt.c_str(), dur);
/*
from_stream sets the failbit of the input stream if it fails to parse
any part of the input format string or if it receives any contradictory
information.
*/
if (ss.good())
{
std::cout << "Successful parse!" << std::endl;
std::cout << dur.count() << std::endl;
return dur;
}
else
{
std::cout << "Failed parse!" << std::endl;
std::cout << dur.count() << std::endl;
return default_val;
}
}
int main()
{
/*
The file is already read in, and regex matches the correct line from the log file and a
format pattern from a related config file.
*/
/*
Two different lines in the log file give:
- str1 = test start time.
- str2 = time between each measurement.
*/
std::string str1("08/03/2021 at 09:37:25"), str2("00:00:05");
std::string fmt1("%d/%m/%Y at %H:%M:%S"), fmt2("%H:%M:%S");
auto test1 = TimeFormat<nano>(str1, fmt1, nano::zero());
/*
--> "Failed parse!" & test1.count() = 14757395258967641292
A little research indicates that this is what VS initializes variables to
in debug mode. If run in release mode test1.count() = 0 in my tests.
*/
auto test2 = TimeFormat<nano>(str2, fmt2, nano::zero());
/*
--> "Failed parse!" & test2.count() = 5000000000 (5 billion nanoseconds)
Chose nanoseconds because it also has to handle windows file times which are measured
relative to 01/01/1601 in hundreds of nanoseconds. Might be worth pointing out.
What's weird is that it fails even though the value it reads is correct.
*/
/*
... Convert to a time_point after this,
e.g auto t1 = std::chrono::time_point<std::chrono::high_resolution_clock, nano>(test1);
*/
}
The MS documentation for from_stream can be found here. With details about different format characters just after the from_stream docs.
| ss.is_good() ?
Is that a type-o in your question or an extension in the Visual Studio std::lib?
I'm going to guess it is a type-o and that you meant ss.good()...
The good() member function checks if all state flags are off:
failbit
badbit
eofbit
eofbit in particular often does not mean "error". It simply means that the parsing reached the end of the stream. You are interpreting "end of stream" as a parsing error.
Instead check failbit or badbit. This is most easily done with the fail() member function.
if (!ss.fail())
...
Update
Any idea why it still won't pass the first string though?
I'm not 100% positive if it is a bug in the VS implementation, or a bug in the C++ spec, or a bug in neither. Either way, it wouldn't return what you're expecting.
For me (using the C++20 chrono preview library), the first parse is successful and returns
34645000000000
which if printed out in hh:mm:ss.fffffffff format is:
09:37:25.000000000
That is, only the time-part is contributing to the return value. This is clearly not what you intended. Your first test appears to intend to parse a time_point, not a duration.
Here is a slightly rewritten program that I think will do what you want, parsing a time_point in the first test, and a duration in the second:
#include <chrono>
#include <string>
#include <sstream>
#include <iostream>
using nano = std::chrono::duration<std::uint64_t, std::nano>;
template <typename TimeType>
TimeType TimeFormat(const std::string& str,
const std::string& fmt,
const TimeType& default_val)
{
TimeType dur;
std::stringstream ss{ str };
std::chrono::from_stream(ss, fmt.c_str(), dur);
/*
from_stream sets the failbit of the input stream if it fails to parse
any part of the input format string or if it receives any contradictory
information.
*/
if (!ss.fail())
{
std::cout << "Successful parse!" << std::endl;
std::cout << dur << std::endl;
return dur;
}
else
{
std::cout << "Failed parse!" << std::endl;
std::cout << dur << std::endl;
return default_val;
}
}
int main()
{
std::string str1("08/03/2021 at 09:37:25"), str2("00:00:05");
std::string fmt1("%d/%m/%Y at %H:%M:%S"), fmt2("%H:%M:%S");
auto test1 = TimeFormat(str1, fmt1, std::chrono::sys_time<nano>{});
auto test2 = TimeFormat(str2, fmt2, nano::zero());
}
For me this outputs:
Successful parse!
2021-03-08 09:37:25.000000000
Successful parse!
5000000000ns
If one wanted the output of the first test in terms of nanoseconds since epoch, then one could extract that from the dur time_point variable with dur.time_since_epoch(). This would then output:
1615196245000000000ns
|
69,726,776 | 69,737,342 | Conan: aggregate multiple packages to be used indepentendly | I am currently using Conan as an "helper tool" for my main project: I have created a conanfile.py that builds all my dependencies and imports them to the current folder. The goal in the end is to archive and redistribute this folder to our multiple machines and just tell CMake that everything is in there.
However, here's the catch: I want this archive to not be dependent on Conan. Our CMakeLists.txt are using Find_Package() and I really want this to work non intrusively. So far, I have managed to get something working, however, my main problem is CMake integration.
Here's how I want to create my archive:
mkdir build
conan install <path to my conanfile> -if build
tar cf archive.tar build
So far, I have managed to properly copy all my dependencies in the correct directories (build/bin contains all binaries, build/include all includes and so on)
My only problem now is using CMake. I tried using cmake_paths and cmake_find_package generators but they all point to the conan cache on my machine.
I then tried the deploy generator, which seems to be very close to what I want to achieve. However, I cannot figure out how to generate cmake files from the directory I just deployed to.
I found the generate() method but I havent had much success with it.
Do I need to implement this externally ? Like patching the files created by the cmake generators ? Or is there a cleaner way ?
Thanks
Edit: Just want to clarify: I do not want to use conan for anything else than simply building my dependencies. It is installed on our main server that hosts the gitlab CI/CD that will build the binaries. It is not used by anything else.
| This question has been answered by Conan's co-founder james here: https://github.com/conan-io/conan/issues/9874
Basically:
Use the CMakeDeps generator instead of cmake / cmake_find_package
Patch the resulting cmake config files at install time inside the generate() method from the main conanfile.py
Edit recipes accordingly (but should be fine most of the time)
|
69,726,974 | 69,728,158 | how to create binary tree class? | how to correctly create a binary tree? i have an error in function AddNode. tree is not filled. root=NULL
i have class Tree with field root of type Node. then i call AddNode to recursively create nodes.
and desctructor don't work for Nodes.
#include <iostream>
#include <string>
class Node {
public:
Node() {
std::cout << "Node Constructor\n";
left = NULL;
right = NULL;
parent = NULL;
};
virtual ~Node() {
std::cout << "Node Destructor\n";
Destroy();
};
void SetEngWord(std::string eng) { engWord = eng; }
void SetRusWord(std::string rus) { rusWord = rus; }
std::string GetEngWord() { return engWord; }
std::string GetRusWord() { return rusWord; }
Node* GetLeft() { return left; }
Node* GetRight() { return right; }
Node* GetParent() { return parent; }
void SetLeft(Node* l) { left = l; }
void SetRight(Node* r) { right = r; }
void SetParent(Node* p) { parent = p; }
void PrintWord() { std::cout << engWord << " - " << rusWord << std::endl; }
void Destroy();
private:
std::string engWord;
std::string rusWord;
Node* left;
Node* right;
Node* parent;
};
void Node::Destroy() {
if (left != NULL) { left->Destroy(); delete left; }
if (right != NULL) { right->Destroy(); delete right; }
delete this;
}
class Tree {
public:
Tree() {
std::cout << "Tree Constructor\n";
root = NULL;
};
virtual ~Tree() {
std::cout << "Tree Destructor\n";
root->Destroy();
};
void Add(std::string eng, std::string rus);
void AddNode(Node* src, Node* parent, Node* n, bool left);
Node* Search(std::string s);
private:
Node* root;
};
void Tree::Add(std::string eng, std::string rus) {
Node* n = new Node;
n->SetEngWord(eng);
n->SetRusWord(rus);
AddNode(root,NULL,n,true);
}
void Tree::AddNode(Node* src, Node* parent, Node* n, bool left) {
if (src == NULL) {
src = n;
if (src->GetParent() == NULL && parent != NULL) {
src->SetParent(parent);
if (left) src->GetParent()->SetLeft(n);
else src->GetParent()->SetRight(n);
}
return;
}
if (n->GetEngWord() < src->GetEngWord()) {
AddNode(src->GetLeft(), src, n, true);
}
else {
AddNode(src->GetRight(), src, n, false);
}
}
Node* Tree::Search(std::string s) {
Node* n;
n = root;
while(true) {
if (n == NULL) break;
if (n->GetEngWord() < s) n = n->GetLeft();
if (n->GetEngWord() > s) n = n->GetRight();
if (n->GetEngWord() == s) break;
}
return n;
}
int main()
{
Tree tree;
tree.Add("a","aa");
tree.Add("b","bb");
tree.Add("c","cc");
Node* n = tree.Search("b");
if (n != NULL) n->PrintWord(); else std::cout << "NULL" << std::endl;
return 0;
}
| void Tree::AddNode(Node*& src, Node* parent, Node* n, bool left) {
if (src == NULL) {
src = n;
if (src->GetParent() == NULL && parent != NULL) {
src->SetParent(parent);
if (left) src->GetParent()->SetLeft(n);
else src->GetParent()->SetRight(n);
}
return;
}
if (n->GetEngWord() < src->GetEngWord()) {
Node* nn = src->GetLeft();
AddNode(nn, src, n, true);
}
else {
Node* nn = src->GetRight();
AddNode(nn, src, n, false);
}
}
|
69,727,030 | 69,795,515 | Is using std::atomic_thread_fence right before an atomic load/store with the same order always redundant? | Given:
std::atomic<uint64_t> b;
void f()
{
std::atomic_thread_fence(std::memory_order::memory_order_acquire);
uint64_t a = b.load(std::memory_order::memory_order_acquire);
// code using a...
}
Can removing the call to std::atomic_thread_fence have any effect? If so is there a succinct example? Keeping in mind that other functions may store/load to b and call f.
| Never redundant. atomic_thread_fence actually has stricter ordering requirements than a load with mo_acquire. It's poorly documented, but the acquire fence isn't one-way permiable for loads; it preserves Read-Read and Read-Write order between accesses on opposite sides of the fence.
Load-acquires on the other hand only require ordering between that load and subsequent loads and stores. Read-Read and Read-Write order is enforced ONLY between that particular load-acquire. Prior loads/stores (in program order) have no restrictions. Thus the load-acquire is one-way permiable.
The release fence similarly loses one-way permiability for stores, preserving Write-Read and Write-Write. See Jeff Preshing's article https://preshing.com/20130922/acquire-and-release-fences/.
By the way, it looks like you have your fence on the wrong side. See Preshing's other article https://preshing.com/20131125/acquire-and-release-fences-dont-work-the-way-youd-expect/. With an acquire-load, the load happens before the acquire, so using fences it would look like this:
uint64_t a = b.load(std::memory_order::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order::memory_order_acquire);
Remember that release doesn't guarantee visibility. All release does is guarantee the order in which writes to different variables become visible in other threads. (Without this, other threads can observe orderings that seem to violate cause-and-effect.)
Here's an example using CppMem tool (http://svr-pes20-cppmem.cl.cam.ac.uk/cppmem/). The first thread is SC, so we know the writes occur in that order. So if c==1, then a and b should both be 1 as well. CppMem gives "48 executions; 1 consistent, race free", indicating that it is possible for the 2nd thread to see c==1 && b==0 && a==0. This is because c.load is allowed to be reordered after a.load, permeating past b.load
int main() {
atomic_int a = 0;
atomic_int b = 0;
atomic_int c = 0;
{{{ {
a.store(1, mo_seq_cst);
b.store(1, mo_seq_cst);
c.store(1, mo_seq_cst);
} ||| {
c.load(mo_relaxed).readsvalue(1);
b.load(mo_acquire).readsvalue(0);
a.load(mo_relaxed).readsvalue(0);
} }}}
}
If we replace the acquire-load with an aquire-fence, c.load is not allowed to be reordered after a.load. CppMem gives "8 executions; no consistent" confirming that it is not possible.
int main() {
atomic_int a = 0;
atomic_int c = 0;
{{{ {
a.store(1, mo_seq_cst);
c.store(1, mo_seq_cst);
} ||| {
c.load(mo_relaxed).readsvalue(1);
atomic_thread_fence(mo_acquire);
a.load(mo_relaxed).readsvalue(0);
} }}}
}
Edit: Improved first example to actually show the variable crossing an acquire operation.
|
69,727,518 | 69,727,639 | how can i solve the Floating point error core dump in this code? | Hi i'm getting trouble to run this code, it's a project for school, i need to make an RSA key,but the time i compiled it,it fail. I have this type of error:
[1] 14790 floating point exception (core dumped) ./a.out
i don't use C++ since 2019 so i forgot some stuff
sorry for the confusion of the code i wrote, i'm just digging in a mental ocean full of shit :)
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
/* -- COSTANTS -- */
const int DIM_ARRAY_KEY = 2;
/* -- -------- --*/
bool isPrime(int number) { // funzione che controlla se un numero è primo
for(int i = 2; i <= number / 2; i++) { // arrivo fino alla meta' del numero
if(number % i == 0) {
return false;
break;
}
return true;
}
//return 1;
}
int getPrimeNumber() { // funzione che ritorna un numero primo
int tmp_number;
do {
tmp_number = rand() % 999 + 1;
if (isPrime(tmp_number)) {
return tmp_number;
}
} while(!isPrime(tmp_number));
//return 1;
}
int getE(int n_){
int e;
do{
e = rand() % 1000;
}while(e > 1 && e < n_ && e/n_ == 0);{
return e;
}
}
void getPQ(int (&array_p_q)[DIM_ARRAY_KEY]){ // funzione che ritorna un array dove P è in prima posizione e Q è in seconda posizione
int p, q;
do {
p = rand() % 1000;
q = rand() % 1000;
} while(p == q || !isPrime(p) || !isPrime(q));
array_p_q[0] = p;
array_p_q[1] = q;
}
int getV(int p, int q) {
return (p-1) * (q-1);
}
int getN(int p, int q) {
return p * q;
}
void getVscomposta(int v) { // funzione che ritorna i numeri che compongono V in un array
vector<int> numbers;
int i = 1;
// numbers.push_back(val) - numbers.insert(val) per inserire infondo
while (v > 1) {
if (isPrime(i) && v%i == 0) {
v /= i;
numbers.push_back(i);
}
i++;
}
}
int getNpri(int (&v_scomposta)[3], int v, int p, int q) { // diverso da P, Q e i numeri che compongono V
getVscomposta(v); // array di numeri che compongono V
for(int i = 0; i < 3; i++){
if(v == v_scomposta[i]){
//cambia
break;
}
}
if(v == p && v == q){//cambia
}
return 0;
}
int getPrivateKey(int n_, int e_){
int k = rand() % 20;
int d = (k*(n_)+1)/e_;
cout<<"private key: "<<d;
return d;
}
int main(){
srand(time(NULL));
int Kpri[DIM_ARRAY_KEY], Kpub[DIM_ARRAY_KEY];
// trovo P e Q
int array_p_q[DIM_ARRAY_KEY];
getPQ(array_p_q);
int p = array_p_q[0];
int q = array_p_q[1];
int v = getV(p, q);
cout<<"p: "<<p<<"\n"<<"q: "<< q<<"\n"<<"V: "<< v;
int n = getN(p, q);
int e = getE(n);
getPrivateKey(n, e);
return 0;
}
| This method:
int getE(int n_){
int e;
do{
e = rand() % 1000;
}while(e > 1 && e < n_ && e/n_ == 0);{
return e;
}
}
Can return zero, and the return value is used in a divide statement.
Also, I don't know what's with the extra brace indentation near the end.
int getE(int n_){
int e;
do{
e = rand() % 1000;
}while(e > 1 && e < n_ && e/n_ == 0);
return e;
}
I think the difference between yours and mine suggests you intended some other code or something. An if-statement? Dunno.
|
69,727,766 | 69,729,343 | How can I resize a dynamic array of pointers without using a vector | If I wanted to resize this array:
int array[5];
I would do this:
int* temp = new int [n];
...
array = temp;
But, how would I do it if I have this array?
int *array[5];
Maybe like this?
int** temp = new int* [n];
| You CAN'T resize a fixed array, period. Its size is constant, determined at compile-time.
You CAN'T assign a new[]'ed pointer to a fixed array, either.
So, neither of your examples will work.
In your 1st example, you would need this instead:
int* array = new int [5];
And in your 2nd example, you would need this instead:
int** array = new int* [5];
Either way, don't forget to delete[] the array before assigning something new to it, eg:
int* array = new int [5];
...
int* temp = new int [n];
...
delete[] array;
array = temp;
|
69,727,800 | 69,727,850 | Do C++ compilers generate a def ctor if the class was not initialized? | I have written a utility class (acts as a helper class, I guess) that has only a few static member functions to be used in another class. It does not have any non-static members (variables or functions). So it also doesn't have any explicit ctors or dtor.
And the question is, does my compiler (GCC v11.2 and -std=c++20) still generate an implicit default ctor and a dtor for the utility class? If it does, then how should I prevent it from doing so? since I haven't initialized any instance of that class in my code.
| (I'm slightly side-stepping your question in lieu of providing unsolicited advice) If you have a collection of static functions and your class does not require any state
class Example
{
public:
static void Foo();
static int Bar();
};
then you should likely not be using a class in the first place, rather these should probably be free functions in a namespace
namespace Example
{
void Foo();
int Bar();
}
which still allows you to invoke them as Example::Foo() and Example::Bar() but now you don't have to worry about someone trying to instantiate your "class" since that's not what you intended to design it for.
|
69,728,362 | 69,779,054 | Why casting a quoted string to "string &" causes a crash? | Please note that's just a curious question, I don't need a problem solution!
I have a method that takes in a string reference (string &some_string) and only reads from referenced string. Writing some code I forgot that it needs a reference and passed a quoted string (not a variable, just like "something") and IDE suggested casting it to string reference, as it won't compile. I didn't give it a thought and applied the suggestion (now passing (string &) "something"). And my program crashed as it reached this piece of code. So, why exactly would it cause a crash, compiling without even a warning (g++, c++11)? I don't really understand it since I'm only reading from this string.
Example:
#include <string>
#include <iostream>
using namespace std;
class CharSet
{
private:
const string basis = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int N = 26;
string array; // string containing all element of the set
int length;
bool add_element(char chr) // Add an element (as char) if not already. Returns true if added, false if not.
{
bool b = false;
if (!in_set(chr) && basis.find(chr) != string::npos) {
array += chr;
length++;
b = true;
}
return b;
}
bool in_set(char chr) const // Checks whether an element (as char) is in set. Returns corresponding bool value.
{
bool b = false;
if (array.find(chr) != string::npos) b = true;
return b;
}
public:
explicit CharSet(string& str) // str - string of possible elements
{
array = "";
length = 0;
int len = (int) str.length();
for (int i = 0; i < len; i++)
add_element(str[i]);
if (str.length() != length)
cout << "\nSome mistakes corrected. Elements read: " << array << endl;
}
};
int main()
{
CharSet A((string &)"AKEPTYUMRX");
getchar();
return 0;
}
| A cast like this
(string)"a string literal"
constructs a new std::string by passing "a string literal" as an argument to its constructor. It is equivalent to static_cast<std::string>("a string literal"). It is completely valid, even though C-style casts in C++ are a bad idea in general.
On the other hand, a cast like this
(string&)"a string literal"
constructs a reference to an std::string object that resides at the same location as the string literal. Since there is no such object at that location, using this reference results in undefined behaviour (often expressed as a crash). This cast is equivalent to reinterpret_cast<std::string&>("a string literal"). You might know that reinterpret_cast is dangerous and should be avoided as much as possible. With reinterpret_cast, the compiler trusts the programmer nearly totally, which is not really a wise thing to do, but such is the C++ way.
For your function to be able to accept a string literal, it should have a const std::string& parameter, or perhaps better, if you are using C++17, an std::string_view.
|
69,728,564 | 69,732,805 | static link pthread on ubuntu causes uninitialised value jumps (valgrind) | When im statically linking the pthread library on ubuntu 20.04, using the gcc 11.1 compiler, during its runtime, my program works exactly as expected. However when i tried to run it in a debug mode and check with valgrind for any problems, i quickly discovered that linking the pthread library causes a lot of warnings to pop up. Why is that and is it something i should be worried about? (both std::thread and std::jthread display the same errors).
If i don't link the library statically, there are no errors or warnings.
main.cpp:
#include <iostream>
#include <thread>
void foo() {
std::cout << "Hello world" << std::endl;
}
int main() {
std::jthread t(foo);
return 0;
}
Compile:
g++ main.cpp -std=c++20 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
The way im linking the pthread lib i took from here. Otherwise i'd get a segfault.
Sample of the errors i'm getting:
==9674== Syscall param set_robust_list(head) points to uninitialised byte(s)
==9674== at 0x404E65: __pthread_initialize_minimal (nptl-init.c:272)
==9674== by 0x4B858E: (below main) (in /home/example)
==9674== Address 0x4000bf0 is in the brk data segment 0x4000000-0x400123f
==9674==
==9674== Conditional jump or move depends on uninitialised value(s)
==9674== at 0x4F5780: __register_atfork (in /home/example)
==9674== by 0x4F574C: __libc_pthread_init (in /home/example)
==9674== by 0x405056: __pthread_initialize_minimal (nptl-init.c:368)
==9674== by 0x4B858E: (below main) (in /home/example)
==9674==
==9674== Conditional jump or move depends on uninitialised value(s)
==9674== at 0x4F5804: __register_atfork (in /home/example)
==9674== by 0x4F574C: __libc_pthread_init (in /home/example)
==9674== by 0x405056: __pthread_initialize_minimal (nptl-init.c:368)
==9674== by 0x4B858E: (below main) (in /home/example)
==9674==
==9674== Conditional jump or move depends on uninitialised value(s)
==9674== at 0x4FA870: malloc_hook_ini (in /home/example)
==9674== by 0x5759DA: _dl_get_origin (in /home/example)
==9674== by 0x5495F4: _dl_non_dynamic_init (in /home/example)
==9674== by 0x54BF45: __libc_init_first (in /home/example)
==9674== by 0x4B85C8: (below main) (in /home/example)
and it goes on and on about uninitialised values.
|
If i don't link the library statically, there are no errors or warnings.
Linking libpthread or libc on Linux statically is almost always the wrong thing to do. Your executable may be broken in many subtle ways, if not now then in the future.
That said, the reason you get Valgrind errors is explained here.
|
69,728,662 | 69,729,131 | How do I have to describe an absolute path to a file in C++? | I want to do a program in C++ that, when is executed (from anywhere), modifies a text file in a very specific path (and always the same one). To do so, I've defined the following function in C++:
void ChangeCourse(string course)
{
ofstream active_course;
active_course.open("~/.universidad/curso_activo.txt");
if (!curso_activo)
cout << "Error: cant't open the file" << endl;
else
{
active_course << course;
curso_activo.close();
}
}
When executing the program that calls the function, I get the message Error: cant't open the file and, indeed, no file is created.
How do I have to define the path of the file such a way the program could read it and find it, regardless of where the program was called.
Note that I'm running the program in macOS.
Hope I've explained my self and thank you in advance.
| In C++17 you can use the filesystem library and hard code the path, if this is what you really want to do.
#include <filesystem>
#include <fstream>
namespace fs=std::filesystem;
int main() {
fs::path p = "your-absolute-path-goes-here"; //
if(fs::exists(p)) {
std::ofstream file(p);
file << "Hello world!" << "\n";
}
return 0;
}
|
69,728,782 | 69,728,861 | Default Constructor Parameter Error - 'Autoturism::Autoturism(char *,unsigned int)': cannot convert argument 1 from 'const char [6]' to 'char *' | A solution is to convert "Rosie" to char* using (char*), I am curious if it is another one.
| First, note that your default parameter value (c = new char[1]()) is a memory leak, since the constructor doesn't take ownership of the new[]'ed memory to delete[] it later. There is never a good reason to use new[]'ed memory for a parameter's default value.
"Rosie" is a string literal. It has a type of const char[6], which in C++11 and later cannot be assigned as-is to a non-const char* pointer, an explicit type-cast is required (in which case, you should use const_cast instead of a C-style cast), eg:
#include <iostream>
#include <string>
class Autoturism
{
static int nr_autoturisme; // nr_autoturis 'active'
char* culoare;
unsigned int a_fabricatie;
public:
Autoturism(char* = nullptr, unsigned int = 0);
~Autoturism();
// TODO: you will also need a copy constructor and a
// copy assignment operator, per the Rule of 3/5/0:
// https://en.cppreference.com/w/cpp/language/rule_of_three
...
};
int Autoturism::nr_autoturisme{ 0 };
Autoturism::Autoturism(char* c, unsigned int an)
{
if (!c) c = const_cast<char*>("");
size_t len = strlen(c);
culoare = new char[len + 1];
strcpy_s(culoare, len + 1, c);
an_fabricatie = an;
++nr_autoturism;
std::cout << "\nConstructorul a fost apelat !";
}
Autoturism::~Autoturism()
{
delete[] culoare;
std::cout << "\nDeconstructorul a fost apelat !";
}
...
int main()
{
Autoturism a1;
Autoturism a2(const_cast<char*>("Rosie"), 1999);
...
return 0;
}
Otherwise, if you really intend to stay with C-style string handling, then you should change the c parameter to const char* instead (it should be a pointer-to-const anyway, since the constructor does not modify the data being pointed at), eg:
#include <iostream>
#include <string>
class Autoturism
{
static int nr_autoturisme; // nr_autoturis 'active'
char* culoare;
unsigned int a_fabricatie;
public:
Autoturism(const char* = "", unsigned int = 0);
~Autoturism();
// TODO: you will also need a copy constructor and a
// copy assignment operator, per the Rule of 3/5/0:
// https://en.cppreference.com/w/cpp/language/rule_of_three
...
};
int Autoturism::nr_autoturisme{ 0 };
Autoturism::Autoturism(const char* c, unsigned int an)
{
if (!c) c = "";
size_t len = strlen(c);
culoare = new char[len + 1];
strcpy_s(culoare, len + 1, c);
an_fabricatie = an;
++nr_autoturism;
std::cout << "\nConstructorul a fost apelat !";
}
Autoturism::~Autoturism()
{
delete[] culoare;
std::cout << "\nDeconstructorul a fost apelat !";
}
...
int main()
{
Autoturism a1;
Autoturism a2("Rosie", 1999);
...
return 0;
}
But, with that said, why are you using this old C-style string handling in C++ at all? You should be using std::string instead (you are already including the <string> header), just let it deal with all of the memory management for you, eg:
#include <iostream>
#include <string>
class Autoturism
{
static int nr_autoturisme; // nr_autoturis 'active'
std::string culoare;
unsigned int a_fabricatie;
public:
Autoturism(const std::string & = "", unsigned int = 0);
// std:string is already compliant with the Rule of 3/5/0,
// so the compiler's auto-generated destructor, copy constructor,
// and copy assignment operator will suffice...
};
int Autoturism::nr_autoturisme{ 0 };
Autoturism::Autoturism(const std::string &c, unsigned int an)
{
culoare = c;
an_fabricatie = an;
++nr_autoturism;
std::cout << "\nConstructorul a fost apelat !";
}
int main()
{
Autoturism a1;
Autoturism a2("Rosie", 1999);
...
return 0;
}
|
69,729,033 | 69,729,264 | Is std::decay_t<T> decay_copy(T&&) equivalent to auto decay_copy(auto&&)? | http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3255.html defines decay_copy as follows:
template<typename T>
std::decay_t<T> decay_copy(T&& v)
{
return std::forward<T>(v);
}
I just wonder:
Is it equivalent to the following simpler one?
auto decay_copy(auto&& v)
{
return v;
}
| It wasn't in 2011, because:
We didn't have auto return type deduction for functions (that's a C++14 feature), and
We didn't have auto&& parameters for functions (that's a C++20 feature), and
Rvalue references were not implicitly moved from in return statements (that's also a C++20 feature)
But in C++20, yes, that is now a valid way to implement decay_copy. auto deduction does decay, return v; implicitly forwards, and everything else is the same.
I guess technically there's an edge case like:
struct X {
X();
X(X&);
};
With the original formulation of decay_copy(X{}), this is ill-formed (there's no viable constructor for constructing an X from an rvalue X). With the new formulation under the existing C++20 rules, it becomes well formed and invokes the non-const copy constructor (because we do this two-step overload resolution).
If P2266 is adopted though, then they would be exactly equivalent because return v; would always treat v as an rvalue, exactly as the existing formulation does.
|
69,729,216 | 69,729,622 | Is it possible to use structured binding in the member initializer list of a constructor? | I would like to create a class with several const member variables. Unfortunately, the function I need to initialize those variables is from a very C-style external library. As a result, I have been employing the following "middle-man" of sorts:
struct Struct {
int foo, bar;
Struct(int baz, int qux) {
initializerFunction(&foo, baz, &bar, qux);
}
}
class Class {
const int foo, bar;
Class(Struct s) : anArray(s.foo), anotherArray(s.bar) {}
public:
Class(int baz, int quz) : Class(Struct(baz, qux)) {}
}
However, I somewhat dislike this construction. I was hoping to be able to do something like this instead:
class Class {
const int foo, bar;
public:
Class(int baz, int qux) : [foo, bar](Struct(baz, qux)) {}
}
Is it possible that I am just using incorrect syntax, or is structured binding truly not allowed in the member initializer list of a constructor?
| Structured bindings declare variables (well, they're not "variables" per-se, but nevermind). You cannot use structured bindings to manipulate existing objects. This includes member objects.
|
69,729,273 | 69,729,501 | cppyy and std::is_same_v (C++17) | If I run the following test script in cppyy v1.6.2 on my Ubuntu 20.04 system:
#!/usr/bin/python3
import cppyy
cppyy.cppdef("""
struct Test {
void test() const {
std::cout << std::is_same<int,double>::value << std::endl; // works
std::cout << std::is_same_v<int,double> << std::endl; // doesn't work
}
};
""");
tt = cppyy.gbl.Test()
tt.test()
I get the following error message:
input_line_21:5:21: error: no member named 'is_same_v' in namespace 'std'
std::cout << std::is_same_v<int,double> << std::endl; // doesn't work
~~~~~^
input_line_21:5:34: error: expected '(' for function-style cast or type construction
std::cout << std::is_same_v<int,double> << std::endl; // doesn't work
~~~^
Traceback (most recent call last):
File "./test.py", line 18, in <module>
tt = cppyy.gbl.Test()
AttributeError: <namespace cppyy.gbl at 0x45baf10> has no attribute 'Test'. Full details:
type object '' has no attribute 'Test'
'Test' is not a known C++ class
'Test' is not a known C++ template
'Test' is not a known C++ enum
Because of the line I highlighted above. Everything else works.
I know that std::is_same_v is C++17, but on the cppyy/cling webpages I found statements that C++17 is supported. What is going on? Does C++17 not work in cppyy? Can this be configured? Is there only a subset of C++17 available?
For my project C++17 is of fundamental importance...
| Why use cppyy 1.6.2? Latest release is 2.1.0. A big difference between the two is a much newer version underlying Clang in the latter (the latter also makes it possible to enable c++2a, even). That said, both 1.6.2 and 2.1.0 have no problem with the above code for me, so most likely it's an installation/build issue.
First, verify whether C++17 was enabled in your install/build. E.g. like so:
$ python
>>> import cppyy
>>> cppyy.gbl.gInterpreter.ProcessLine('__cplusplus')
The result should be 201703 or higher if C++17 is enabled.
If it isn't, reinstall, e.g. with pip, assuming you still want 1.6.2 (otherwise drop the explicit version):
$ STDCXX=17 python -m pip install cppyy==1.6.2 --no-cache-dir --force-reinstall
Note that if your system compiler (used when building CPyCppyy) does not support C++17, it will still ratchet down to C++14 or C++11, as needed, even with STDCXX=17.
|
69,729,696 | 69,729,741 | why is there a "no instance of overloaded function matches the argument list" error when attempting vector push_back? | I am doing an assignment for a C++ class and I am getting an error when using push back with vector. I honestly cannot find any info on why this isnt working and giving me a "no instance of overloaded function" error
class StudentData {
class StudyModule {
private:
const int studyModuleCode;
const std::string studyModuleName;
public:
StudyModule();
StudyModule(const StudyModule& copy);
~StudyModule();
};
private:
const int studentNumber;
std::string studentName;
std::vector<StudyModule*> modules;
public:
StudentData();
StudentData(const StudentData& copy);
~StudentData();
void addModules(const StudyModule& module);
int howManyModules();
};
void StudentData::addModules(const StudyModule& module)
{
this->modules.push_back(&module);
}
| The function addModules() is declared like this:
void addModules(const StudyModule& module);
that is, its parameter is a reference to const object.
But the vector has a pointer to a non-const object as its template argument:
std::vector<StudyModule*> modules;
Thus, the compiler issues a message for this statement:
this->modules.push_back(&module);
because the expression &module has the type const StudyModule *, ie a pointer to a const object.
Even if you would change the template argument of the vector like this:
std::vector<const StudyModule *> modules;
your approach will be unsafe, because the user can pass a temporary object of type StudyModule to the function. In this case, storing a pointer to this object in the vector will become invalid when the temporary object is destroyed afterwards.
|
69,729,824 | 69,730,210 | Rules of injecting behavior to templated function using function overloading | When writing templated libraries, sometimes it is desirable to implement behavior later than the definition of a function template. For example, I'm thinking of a log function in a logger library that is implemented as
template< typename T >
void log(const T& t) {
std::cout << "[log] " << t << std::endl;
}
Later if I want to use log on my own type, I would implement std::ostream& operator<<(std::ostream&, CustomType) and hope that log function works on CustomType automatically.
However, I'm very unsure whether this pattern is conformant to the standard. To see how compilers treat it, I wrote the following minimal example.
#include<iostream>
// In some library...
void foo(double) { std::cout << "double" << std::endl; }
template< typename T>
void doFoo(T x) {
foo(x);
}
// In some codes using the library...
struct MyClass {};
template< typename T > struct MyClassT {};
namespace my { struct Class {}; }
void foo(MyClass) { std::cout << "MyClass" << std::endl; }
void foo(MyClassT<int>) { std::cout << "MyClassT<int>" << std::endl; }
void foo(my::Class) { std::cout << "my::Class" << std::endl; }
void foo(int) { std::cout << "int" << std::endl; }
int main() {
doFoo(1.0); // okay, prints "double".
doFoo(MyClass{}); // okay, prints "MyClass".
doFoo(MyClassT<int>{}); // okay, prints "MyClassT<int>".
doFoo(42); // not okay, prints "double". int seems to have been converted to double.
// doFoo(my::Class{}); // compile error, cannot convert my::Class to int.
return 0;
}
where I hope to inject to doFoo function template by overloading the foo function. The results seem very inconsistent, because it works for custom (templated) types, but not for custom types in namespaces or built-in types. The results are the same for compilers MSVC (bundled with Visual Studio 16.10.1), as well as gcc 9.3.0.
I'm now very confused about what should be the correct behavior. I guess it has something to do with the location of instantiation. My questions are:
Are the codes above legal? Or are they ill-formed?
If the codes are legal, what causes the inconsistent behaviors for different overloads?
If the codes are illegal, what would be a good alternative to injecting library templates? (I'm thinking of passing functions/functors explicitly to my doFoo function, like what <algorithm> is doing.)
|
If the codes are illegal, what would be a good alternative to injecting library templates? (I'm thinking of passing functions/functors explicitly to my doFoo function, like what <algorithm> is doing.)
You can combine functors with a default trait type to get a "best of both worlds". That's essentially how the unordered containers in the standard library use std::hash.
It allows injection either via specializing the trait or passing a functor explicitly.
#include<iostream>
// In some library...
template <typename T>
struct lib_trait;
template<>
struct lib_trait<double> {
void operator()(double) const { std::cout << "double" << std::endl; }
};
template<typename T, typename CbT=lib_trait<T>>
void doFoo(T x, const CbT& cb={}) {
cb(x);
}
// In some codes using the library...
struct MyClass {};
template< typename T > struct MyClassT {};
namespace my { struct Class {}; }
template<>
struct lib_trait<MyClass> {
void operator()(MyClass) const { std::cout << "MyClass" << std::endl; }
};
template<>
struct lib_trait<MyClassT<int>> {
void operator()(MyClassT<int>) const { std::cout << "MyClassT<int>" << std::endl; }
};
template<>
struct lib_trait<int> {
void operator()(int) const { std::cout << "int" << std::endl; }
};
int main() {
// Leverage default argument to get the same syntax.
doFoo(1.0); // okay, prints "double".
// Handled by specializations defined later.
doFoo(MyClass{}); // okay, prints "MyClass".
doFoo(MyClassT<int>{}); // okay, prints "MyClassT<int>".
doFoo(42); // okay, prints "int".
// Pass in an explicit functor.
doFoo(my::Class{}, [](const auto&){});
return 0;
}
|
69,730,161 | 69,730,367 | C++ Program is not entering "for" loop | I am making a program that finds how many anagrams does a line contain for homework and I have a problem. My program is not entering a simple "for" loop. I've been reading whole evening and I cannot understand what is the problem. I've put 7 control cout-s to see where exactly does it enter and where not. Results are - 1, 2, 3 ,7 - not even entering the "for" loop. What could be the problem? Here is my code:
#include<iostream>
#include<string>
#include <sstream>
#include<vector>
#include <algorithm>
using namespace std;
bool isAnagram(string x, string y)
{
vector<char>v;
int szX = x.size(), szY = y.size();
for (int i = 0; i < szX; i++)
{
if (!(find(v.begin(), v.end(), x[i]) != v.end()))
{
v.push_back(x[i]);
}
}
for (int j = 0; j < szY; j++)
{
if (!(find(v.begin(), v.end(), y[j]) != v.end()))
{
return false;
}
}
return true;
}
void breakStringToWords(string str, vector<string> w)
{
istringstream ss(str);
string word;
while (ss >> word)
{
w.push_back(word);
}
}
int main()
{
string x;
vector<string>v;
int cnt=0,sz;
while(getline(cin, x))
{
if(x=="")
{
return 0;
}
cout<<1<<endl;
breakStringToWords(x, v);
cout<<2<<endl;
sz=v.size();
cout<<3<<endl;
for(int i=0; i<sz; i++)
{
cout<<4<<endl;
if (isAnagram(v[i - 1], v[i]))
{
cout<<5<<endl;
cnt++;
}
cout<<6<<endl;
}
cout<<7<<endl;
cout<<cnt<<endl;
}
return 0;
}
Thank you in advance!
| Re:
It entered the loop and threw another exception
when i is 0, you are accessing v[-1]:
for(int i=0; i<sz; i++)
{
cout<<4<<endl;
if (isAnagram(v[i - 1], v[i]))
|
69,730,239 | 69,731,930 | C++ template return type for an abstract method (similar to java) | Let say I have a visitor in Java.
interface Visitor<T> {
T visitA(VisitableA a);
T visitB(VisitableB b);
}
abstract class Visitable {
abstract <T> T accept(Visitor<T> visitor);
}
class VisitableA extends Visitable {
@Override <T> T accept(Visitor<T> visitor) {
return visitor.visitA(this);
}
}
class VisitableB extends Visitable {
@Override <T> T accept(Visitor<T> visitor) {
return visitor.visitB(this);
}
}
Now, if I wanted to take that and write it in C++, I could do it like this
class VisitableA;
class VisitableB;
template <typename T> class Visitor {
virtual T visitA(VisitableA& a) = 0;
virtual T visitB(VisitableB& b) = 0;
};
class MyVisitor : public Visitor<int> {
int visitA(VisitableA& a) override { /* do something */ return 42; }
int visitB(VisitableB& b) override { /* do something */ return 1337; }
};
class Visitable {
template <typename T> virtual T accept(Visitor<T>& visitor) = 0;
};
class VisitableA : public Visitable {
template <typename T> T accept(Visitor<T>& visitor) override { return visitor.visitA(*this); }
};
class VisitableB : public Visitable {
template <typename T> T accept(Visitor<T>& visitor) override { return visitor.visitB(*this); }
};
But this does not compile, since I cannot have a virtual templated method.
I could use std::any (or something similar) but I was wondering if there was a way do implement this without it.
It must be noted that the accept return type is not known at the construction of the Visitables.
C++20 is fine if required.
| Do what Java does under the hood.
Replace T with std::any.
For Visitable make a base class that returns any to both methods. Then make a template class that implements the any returning as final, and creates a T returning Visit as pure for implementors to implement.
Visitable has two methods; a pure virtual private one taking a Visitable, and a public template taking a VitiableT template. It calls the pure virtual one and casts the any to a T.
Java generics are basically just writing that glue for you.
You may have to do casting under the hood, or look at typeids, depending on how you use this.
struct VistableA; struct VistableB;
struct Visitor{
virtual std::any visitA(VisitableA&)=0;
virtual std::any visitB(VisitableB&)=0;
};
template<class T>
struct VisitorT:Visitor{
std::any visitA(VisitableA& a) final{ return visitTA(a); }
T visitTA(VisitableA& a) = 0;
std::any visitB(VisitableB& b) final{ return visitTB(b); }
T visitTB(VisitableB& b) = 0;
};
class MyVisitor : public VisitorT<int> {
int visitTA(VisitableA& a) override { /* do something */ return 42; }
int visitTB(VisitableB& b) override { /* do something */ return 1337; }
};
class Visitable {
template <typename T> T accept(VisitorT<T>& visitor) {
return std::any_cast<T>(accept(static_cast<Visitor&>(visitor)));
}
virtual std::any accept(Visitor& visitor)=0;
};
class VisitableA : public Visitable {
std::any accept(Visitor& visitor) override { return visitor.visitA(*this); }
};
class VisitableB : public Visitable {
std::any accept(Visitor& visitor) override { return visitor.visitB(*this); }
};
now this being C++ there are another half dozen ways to solve your problem that do not emulate Java. But this is the Java esque way.
Note because we are writing the glue code Java writes for you, if we make a mistake in the glue we aren't type safe.
And in VisitableA Java checks that the same "generic type" is used for all of the Ts; in C++ I used a std::any, which could be mixed up with other "generics" and break some type safety. You could imagine a complex system of tagged std::any to avoid this.
|
69,730,386 | 69,730,690 | C++ timedelta with strftime? | I want to do a function to get the current time with a certain format. C++ is not my main language but im trying to do this:
current_datetime(timezone='-03:00', offset=timedelta(seconds=120))
def current_datetime(fmt='%Y-%m-%dT%H:%M:%S', timezone='Z', offset=None):
offset = offset or timedelta(0)
return (datetime.today() + offset).strftime(fmt) + timezone
My best so far searching internet was this, but is missing the offset part:
#include <iostream>
#include <ctime>
std::string current_datetime(std::string timezone="Z", int offset=1)
{
std::time_t t = std::time(nullptr);
char mbstr[50];
std::strftime(mbstr, sizeof(mbstr), "%Y-%m-%dT%H:%M:%S", std::localtime(&t));
std::string formated_date(mbstr);
formated_date += std::string(timezone);
return formated_date;
}
int main()
{
std::cout << current_datetime() << std::endl; //2021-10-26T21:34:48Z
std::cout << current_datetime("-05:00") << std::endl; //2021-10-26T21:34:48-05:00
return 0;
}
The idea is to get a string that is a "start date" and one as "end date" that is X seconds in the future. Im stuck with the offset/delta part
| Just add the offset to the seconds since epoch.
std::time_t t = std::time(nullptr) + offset;
You would also make offset of type std::time_t, as it represents a distance in time in seconds.
|
69,730,892 | 69,731,101 | Typedef (anonymous) struct array of size 1 | So recently I've been poking around in the internals of GMP for a project I'm working on, and I've encountered a construct that makes very little sense to me: (taken from the header for version 6.2.1)
/* For reference, note that the name __mpz_struct gets into C++ mangled
function names, which means although the "__" suggests an internal, we
must leave this name for binary compatibility. */
typedef struct
{
int _mp_alloc; /* Number of *limbs* allocated and pointed
to by the _mp_d field. */
int _mp_size; /* abs(_mp_size) is the number of limbs the
last field points to. If _mp_size is
negative this is a negative number. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpz_struct;
#endif /* __GNU_MP__ */
typedef __mpz_struct MP_INT; /* gmp 1 source compatibility */
typedef __mpz_struct mpz_t[1];
On the final line here, we typedef mpz_t to be an array of size 1 containing __mpz_structs. This is very strange to me, and I've never seen a construction like this before. I understand that this results in mpz_t effectively being a pointer to an __mpz_struct, but is this equivalent or not to
typedef __mpz_struct* mpz_t;
Could somebody explain the logic behind this?
| Given typedef __mpz_struct mpz_t[1];, you can declare an actual mpz_t object with mpz_t foo;. This will reserve memory for an mpz_t.
In contrast, if the type were typedef __mpz_struct *mpz_t;, then mpz_t foo; would only give you a pointer. There would be no space for an mpz_t. You would have to allocate it, and you would have to free it later. So more code is required, and it would be a nuisance.
At the same time, when an mpz_t is passed to a function, only its address is passed, due to the automatic conversion of arrays to pointers. This allows writing mpz_add(z, x, y);, which is less cluttered than mpz_add(&z, &x, &y);. There may be arguments among programmers about whether it is bug-prone to use a type definition that effectively results in a reference to an object being passed to a function when the code nominally looks like just a value is passed, but this style may be more suitable for the type of programming done with GMP.
|
69,731,073 | 69,742,354 | Interpreting UTF-8 unicode strings in c++ | Currently coding in C++20 using WSL2 Ubuntu, G++.
If I had a .txt file consisting of utf-8 unicode characters:
▄ ▄ ▄▄▄ ▄ ▄ ▄▄▄▄ ▄▄ ▄ ▄ ▄▄▄
How can I get the length (number of unicode characters) of this unicode string?
How can I read the file content and print out the unicode string?
| Assumptions:
stdout supports UTF-8 (on Windows you can get by with chcp 65001 at the cmd prompt)
We're counting Unicode code points, not glyphs made up of multiple code points.
UTF-8 encoding consists of start bytes following the bit patterns:
0xxxxxxx (single byte encoding)
110xxxxx (two-byte encoding)
1110xxxx (three-byte encoding)
11110xxx (four-byte encoding)
Follow-on bytes use 10xxxxxx as a bit pattern.
UTF-8 can be read using std::string and the bytes processed accordingly.
Demo code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream f("input.txt");
string s;
getline(f,s);
cout << "string: " << s << endl;
cout << "length(bytes): " << s.length() << endl;
int codepoints = 0;
for(auto b : s) {
if((b & 0xC0) != 0x80) // not UTF-8 intermediate byte?
++codepoints;
}
cout << "length(code points): " << codepoints << endl;
}
Output:
string: ▄ ▄ ▄▄▄ ▄ ▄ ▄▄▄▄ ▄▄ ▄ ▄ ▄▄▄
length(bytes): 72
length(code points): 36
|
69,731,086 | 69,731,107 | What does the "@" symbol mean in a makefile when after an -I flag such as -I @mathinc@? | I'm trying to understand the following line in a Makefile.in file:
CXXFLAGS += -O3 -DNDEBUG -std=c++11 -Wno-deprecated-declarations -Isrc -I @mathinc@
I know the -I flag adds a directory to the list of places where the compiler will search for included files but what does @mathinc@ mean?
| Note that the file is called Makefile.in -- this signifies that it is input to another file (or transformation).
In short, configure will run and determine, say, where the relevant include files are for @mathinc -- likely some math headers. After you run configure it will produce Makefile (no trailing .in) based on what it finds. Do inspect that file.
configure scripts are created in a system called autoconf which, like all build systems, has its fans and its haters. There are some decent tutorials as for example this one.
|
69,731,174 | 69,731,242 | Compiling a .cpp file with c++ command instead of g++ (Linux) | Let's say we have a simple c++ file named hello.cpp which prints "Hello World!".
We generally create the executable using g++ hello.cpp. When I tried executing the command c++ hello.cpp it creates the executable successfully. Shouldn't it throw an error saying there is no c++ command available? and suggest us to use g++?
I tried running man c++ on the terminal, this brings up the GNU C Project page. So, does the terminal replace our c++ hello.cpp with g++ hello.cpp internally? It shouldn't do that right?
Additional Info:
Similarly, if I have a hello.c program that prints "Hello World!". When I execute c hello.c on the command line, I get the error:
$ c hello.c
c: command not found
This is expected since we have to use gcc hello.c. Why am not getting a similar error for the c++ hello.cpp?
|
Shouldn't it throw an error saying there is no c++ command available? and suggest us to use g++?
Weeelll, there are no regulations or standards that restrict or require c++ command to do anything, so there is no "should" or "shouldn't". However, it would be strongly expected that c++ is a working C++ compatible compiler, that supports similar or same flags as cc does.
does the terminal replace our c++ hello.cpp with g++ hello.cpp internally?
A terminal is the device that displays things. Terminal does not replace it, it has no effect on it.
Most probably your system designer, but maybe administrator or publisher or distributor or package designer (or anyone in the chain), configured your system to provide a command named c++. Usually, that command is a symbolic link to a working C++ compiler, usually g++ on Linux systems. On my system, /usr/bin/c++ program is just installed with package named gcc, but some systems allow it to be configurable.
It shouldn't do that right?
As stated above, terminal shouldn't replace commands, it has no effect on it.
This is expected since
It is expected since there is no command named c. There are endless other unknown commands.
cc is the good old name for a C compiler. c99 is the standardized name of C99 compatible compiler.
Why am not getting a similar error for the c++ hello.cpp?
Because a command named c++ exists on your system.
|
69,732,120 | 69,819,318 | Simple OpenMP-enabled code does not compile: "clang: error: linker command failed with exit code 1" | I tried to test OpenMP on MacOS with the Apple Clang compiler that comes with Xcode.
Code:
#include <iostream>
#include <cmath>
#include </usr/local/opt/libomp/include/omp.h>
int main() {
std::cout << "Hello, World!" << std::endl;
#pragma omp parallel
{
printf("Hello World! \n");
}
return 0;
}
and this is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.19)
project(untitled)
set(CMAKE_CXX_STANDARD 14)
include (FindOpenMP)
if (OPENMP_FOUND)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
message (VERBOSE "OpenML library found")
else()
message (FATAL_ERROR "OpenML library not found (required for multithreading)")
endif ()
add_executable(untitled main.cpp)
This is the compiler's error:
Scanning dependencies of target untitled
[ 50%] Building CXX object CMakeFiles/untitled.dir/main.cpp.o
[100%] Linking CXX executable untitled
Undefined symbols for architecture x86_64:
"___kmpc_fork_call", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [untitled] Error 1
make[2]: *** [CMakeFiles/untitled.dir/all] Error 2
make[1]: *** [CMakeFiles/untitled.dir/rule] Error 2
make: *** [untitled] Error 2
The OpenMP is installed using hombrew libomp I also tried adding environment variable LDFLAGS=-L/usr/local/opt/libomp/lib/ and it does not affect the result
UPDATE: COMPILATION WITH VERBOSE=1:
...
[100%] Linking CXX executable untitled
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake -E cmake_link_script CMakeFiles/untitled.dir/link.txt --verbose=1
/Library/Developer/CommandLineTools/usr/bin/c++ -Xclang -fopenmp -g -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX11.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names -L/usr/local/opt/libomp/lib/ CMakeFiles/untitled.dir/main.cpp.o -o untitled
Undefined symbols for architecture x86_64:
"___kmpc_fork_call", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [untitled] Error 1
make[2]: *** [CMakeFiles/untitled.dir/all] Error 2
make[1]: *** [CMakeFiles/untitled.dir/rule] Error 2
make: *** [untitled] Error 2
| By using set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") and using set in other places, you are replacing the flags that CMAKE puts. It is better to append in this case rather than replace. You can use add_compile_options(-Wall) here.
As mentioned by @Tsyvarev, it is perhaps better to use imported library. Here are a few other ways you can use target_link_libraries.
For your particular case, it is best to replace
find_package(OpenMP REQUIRED)
where you currently have include (FindOpenMP). Further, remove the if condition as well. Finally, add the following to the end of your CMakeLists.txt file.
target_link_libraries(
untitled
PRIVATE
OpenMP::OpenMP_CXX
)
Here is a good explanation of the difference between PRIVATE and PUBLIC.
Your final CMakeLists.txt file should look like:
cmake_minimum_required(VERSION 3.19)
project(untitled)
set(CMAKE_CXX_STANDARD 14)
find_package(OpenMP REQUIRED)
add_executable(
untitled
main.cpp
)
target_link_libraries(
untitled
PRIVATE
OpenMP::OpenMP_CXX
)
Thanks to Tsyvarev, for helping me with CMake a few months ago. Further, thanks to the answers that Tsyvarev points toward, which my answer is based on (along with my own testing).
|
69,732,129 | 69,732,422 | Errors in a custom sine function | I am prototyping a sine function for an extremely simple programing language (Namely, limitations being only signed int variable types, and only operations between variables). However, there seems to be an error every radian or so with a given value for "s" that is greater than or equal to 0.9. This error seems to be an offset of 1, and then -1 for a small range (This is all within the same error - the 1 and then -1 is consecutive without any correct output values between). This error didn't show up on a desmos graph with the same function (The error in the desmos graph is a small jump between the approximated values). I did assume that it would be a problem with the approximation for pi and tau, but it seemed otherwise given a larger value for "s".
My code is as follows:
#include <iostream>
int sin(int x, int s1, int s2)
{
int p = x;
int pi = 314159;
int k = 1000;
int tau = 628318;
int six = 6;
int oneHundredTwenty = 120;
int fiveThousandFourty = 5040;
int ans;
int a3;
int a5;
int a7;
float s = 0.9;
pi *= s;
pi /= 100;
tau *= s;
tau /= 100;
k *= s;
p %= tau;
p -= pi;
a3 = p;
a5 = p;
a7 = p;
ans = p;
a3 *= p;
a3 /= k;
a3 *= p;
a3 /= k;
a3 /= six;
a5 *= p;
a5 /= k;
a5 *= p;
a5 /= k;
a5 *= p;
a5 /= k;
a5 *= p;
a5 /= k;
a5 /= oneHundredTwenty;
a7 *= p;
a7 /= k;
a7 *= p;
a7 /= k;
a7 *= p;
a7 /= k;
a7 *= p;
a7 /= k;
a7 *= p;
a7 /= k;
a7 *= p;
a7 /= k;
a7 /= fiveThousandFourty;
ans -= a3;
ans += a5;
ans -= a7;
return 30 + ans / 33;
}
int main()
{
for(int i = 0; i < 1000; i ++)
{
for(int j = 0; j < sin(i * 100, 1, 1); j ++)
{
std::cout << "#";
}
std::cout << "\n";
}
return 0;
}
| Your a7 variable is overflowing.
In your code, the value of a7 gets as large as 2,431,570,725 and as small as -2,443,460,910. Your int range is probably almost, but not quite, that large. A typical value of INT_MAX is 2,147,483,647.
Change it to a long or long long or something like that.
|
69,732,251 | 69,732,408 | Got an error while compiling this code for K sorted array problem | i was doing this question where we need to sort k sorted arrays in a single array and compiler threw an error:
"prog.cpp:20:23: error: expected ) before & token
struct mycomp(triplet &t1 , triplet &t2){"
I am a begginner can someone help me understand whats the issue.
`` code ```
struct triplet{
int val; int apos; int valpos;
};
struct mycomp(triplet &t1 , triplet &t2){
bool operator(triplet &t1 , triplet &t2){
return t1.val<t2.val;
}
};
class Solution
{
public:
//Function to merge k sorted arrays.
vector<int> mergeKArrays(vector<vector<int>> arr, int K)
{
//code here
vector<int> v;
priority_queue<triplet , vector<triplet> ,mycomp) pq;
for(int i=0; i<k; i++){
triplet t = {arr[i][0] , i ,0}
pq.push_back(t);
}
while(pq.empty()==false){
triplet t = pq.top(); pq.top();
v.push_back(t.val);
int ap == curr.apos; int vp = curr.valpos;
if(vp+1<arr[ap].size()){
triplet t = (arr[ap][vp+1] , ap , vp+1);
pq.push(t);
}
}
return v;
}
};
| There are many other errors/mistakes in your given program. The one you mentioned is because mycomp is a struct and so while writing its definition you can't pass parameters to it(since it is not a function definition). This particular error can be fixed by changing mycomp definition to:
//mycomp is a struct and not a function so don't pass parameters
struct mycomp{
bool operator()(triplet &t1 , triplet &t2)//note the parenthesis () i have added to overload operator()
{
return t1.val<t2.val;
}
};
Also for how to use std::priority_queue correctly you can refer to this.
|
69,732,496 | 69,732,651 | how do I handle an Array for a 2D Vector in an Object of another class? | I need a little help with an appointment of mine.
My professor gave us this class (and a Color class that has RGB colors as float variables inside) now I have to implement the functions shown in the header.
#include "color.h"
#include <assert.h>
Color::Color()
{
R = 255;
G = 255;
B = 255;
}
Color::Color( float r, float g, float b)
{
R = r;
G = g;
B = b;
}
Color Color::operator*(const Color& c) const
{
return Color(R * c.R, G * c.G, B * c.B );
}
Color Color::operator*(const float Factor) const
{
return Color(R * Factor, G * Factor, B * Factor);
}
Color Color::operator+(const Color& c) const
{
return Color(R + c.R, G + c.G, B + c.B);
}
Color& Color::operator+=(const Color& c)
{
R += c.R;
G += c.G;
B += c.B;
return *this;
}
Header RGBImage
The Konstruktor should create a 2DImage memory to save width*height Pixel. (Dunno what the best solution here would be? Array of type Color or a Vector?)
My first guess was this:
RGBImage class (i just got empty methodes)
#include "rgbimage.h"
#include "color.h"
#include "assert.h"
using namespace std;
RGBImage::RGBImage( unsigned int Width, unsigned int Height)
{
m_Image = new Color[Width * Height]; // probably wrong?
m_Width = Width;
m_Height = Height;
}
RGBImage::~RGBImage()
{
}
void RGBImage::setPixelColor( unsigned int x, unsigned int y, const Color& c)
{
if (x < width() && y < height())
{
// get offset of pixel in 2D array.
const unsigned offset = (y * width()) + x;
m_Image[offset] = c;
}
}
const Color& RGBImage::getPixelColor( unsigned int x, unsigned int y) const
{
if (x < width() && y < height())
{
// get offset of pixel in 2D array.
const unsigned offset = (y * width()) + x;
return m_Image[offset];
}
}
unsigned int RGBImage::width() const
{
return this->m_Width;
}
unsigned int RGBImage::height() const
{
return this->m_Height;
}
unsigned char RGBImage::convertColorChannel( float v)
{
if (v < 0) {
v = 0;
}
else if (v > 1) {
v = 1;
}
int convertedColorChannel = v * 255;
return convertedColorChannel;
}
bool RGBImage::saveToDisk( const char* Filename)
{
// TODO: add your code
return false; // dummy (remove)
}
afterward, I realized Color arrays are no variable of the Class RGBImage per definition of his Header so how can I save the Pixel in an RGBImage, or is it a viable option to continue this approach. If so how can I set the Color in a setter? tryed it with this.bildspeicher[x] didnt work...
I'm fairly new to Programming, and this is my first question on this platform, so sorry if I stated my problem poorly.
| RGB data is usually stored in a one-dimensional array, as is the case for RGBImage. The pixels are packed line-by-line, starting either from the bottom left, or the top-left of the image. The orientation should not affect the functions accessing individual rows of pixels, but will affect how the calling application handles the pixel data.
For accessing individual pixels, use this formula:
// ...
inline void setPixel(unsigned x, unsigned y, const Color& clr)
{
if (x < width() && y < height()) // ALWAYS crop!
{
// get offset of pixel in 2D array.
const unsigned offset = (y * width()) + x;
m_image[offset] = clr;
}
}
I've put the formula in its own line of code, but this is usually done as a one-liner.
The same formula can be used for reading pixels. Note that this formula assumes the lines of pixels have no alignment. Some bitmap fprmats do require 2 of 4 byte alignment of each line within the 2d array, in which case you'd multiply y by alignedWidth() instead of width()).
|
69,733,052 | 69,734,891 | Binary Search in C plus plus | the code when executes creates an infinite loop.
What is wrong with this code :-(
using namespace std;
int main(){
int arr[10]={1,20,30,75,90,189,253,302,304,455}, start=0, end=9, item, mid, i;
cin>>item;
mid=(start+end)/2;
while(arr[mid]!=item){
mid=(start+end)/2;
if(item>mid){
start=mid+1;
}
else if(item<mid){
end=mid-1;
}
}
cout<<"Found at location : "<<mid<<endl;
return 0;
}
| Answering your actual question: "What is wrong with this code?", see comments below:
using namespace std;
int main(){
int arr[10] = {1,20,30,75,90,189,253,302,304,455}, start=0, end=9, item, mid, i;
cin >> item;
mid = (start+end) / 2;
// You function loops indefinitely... The first place to look is here, at
// the test for your loop.
// One thing is quite plain here : You will loop indefinitely if the item you
// search for is not in the list.
//
// You should also stop looping when your search interval has reduced to
// nothingness, as this indicates the item is not found...
//
while (arr[mid] != item) { // <-- BUG
// try this instead:
while (start <= end) { // loop while interval size is >= 1 ('end' is inclusive)
const int mid = (start + end) / 2;
// Check for search success here:
if (arr[mid] == item)
{
cout << "Found at location : " << mid << endl;
return 1; // we're done! exit loop
}
if (item > mid) { // <-- BUG!!!
// should be
if (arr[mid] < item)
start = mid + 1;
else
end = mid - 1;
}
cout << "Not found." << endl;
return 0;
}
|
69,733,736 | 69,733,931 | How can I eliminate garbage value in this output? | In this below program, I'm trying to marge 2 arrays into a single vector, but while returning the function I'm getting additional garbage values along with it.
Please anyone suggest me how to remove those!
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector <int> merge(int a[],int b[]){
vector <int> marr1;
marr1.clear();
int i=0,j=0;
while(i+j <= ((*(&a+1)-a)+(*(&b+1)-b)))
{
if ((i<= *(&a+1)-a)){
marr1.push_back(a[i]);
i++;
}
else{
marr1.push_back(b[j]);
j++;
}
}
sort(marr1.begin(),marr1.end());
return marr1;
}
int main(){
//array imlementation
int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
vector <int> ans;
ans.clear();
ans = merge(arr1,arr2);
for (auto i=ans.begin();i<ans.end();++i){
cout<<*i<<"\t";
}
}
output produced:
0 0 0 0 1 3 4 5 5 7 7 8 9 32614 32766 4207952 1400400592
| You want something like this:
include <iostream>
#include <vector>
#include <algorithm> // <<<< dont use #include <bits/stdc++.h>,
// but include the standard headers
using namespace std;
vector <int> mergeandsort(int a[], int lengtha, int b[], int lengthb) { // <<<< pass the lengths of the arrays
vector <int> marr1; // <<<< and use meaningful names
// marr1.clear(); <<<< not needed
for (int i = 0; i < lengtha; i++)
{
marr1.push_back(a[i]);
}
for (int i = 0; i < lengthb; i++)
{
marr1.push_back(b[i]);
}
sort(marr1.begin(), marr1.end());
return marr1;
}
int main() {
int arr1[] = { 5,7,4,5 }, arr2[] = { 8,3,7,1,9 };
vector <int> ans;
// ans.clear(); <<<< not needed
ans = mergeandsort(arr1, 4, arr2, 5);
for (auto i = ans.begin(); i < ans.end(); ++i) {
cout << *i << "\t";
}
}
Look at the <<<< comments for explanations.
There is still room for improvement:
passing the hard coded lengths of the arrays in mergeandsort(arr1, 4, arr2, 5) is bad practice, if you add/remove element from the arrays, you need to change the lengths too.
you shouldn't use raw arrays in the first place but vectors like in vector<int> arr1[] = { 5,7,4,5 };, then you don't need to care about the sizes as a vectors knows it's own size. I leave this as an exercise for you.
|
69,733,780 | 69,733,813 | How to add to std::map an object with constant field? | Suppose I have the following code:
#include <string>
#include <map>
struct A {
const int value;
A(int value) : value{value} {}
};
int main() {
A a{3};
std::map<std::string, A> myMap;
myMap["Hello"] = a; // Error: Copy assignment operator of 'A' is implicitly deleted because
// field 'value' is of const-qualified type 'const int'.
return 0;
}
Well I understand the error. But I can't override operator= for this type of structure, because it has const int value field. So what should I do?
Commenters here suggest different solutions with their own pros and cons. Let me clear up the behaviour I need.
const int value is constant forever. No tricks or hacks to modify it.
If the key doesn't exist in a map, then assignment means "add pair [key, value] to the map". But if the key exists, then replace the value.
No default creation of A objects. Accessing to map using a key that doesn't exist in a map should throw an error or abort or something. But creating default 'A' objects for an unexisting key is not allowed.
If I understand all the presented solutions, the best thing I can do is to create some wrapper around std::map. How do you think?
| Use map::emplace to construct A in-place:
myMap.emplace("Hello", 3);
Demo.
If the key doesn't exist in a map, then assignment means "add pair
[key, value] to the map". But if the key exists, then replace the
value.
As @Serge Ballesta commented, when the key already exists, you need to erase the node from the map and emplace a new node:
const char* key = "Hello";
const int value = 3;
const auto it = myMap.find(key);
if (it != myMap.end())
myMap.erase(it);
myMap.emplace(key, value);
|
69,734,062 | 69,734,161 | Why do we need object files? | Why do we need object files? I've tried linking multiple files by using the command g++ -o main.exe main.cpp (other files).cpp, and it works. However, from tutorials online, it needs the files to be turned into *.o files first by using the command g++ -c main.cpp (other files).cpp, and use g++ -o main.exe main.o (other files).o to link the files together. If we can just do the same thing with g++ -o main.exe main.cpp (other files).cpp, why do we need to turn files into *.o first?
| TL;DR version:
You don’t need to create the object files. It’s fine to directly compile into an executable.
Long version:
You do not need to explicitly create the object files here. However, do note that the compiler does create these object files as intermediate files for each source file. Once, the compiler has all the object files available, the linker comes into play and matches definitions of each function with an implementation (amongst other things). The linker finally creates the executable and deletes the object files since you didn’t ask for them.
However, you can ask the compiler to store these intermediate files using the command as stated in your question.
As mentioned in the comments, it’s almost always good practice to compile only the source files that have changed in the last development cycle. This necessitates that you have object files available for the unchanged source files. I simply wanted to state that directly compiling is legal.
|
69,734,167 | 69,734,192 | What's the difference between (const_cast<char*> and without? | I'm having a hard time understanding the difference between those two commands
char name[0x36];
sprintf_s(name, "Some Text (%d%% Water) [%dm]", amount, dist);
Drawing::RenderText(const_cast<char*>(name), screen, cfg.visuals.ships.textCol);
and
char name[0x36];
sprintf_s(name, "Some Text (%d%% Water) [%dm]", amount, dist);
Drawing::RenderText(name, screen, cfg.visuals.ships.textCol);
and here's the RenderText func:
void xD::Renderer::Drawing::RenderText(const char* text, const FVector2D& pos, const ImVec4& color, const bool outlined = true, const bool centered = true)
{
if (!text) return;
auto ImScreen = *reinterpret_cast<const ImVec2*>(&pos);
if (centered)
{
auto size = ImGui::CalcTextSize(text);
ImScreen.x -= size.x * 0.5f;
ImScreen.y -= size.y;
}
auto window = ImGui::GetCurrentWindow();
if (outlined)
{
window->DrawList->AddText(nullptr, 0.f, ImVec2(ImScreen.x - 1.f, ImScreen.y + 1.f), ImGui::GetColorU32(IM_COL32_BLACK), text);
}
window->DrawList->AddText(nullptr, 0.f, ImScreen, ImGui::GetColorU32(color), text);
}
Im working with ImGui
|
What's the difference between (const_cast<char*> and without?
The difference is that in one case the conversion is implicit and in the other case the conversion is explicit. There is no other difference.
|
69,734,237 | 69,734,388 | Dynamic binding and virtual functions - Vector of base class objects, access the "correct" member function | I'm fairly new to c++, and I'm trying to understand as much as possible of the language and the underlying mechanics.
I am confused about a specific case where I can't seem to access the correct member function when I have two classes (Base and Derived) even though I define them as virtual.
class Base {
public:
virtual void print() { std::cout << "Base" << std::endl; };
};
class Derived : public Base {
public:
virtual void print() { std::cout << "Derived" << std::endl; };
};
int main() {
Base b;
Derived d;
b.print();
d.print();
Base* p1 = &b;
Base* p2 = &d;
p1->print();
p2->print();
std::vector<Base> v { b, d };
v[0].print();
v[1].print(); // Why doesn't this print "Derived?"
return 0;
}
Output:
Base
Derived
Base
Derived
Base
Base <- ??
virtual seems to "work" with pointers of type Base, but not for objects in vector<Base>.
What's going on?
| Because of object slicing. When you create your vector you copy your objects into it.
std::vector<Base> v{ b, d };
The catch is that inside the std::vector you have only objects of type Base, NOT Base and Derived. If you want polymorphic behavior with containers in C++, you usually do it with pointers, as you can't keep raw references in them.
std::vector<Base*> v{ &b, &d };
for (Base* ptr : v) {
ptr->print();
}
|
69,734,500 | 69,735,384 | Using macros with bazel build | I am using macro for enabling logging in my code. Also, I am using bazel build.
Currently i need to change my .cpp file to include #define to enable this macro. Is there a way that i can provide this alongwith bazel build command ?
| One option would be to control the #define directly with the --cxxopt flag.
Consider for example this code:
#include <iostream>
#ifndef _MY_MESSAGE_
#define _MY_MESSAGE_ "hello"
#endif
int main(int argc, char const *argv[]) {
std::cerr << "message: " _MY_MESSAGE_ "\n";
#ifdef _MY_IDENTIFIER_
std::cerr << "if branch \n";
#else
std::cerr << "else branch \n";
#endif
return 0;
}
Building without flags should result in the following:
> bazel build :main
...
> ./bazel-bin/main
message: hello
else branch
While by settings the flags:
> bazel build --cxxopt=-D_MY_IDENTIFIER_ --cxxopt=-D_MY_MESSAGE_="\"hi\"" :main
> ./bazel-bin/main
message: hi
if branch
Same applies to bazel run:
> bazel run --cxxopt=-D_MY_IDENTIFIER_ --cxxopt=-D_MY_MESSAGE_="\"hi\"" :main
...
message: hi
if branch
(tested only on linux)
|
69,734,567 | 69,734,711 | Why to use _tcscpy_s instead of _tcscpy? | I am new to C++ programming. I am carrying out an SAST violations check for my code, and the scan throws a warning:
_tcscpy(destination_array,Source);
The dangerous function, _tcscpy, was found in use at line 58 in Source.cpp file. Such functions may expose information and allow an attacker to get full control over the host machine
So instead, now I had to use this which makes the warning go away:
_tcscpy_s(destination_array,_countof(destination_array),Source);
What is the actual difference between _tcscpy and _tcscpy_s, and how does it make the code safe?
| The actual difference is that _s functions check the destination buffer before writing to it. If the buffer is too small then either the program is aborted, or an error value is reported, depending on the current error handler.
This prevents buffer overrun attacks, when malicious data is formed in some specific way to overwrite other data and gain the control over the program.
Sure the prevention only works if the size of destination buffer is passed correctly. If not, buffer overruns and attacks are still possible.
Even if the application does not have security implication, it may be useful to use _s functions anyway to avoid hard to pinpoint memory corruption bugs.
Visual C++ provides a templated version of _tcscpy_s, so for arrays instead of
_tcscpy_s(destination_array,_countof(destination_array),Source);
you can use
_tcscpy_s(destination_array,Source);
this is even more safe, as the size is deduced, so an incorrect size is not possible.
|
69,735,035 | 69,735,114 | When dose move constructor and default constructor called | I have this code
class MyString {
public:
MyString();
MyString(const char*);
MyString(const String&);
MyString(String&&) noexcept;
...
};
String::String()
{
std::cout << "default construct!" <<std::endl;
}
String::String(const char* cb)
{
std::cout << "construct with C-char!" <<std::endl;
...
}
String::String(const String& str)
{
std::cout << "copy construct!" <<std::endl;
...
}
String::String(String&& str) noexcept
{
std::cout << "move construct!" <<std::endl;
...
}
In main()
MyString s1(MyString("test"));
I thought result would be this:
construct with C-char! <---- called by MyString("test")
move construct! <---- called by s1(...)
But what I get was this:
construct with C-char! <---- maybe called by MyString()
The steps what I thought
MyString("test") construct a rvalue by using the constructor with char*
Construct s1(arg)
Because of arg is a rvalue, s1 should construct by move constructor
But I find move constructor won't be called without std::move.
Why is that happening?
How to use move constructor without std::move()?
Compiler:
Gnu C++ 9.3.0
|
Why is that happening?
Since C++17: Because MyString("test") is a prvalue, and the language says that s1 is directly initialised from "test" in this case.
Before C++17: Because the side effects of move (and copy) constructor are not required/guaranteed to occur which allows the compiler to optimise by not creating the temporary object. This optimisation is called copy elision, and it's what your compiler did here.
How to use move constructor without std::move()?
You shouldn't want to use the move constructor. It's better to not create redundant temporary objects. What you've observed is better than what you were expecting.
In cases where you do need std::move (which doesn't apply here), you shouldn't want to avoid using it.
As such, the question is analogous to, "How do I make my pipes leak without using the appropriate tool?". 1. You don't want to make your pipes leak, and 2. If you for some reason do, just use the appropriate tool.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.