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 |
|---|---|---|---|---|
72,428,516 | 72,428,803 | Have 2 Lambda expressions within the same function call each other | I've been using SFML for a project, and I'm attempting to make a pause state while still using the SFML game loop. Long story short, I have been attempting to use 2 Lambda expressions within the same function to toggle between the pause and run states I have running. Here's some example code:
int main() {
//some stuff here...
auto pauseloop = [&] {
//do some stuff here...
runloop();
}
auto runloop = [&] {
//some more code, include SFML game loop here...
if (paused)
pauseloop();
}
runloop();
}
This works fine at first, but runs into an issue almost immediately: upon calling pauseloop() from within runloop(), I cannot call runloop() from within pauseloop(). I tried to add something to the effect of this above my main() function:
auto pauseloop = [&] {}; //initializer
auto runloop = [&] {}; //initializer
However, after some extensive testing and debugging, this causes the runloop() Lambda expression above the main() function to be called when being called from pauseloop(), however the intended, fully declared, runloop() is called when called at the end of the main() function.
First, is there any way to get two Lambda expressions from within the same function to call each other? Second, why does the pauseloop() expression call the initializer version of runloop(), while the runloop() at the end of main() calls the intended one? From my best guess, I would have assumed that because runloop() and pauseloop() were both initialized defined before either one was called, the pauseloop() would call the declared version, as it had been read in its entirety and correctly overwritten the initializer, yet this seems completely off compared to what is actually happening. Thank you in advance!
Edit 1: To be concise, the above attempts don't work for the intended solution (having Lambda expression "a" call Lambda expression "b" and vice versa). How would I write two Lambda expressions that can?
| As long as your lambdas have captures, and it seems like yours do, you can't have them call each other directly because there is a circular dependency when you declare them. To work around this, you can assign them to pointers.
If you did not have captures, the compiler would simply generate anonymous functions for your lambdas and you could assign them to function pointers like this:
void (*pauseloop)() = nullptr;
void (*runloop)() = nullptr;
pauseloop = []() {
//...
runloop();
//...
};
runloop = []() {
//...
pauseloop();
//...
};
Since you do have captures, the solution is very similar but you would use std::function instead. Actually, since you can use std::function with functions as well, this is my recommendation in any case:
std::function<void()> pauseloop, runloop;
pauseloop = [&]() {
// ...
runloop();
// ...
};
runloop = [&]() {
// ...
pauseloop();
// ...
};
Note that, in both cases, it is not going to be enough to capture the function pointer / std::function by value. At least one of the lambdas will have to capture it by reference or use it as a global. Otherwise it will only capture the initial nullptr value.
https://ideone.com/c7FGCo
|
72,428,603 | 72,429,946 | Optimize Binary Search in sorted array find number of occurences | Im trying to do the smallest number of operations possible to find the number of occurences of an element in the array. Save even 1 operation if possible. So far this is the best binary search version I know. I cant use vectors or any other std:: functions
int modifiedbinsearch_low(int* arr, int low, int high , int key){
if(low==high) return high ;
int mid = low + (high-low) /2;
if(key > arr[mid] ) { modifiedbinsearch_low(arr,mid + 1 , high,key); }
else { modifiedbinsearch_low(arr,low,mid,key); }
}
int modifiedbinsearch_high(int* arr, int low, int high , int key){
if(low==high) return high ;
int mid = low + (high-low) /2;
if(key < arr[mid] ) { modifiedbinsearch_high(arr,low,mid,key); }
else { modifiedbinsearch_high(arr,mid+1,high,key); }
}
int low = modifiedbinsearch_low( ...)
int high = modifiedbinsearch_high( ...)
This version collapsed both functions into just one but it takes almost double the time. Im wondering the idea is good for it to become the fastest but the implementation is wrong.
#include<stdio.h>
int binarysearch(int a[],int n,int k,bool searchfirst){
int result=-1;
int low=0,high=n-1;
while(low<=high){
int mid=(low+high)/2;
if(a[mid]==k) {
result=mid;
if(searchfirst)
high=mid-1;
else
low=mid+1;
}
else if(k<a[mid]) high=mid-1;
else low=mid+1;
}
return result;
}
int main(){
int a[]={1,1,1,2,2,3,3,3,6,6,6,6,6,7,7};
int n=sizeof(a)/sizeof(a[0]);
int x=6;
int firstindex=binarysearch(a,n,x,true);
printf("%d\n",firstindex);
if(firstindex==-1){
printf("elment not found in the array:\n ");
}
else {
int lastindex=binarysearch(a,n,x,false);
printf("%d\n",lastindex);
printf("count is = %d", lastindex-firstindex+1);
}
}
Shorter version
int binmin(int a[], int start, int end,int val ) {
if(start<end) {
int mid = (start+end)/2;
if(a[mid]>=val)
binmin(a,start,mid-1,val);
else if(a[mid]<val)
binmin(a,mid+1,end,val);
}
else if(start>end)
return start;
}
| Here's a performance issue. In the main while loop, you aren't breaking out fo the loop when you find the target value.
while(low<=high){
int mid=(low+high)/2;
if(a[mid]==k) {
result=mid; // you need to break out of the loop here
if(searchfirst)
high=mid-1;
else
low=mid+1;
}
But that's not the only issue. The searchfirst value shouldn't be what dictates adjusting high or low as you are doing it. In a classic binary search, adjust the high or low parameter based on how a[mid] compares to k`. Probably closer to this:
while(low<=high) {
int mid=(low+high)/2;
if(a[mid]==k) {
result=mid; // you need to break out of the loop here
break;
}
if(a[mid] > k)
high=mid-1;
else
low=mid+1;
}
You have the right idea. Binary search to find the element. But let me suggest the simpler solution after the initial binary search is to just "scan to the left" and "scan to the right" to count duplicate elements.
Let me know what you think of this:
int binarySearch(int* arr, int start, int end, int value) {
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == value) {
return mid;
}
start = (arr[mid] < value) ? (mid + 1) : start;
end = (arr[mid] > value) ? (mid - 1) : end;
}
return -1;
}
int countSide(int* arr, int length, int index, int value, int step) {
int count = 0;
while (index >= 0 && index <= (length - 1) && arr[index] == value) {
count++;
index += step;
}
return count;
}
int main() {
int a[] = { 1,1,1,2,2,3,3,3,6,6,6,6,6,7,7 };
int n = sizeof(a) / sizeof(a[0]);
int x = 6;
int firstindex = binarySearch(a, 0, n - 1, x);
printf("%d\n", firstindex);
if (firstindex == -1) {
printf("elment not found in the array:\n ");
}
else {
int count = countSide(a, n, firstindex, x, -1);
count += countSide(a, n, firstindex, x, 1);
count--; // because we counted the middle element twice
printf("count is = %d\n", count);
}
}
Updated
Here's a solution that does two binary searches to find the lower and upper bounds of the target value in the array and simply measures the distance between the indices to get the count:
int bound(int* arr, int length, int value, bool isUpperBound) {
int best = -1;
int start = 0;
int end = start + length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == value) {
best = mid;
if (isUpperBound) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
else if (arr[mid] < value) {
start = mid + 1;
}
else if (arr[mid] > value) {
end = mid - 1;
}
}
return best;
}
int main() {
int a[] = { 1,1,1,2,2,3,3,3,6,6,6,6,6,7,7 };
int n = sizeof(a) / sizeof(a[0]);
int x = 6;
int firstindex = bound(a, n, x, false);
int lastindex = bound(a, n, x, true);
printf("%d - %d\n", firstindex, lastindex);
if (firstindex == -1) {
printf("elment not found in the array:\n ");
}
else {
int count = lastindex-firstindex + 1;
printf("count is = %d\n", count);
}
}
|
72,429,210 | 72,438,310 | How to read n bytes of a file in QT C++? | Hi im new to Qt and im trying to read for example the first 4 bytes of my .txt file and show it. I've been searching and figure that QbyteArray may help me best in this situation. so I really like to know how can i read the first 4 bytes of my file with QbyteArray? (appreciate if u write any example code)
| Assuming your code contains something like this:
QFile file{ "path/to/file.txt" };
You can read a number of bytes from a file with file.read(n), assuming n to be a number of bytes. you can also use file.readAll() to get the entire thing
for more advanced input/output operations, you can use the QTextStream class as such:
QFile file { "path/to/file.txt" };
QTextStream stream { &file };
(This is a stream that can read and write data to the provided device, here, a file.)
For more info, see here:
https://doc.qt.io/qt-6/qfile.html for QFile
https://doc.qt.io/qt-6/qtextstream.html for QTextStream
|
72,429,519 | 72,429,582 | C++: Cannot use designated initializers on extended structs/classes | I am trying to figure out a way to use designated initializers to build a struct, which has been extended off of another one. In my use case, the struct S is a domain object, and the struct S2 adds some application-specific logic for converting it to/from json. As far as I can tell, you cannot use designated initializers if you have a "real" constructor, but all is well if you have a static method returning a new instance for you.
I have a MVP like so (view in Godbolt):
#include <iostream>
struct S {
int i;
};
struct S2 : public S {
static S2 create() {
return S2 { .i = 1234 };
}
};
int main() {
std::cout << S2::create().i;
}
When building (using -std=c++20), I get the following error:
<source>:9:31: error: 'S2' has no non-static data member named 'i'
9 | return S2 { .i = 1234 };
| ^
I expect that the i field would be carried over and initialized, but it isn't.
Am I trying to do something C++ cannot support?
| i is data member of S, but not S2.
You can add another braces referring to the base subobject, e.g.
return S2 { {.i = 1234} };
Or you can just take advantage of brace elision:
return S2 { 1234 };
|
72,430,369 | 72,430,675 | How to check that a type is 'formattable' using type traits / concepts? | I would like to check if a certain type can be used with std::format.
This is my naive attempt:
template<typename Object>
concept formattable = requires(const Object & obj)
{
std::format("{}", obj);
};
But this does not work. It basically returns true for all types. Even those that can't be used with std::format.
static_assert(!formattable<std::vector<int>>); // should return false
Why doesn't it work?
| Since std::format is not a constrained function, the expression std::format("{}", obj) is always well-formed. You might want to do
#include <format>
template<typename T>
concept formattable = requires (T& v, std::format_context ctx) {
std::formatter<std::remove_cvref_t<T>>().format(v, ctx);
};
which mainly based on the constraints of the basic_format_arg's constructor in [format.arg].
Demo
|
72,430,383 | 72,432,821 | make error: undefined reference to cpp_redis::client::set(..) and cv::Mat::~Mat() | Complete error stack trace:
undefined reference to `cv::Mat::Mat(int, int, int, void*, unsigned long)'
undefined reference to `cv::imencode(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&, std::vector<unsigned char, std::allocator<unsigned char> >&, std::vector<int, std::allocator<int> > const&)'
undefined reference to `cpp_redis::client::client()'
undefined reference to `cpp_redis::client::connect(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long, std::function<void (std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long, cpp_redis::connect_state)> const&, unsigned int, int, unsigned int)'
undefined reference to `cpp_redis::client::set(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
undefined reference to `cpp_redis::client::sync_commit()'
undefined reference to `cpp_redis::client::~client()'
undefined reference to `cv::Mat::~Mat()'
undefined reference to `cpp_redis::client::~client()'
undefined reference to `cv::Mat::~Mat()'
collect2: error: ld returned 1 exit status
src/sensors/camera/camera/CMakeFiles/sample_camera.dir/build.make:130: recipe for target 'src/sensors/camera/camera/sample_camera' failed
make[2]: *** [src/sensors/camera/camera/sample_camera] Error 1
CMakeFiles/Makefile2:2246: recipe for target 'src/sensors/camera/camera/CMakeFiles/sample_camera.dir/all' failed
make[1]: *** [src/sensors/camera/camera/CMakeFiles/sample_camera.dir/all] Error 2
Makefile:149: recipe for target 'all' failed
make: *** [all] Error 2
Here is the code snippet which is causing make to fail:
std::vector<uchar> buf;
cv::Mat matImage = cv::Mat(imgCPU->prop.width, imgCPU->prop.height, CV_8UC3, imgCPU->data[0]);
cv::imencode(".jpg", matImage, buf);
cpp_redis::client client;
client.connect();
client.set("image", {buf.begin(), buf.end()});
client.sync_commit();
Note that
imgCPU->prop.width, imgCPU->prop.height are ints and
imgCPU->data[0] is uint8_t *.
What changes should I make in the CMakeLists.txt file for my program to compile correctly?
Here is what my CMakeLists.txt file looks:
project(sample_camera C CXX)
pkg_check_modules(OPENCV opencv)
if(${OPENCV_FOUND})
MESSAGE("OPENCV_FOUND:" ${OPENCV_FOUND})
MESSAGE("OPENCV_VERSION:" ${OPENCV_VERSION})
MESSAGE("OPENCV_LIBRARIES:" ${OPENCV_LIBRARIES})
MESSAGE("OPENCV_INCLUDE_DIRS:" ${OPENCV_INCLUDE_DIRS})
MESSAGE("OPENCV_LIBRARY_DIRS:" ${OPENCV_LIBRARY_DIRS})
INCLUDE_DIRECTORIES(${OPENCV_INCLUDE_DIRS})
INCLUDE_DIRECTORIES("/usr/include/opencv4")
INCLUDE_DIRECTORIES("/usr/include/opencv4/opencv2")
LINK_DIRECTORIES(${OPENCV_LIBRARY_DIRS})
LINK_DIRECTORIES("/usr/include/opencv4/opencv2")
endif()
#-------------------------------------------------------------------------------
# Project files
#-------------------------------------------------------------------------------
set(PUBLIC_DOCS
README.md
)
set(SOURCES
main.cpp
)
set(LIBRARIES
${Driveworks_LIBRARIES}
samples_framework
lodepng-src
)
#-------------------------------------------------------------------------------
# Final target
#-------------------------------------------------------------------------------
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(${PROJECT_NAME} PRIVATE ${LIBRARIES})
set_property(TARGET ${PROJECT_NAME} PROPERTY FOLDER "Samples")
# ------------------------------------------------------------------------------
# Install target
# ------------------------------------------------------------------------------
sdk_add_sample(${PROJECT_NAME})
sdk_add_sample_data(${PROJECT_NAME} "samples/sensors/camera/camera")
| Your CMakeLists.txt is wrong and messy try this:
cmake_minimum_required(VERSION 3.16)
project(DisplayImage CXX)
find_package(OpenCV REQUIRED COMPONENTS core imgproc video)
...
add_executable(${PROJECT_NAME} ${SOURCES})
target_link_libraries(${PROJECT_NAME}
PRIVATE
opencv_core
opencv_video
opencv_imgproc)
Drop INCLUDE_DIRECTORIES and LINK_DIRECTORIES since it is obsolete (wrong) in modern CMake.
|
72,430,636 | 72,430,993 | Clean way to get function pointer from external std::function | Because C, I need a function pointer from a std::function I receive at runtime.
Let's call defineProxyCallback the C function taking as input a function of unsigned char.
My hack to make this work has been :
struct callBacker {
std::function<void(unsigned char)> normalKey;
};
callBacker cb = callBacker();
extern callBacker cb;
void proxy(unsigned char c) { cb.normalKey(c); };
void maincode {
// Actually cb.normalKey is taken as an input from outside
cb.normalKey = [](unsigned char c){std::cout << c << std::endl;} ;
// this was just to lake the code work
defineCallback(proxy);
}
defineCallback is defined somewhere else :
void defineCallback(void (*func)(unsigned char))
{
*func("hello world");
//should be : glutKeyboardFunc(func);
}
This works, but it's ugly AF. However, because the function pointer comes from a static function, I did not find any other way than using extern.
I've looked around but I've never found a solution for this exact problem. Any tip on making it cleaner ?
Thank you very much !
For clarity : I cannot change the fact that I need to provide a function pointer to defineCallback, nor that I receive a std::function from outside.
| I don't think this is ever going to be super-neat and tidy. If it were me I would probably use inline functions so that they could go in a header file and I would use thread_localstorage to add a little thread safety.
Something a bit like this:
// force the compiler to make sure only one of these functions
// is linked and this can go in the header file
inline std::function<void(unsigned char)>& get_std_function()
{
// returns a different object for each thread that calls it
static thread_local std::function<void(unsigned char)> fn;
return fn;
}
inline void proxy(unsigned char c){ get_std_function()(c); };
void maincode() {
// Actually cb.normalKey is taken as an input from outside
get_std_function() = [](unsigned char c){std::cout << c << std::endl;} ;
// this was just to lake the code work
defineCallback(proxy);
}
|
72,431,090 | 72,431,427 | Can I use an std::ostream to print into a given buffer? | I have a given buffer of characters (maybe even the buffer backing an std::string, but never mind that). I want to print into that buffer using an std::ostream, i.e. I want to be able to write:
span<char> my_buffer = get_buffer();
auto my_os = /* magic */;
static_assert(
std::is_base_of<std::basic_ostream<char>,decltype(my_os)>::value,
"magic failed");
my_os << "hello" << ',' << 123 << '\0';
std::cout << my_buffer << '\n';
and get:
hello,123
on the standard output.
Note: C++11 if possible, and please mention the language standard you're using. (And yes, I know C++11 doesn't have spans.)
| (Thank @BoP and @T.C. for the two parts of this solution)
This can be done... if you're willing to use a deprecated C++ construct: std:ostrstream.
#include <strstream>
#include <iostream>
int main() {
const size_t n = 20;
char my_buffer[n];
std::ostrstream my_os(my_buffer, n);
my_os << "hello" << ',' << 123 << '\0';
std::cout << my_buffer << '\n';
}
Notes about this code:
It works (GodBolt)
It is valid C++98! ... of course I had to let go of std::span, auto type inference etc. It's also valid C++11 and later standards.
This will construct an std::strstreambuf, which is what an std::ostrstream uses directly, from your buffer of chars.
(see this on GodBolt)
Unfortunately, with the deprecation of std::ostrstream, we were left with no fully-valid alternative up to, and including, C++20. You would need to implement a custom std::basic_streambuf, and assign it to an std::ostream. :-(
But in C++23 - you are luck! The standard library does offer exactly what you asked for: std::spanstream: A std::ostream backed by a span of char's which it is given at construction.
|
72,431,265 | 72,431,869 | How to print .html files using ShellExecuteExW? | The goal is to print a htm/html file via Windows-API ::ShellExecuteExW.
The parameters of ::ShellExecuteExW are
shell_info.lpVerb = "open";
shell_info.lpFile = "C:\Windows\System32\rundll32.exe";
shell_info.lpParameters = "C:\Windows\System32\mshtml.dll ,PrintHTML "C:\Temp\test.html"";
lpFile and lpParameters are fetched from the registry key "\HKEY_CLASSES_ROOT\htmlfile\shell\print\command"
The error message:
Everything is fine if running the C:\Windows\system32\rundll32.exe C:\Windows\system32\mshtml.dll ,PrintHTML "C:\Temp\test.html" via cmd. The printing dialog appears.
How does ::ShellExecuteExW need to be called to achieve the same behavior as the cmd?
| Is it possible that the code that generates the error in the screenshot looks different from what you show us here? I'm asking this because you don't seem to escape any double quote or backslash. Seems to me your compiler should at least give one error when compiling that code.
However I just tried the code below and this seem to work. Hope it helps.
int main()
{
SHELLEXECUTEINFOW shell_info = { 0 };
shell_info.cbSize = sizeof(SHELLEXECUTEINFOW);
shell_info.lpVerb = L"open";
shell_info.lpFile = L"C:\\Windows\\System32\\rundll32.exe";
shell_info.lpParameters = L"C:\\Windows\\System32\\mshtml.dll ,PrintHTML \"C:\\Temp\\test.html\"";
shell_info.nShow = SW_SHOWNORMAL;
ShellExecuteExW(&shell_info);
return 0;
}
|
72,431,311 | 72,431,434 | When I am trying to implement a vector inside a strcuture I am getting garbage values, How can I remove those garbage values | #include <iostream>
#include <vector>
using namespace std;
#pragma pack(1)
struct person{
int age = 25;
int salary = 20000;
vector<int> a = {1,2,3,4,5};
};
#pragma pack()
int main() {
person obj;
person *p = new person(obj);
int* ch = reinterpret_cast<int*>(p);
for(int i=0;i<32;i++){
std::cout<<"struct values"<<*ch++<<std::endl;
}
cout<<sizeof(struct person)<<endl;
}
Output:
struct values25
struct values20000
struct values-1272049920
struct values21971
struct values-1272049900
struct values21971
struct values-1272049900
struct values21971
struct values0
struct values0
struct values33
struct values0
struct values1
struct values2
struct values3
struct values4
struct values5
struct values0
struct values4113
struct values0
struct values1970435187
struct values1981838435
struct values1702194273
struct values808923507
struct values892547641
struct values168440116
struct values10
struct values0
struct values0
struct values0
struct values0
struct values0
32
| The problem is that you're typecasting a person* to an int* and then dereferencing that int* which leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
In your code there is no need to use new or reinterpret_cast and you can use -> to get access to the vector data member a as shown below:
struct person{
int age = 25;
int salary = 20000;
std::vector<int> a = {1,2,3,4,5};
};
int main() {
person obj;
person *p = &obj; //or person *p = new person(obj)
for(const auto& element: p->a)
{
std::cout<<element<<std::endl;
}
//no need to use delete here as we've not used new. But if you were to use new make sure you use delete
}
Demo
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
72,431,360 | 72,431,533 | Serial.write(5) not able to send decimal? | I am trying, as a test to Serial.write the int value: 5, to serial monitor, and if received, i want to print the the text "SUCCESS!" to the serial monitor.
But when writing Serial.write((int)5); All i get in the serial monitor is:
I have tried using Serial.println(5); which works fine, but then i am not able to read it.
My code:
enum read_states {
Modtag_Adresse,
Modtag_Bit_Position_I_Adresse,
Modtag_Bit_Position_Vaerdi
};
enum read_states state;
void setup() {
state = Modtag_Adresse;
Serial.begin(9600);
}
void loop() {
if(state == Modtag_Adresse) {
Serial.write((int)5);
delay(1000);
if(Serial.available() > 0) {
int serialReceived = Serial.read();
if(serialReceived >= 0) {
// Receive value 5
Serial.print("SUCCESS!!");
}
}
}
else if(state == Modtag_Bit_Position_I_Adresse) {
//
}
else if(state == Modtag_Bit_Position_Vaerdi) {
//
}
else {
// Failure.
}
}
| Serial.write(5) sends the byte 5 to the computer. It appears as a square, because it's not an ASCII code of a letter or number or symbol.
Serial.print(5) sends the ASCII code for 5 (which is 53).
The reason you can't read what you wrote is because Serial.write sends data to the computer and Serial.read returns data received from the computer. If it read data from the Arduino program, it would be pointless because you don't need to use serial for that.
|
72,431,414 | 72,435,116 | IBM xlc compile fail with error message "The test "std::function" is unexpected | I use IBM xlc to compile C++ code but it failed with error message "The test "std::function" is unexpected. I use std::function in my code and add compile option "-qlanglvl=extended0x". The xlc version is 13.1. By the way, the same code is compiled successfully with G++.
Does anybody know the reason. Thanks.
| The xlC compiler -qlanglvl=extended0x only has experimental C++11 support and is notably missing C++11 library. You need to move up to the V16 xlclang++ compiler or V17 ibm-clang++ compiler to get full C++11 support.
|
72,431,661 | 72,432,505 | Are C++ exceptions expected to be handled in main()? | I am doing a project in C++, and I am new to OOP.
I have some doubts regarding C++ exceptions and where they have to be handled.
I read that it is a good practice to insert the try/catch block into the main() function, letting the exceptions thrown into "deep placed" methods to climb up to main() and be handled there, programming the user feedback in such cases.
The problem is that not all the errors of the project are treated like exceptions, and for that reason high level functions called in main() return a bool value that is a first indicator of an error state.
So, I am wondering whether it is a good thing not to handle exceptions in main() in that case, placing the try/catch block into low-level methods and returning a false value in the high-level one when an exception has been caught in the former, allowing me to treat all the errors the same way.
| There is no general rule where these handlers should go.
But you describe your program as "high level functions called in main() return a bool value". That is a reasonable choice: any specific exception handling is taken care of by those high-level functions. From the perspective of main, these high-level functions either succeed or they fail. Hence, main does not need to bother with exceptions in your specific design.
|
72,432,379 | 72,432,783 | Allocate a dynamic array of pointers to the structure | I have created the dynamic array
struct Student{
string name;
string dateOfBirth;
};
Student **students = new Student*[5]
But I'm getting error when I try to store data
Exception thrown: read access violation.
this was 0xCDCDCDCD.
(*students[iterator]).name = name;
| If you want to allocate memory like this:
struct Student{
string name;
string dateOfBirth;
};
Student **students = new Student*[5];
Just like the comments say, you need to think about what the datatype of students[0] actually is. In this case, it's a Student *, meaning you have to treat it as such. If you try to assign a value directly to that by doing something like the following, you'll get all sorts of memory errors (and hopefully compiler errors/warnings)
Student **students = new Student*[5];
students[0] = Student{"Bob", "1st Jan 1970"}; // Nope
*students[0] = Student{"Bill", "1st Jan 1970"}; // Also no
The first one clearly won't work, because we're trying to assign a Student to a Student *, which isn't possible. The reason for the second one not working is to do with how memory allocation works.
When you call Student **students = new Student*[5], you're telling the compiler to allocate memory for 5 Student * objects, which are all ultimately just 64bit unsigned integers. That means there is memory available for those 64x5 bits, but remember, they're pointers, so they need to point somewhere.
The way to assign a value to would be something like the following:
students[0] = new Student{"Barry", "1st Jan 1970"}; // (Notice the 'new')
This will dynamically allocate memory for a new Student and set the pointer in students to point to it, allowing you to access it.
======== A Warning ========
When you allocate memory dynamically (i.e. using new or malloc, etc.) you are responsible for calling delete[] or delete or free, depending on the situation. Without these calls, the memory will never be freed and you'll end up with a memory leak, which can be very problematic. The difficulty with using a pointer to pointers is that you'll need to free each sub-pointer before freeing the main pointer. Trying to do it the other way around will lead to other fun problems which you're better off just not having to suffer through.
Hopefully this helps. Let me know if anything could be cleared up or if it doesn't work...
|
72,432,729 | 72,439,826 | Having trouble iterating over the right children to change their color | I'm looking to make a menu where there are more than one wxStaticTexts and when one of them is clicked it turns black and the rest are/revert back to being grey (if they were clicked before, otherwise they would just stay grey)
The problem is I usurped this code which works great for doing the first part, it turns the item that was clicked black, but it doesn't turn the rest back to grey. My attempt at a solution is in the else block. I haven't attempted anything else because I'm still figuring both C++ and WxWidgets out and I still don't have a complete understanding of some concepts used in this snippet.
void MyFrame::OnMenuTxtBtnLeftClickPanel(wxMouseEvent& event) {
wxObject* obj = event.GetEventObject();
wxPanel* objPanel = ((wxPanel*)obj);
wxWindowList objChild = objPanel->GetChildren();
for (wxWindowList::iterator it = objChild.begin(); it != objChild.end(); it++) {
wxStaticText* aStaticText = dynamic_cast<wxStaticText*>(*it);
if (aStaticText) {
aStaticText->SetForegroundColour(wxColour("#000000"));
}
else {
// Doesn't do anything when compiled
// it should change the StaticTexts that weren't clicked back to grey
dynamic_cast<wxStaticText*>(*it)->SetForegroundColour(wxColour("#C8C6C6"));
}
}
| This works for me:
void MyFrame::OnMenuTxtBtnLeftClickPanel(wxMouseEvent& event)
{
wxWindow* cur = wxDynamicCast(event.GetEventObject(),wxWindow);
wxColor fg = m_panel1->GetForegroundColour();
wxWindowList& children = m_panel1->GetChildren();
for ( auto it = children.begin() ; it != children.end() ; ++it )
{
wxWindow* win = *it;
if ( wxDynamicCast(win, wxStaticText) )
{
if ( win == cur )
{
win->SetForegroundColour(wxColour("#000000"));
}
else
{
win->SetForegroundColour(fg);
}
}
}
}
In this code, m_panel1 is a wxPanel that is the parent of all the static texts.
On GTK, it looks like this:
The handler was bound to each static text control in the frame constructor like this:
m_staticText1->Bind(wxEVT_LEFT_UP,&MyFrame::OnMenuTxtBtnLeftClickPanel,this);
m_staticText2->Bind(wxEVT_LEFT_UP,&MyFrame::OnMenuTxtBtnLeftClickPanel,this);
m_staticText3->Bind(wxEVT_LEFT_UP,&MyFrame::OnMenuTxtBtnLeftClickPanel,this);
m_staticText4->Bind(wxEVT_LEFT_UP,&MyFrame::OnMenuTxtBtnLeftClickPanel,this);
m_staticText1, etc. should be changed to the names you're using for the text controls.
|
72,433,291 | 72,436,570 | operator [][] matrix c++ | Im trying to create an operator that gives me the value for the position i,j of a certain matrix and another one that "fills" the matrix in the given positions, ive tried to put the operator that you can see in the header but it isnt working, the problem might be somewhere else but i think this it the main issue:
int main()
{
matriz a(3,3);
matrizQuad b(3);
for(size_t i=0;i<3;++i)
for(size_t j=0;j<3;++j){
a[i][j]=1;
b[i][j]=2;
}
matriz c=a+b;
cout << "a+b:\n" << c << "\n";
cout << "traco: " << b.traco() << "\n";
return 0;
} ```
Header:
#ifndef MATRIZES_H
#define MATRIZES_H
#include <iostream>
#include <vector>
#include <ostream>
#include <sstream>
using namespace std;
typedef vector<vector<double>> array;
class matriz
{
protected:
int iLargura, iComprimento;
array m;
public:
matriz(int L, int C): iLargura (L), iComprimento (C)
{
array m(L);
for (int i = 0; i<L;i++)
m[i].resize(C);
};
int nL() const {return iLargura;}
int nC() const {return iComprimento;}
vector<double>& operator[] (int i) {return m[i];}
const vector<double>& operator[] (int i) const {return m[i];}
};
class matrizQuad: public matriz
{
public:
matrizQuad (int T): matriz(T,T) {}
double traco();
};
matriz operator+(const matriz& m1, const matriz& m2);
ostream& operator<<(ostream& output, const matriz& m1);
#endif // MATRIZES_H
Body:
#include "matriz.h"
double matrizQuad::traco()
{
double dSoma = 0;
for (int i = 0;i<iLargura; i++)
for (int j = 0;i<iLargura; i++)
if (i==j)
dSoma = dSoma + m[i][j];
return dSoma;
}
matriz operator+(const matriz& m1, const matriz& m2)
{
int C1 = m1.nC();
int L1 = m1.nL();
matriz m(C1,L1);
for (int i = 0;i<C1; i++)
for (int j = 0;i<L1; i++)
m[i][j] = m1[i][j] + m2[i][j];
return m;
}
ostream& operator<<(ostream& output, const matriz& m1)
{
for(int i = 0; i< m1.nL();i++)
{
for (int j=0;j<m1.nC();j++)
output << m1[i][j] << " ";
output << "\n";
}
return output;
}
| Fixing the array resize as 463035818_is_not_a_number suggested gives you a somewhat working matrix.
matriz(int L, int C): iLargura (L), iComprimento (C)
{
m.resize(L);
for (int i = 0; i<L;i++)
m[i].resize(C);
};
If you also print the matrixes a and b you get:
a:
1 1 1
1 1 1
1 1 1
b:
2 2 2
2 2 2
2 2 2
a+b:
3 0 0
3 0 0
3 0 0
So setting and printing matrixes works just fine. The error is in the operator +:
matriz operator+(const matriz& m1, const matriz& m2)
{
int C1 = m1.nC();
int L1 = m1.nL();
matriz m(C1,L1);
for (int i = 0;i<C1; i++)
for (int j = 0;i<L1; i++)
m[i][j] = m1[i][j] + m2[i][j];
return m;
}
specifically:
for (int j = 0;i<L1; i++)
I guess you copy&pasted the previous loop for i and forgot to rename all the variables.
|
72,433,476 | 72,433,841 | how to use a parent class as a parameter in an inherited child class in c++? | it could be not good question and i know i need more time to learn about it
but i'm really wondering how to make it work
here is my code
#include <bits/stdc++.h>
using namespace std;
class Parent{
protected:
int value;
int size;
public:
Parent();
Parent(const Parent &p);
};
Parent::Parent()
{
this->value = 0;
this->size = 0;
}
Parent::Parent(const Parent &p)
{
this->value = p.value;
this->size = p.size;
}
class Child:public Parent{
public:
Child();
Child(const Parent& p);
};
Child::Child()
{
this->value = 0;
this->size = 0;
}
Child::Child(const Parent& p)
{
this->value = ??
this->size = ??
}
as i want to use parent class as a parameter in an inherited child class,
the problem is i can't use p.size or p.value in child class.
is there any way to solve this problem?
thank u for read this.
| This Child(const Parent& p); is not a proper copy constructor. A copy constructor for a class T takes a &T (possibly with CV-qualifier) as argument. In this case it should be Child(const Child& p);.
Furthermore, if we look at https://en.cppreference.com/w/cpp/language/access, then we can see that:
A protected member of a class is only accessible
to the members and
friends of that class;
to the members and friends (until C++17) of
any derived class of that class, but only when the class of the object
through which the protected member is accessed is that derived class
or a derived class of that derived class
So a function in Child that takes a Child as argument has access to that other Childs protected members, but a function that takes a Parent does not have access to that Parents protected members.
For example, if you have a Button and TextBox that both inherit from UIWidget, then the Button can access UIWidget protected members in other Buttons, but not in TextBoxes.
Edit:
If you really want to have a constructor that takes a Parent as argument, then you can do as Roy Avidan suggests in his answer, and do this:
Child::Child(const Parent& p)
: Parent(p) // <- Call the Parent copy constructor
{
// No access to protected members of p here!
}
This works because it calls the copy constructor of Parent with a Parent argument, which means that any access to the protected members of Parent happens in Parent. Note that any access to a protected member of p in the body is an access violation of p.
|
72,433,545 | 72,448,172 | Hook APIs that imported to program by LoadLibrary/GetProcAddress | I know how I can hook functions from the IAT table, but I have a problem with APIs which were imported by calling LoadLibrary/GetProcAddress functions. I want to know exactly how someone could hook those functions. I realize that I should hook the GetProcAddress function but how can I check the parameters that were passsed to that function?
For example, consider a program which is going to include MessageBoxW via LoadLibrary/GetProcAddress, how can I hook that MessageBoxW and then check the parameters that have been passed to it?
I have searched a lot in StackOverflow and Google, but I couldn't find a step-by-step tutorial about this. So, if you have such a tutorial or article, I would be really grateful to read them.
| In order to hook APIs that they are loaded into a binary dynamically with help of LoadLibrary/GetProcAddress, you should intercept return address of the GetProcAddress and name of the functions that passed to it (for example, consider a program try to load MessageBoxA in this way).
In the second step, you should save that original address of MessageBoxA API in a variable like OriginalMessageBoxA.
In the third and final step, you should return address of your modified API (HookedMessageBoxA) to the callee of the GetProcAddress so when the program try to call that address, program redirected to your function. Something like the following one:
VOID* HookedGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
if (std::string(lpProcName).compare("MessageBoxA") == 0)
{
OMessageBoxA = (PMessageBoxA)GetProcAddress(hModule, lpProcName);
return HookedMessageBoxA;
}
else
{
return OGetProcAddress(hModule, lpProcName);
}
}
In that moment, caller will go through your HookedMessageBoxA and you can check parameters that passed to MessageBoxA. As folks said, it is kinda same like normal IAT hook with a minor changes and tricks.
|
72,433,547 | 72,433,836 | C++ "for" loop with a pow function in it gives incorrect results | I'm studying coding basics, and had to make a code that calculates how many levels of a pyramid could be built with blocks available "x", if each level is squared (e.g. 1st=1, 2nd=4, 3rd=9 etc.)
here's what I have so far, and for the life of me, I can't see where I'm wrong, but the code keeps returning a value of 2 more than it should (e.g. x=25 should result in 3 not 5)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i, x, y=0;
cout<< "How many blocks do you have?"<< endl;
cin>> x;
for (i=1; y<=x; i++) {
y=y+pow(i, 2);
} cout<< i <<endl;
return 0;
}
EDIT:
Thanks for the answers. copied and tried them out, the for function seems to be the worse option here, so I ended up using while.
| It is because your for loop works even if next layer is impossible to make and then it increments i once more . That's why your result is bigger by 2 than it should be . Try this:
int tmp;
while(true){
tmp = y+i*i;
if(tmp > x) //check if this layer is possible to create
{
i--; //its impossible , so answer is previous i
break;
}
i+=1;
y = tmp;
} cout<< i <<endl;
|
72,433,667 | 72,434,289 | How to deal: if boost::asio::post is endlessly repeated, when boost::asio::thread_pool destructor is triggered? | I have a class wrapper for boost::asio::thread_pool m_pool. And in wrapper's destructor i join all the threads:
ThreadPool::~ThreadPool()
{
m_pool.join();
cout << "All threads in Thread pool were completed";
}
Also I have queue method to add new task to threadpool:
void ThreadPool::queue(std::function<void()> task, std::string label)
{
boost::asio::post(m_pool, task);
cout << "In Thread pool was enqueued task: " << label;
}
In boost documentation for thread_pool destructor is said:
Automatically stops and joins the pool, if not explicitly done beforehand.
How to deal with the situation when I have boost::asio::post endlessly repeated, when boost::asio::thread_pool destructor is triggered?
Will I got something like an endless thread_pool?
| 1+1 == 2: just remove the join(). As you've noted, that risks blocking indefinitely. You don't want/need that, so why ask for it?
Alternatively, you could manually stop and join the pool. I'd suggest removing the destructor.
|
72,434,281 | 72,435,212 | ZeroMQ pub-sub send last message to new subscribers | Can ZeroMQ Publisher Subscriber sockets be configured so that a newly-connected client always receive last published message (if any)?
What am I trying to do: My message is a kind of system state so that new one deprecates previous one. All clients has to have current states. It works for already connected clients (subscribers) but when the new subscriber appears it has to wait for a new state update that triggers a new message. Can I configure PubSub model to send the state to the client immediately after connection or do I have to use a different model?
| There is an example in
the ZMQ guide called Last Value Caching. The idea is to put a proxy in between that caches the last messages for each topic and forwards it to new subscribes. It uses an XPUB instead of a PUB socket to react on new connections.
|
72,434,416 | 72,435,146 | What's the difference between Radio r = Radio("PSR", 100.8) and Radio("PSR", 100.8)? | I'm new to C++ and trying to understand something. I have this code in my main.cpp:
Radio r = Radio("PSR", 100.8);
or that code:
Radio r("PSR", 100.8);
Both seem to work and doing the same thing. So what's the difference?
| Radio r = Radio("PSR", 100.8); is copy initialization while Radio r("PSR", 100.8); is direct initialization.
C++17
From C++17 due to mandatory copy elison both are the equivalent.
Radio r = Radio("PSR", 100.8); //from C++17 this is same as writing Radio r("PSR", 100.8);
Prior C++17
But prior to C++17, the first case Radio r = Radio("PSR", 100.8); may result in the creation of a temporary using which r is copy initialized. This is because prior to C++17, there was non-mandatory copy elison.
Another thing to note is that if you were to write:
type name(); //this is a function declaration
the above is a declaration for a function named name which has the return type of type and has 0 parameters.
|
72,434,675 | 72,502,244 | How to transform different containers with std library? | Does it exist a way to transform containters of different types using std functions?
QSet<QString> res;
QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
for(const auto& interface : allInterfaces){
res.insert(interface.name());
}
| std::transform can accept different containers. You can see it in the function signature:
template< class InputIt,
class OutputIt,
class UnaryOperation >
OutputIt transform( InputIt first1,
InputIt last1,
OutputIt d_first,
UnaryOperation unary_op );
As you can see there are two template arguments InputIt and OutputIt, so it means they can be different.
Here's an example using std containers:
#include <iostream>
#include <vector>
#include <set>
int main()
{
std::set<int> set = {0, 1, 2, 3 };
std::vector<bool> vec(set.size());
std::transform(set.begin(), set.end(), vec.begin(), [](int v){ return v % 2 == 0; });
for(auto&& e : vec){
std::cout << e << " ";
}
std::cout << std::endl;
}
Live Example
With Qt containers should be something like (I can't verify though)
QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
QSet<QString> res(allInterfaces.size());
std::transform(allInterfaces.begin(), allInterfaces.end(), res.begin(), [](const QNetworkInterface& interface){
return interface.name();
});
|
72,434,731 | 72,435,031 | Why does the compiler try to instantiate the wrong STL template? (BinaryOperation instead of UnaryOperation) | I want to use std::transform with a parallel execution policy. The documentation tells to use the template (2):
template< class ExecutionPolicy,
class ForwardIt1,
class ForwardIt2,
class UnaryOperation >
ForwardIt2 transform( ExecutionPolicy&& policy,
ForwardIt1 first1,
ForwardIt1 last1,
ForwardIt2 d_first,
UnaryOperation unary_op );
My code is as follows, and seems to match the template:
const std::vector<SimulatedBody>& bodies = m_data.back().m_bodies;
std::vector<SimulatedBody> updated_bodies;
std::transform(std::execution::par,
bodies.begin(),
bodies.end(),
std::back_inserter(updated_bodies),
[&](const SimulatedBody& body) {
return body.updated(*quadtree, m_dt, m_force_algorithm_fn);
});
The return type of body.updated is a new SimulatedBody:
SimulatedBody SimulatedBody::updated(
const bh::Node& quadtree, float dt,
const std::function<Vector2d(const Node&, const Body&)>&
force_algorithm_fn = bh::compute_approximate_net_force_on_body) const
However, when I compile, it raises the following error:
/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/pstl/glue_algorithm_impl.h:325:44: error: argument may not have 'void' type
[__op](_InputType __x, _OutputType __y) mutable { __y = __op(__x); },
^
/home/steddy/CLionProjects/barnes-hut/src/simulation/simple_simulator.cpp:35:8: note: in instantiation of function template specialization 'std::transform<const __pstl::execution::parallel_policy &, __gnu_cxx::__normal_iterator<const bh::SimulatedBody *, std::vector<bh::SimulatedBody>>, std::back_insert_iterator<std::vector<bh::SimulatedBody>>, (lambda at /home/steddy/CLionProjects/barnes-hut/src/simulation/simple_simulator.cpp:37:18)>' requested here
std::transform(std::execution::par, bodies.begin(), bodies.end(),
^
From the error, it seems that the compiler it is trying to use the wrong template; in particular, one with a BinaryOperation.
Am I missing something?
I am using gcc version 12.1.1 20220507 (Red Hat 12.1.1-1).
|
My code [...] seems to match the template:
It doesn't:
template< class ExecutionPolicy,
class ForwardIt1,
class ForwardIt2,
class UnaryOperation >
ForwardIt2 transform( ExecutionPolicy&& policy,
ForwardIt1 first1,
ForwardIt1 last1,
ForwardIt2 d_first, // < here
UnaryOperation unary_op );
In the Parameters section, the documentation you linked specifies the beginning of the destination range, parameter d_first, should be a forward iterator:
Type requirements
[...]
ForwardIt1, ForwardIt2, ForwardIt3 must meet the requirements of LegacyForwardIterator.
You're passing it an output iterator, i.e.:
std::back_inserter(updated_bodies)
If SimulatedBody is default constructible, you may resize updated_bodies to the size of bodies and pass updated_bodies.begin() (which is a random-access iterator, hence a forward iterator too) to std::transform:
const std::vector<SimulatedBody>& bodies = m_data.back().m_bodies;
std::vector<SimulatedBody> updated_bodies;
updated_bodies.resize(bodies.size()); // Resize output vector
std::transform(std::execution::par,
bodies.begin(),
bodies.end(),
updated_bodies.begin(), // Pass iterator to first element
[&](const SimulatedBody& body) {
return body.updated(*quadtree, m_dt, m_force_algorithm_fn);
});
|
72,434,897 | 72,435,847 | Enforcing a common interface with std::variant without inheritance | Suppose you have some classes like Circle, Image, Polygon for which you need to enforce a common interface that looks like this (not real code):
struct Interface {
virtual bool hitTest(Point p) = 0;
virtual Rect boundingRect() = 0;
virtual std::string uniqueId() = 0;
}
so for example the Circle class would like:
struct Circle {
// interface
bool hitTest(Point p) override;
Rect boundingRect() override;
std::string uniqueId() override;
double radius() const;
Point center() const;
// other stuff
}
I would like to use std::variant<Circle, Image, Polygon> to store instances of my classes in a std::vector and then use it like this:
using VisualElement = std::variant<Circle, Image, Polygon>;
std::vector<VisualElement> elements;
VisualElement circle = MakeCircle(5, 10);
VisualElement image = MakeImage("path_to_image.png");
elements.push_back(circle);
elements.push_back(image);
auto const &firstElement = elements[0];
std::cout << firstElement.uniqueId() << std::endl;
Using inheritance I could do this by creating a base class and then each of my classes would become a subclass of the base (and obviously if a derive class doesn't implement the interface the program wouldn't compile). Then instead of using variants, I could use smart pointers to store the instances in a vector (e.g. std::vector<std::unique_ptr<BaseElement>>). I would like to avoid this, so I'm wondering what would be the best way (if there is any) to enforce the same design using std::variant and C++20.
| The simplest and quite execution time optimal solution is have separate container for each type. Any example showing that Data Oriented Design is better then Object Oriented Programing is using this approach to show difference in performance.
Other way is to create some wrapper for variant:
class VisualElement
{
BaseElement* self;
std::variant<Circle, Image, Polygon> item;
public:
template<typename T, bool = std::is_base_of_v<BaseElement, T>>
VisualElement(const &T other) {
item = other;
self = &item.get<T>();
}
template<typename T, bool = std::is_base_of_v<BaseElement, T>>
VisualElement& operator=(const &T other) {
item = other;
self = &item.get<T>();
return *this;
}
bool hitTest(Point p) {
return self->hitTest(p);
// or use of std::visit and drop common interface ancestor.
}
Rect boundingRect() {
return self->boundingRect();
}
std::string uniqueId() {
return self->uniqueId();
}
};
|
72,435,013 | 72,435,428 | Why bind function does not work with dereferencing iterator? | I am new to c++ programming. I am using bind function to bind an object with class setter and call the setter. When I try to dereference the iterator as the object in the bind function, the object variable does not change. However, when I just pass in the iterator as the object in bind function, it works. Can anyone please explain to me why is it so?
string name;
char temp;
bool manager;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Employee Name: ", getline(cin, name, '\n');
auto employee = find(employee_list.begin(), employee_list.end(), name);
if (employee != employee_list.end()){
cout << "Change Detail " << endl;
cout << "1. Name" << endl;
cout << "2. Phone" << endl;
cout << "3. Address" << endl;
string choice;
string new_value;
map<string, function<void(string_view)>> subMenu;
do{
cout << "Selection: ", cin >> choice;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "New Value: ", getline(cin, new_value, '\n');
subMenu = {
{"1", bind(&Employee::set_name, *employee, new_value)},
{"2", bind(&Employee::set_phone, *employee, new_value)},
{"3", bind(&Employee::set_address, *employee, new_value)}
};
if(subMenu.find(choice) == subMenu.end()){
cout << "\nSelection Not Found\n" << endl;
}
}
while (subMenu.find(choice) == subMenu.end());
auto selection = subMenu.find(choice)->second;
selection(new_value);
cout << "Operation complete" << right << endl;
}
Setter functions:
void Employee::set_name(std::string_view p_name){
std::cout << "Set Name: " << std::endl;
std::cout << "Old value: " << name << std::endl;
name = p_name;
std::cout << "New value: " << name << std::endl;
}
void Employee::set_phone(std::string_view p_phone){
phone = p_phone;
}
void Employee::set_address(std::string_view p_address){
address = p_address;
}
When I try to use *employee, it does not change the variable of the object. However, when I just pass in the iterator (employee) returned by find function, it works and I don't understand that.
I know I can easily do this with if/else statement but I want to learn more on c++.
| As stated in the std::bind page on cpprefrence:
The arguments to bind are copied or moved, and are never passed by reference unless wrapped in std::ref or std::cref.
If you want to change the objects pointed to by *employee, you should wrap them in a std::reference_wrapper, e.g. by means of helper function std::ref:
subMenu = {
{"1", bind(&Employee::set_name, std::ref(*employee), new_value)},
{"2", bind(&Employee::set_phone, std::ref(*employee), new_value)},
{"3", bind(&Employee::set_address, std::ref(*employee), new_value)}
};
|
72,435,144 | 72,436,561 | Control may reach end of non-void fct in recursive function | I know why and whats happening for this error. Mainly bc the return in inside the if. However Id like to fix the flow so its error/warning free.
Ive added inconsequential returns at the end as well as modifying the flow the best I could but with no luck.
int modifiedbinsearch_low(int* arr, int low, int high , int key){
if(low==high) return high ;
int mid = low + (high-low) /2;
if(key > arr[mid] ) { modifiedbinsearch_low(arr,mid + 1 , high,key); }
else { modifiedbinsearch_low(arr,low,mid,key); }
}
int modifiedbinsearch_high(int* arr, int low, int high , int key){
if(low==high) return high ;
int mid = low + (high-low) /2;
if(key < arr[mid] ) { modifiedbinsearch_high(arr,low,mid,key); }
else { modifiedbinsearch_high(arr,mid+1,high,key); }
}
int low = modifiedbinsearch_low( ...)
int high = modifiedbinsearch_high( ...)
| The both functions return nothing when the control is reached if statements
if(key > arr[mid] ) { modifiedbinsearch_low(arr,mid + 1 , high,key); }
else { modifiedbinsearch_low(arr,low,mid,key); }
and
if(key < arr[mid] ) { modifiedbinsearch_high(arr,low,mid,key); }
else { modifiedbinsearch_high(arr,mid+1,high,key); }
By the way the both functions have redundant parameters. For example it is enough to declare the function modifiedbinsearch_low the following way
int * modifiedbinsearch_low( int* arr, size_t n , int key);
That is similarly to the standard algorithm std::lower_bound and std::upper_bound the functions should return a pointer instead of a value of the type int.
If to call the function like for example
auto first = modifiedbinsearch_low( arr, n, key );
auto last = modifiedbinsearch_high( arr, n, key );
then the pair first-last shall determine the range [first, last) where elements with the value key are stored in the array.
I would declare and define the function the following way as it is shown in the demonstration program below
#include <iostream>
#include <iterator>
int main()
{
int a[] = { 1, 2, 2, 2, 3 };
auto first = modifiedbinsearch_low( a, std::size( a ), 2 );
auto last = modifiedbinsearch_high( a, std::size( a ), 2 );
for (; first != last; ++first)
{
std::cout << *first << ' ';
}
std::cout << '\n';
}
The program output is
2 2 2
If you want that the function would return indices instead of pointers then they can look the following way as it is shown in the next demonstration program.
#include <iostream>
#include <iterator>
size_t modifiedbinsearch_low( const int a[], size_t n, int key )
{
if (n == 0)
{
return n;
}
else if (a[n / 2] < key)
{
return n / 2 + 1 + modifiedbinsearch_low( a + n / 2 + 1, n - n / 2 - 1, key );
}
else
{
return modifiedbinsearch_low( a, n / 2, key );
}
}
size_t modifiedbinsearch_high( const int a[], size_t n, int key )
{
if (n == 0)
{
return n;
}
else if (key < a[n / 2])
{
return modifiedbinsearch_high( a, n / 2, key );
}
else
{
return n / 2 + 1 + modifiedbinsearch_high( a + n / 2 + 1, n - n / 2 - 1, key );
}
}
int main()
{
int a[] = { 1, 2, 2, 2, 3 };
auto first = modifiedbinsearch_low( a, std::size( a ), 2 );
auto last = modifiedbinsearch_high( a, std::size( a ), 2 );
for (; first != last; ++first)
{
std::cout << a[first] << ' ';
}
std::cout << '\n';
}
The program output is the same as shown above
2 2 2
If your compiler does not support the function std::size then this expression std::size( a ) you may rewrite like sizeof( a ) / sizeof( *a ).
|
72,435,397 | 72,455,108 | How to get date (day/month/year) from MonthCalendar in C++ Builder 6? | I'm creating an age counter app, but I couldn't use the date, which is user chose from the calendar. How can I use the day/month/year specified in MonthCalendar in my program?
| TMonthCalendar has a Date property, which returns the user's selected date as a TDateTime value. You can extract the individual month, day, and year values from that, if needed, by using the TDateTime::DecodeDate() method.
TDateTime dtSelected = MonthCalendar1->Date;
Word wYear, wMonth, wDay;
dtSelected.DecodeDate(&wYear, &wMonth, &wDay);
...
|
72,435,574 | 72,435,695 | Thread leak detected when using condition variable instead of join() with pthread | I'm new to pthread synchronization, searched "pthread condition variable" in google and grab an example from the pdf: https://pages.cs.wisc.edu/~remzi/OSTEP/threads-cv.pdf .
The example code is as follow, whose purpose is "use condition variable and a variable done to implement pthread_join()" (as I understand):
// https://godbolt.org/z/8rPMq54K8
#include <stdio.h>
#include <pthread.h>
volatile int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
void thr_exit() {
pthread_mutex_lock(&m);
done = 1;
pthread_cond_signal(&c);
pthread_mutex_unlock(&m);
}
void *child(void *arg) {
printf("child\n");
thr_exit();
return NULL;
}
void thr_join() {
pthread_mutex_lock(&m);
while (done == 0)
{
pthread_cond_wait(&c, &m);
}
pthread_mutex_unlock(&m);
}
int main(int argc, char *argv[])
{
printf("parent: begin\n");
pthread_t p;
pthread_create(&p, NULL, child, NULL);
thr_join();
printf("parent: end\n");
return 0;
}
Compiled with:
clang++ main.cpp -fsanitize=thread -g -fno-omit-frame-pointer
Running it will see "thread leak" reported:
(base) ➜ case12 git:(main) ✗ ./a.out
a.out(71120,0x10433c580) malloc: nano zone abandoned due to inability to preallocate reserved vm space.
parent: begin
child
parent: end
==================
WARNING: ThreadSanitizer: thread leak (pid=71120)
Thread T1 (tid=1365892, finished) created by main thread at:
#0 pthread_create <null>:74364228 (libclang_rt.tsan_osx_dynamic.dylib:arm64e+0x2bbe8)
#1 main main_v4.cpp:31 (a.out:arm64+0x100003e38)
SUMMARY: ThreadSanitizer: thread leak main_v4.cpp:31 in main
==================
ThreadSanitizer: reported 1 warnings
Is this C++ code really a thread leak, or just a false positive report from tsan?
|
Is this C++ code really a thread leak, or just a false positive report from tsan?
It is really a thread leak, arising from the fact that you cannot implement a substitute for pthread_join(). At least, not in any portable way or based only on the C++ (or C) and pthreads specifications. The program starts a thread and neither detaches nor joins it before terminating. That's a thread leak.
The program does successfully and reliably wait to terminate until the child thread provides evidence that it has called thr_exit(), but that is not a substitute for joining the child thread.
|
72,435,683 | 72,435,863 | std::any_cast without needing the type of the original object | Is it possible to use std::any_cast without putting in the first template argument (the type of the object the any is covering)? I tried using any_cast<decltype(typeid(toCast).name())> but it didn't work.
Also tried to store the objects types from the beginning, but that also didn't work because variables can't store types.
| One of the fundamentals principles of C++ is that the types of all objects are known at compile time. This is an absolute rule, and there are no exceptions.
The type of the object in question is std::any. It is convertible to some other type only if that type is also known at compile time.
You will note that std::type_info::name() is not a constexpr expression. The returned string is known only at run time. You are attempting to cast something to an object whose type would only be known at run time. C++ does not work this way.
In general, whenever such a situation occurs, nearly all the time the correct solution will involve virtual methods getting invoked on a base class. You will likely need to redesign your classes to use inheritance and virtual methods; using their common base class instead of std::any; then invoking its virtual methods. In some situations std::variant may also work, too.
|
72,435,684 | 72,435,725 | Reference to object method | I would like to have a reference to the call of an object's method. Is this possible in C++? What is the technical name I should be searching for? Can we supply some arguments with predetermined values?
The following code highlights what I would like to use
struct Foo {
void barNoArgs();
void barMultArgs(int, float, bool);
};
Foo f;
auto& refToBarNoArgs = f.barNoArgs;
refToBarNoArgs(); // should call f.barNoArgs()
auto& refToBarMultArgs = f.barMultArgs(?, 3.14f, ?);
refToBarNoArgs(42, true); // should call f.barMultArgs(42, 3.14f, true)
|
What is the technical name I should be searching for?
This is called Argument Binding, or sometimes a Partial Function
But first, you should know that both of your examples are the exact same problem. Methods are essentially functions with a hidden first parameter called this after all.
So refToBarNoArgs is a function taking 0 arguments that calls Foo::barNoArgs with the first argument pre-populated. And refToBarNoArgs is a function that takes 2 arguments, and calls Foo::barMultArgs with the first and third arguments pre-populated, and the second and fourth with its own arguments.
The key point here is that your "reference" can't be a reference in the C++ sense of the term. References don't actually exist (as in there is no object associated with the reference itself). Here, in both cases, we need to store the values of the pre-populated arguments, as well as manage their lifetimes. It has to be an actual object, with storage and lifetime, that behaves like a function. This is called a Functor.
The language provides us with a convenient bit of syntactic sugar to facilitate creating both the type and a single instance of such a functor all at once: Lambdas.
auto refToBarNoArgs = [&f](){f.barNoArgs();};
refToBarNoArgs();
auto refToBarMultArgs = [&f](int i, bool b){f.barMultArgs(i, 3.14f, b);};
refToBarNoArgs(42, true);
If you are not familiar with lambdas, be wary of the [&f] in my examples. It means that the lambda captures f by reference. Because of this, they should not be allowed to live (for example, stored in an std::function<>) longer than the lifetime of f.
You can also use std::bind to get effectively the same thing. In fact, the end result is very close to your original code:
#include <functional>
struct Foo {
void barNoArgs();
void barMultArgs(int, float, bool);
};
int main() {
using namespace std::placeholders; // for _1, _2, _3...
Foo f;
auto refToBarNoArgs = std::bind(&Foo::barNoArgs, &f);
refToBarNoArgs();
auto refToBarMultArgs = std::bind(&Foo::barMultArgs, &f, _1, 3.14f, _2);
refToBarNoArgs(42, true);
}
Personally, I find lambdas much clearer.
|
72,435,808 | 72,435,986 | Why is this recursive selection sort not working | I tried to run the code but it just gets stuck. NO error no warning nothing.Is there a better way to write a recursive selection sort?
#include <iostream>
using namespace std;
void scan(int *arr, int size){
for(int i = 0; i < size; i++){
cin >> arr[i];
}
}
void print(int *arr, int size){
for(int i = 0; i < size; i++){
cout << arr[i] << " ";
}
cout << "\n";
}
void swap(int *p1, int *p2){
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void insertion(int *arr, int size){
if(size <= 1)return;
int i, max = size - 1;
for(int i = 0; i < size; i++){
if(arr[i] > arr[max])max = i;
}
swap(&arr[max], &arr[i]);
insertion(arr, size - 1);
}
int main(){
int *arr;
int size;
cout << "Enter the size of the array - ";
cin >> size;
arr = (int*)malloc(size*sizeof(int));
cout << "Enter the elements of the array - ";
scan(arr, size);
print(arr, size);
insertion(arr, size);
print(arr, size);
}
I feel like there is something wrong with the base case of the recursion. How do you generally solve these types of problems.
| There was 1 small problem in your code. When you call the swap function in the insertion function you have to call it with &arr[max] and &arr[size-1], you can also use i-1, as the value of i is size here.
Code Attached for insertion function
void insertion(int *arr, int size){
if(size <= 1)return;
int i, maxIndex = 0;
for(i = 0; i < size; i++){
if(arr[i] > arr[maxIndex]) maxIndex = i;
}
swap(&arr[maxIndex], &arr[size-1]);
insertion(arr, size - 1);
}
The way to debug are many, you can learn to use the gnu debugger which is gdb or use print statements to find out where your code is going wrong.
|
72,435,912 | 72,448,008 | Windows gcp List objects fails - Curl error [77] | Trying to list all object in a google storage bucket - this code runs fine in UNIX systems(centos 7/Mac), However when run from a windows server 2012/16 Vm I get Permanent error in ListObjects : EasyPerform() - CURL error [77]=Problem with the SSL CA cert (path? access rights?)[UNKNOWN]
void gcpFileDialog::getListOfObjectsInBucket()
{
QString bucket = "exampleBucketName";///_gcpBucketLineEdit->text();
if ((bucket.isNull()) || (bucket.isEmpty()))
{
QMessageBox::critical(this, tr("Error"), tr("GCP Bucket is invalid"));
return;
}
namespace gcs = ::google::cloud::storage;
// Create a client to communicate with Google Cloud Storage. This client
// uses the default configuration for authentication and project id.
google::cloud::StatusOr<gcs::ClientOptions> options = gcs::ClientOptions::CreateDefaultClientOptions();
google::cloud::StatusOr<gcs::Client> client = gcs::Client::CreateDefaultClient();
if (!client)
{
QMessageBox::critical(this, tr("Error"), tr("Failed to create Storage Client.\n\n%1").arg(QString::fromStdString(client.status().message())));
return;
}
QStringList objectsInBucketList;
for (auto&& object_metadata : client->ListObjects(bucket.toStdString()))
{
if (!object_metadata)
{
QMessageBox::critical(this, tr("Error"), tr("There was an Error listing the objects.\n\n%1").arg(QString::fromStdString(object_metadata.status().message())));
client->ListObjects
return;
}
objectsInBucketList.append(QString::fromStdString(object_metadata->name()));
}
if (objectsInBucketList.isEmpty())
{
QMessageBox::critical(this, tr("Error"), tr("No Objects found in bucket"));
return;
}
for (QString& object : objectsInBucketList)
{
///list of bucket object _gcpBucketObjectListTextEdit->append(object);
}
}
I know next to nothing about curl / open ssl certificates (I don't believe this is related to the google managed ssl certificates either)
I have used Choco to install openssl and curl on the host vm and added a lot of server roles and features.
The command works when called from Google Cloud SDK Shell - GSUTIL
Any help tracking down the issue would be greatly appreciated.
| I think you need to install the certificate bundles as described in:
https://curl.se/docs/sslcerts.html
With newer versions of google-cloud-cpp you can use CARootsFilePathOption to override the default location of the CA cert file.
|
72,436,303 | 72,438,175 | I get no sound in Game in UE 5 | Same project ToonTanks had sound normally in UE4 but when I migrated to UE5 there is no projectile sound.
In projectile.h I declare a sound like this
UPROPERTY(EditAnywhere, Category="combat")
USoundBase* LaunchSound;
and I set it in the blueprint then in projectile.cpp BeginPlay I play the sound like this
if (LaunchSound) {
UGameplayStatics::PlaySoundAtLocation(this, LaunchSound, GetActorLocation());
}
Editor output sound normally when I press on the stop button also I tried FPS demo it has sound in game normally. I debugged this game and the execution go inside if but no sound. Any advise ?
| Fixed using these steps:
1-Delete the folder Intermediate
2-Right click the uproject file and select generate vs files
3-open rider and choose for ex development editor build
4-wait until rider update source files
5-build from rider
6-open UE5 editor and run and sound work as expected.
|
72,436,604 | 72,437,204 | Visual Studio compiling to wrong path AND trying to run wrong path when used with CMake | I'm very new to CMake (and new to C++ too, although that shouldn't matter here), and I am having a problem using CMake with Visual studio.
I have created a directory, let's say it's called Project, and put in it a simple project with the following structure:
Project/
build/ <empty>
src/
main.cpp
CMakeLists.txt
CMakePresets.json
Inside these files is just the most basic, default code:
CMakeLists.txt:
cmake_minimum_required (VERSION 3.8)
project (Project)
set (CMAKE_CXX_STANDARD 20)
set (CMAKE_CXX_STANDARD_REQUIRED True)
add_executable (Project src/main.cpp)
CMakePresets.json (this code is just the default that was generated):
{
"version": 3,
"configurePresets": [
{
"name": "windows-base",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/out/build/${presetName}",
"installDir": "${sourceDir}/out/install/${presetName}",
"cacheVariables": {
"CMAKE_C_COMPILER": "cl.exe",
"CMAKE_CXX_COMPILER": "cl.exe"
},
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
}
},
{
"name": "x64-debug",
"displayName": "x64 Debug",
"inherits": "windows-base",
"architecture": {
"value": "x64",
"strategy": "external"
},
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
},
{
"name": "x64-release",
"displayName": "x64 Release",
"inherits": "x64-debug",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release"
}
},
{
"name": "x86-debug",
"displayName": "x86 Debug",
"inherits": "windows-base",
"architecture": {
"value": "x86",
"strategy": "external"
},
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
},
{
"name": "x86-release",
"displayName": "x86 Release",
"inherits": "x86-debug",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release"
}
}
]
}
src/main.cpp:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
Then, I have used CMake to create a Visual Studio solution:
C:\...\Project\build> cmake ..
This has worked fine without any errors, and Visual Studio can open the solution. It can also build the project correctly...
But it cannot run the executable which it has built. After successfully building the project, it has written the executable to C:\...\Project\build\Debug\Project.exe, but it tries to open C:\...\Project\build\x64\Debug\ALL_BUILD instead, and I get an error popup.
I gather that there are two things wrong here:
The executable file should be written within the C:\...\Project\build\x64\Debug folder, not just the C:\...\Project\build\Debug folder. This is how it has worked whenever I have used Visual Studio before, and this is the folder it is trying to search in.
It should be searching for an executable called Project.exe, not one called ALL_BUILD.
When I run Project.exe manually from the command line, it works fine. But I cannot seem to make Visual Studio run it correctly.
What have I done wrong here, and how can I get this to work?
| Default project is set to ALL_BUILD to change the default for the VS generators use the following CMake statement:
set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT Project)
Anywhere after the add_executable command.
|
72,436,671 | 72,436,961 | ADSI GetInfoEx not retrieving mail attribute | I can't get the Win32 ADSI c++ GetInfoEx API to retrieve the an AD user's mail attribute.
The Get call instead returns hr 0x8000500D (E_ADS_PROPERTY_NOT_FOUND).
Any ideas of how I can get the get the mail attribute? Here's my code.
HRESULT hr = CoInitialize(NULL);
if (hr == S_OK || hr == S_FALSE)
{
IADs *pUsr = NULL;
hr = ADsGetObject(L"WinNT://adomainname/ausername,user", IID_IADs, (void**)&pUsr);
if (SUCCEEDED(hr))
{
VARIANT var;
VariantInit(&var);
LPWSTR pszAttrs[] = { L"mail" };
DWORD dwNumber = sizeof(pszAttrs) / sizeof(LPWSTR);
HRESULT hrAry = ADsBuildVarArrayStr(pszAttrs, dwNumber, &var);
hr = pUsr->GetInfoEx(var, 0);
VariantClear(&var);
if (SUCCEEDED(hrAry) && SUCCEEDED(hr))
{
hr = pUsr->Get(CComBSTR("mail"), &var);
if (SUCCEEDED(hr))
{
printf("mail: %S\n", V_BSTR(&var));
VariantClear(&var);
}
}
if (pUsr)
pUsr->Release();
}
CoUninitialize();
}
| The mail attribute is not available when using the WinNT provider: Unsupported IADsUser Properties
You have to use LDAP.
If you have the distinguishedName of the account, you can use that:
hr = ADsGetObject(L"LDAP://CN=someuser,OU=Users,DC=example,DC=com", IID_IADs, (void**)&pUsr);
If all you have is the domain and username, then you can use LDAP://adomainname and search domain for the username with the filter:
(&(objectClass=user)(objectCategory=person)(sAMAccountName=ausername))
Or you can use IADsNameTranslate to translate the domain\username (ADS_NAME_TYPE_NT4) into the distinguished name (ADS_NAME_TYPE_1779).
|
72,437,210 | 72,441,224 | How to call derived destructor using my custom shared pointer class without virtual destructor? | I am creating my custom shared pointer class and I want my shared pointer class should call derived class destructor when it goes out of scope for the below code.
...
...
template<class T>
MySharedPtr<T>::MySharedPtr(T * p) : ptr(p), refCnt(new RefCount())
{
refCnt->AddRef();
}
template<class T>
void MySharedPtr<T>::release()
{
if (refCnt->Release() == 0)
{
delete ptr;
delete refCnt;
}
ptr = nullptr;
refCnt = nullptr;
}
...
...
Base class destructor called when it goes out of scope but if I use std::shared_ptr<Base> bptr(new Derived());, it calls derived destructor and base destructor when it goes out of scope. How can I achieve the same behaviour with my custom class?
class Base
{
public:
Base() {
cout << "Base default constructor" << endl;
}
~Base() {
cout << "Base destructor" << endl;
}
virtual void display() {
cout << "in Base" << endl;
}
};
class Derived : public Base
{
public:
Derived() {
cout << "Derived default constructor" << endl;
}
~Derived() {
cout << "Derived destructor" << endl;
}
virtual void display() {
cout << "in Derived" << endl;
}
};
int main()
{
MySharedPtr<Base> bptr(new Derived());
bptr->display();
}
| You can store a callback as part of the RefCount object which will be called when the reference count goes to zero. This callback can "remember" what it needs to do based on the pointer type that was used to originally construct the MySharedPtr object, even though the knowledge of that most derived type might have been lost elsewhere.
You must modify the constructor of MySharedPtr so that the type information is not immediately destroyed when the constructor is called. It needs to take U*, not T*. If it takes T*, then as soon as the constructor is entered, you already don't know what the original argument type was, since it has been converted to T*.
template <class T>
class MySharedPtr {
public:
template <class U>
MySharedPtr(U* p);
// ...
};
template <class T>
template <class U>
MySharedPtr<T>::MySharedPtr(U* p) : ptr(p), refCnt(new RefCount(p))
{
refCnt->AddRef();
}
The RefCount constructor needs to set up the stored callback based on this pointer:
class RefCount {
public:
template <class U>
RefCount(U* p) : deleter_{[p]{ delete p; }} {}
// ...
void invoke_deleter() { deleter_(); }
private:
int ref_count_ = 0;
std::function<void()> deleter_;
};
So now, if you do:
MySharedPtr<Base> bptr(new Derived());
the Derived* will be passed to the RefCount constructor, and it will store a callback that calls delete on that pointer (of type Derived*) and not the ptr stored in the MySharedPtr, which is of type Base*.
You need to add the code to invoke this deleter when the ref count goes to 0:
template<class T>
void MySharedPtr<T>::release()
{
if (refCnt->Release() == 0)
{
refCnt->invoke_deleter();
delete refCnt;
}
ptr = nullptr;
refCnt = nullptr;
}
This is basically how std::shared_ptr works, although I suspect it doesn't use std::function internally, but some custom type erasure mechanism with lower overhead since it doesn't need to support most std::function features.
|
72,437,284 | 72,437,685 | Alternatives for CMake commands | I am new to CMake and was going through the CMake documentations and tutorials. I was able to understand that the target_include_directories command is just the -I option for the compiler (gcc for me). I tried doing it adding the directories manually by using set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I <Path>") and it worked perfectly fine!!
My CMakeLists.txt looks something like this:
cmake_minimum_required(VERSION 3.6)
project(Project VERSION 1.0 DESCRIPTION "C Project" LANGUAGES C)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I <path-to-header>")
add_library(basic file1.c file2.c)
#target_include_directories(basic PUBLIC "path-to-header")
#target_include_directories() is commented out as CMAKE_C_FLAGS have been set
add_executable(main.out main.c)
target_link_libraries(main.out PRIVATE basic)
I wanted to know if there any similar and alternative for the target_link_libraries command using which we can pass -L and -l options to linker in CMake??
| To answer your question literally: There is the variable CMAKE_EXE_LINKER_FLAGS and its specializations CMAKE_EXE_LINKER_FLAGS_<CONFIG> for certain configurations like RELEASE or DEBUG or whatever configurations you might have defined. See the CMake documentation for more.
BUT, I highly disrecommend to use these unless you need to pass a very special compiler/linker option CMake does not know about, because these are specific to your compiler.
The point of using CMake is to describe the build process independent of the concrete compiler and platform, such that you can easily switch to another one or at least update your compiler without having to refactor your build code. So, better stick with the generic target_include_directories, target_link_libraries, and similar commands as much as possible.
If you really have to use CMAKE_C_FLAGS or CMAKE_EXE_LINKER_FLAGS I'd recommend to wrap them into an if clause making sure that you are building with the expected compiler on the expected platform and put a fatal error message into the else clause to make future users aware of a possible problem.
|
72,437,379 | 72,442,710 | Win32:Does ImageList_ReplaceIcon failed with unproper ImageList_Create | As the title says, I'm trying to write a simple window program, but when I try to change the icon of my TreeView, it goes wrong. I'm pretty sure my icon was loaded because I did this:
HICON hIcon;
//hinst is my global variable
hIcon = LoadIcon(hinst,(char*)IDI_ICON_MAIN);
if (hIcon == NULL)
{
MessageBox(NULL, "LoadIcon failed", "error", MB_OK);
}
It works fine then I use ImageList_ReplaceIcon():
if (ImageList_ReplaceIcon(iml, 3, hIcon) == -1)
{
MessageBox(NULL, "replace icon failed", "error", MB_OK);
}
TreeView_SetImageList(hwndTV, iml, TVSIL_STATE);
First, I thought, maybe it's because I gave the wrong ILC_COLOR in ImageList_Create(), then I rechecked the bit of my icon then reset the parameter, but it's still not working.
Can anyone give me some clue of what is wrong? I already checked with Google and read the docs mutiple times, perhaps I missed something?
UPDATE [2022/05/31]
Here is my TreeView:
I'm tring to change my icon to the red circle.
| I can see my icon now, thanks. I appreciate those who gave me advice.
ReplaceIcon() can only be used when I have already added an icon into it. If there's no icon in it then the only condition I can use is to set the index to -1, so that the ReplaceIcon() can add the icon for me.
|
72,437,399 | 72,437,483 | why do we need a reference count in this Reentrant lock example? | Why do we need m_refCount in the example below? What would happen if we leaved it out and also removed the if statement and just left its body there ?
class ReentrantLock32
{
std::atomic<std::size_t> m_atomic;
std::int32_t m_refCount;
public:
ReentrantLock32() : m_atomic(0), m_refCount(0) {}
void Acquire()
{
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
// if this thread doesn't already hold the lock...
if (m_atomic.load(std::memory_order_relaxed) != tid)
{
// ... spin wait until we do hold it
std::size_t unlockValue = 0;
while (!m_atomic.compare_exchange_weak(
unlockValue,
tid,
std::memory_order_relaxed, // fence below!
std::memory_order_relaxed))
{
unlockValue = 0;
PAUSE();
}
}
// increment reference count so we can verify that
// Acquire() and Release() are called in pairs
++m_refCount;
// use an acquire fence to ensure all subsequent
// reads by this thread will be valid
std::atomic_thread_fence(std::memory_order_acquire);
}
void Release()
{
// use release semantics to ensure that all prior
// writes have been fully committed before we unlock
std::atomic_thread_fence(std::memory_order_release);
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
std::size_t actual = m_atomic.load(std::memory_order_relaxed);
assert(actual == tid);
--m_refCount;
if (m_refCount == 0)
{
// release lock, which is safe because we own it
m_atomic.store(0, std::memory_order_relaxed);
}
}
bool TryAcquire()
{
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
bool acquired = false;
if (m_atomic.load(std::memory_order_relaxed) == tid)
{
acquired = true;
}
else
{
std::size_t unlockValue = 0;
acquired = m_atomic.compare_exchange_strong(
unlockValue,
tid,
std::memory_order_relaxed, // fence below!
std::memory_order_relaxed);
}
if (acquired)
{
++m_refCount;
std::atomic_thread_fence(
std::memory_order_acquire);
}
return acquired;
}
};
EDIT: Example is from a book called "Game engine architecture 3rd edition" by Jason Gregory
| The count is needed to implement recursive locking. If it were not there, Release would always unlock no matter how many Acquire calls there were, that is not what you expect and want in many cases.
Consider the following common pattern:
void helper_method(){
Acquire();
// Work #2
Release();
}
void method(){
Acquire();
// Work #1
helper_method();
// Work #3
Release();
}
One has to be careful if the lock is not recursive. In that case #3 is no longer called under lock and you now have a hard to trace bug. It happens just because Release() in helper_method unlocked the lock, doing so in good faith because it locked it in the first place, not knowing it was already locked before.
This is also the reason why there are std::mutex and std::recursive_mutex, locking the former twice is UB (will often deadlock in my experience).
|
72,437,676 | 72,437,859 | Overriding only some virtual funtion of base class with the same name | I have a base class with a virtual fonction foo(int i) and foo() (same name, not same arguments).
The derived class override only foo().
Now the derived class doesn't knows foo(int i) anymore.
class Base
{
public:
virtual void foo(int i) {
std::cout << "Base::foo(int i)" << std::endl;
}
virtual void foo() {
std::cout << "Base::foo()" << std::endl;
};
};
class Derived : public Base
{
public:
void foo() override {
std::cout << "Derived::foo()" << std::endl;
}
};
int main(const int ac, const char* const av[])
{
Base base;
base.foo();
base.foo(42);
Derived derived;
derived.foo();
derived.foo(42);//ERROR : Function unknown
}
Should output :
Base::foo()
Base::foo(int i)
Derived::foo()
Base::foo(int i)
Where does the problem come from and what would be the solutions?
The derived class will sometimes override foo(), sometimes foo(int i) and sometimes both.
Note
If I go through the base class it works, but this solution is not ideal in my program :
Derived derived;
Base* pBase = &derived;
pBase->foo();
pBase->foo(42); //WORK
Edit
Okay, I found on geeksforgeeks.org that you need to use using Base::foo; in derivate class to import other foo functions.
Someone know why and what's going one in the backgourd? I don't like to not understand somethings.
| Just add a using declaration inside derived class as shown below. In particular, a using declaration for a base-class member function (like foo) adds all the overloaded instances of that function to the scope of the derived class. Now you can override the version that takes an argument of type int and use the implementation of others that were added in the derived class' scope using the using declaration.
class Derived : public Base
{
public:
//added this using declaration
using Base::foo;
void foo() override {
std::cout << "Derived::foo()" << std::endl;
}
};
Working demo
The output of the above modified program is as you wanted:
Base::foo()
Base::foo(int i)
Derived::foo()
Base::foo(int i)
|
72,437,818 | 72,439,230 | Traverse 2D Matrix diagonally omitting first row and first column | I am trying to traverse a 2D matrix diagonally and the function below prints all elements in a diagonal.I want to skip the first row and first column elements and start the diagonal traversal from matrix[1][1] because the values in the 0th row and 0th column are not required.So it is like slicing the matrix from the top and starting from [1][1] but not making any changes to the bottom of the matrix.
void diagonalOrder(int matrix[][COL])
{
for(int line = 1;
line <= (ROW + COL - 1);
line++)
{
int start_col = max(0, line - ROW);
int count = min(line, (COL - start_col), ROW);
/* Print elements of this line */
for(int j = 0; j < count; j++)
cout << setw(5) <<
matrix[minu(ROW, line) - j - 1][start_col + j];
cout << "\n";
}
I will update my question with an example to make it clear.Consider the following matrix.
0 1 2 3 4
matrix[5][5] = 1 8 5 3 1
2 4 5 7 1
3 6 4 3 2
4 3 4 5 6
The above function will print the values of this diagonally.
Output:
0
1 1
2 8 2
3 4 5 3
4 6 5 3 4
3 4 7 1
4 3 1
5 2
6
I want to skip the elements of the first row and the first column and starting at matrix[1][1] want to traverse the matrix diagonally.
Desired Output:
8
4 5
6 5 3
3 4 7 1
4 3 1
5 2
6
| From your example it looks like you want to print antidiagonals not diagonals, ie third line is 3 4 5 3 not 3 5 4 3.
To get started keep things simple: Indices (i,j) along an antidiagonal are those i and j where i+j == some_constant. Hence this is a simple (not efficient) way to print elements along one antidiagonal:
void print_antidiagonal(int matrix[5][5],int x){
for (int i=4;i >= 0; --i) {
for (int j=0;j < 5; ++j) {
if (i+j == x) std::cout << matrix[i][j] << " ";
}
}
std::cout << "\n";
}
Further there are nrows + (ncols-1) antidiagonals, hence you can print them all via:
for (int i=0;i < 5+4; ++i) {
print_antidiagonal(matrix,i);
}
The function above isnt very efficient, but it is simple. It is obvious how to skip the first row and first column:
for (int i=4;i >= 1; --i) { // loop till 1 instead of 0
for (int j=1;j < 5; ++j) { // loop from 1 instead of 0
This is sufficient to produce desired output (https://godbolt.org/z/7KWjb7qh7). However, not only is the above rather inefficient, but also the code is not very clear about its intent. print_antidiagonal prints elements along a single anti-diagonal, hence iterating all matrix elements is a bad surprise.
I suggest to print the indices rather than the matrix elements to get a better picture of the pattern (https://godbolt.org/z/TnrbbY4jM):
1,1
2,1 1,2
3,1 2,2 1,3
4,1 3,2 2,3 1,4
4,2 3,3 2,4
4,3 3,4
4,4
Again, in each line i+j is a constant. And that constant increments by 1 in each line. In each line i decrements while j increments, until either i == 1 or j==4. The first element is such that i is maximum and j = constant - i.
Hence:
void print_antidiagonal(int matrix[5][5],int x){
int i = std::min(x-1,4);
int j = x - i;
while (i >= 1 && j <= 4) {
std::cout << matrix[i][j] << " ";
--i;
++j;
}
std::cout << "\n";
}
Live Example.
PS: I used hardcoded indices, because I considered it simpler to follow the logic. For a more realistic solution the matrix size and offset should be parametrized of course.
|
72,438,381 | 72,438,966 | How to pass a class member function that modifies class members to a function that takes a function pointer | I am writing software for an Arduino-powered weather station.
I have a class for each of the sensor systems (some simple, some complex) and the rain gauge one needs to use the Arduino attachInterrupt function.
Signature:
void attachInterrupt(uint8_t interruptNum, void (*userFunc)(), int mode)
This is used to execute a callback when a pin changes state, which increment a counter (which is a member variable of the class).
I currently have the following:
// `pulses` and `pin` are member variables.
void RainGauge::begin()
{
pulses = 0;
attachInterrupt(digitalPinToInterrupt(pin), callback, FALLING);
}
I need to somehow define that callback.
I have tried this, without success, due to the capturing aspect:
void RainGauge::begin()
{
pulses = 0;
auto callback = [this](void) {
pulses++;
};
attachInterrupt(digitalPinToInterrupt(pin), callback, FALLING);
}
This gives the error no suitable conversion function from "lambda []()->void" to "void (*)()" existsC/C++(413).
Is there any way to do this?
| The problem is, on what object should the function be invoked when the interrupt occurs?
You could do it this way for example:
class RainGauge {
int pulses;
public:
void begin(int pin, void (*callback)());
void increment();
};
void RainGauge::begin(int pin, void (*callback)())
{
pulses = 0;
attachInterrupt(digitalPinToInterrupt(pin), callback, FALLING);
}
void RainGauge::increment()
{
pulses++;
}
RainGauge RainGauge1;
RainGauge RainGauge2;
void setup() {
RainGauge1.begin(2, []() {RainGauge1.increment();});
RainGauge2.begin(3, []() {RainGauge2.increment();});
}
void loop() {
}
|
72,438,547 | 72,438,917 | C++ linked list input memory not carrying over (Maybe) | I am quite inexperienced at coding so I am not sure what is going on, but I have run my code through godbolt compiler/debugger, and it says that there is a memory leak but I don't know how to solve this problem I do believe the issue is within the void end function though.
GodBolt Link
#include <iostream>
#include <stdio.h>
using namespace std;
class node {
public:
int value = 0;
string month;
node* next;
};
struct NewValues {
long int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
} n;
//function moves newvalues infront of linked list
void AtFront(node** head)
{
node* Dec = new node();
Dec->value = n.c;
Dec->month = "December 2021: $";
Dec->next = *head;
*head = Dec;
node* Nov = new node();
Nov->value = n.b;
Nov->month = "November 2021: $";
Nov->next = *head;
*head = Nov;
node* Oct = new node();
Oct->value = n.a;
Oct->month = "October 2021: $";
Oct->next = *head;
*head = Oct;
}
//puts new values at the end of the linked list
void End(node** head)
{
node* June = new node();
June->value = n.d;
June->month = "June 2022: $";
June->next = NULL;
//if linked list is empty, newnode will be a head node
if (*head == NULL) {
*head = June;
return;
}
//find the last node
node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = June;
node* July = new node();
July->value = n.e;
July->month = "July 2022: $";
July->next = NULL;
last->next = July;
node* Aug = new node();
Aug->value = n.f;
Aug->month = "August 2022: $";
Aug->next = NULL;
last->next = Aug;
}
void sumOfNodes(node* head, long int* sum)
{
// if head = NULL
if (!head)
return;
// recursively traverse the remaining nodes
sumOfNodes(head->next, sum);
// accumulate sum
*sum = *sum + head->value;
}
int sumOfNodesUtil(node* head)
{
long int sum = 0;
// find the sum of nodes
sumOfNodes(head, &sum);
// required sum
return sum;
}
void printList(node* n)
{
cout << "\nList of earnings from October 2021 - August 2022\n" << endl;
while (n != NULL) {
cout << n->month << n->value << endl;
n = n->next;
}
}
int main()
{
node* head = new node();
node* second = new node();
node* third = new node();
node* fourth = new node();
node* fifth = new node();
cout << "There are a total of 6 months unaccounted for.." << endl;
cout << "please enter in the data for the month when prompted" << endl;
cout << "\nOctober 2021: $";
cin >> n.a;
cout << "November 2021: $";
cin >> n.b;
cout << "December 2021: $";
cin >> n.c;
cout << "June 2022: $";
cin >> n.d;
cout << "July 2022: $";
cin >> n.e;
cout << "August 2022: $";
cin >> n.f;
head->value = 500;
head->month = "January 2022: $";
head->next = second;
second->value = 125;
second->month = "Febuary 2022: $";
second->next = third;
third->value = 200;
third->month = "March 2022: $";
third->next = fourth;
fourth->value = 300;
fourth->month = "April 2022: $";
fourth->next = fifth;
fifth->value = 600;
fifth->month = "May 2022: $";
fifth->next = NULL;
AtFront(&head);
End(&head);
printList(head);
long int avg = sumOfNodesUtil(head) / 11;
cout << "\nTotal earnings: $" << sumOfNodesUtil(head) << endl;
cout << "Average: $" << avg << endl;
}
| For every use of new to dynamically allocate memory, you must also use delete to deallocate that memory. You have used new but not delete so you have a memory leak.
When dealing with a linked list, each node links to the next. The trick is that if you delete a node, you've deleted the pointer to the rest of the list, but not the data it points to.
Consider a very basic linked list. (The principle transfers.)
I'm going to give it a constructor for ease of use.
struct Node {
int val;
Node *next;
Node(int v, Node *n=nullptr) : val(v), next(n) { }
};
We can allocate a new node:
Node *head = new Node(42);
And a list with a few items:
Node *head = new Node(42);
head->next = new Node(27);
head->next->next = new Node(13);
Now, if I delete head; I haven't actually deleted the next two nodes. Rather I've destroyed anyway of getting to those to delete them, guaranteeing I'll leak memory.
We can iterate over the list and delete as we go, using temp pointers so we don't lose track of the rest of the list.
Node *head = new Node(42);
head->next = new Node(27);
head->next->next = new Node(13);
Node *temp = head;
while (temp) {
Node * temp2 = temp->next;
delete temp;
temp = temp2;
}
We can integrate this functionality into a destructor.
struct Node {
int val;
Node *next;
Node(int v, Node *n=nullptr) : val(v), next(n) { }
~Node() {
Node *temp = next;
while (temp) {
Node *temp2 = temp->next;
delete temp;
temp = temp2;
}
}
};
With the destructor, the list will clean itself up automatically when going out of scope if it's been automically allocated; or if it's been dynamically allocated with new, we need only delete the head:
Node *head = new Node(42);
head->next = new Node(27);
head->next->next = new Node(13);
delete head;
|
72,438,610 | 72,438,708 | std::map with custom key | I would like to use a standard map with the following custom key:
struct ParserKey{
ParserKey(uint16_t compno,
uint8_t resno,
uint64_t precinctIndex) : compno_(compno),
resno_(resno),
precinctIndex_(precinctIndex)
{
}
uint16_t compno_;
uint8_t resno_;
uint64_t precinctIndex_;
};
There's no obvious way of ordering the keys, though.
Can these keys be ordered, or do I need a different associative collection ?
| If you don't care about the specific order and just want to satisfy the requirements for sorting, a common and simple pattern is to use std::tie with all of the class members of the compared instances, and compare those results instead.
std::tie creates a std::tuple of references to the members, and std::tuple implements operator< which compares its elements (the members of the object in this case) lexicographically.
In your case, using member operator< :
bool operator<(const ParserKey & other) const
{
return std::tie(compno_, resno_, precinctIndex_) <
std::tie(other.compno_, other.resno_, other.precinctIndex_);
}
Live example https://godbolt.org/z/v433v54jz
|
72,438,768 | 72,441,795 | Making guides for function template argument deduction in C++ | Before anyone says that this question is duplicate... I checked the other question and that didn't satisfy me. It was not what I was looking for.
Is it possible to have argument deduction guides for function templates ?
If yes then how ?
It will be appreciated if someone can give easy examples.
Thanks in advance.
| OK I got the answer actually functions can't have deduction guides. It only works with class templates. Thanks for pointing me to the right direction.
|
72,438,852 | 72,439,045 | std::function vs callable as template parameter | In the example below, why line 20 causes the error described from line 27 to 30?
Calling exec1 in line 33 works fine.
#include <cstdint>
#include <functional>
#include <iostream>
#include <tuple>
#include <type_traits>
template <typename... t_fields>
void exec0(std::function<std::tuple<t_fields...>()> generate,
std::function<void(t_fields &&...)> handle) {
std::tuple<t_fields...> _tuple{generate()};
std::apply(handle, std::move(_tuple));
}
template <typename t_generate, typename t_function>
void exec1(t_generate generate, t_function handle) {
auto _tuple{generate()};
std::apply(handle, std::move(_tuple));
}
int main() {
auto _h = [](uint32_t u) -> void { std::cout << "u = " << u << '\n'; };
auto _g = []() -> std::tuple<uint32_t> { return std::tuple<uint32_t>{456}; };
// exec0<uint32_t>(_g, _h);
/*
main.cpp:25:3: error: no matching function for call to 'exec0'
main.cpp:8:6: note: candidate template ignored: could not match
'function<tuple<unsigned int, type-parameter-0-0...> ()>' against '(lambda at
/var/tmp/untitled002/main.cpp:23:13)'
*/
exec1(_g, _h);
return 0;
}
g++ --version replies:
g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
| Even though you specified <uint32_t> as a template argument, the compiler seems to try to deduce more elements for the parameter pack, fails to do so (because the type of a lambda is not std::function<...>), and becomes upset.
You need to somehow inhibit template argument deduction.
Either call it as exec0<uint32_t>({_g}, {_h});, or wrap parameter types in std::type_identity_t<...> (or, pre-C++20, std::enable_if_t<true, ...>).
Then the compiler will accept your uint32_t as the only type in the pack, and won't try to add more types.
|
72,439,654 | 72,440,114 | C++ adding string and int | I have been tasked to rewrite a small program written in C++ to C#.
But I came across this line that I couldn't understand fully. Is it concatenating the string length to the string or the pointer?
int n = _keyData * int(*(int*)(_chap + strlen(_chap) - 4));
This is the variables:
short _ver = 12;
short _keyData = short(_ver * _ver);
char _chap[100]; // Hold time with format [%02d-%02d %02d:%02d:%02d:%03d]
| *(int*)(_chap + strlen(_chap) - 4) is a strict aliasing violation. Reinterpreting raw bytes as an int is type punning and is not allowed in C++ (even though some compilers tolerate it).
To fix it (assuming a little-endian system), you can rewrite it like this:
short _ver = 12;
short _keyData = short(_ver * _ver);
char _chap[100]; // Hold time with format [%02d-%02d %02d:%02d:%02d:%03d]
int len = strlen(_chap);
int x = (int)(((unsigned)_chap[len - 1] << 24) |
((unsigned)_chap[len - 2] << 16) |
((unsigned)_chap[len - 3] << 8) |
(unsigned)_chap[len - 4]);
int n = _keyData * x;
Coincidently, it should be easy to port this to C# now.
|
72,439,702 | 72,439,840 | CMake & C++ : linker error : undefined reference to function | I am trying to compile a simple C++ program with CMake, but I am getting a linker error :
[2/2] Linking CXX executable bin/MY_PROGRAM
FAILED: bin/MY_PROGRAM
: && g++ -g CMakeFiles/MY_PROGRAM.dir/src/main.cpp.o -o bin/MY_PROGRAM && :
/usr/bin/ld: CMakeFiles/MY_PROGRAM.dir/src/main.cpp.o: in function `main':
/home/user/Code/root/src/main.cpp:27: undefined reference to `str_toupper(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&)'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
I have tried looking at some questions with similar issues but couldn't find what I did wrong. There must be a problem with my directory structure and CMake files. I could change the directory structure to make things easier, but I may be missing something important and I'd like to figure out why. Also, I am new to C++ so I might be doing something wrong in the code itself, but my IDE doesn't find any issue.
My directory structure is :
root
|-- CMakeLists.txt
|-- src
|-- main.cpp
|-- utils
|-- CMakeLists.txt
|-- src
|-- strutils.cpp
|-- include
|-- strutils.h
The top-level CMakeLists.txt is :
// general stuff (standard, etc...)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin)
set(MY_PROGRAM_SRC src/main.cpp)
add_executable(MY_PROGRAM ${MY_PROGRAM_SRC})
include_directories(utils/include)
link_libraries(MY_LIBRARY)
and utils/CMakeLists.txt :
set(MY_LIBRARY_SRC include/strutils.h src/strutils.cpp)
add_library(MY_LIBRARY STATIC ${MY_LIBRARY_SRC})
// This is to include strutils.h in strutils.cpp
// (but is it needed ? I could just #include <string> in strutils.cpp, I guess)
target_include_directories(MY_LIBRARY PUBLIC include)
Finally, the source files :
// strutils.h
#include <string>
void str_toupper(const std::string &in, std::string &out);
// strutils.cpp
#include <algorithm>
#include <strutils.h>
void str_toupper(const std::string &in, std::string &out) {
std::transform(in.begin(), in.end(), out.begin(), [](char c){return std::toupper(c);});
}
// main.cpp
#include <strutils.h>
#include <cstdlib>
#include <cstdio>
#include <string>
int main(int argc, char *argv[]) {
// ...
std::string arg_in;
for (int i = 0; i < argc; i++) {
str_toupper(std::string(argv[i]), arg_in);
}
}
Does anyone have an idea of what's going on ? Thanks !
| The first sentence in the manual link_libraries
Link libraries to all targets added later.
You use this directive after the target MY_PROGRAM is added - the target MY_PROGRAM is added prior link_libraries.
Prefer use target_link_libraries(MY_PROGRAM MY_LIBRARY) - other targets can require different dependencies and it's better not use a global set of dependencies for all targets.
|
72,440,057 | 72,440,324 | C++ chrono: How do I convert an integer into a time point | I managed to convert a time point into an integer and write it into a file using code that looks like the following code:
std::ofstream outputf("data");
std::chrono::time_point<std::chrono::system_clock> dateTime;
dateTime = std::chrono::system_clock::now();
auto dateTimeSeconds = std::chrono::time_point_cast<std::chrono::seconds>(toSerialize->dateTime);
unsigned long long int serializeDateTime = toSerialize->dateTime.time_since_epoch().count();
outputf << serializeDateTime << "\n";
Now I'm trying to read that integer from the file, convert it into a time_point, and print it. Right now, my code looks something like this:
std::ifstream inputf("data");
unsigned long long int epochDateTime;
inputf >> epochDateTime;
std::chrono::seconds durationDateTime(epochDateTime);
std::chrono::time_point<std::chrono::system_clock> dateTime2(durationDateTime);
std::time_t tt = std::chrono::system_clock::to_time_t(dateTime2);
char timeString[30];
ctime_s(timeString, sizeof(timeString), &tt);
std::cout << timeString;
However, it doesn't print anything. Does anyone know where I went wrong?
| You have some strange conversions and assign to a variable that you don't use. If you want to store system_clock::time_points as std::time_ts and restore the time_points from those, don't involve other types and use the functions made for this: to_time_t and from_time_t. Also, check that opening the file and that extraction from the file works.
Example:
#include <chrono>
#include <ctime>
#include <fstream>
#include <iostream>
int main() {
{ // save a time_point as a time_t
std::ofstream outputf("data");
if(outputf) {
std::chrono::time_point<std::chrono::system_clock> dateTime;
dateTime = std::chrono::system_clock::now();
outputf << std::chrono::system_clock::to_time_t(dateTime) << '\n';
}
}
{ // restore the time_point from a time_t
std::ifstream inputf("data");
if(inputf) {
std::time_t epochDateTime;
if(inputf >> epochDateTime) {
// use epochDateTime with ctime-like functions if you want:
std::cout << std::ctime(&epochDateTime) << '\n';
// get the time_point back (usually rounded to whole seconds):
auto dateTime = std::chrono::system_clock::from_time_t(epochDateTime);
// ...
}
}
}
}
|
72,440,193 | 72,448,375 | Undefined reference grpc and protobuf error - C++ | I am writing a grpc communication code between two entities, matchmaker and host. My makefile looks as below:
CXX = g++
LDFLAGS += `pkg-config --cflags --libs protobuf grpc grpc++`\
-lgrpc++_reflection\
-ldl
host: comm hosts/host.cc hosts/host.h
$(CXX) $(LDFLAGS) hosts/host.cc build/matchmaker.grpc.pb.o build/matchmaker.pb.o -g -o build/host.o
comm: comm/matchmaker.grpc.pb.cc comm/matchmaker.grpc.pb.h comm/matchmaker.pb.cc comm/matchmaker.pb.h
$(CXX) $(LDFLAGS) comm/matchmaker.grpc.pb.cc -g -c -o build/matchmaker.grpc.pb.o
$(CXX) $(LDFLAGS) comm/matchmaker.pb.cc -g -c -o build/matchmaker.pb.o
I am getting multiple undefined reference errors for grpc and protobuf class codes. Some part of the error is shown below:
/usr/bin/ld: /tmp/cciFPkpo.o: in function `Host::RegisterHost()':
~/Projects/p1/hosts/host.cc:11: undefined reference to `grpc::ClientContext::ClientContext()'
/usr/bin/ld: ~/Projects/p1/hosts/host.cc:11: undefined reference to `grpc::ClientContext::~ClientContext()'
/usr/bin/ld: ~/Projects/p1/hosts/host.cc:11: undefined reference to `grpc::ClientContext::~ClientContext()'
/usr/bin/ld: /tmp/cciFPkpo.o: in function `main':
~/Projects/p1/hosts/host.cc:27: undefined reference to `grpc::InsecureChannelCredentials()'
.
.
.
~/Projects/p1/hosts/../comm/matchmaker.pb.h:895: undefined reference to `google::protobuf::RepeatedField<float>::Set(int, float const&)'
The output for pkg-config --cflags --libs protobuf grpc grpc++ is as below:
-DNOMINMAX -maes -msse4.1 -DNOMINMAX -maes -msse4.1 -DNOMINMAX -I~/grpc/include -L~/grpc/lib -lprotobuf -pthread -lgrpc++ -lgrpc -laddress_sorting -lre2 -lupb -lcares -lz -lgpr -lssl -lcrypto -labsl_raw_hash_set -labsl_hashtablez_sampler -labsl_hash -labsl_city -labsl_low_level_hash -labsl_random_distributions -labsl_random_seed_sequences -labsl_random_internal_pool_urbg -labsl_random_internal_randen -labsl_random_internal_randen_hwaes -labsl_random_internal_randen_hwaes_impl -labsl_random_internal_randen_slow -labsl_random_internal_platform -labsl_random_internal_seed_material -labsl_random_seed_gen_exception -labsl_statusor -labsl_status -labsl_cord -labsl_cordz_info -labsl_cord_internal -labsl_cordz_functions -labsl_exponential_biased -labsl_cordz_handle -labsl_bad_optional_access -labsl_str_format_internal -labsl_synchronization -labsl_graphcycles_internal -labsl_stacktrace -labsl_symbolize -labsl_debugging_internal -labsl_demangle_internal -labsl_malloc_internal -labsl_time -labsl_civil_time -labsl_strings -labsl_strings_internal -lrt -labsl_base -labsl_spinlock_wait -labsl_int128 -labsl_throw_delegate -labsl_time_zone -labsl_bad_variant_access -labsl_raw_logging_internal -labsl_log_severity
grpc and protobuf was previous installed via software center, which I removed. The current grpc and protobuf is built from the source code.
I am not sure how to resolve the undefined reference error. Any pointers will be really helpful. Thanks in advance.
| You need to move the $(LDFLAGS) until after the object files that depend on it:
host: comm hosts/host.cc hosts/host.h
$(CXX) hosts/host.cc build/matchmaker.grpc.pb.o build/matchmaker.pb.o -g -o build/host $(LDFLAGS)
|
72,441,174 | 73,968,626 | AWS Gamekit - Could not create resources Identity And Authentication feature | I am new to AWS Gamekit as I am trying to create the resource Identity and Authentication but it gives me this Error in Unreal Engine:
LogAwsGameKit: Display: [@22920]~ Plugin settings file loaded from C:/Users/najb1/OneDrive/Documents/Unreal Projects/MyProject2/myproject2/saveInfo.yml
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ CreateStack Successful; StackId: arn:aws:cloudformation:us-east-1:333725018856:stack/gamekit-dev-myproject2-main/2144b610-e041-11ec-845e-0ae2abc8cfd3
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ Creating stack resources for stack: gamekit-dev-myproject2-main
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: gamekit-dev-myproject2-main | CREATE_IN_PROGRESS: User Initiated
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: ApiGatewayLoggingRole | CREATE_IN_PROGRESS:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: EmptyS3BucketOnDeleteLambdaRole | CREATE_IN_PROGRESS: Resource creation Initiated
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: RestApi | CREATE_COMPLETE:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: RootGetMethod | CREATE_IN_PROGRESS: Resource creation Initiated
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: MainRequestValidator | CREATE_COMPLETE:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: RestApiDeployment | CREATE_IN_PROGRESS:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: MainDeploymentStage | CREATE_IN_PROGRESS:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: EmptyS3BucketOnDeleteLambda | CREATE_IN_PROGRESS:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: UsagePlan | CREATE_FAILED: Resource creation cancelled
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: RemoveLambdaLayersOnDeleteLambda | DELETE_IN_PROGRESS:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: ApiGatewayLogGroup | DELETE_COMPLETE:
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ gamekit-dev-myproject2-main: RemoveLambdaLayersOnDeleteLambdaRole | DELETE_IN_PROGRESS:
LogAwsGameKit: Error: [000001F43C21EF70@22920]~ CloudFormation creation failed.
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ ~GameKitFeatureResources()
LogAwsGameKit: Display: [000001F43C21EF70@22920]~ AwsApiInitializer::Shutdown(): Not shutting down (count: 6)
LogAwsGameKit: Error: FeatureResourceManager::CreateOrUpdateResources() Creating/Updating stack failed. : 0x3f2
LogAwsGameKit: Display: AwsGameKitSessionManagerWrapper::ReloadConfig(myproject2/dev/)
LogAwsGameKit: Display: Copied config from C:/Users/najb1/OneDrive/Documents/Unreal Projects/MyProject2/myproject2/dev/awsGameKitClientConfig.yml to ../../../../../../Users/najb1/OneDrive/Documents/Unreal Projects/MyProject2/Content/GameKitConfig/awsGameKitClientConfig.yml
LogAwsGameKit: Display: [@22920]~ GameKitSessionManager::ReloadConfigFile()
LogAwsGameKit: Error: FeatureResourceManager::CreateOrUpdateResources() for Main feature: Could not create resources. : 0x3f2. Please find more details in https://docs.aws.amazon.com/gamekit/latest/DevGuide/versions.html#versions-knownissues
LogAwsGameKit: Display: [000001F43C221EE0@22920]~ ~GameKitFeatureResources()
LogAwsGameKit: Display: [000001F43C221EE0@22920]~ AwsApiInitializer::Shutdown(): Not shutting down (count: 5)
LogAwsGameKit: FeatureResourceManager::GetResourcesStackStatus()
LogAwsGameKit: Display: [000001F43C220DA0@22920]~ AwsApiInitializer::Initialize(): Already initialized (count: 4)
LogAwsGameKit: Display: [000001F43C220DA0@22920]~ GameKitFeatureResources()
LogAwsGameKit: Display: Error: FeatureResourceManager::CreateOrUpdateResources() for Main feature: Could not create resources.
I think the problem is caused by a role not being specified. But I can't figure out which one. Could anyone be of help
| I just got this using eu-west-2 (yours looks like us-east-1). Changed the environment region to us-west-2 (or try whichever else) and there were no problems.
Also, noticed in aws GameLift they don't offer matchmaking in certain regions, etc., so keep these region limitations in mind.
|
72,441,275 | 72,442,063 | segmentation fault when try reading binary file using overloaded operator >> | I am trying read a binary file which was created with code like that:
#include <list>
#include <string>
#include <bitset>
#include <fstream>
struct Node {
char data;
int frequency;
friend std::istream& operator>>(std::istream& input, Node& e) {
input.read(&e.data, sizeof(e.data));
input.read(reinterpret_cast<char*>(e.frequency), sizeof(e.frequency));
return input;
};
friend std::ostream& operator<<(std::ostream& output, const Node& e) {
output.write(&e.data, sizeof(e.data));
output.write(reinterpret_cast<const char*>(&e.frequency), sizeof(e.frequency));
return output;
};
};
int main() {
std::list<struct Node> list;
for(char i='a'; i<='z'; i++) {
struct Node n;
n.data = i;
n.frequency = 1;
list.push_back(n);
}
std::string encoded_file = "";
for(int i=0; i<100; i++) {
encoded_file = encoded_file + "101010";
}
std::fstream output;
output.open("output.txt", std::ios_base::out | std::ios_base::binary);
if (output.is_open()) {
output << list.size();
for(int i=0; i<list.size(); i++) {
output << list.front();
list.pop_front();
}
for(long unsigned int i=0; i<encoded_file.length(); i+=8) {
std::string data = encoded_file.substr(i, 8);
std::bitset<8> b(data);
unsigned long x = b.to_ulong();
unsigned char c = static_cast<unsigned char>( x );
output << c;
}
}
output.close();
return 0;
}
This code seems to work fine, and the file output.txt is generated without problems.
But, when I try reading the file with this code:
#include <list>
#include <string>
#include <bitset>
#include <fstream>
#include <iostream>
struct Node {
char data;
int frequency;
friend std::istream& operator>>(std::istream& input, Node& e) {
input.read(&e.data, sizeof(e.data));
input.read(reinterpret_cast<char*>(e.frequency), sizeof(e.frequency));
return input;
};
friend std::ostream& operator<<(std::ostream& output, const Node& e) {
output.write(&e.data, sizeof(e.data));
output.write(reinterpret_cast<const char*>(&e.frequency), sizeof(e.frequency));
return output;
};
};
int main() {
std::list<struct Node> list;
std::string encoded_file = "";
std::fstream input;
input.open("output.txt", std::ios_base::in | std::ios_base::binary);
if (input.is_open()) {
std::cout << "1" << std::endl;
int size = 0;
input >> size;
std::cout << "size: " << size << std::endl;
for(int i=0; i<size; i++) {
Node node;
input >> node;
std::cout << node.data << " (" << node.frequency << ")" << std::endl;
list.push_back(node);
}
std::cout << "2" << std::endl;
char c;
while(input.get(c)) {
std::bitset<8> b(c);
encoded_file = encoded_file + b.to_string();
}
std::cout << "3" << std::endl;
}
input.close();
return 0;
}
I get a segmentation fault. The error occurs when I try to execute input >> node;. I checked, and apparently when the program enters Node::operator>>, e.data is read, but frequency is not.
Can anyone give me any tips of how to fix this?
| You have a typo in your Node::operator>>. When reading e.frequency, you are missing a &:
input.read(reinterpret_cast<char*>(&e.frequency), sizeof(e.frequency));
^
That was a typo in my previous answer where you got this code from. I have corrected that mistake.
With that said, I see other problems in your code.
You are creating the file in binary mode, but you are not streaming everything into it as binary values. Only your Node class is being streamed as binary, but your other values are being streamed as text instead. Don't mix formatting schemes.
output << list.size() and output << c are performing formatted I/O. Use write() instead of operator<< for binary I/O, eg:
size_t size = list.size();
output.write(reinterpret_cast<char*>(&size), sizeof(size));
...
unsigned char c = ...;
output.write(reinterpret_cast<char*>(&c), sizeof(c));
And then reverse that process when reading the file, eg:
input.read(reinterpret_cast<char*>(&size), sizeof(size));
...
unsigned char c;
while(input.read(reinterpret_cast<char*>(&c), sizeof(c))) {
...
}
Also, in your code that is creating the file, your 1st for loop is wrong. You are modifying the list while looping through it, thus affecting its size(). So you end up skipping nodes in the list. You should iterate using iterators instead of indexes, and without modifying the list at all, eg:
for(std::list<Node>::const_iterator iter = list.cbegin(); iter != list.cend(); ++iter) {
output << *iter;
}
Or simpler:
for(const auto &item : list) {
output << item;
}
|
72,441,329 | 72,441,631 | TPMT_PUBLIC Serialize to other Format file? | [a similar questions link][1]
[1]: https://stackoverflow.com/questions/60340870/serialize-tpm-public-key-to-der-or-pem
But,I don't Know how to do that,using botan to covert data.
TPMT_PUBLIC ===> PEM
| TPMS_RSA_PARMS *rsaParms = dynamic_cast<TPMS_RSA_PARMS*>(&*persistentPub.outPublic.parameters);
if (rsaParms == NULL)
{
throw domain_error("Only RSA encryption is supported");
}
TPM2B_PUBLIC_KEY_RSA *rsaPubKey = dynamic_cast<TPM2B_PUBLIC_KEY_RSA*>(&*persistentPub.outPublic.unique);
auto rsaPublicKey = Botan::RSA_PublicKey(Botan::BigInt(rsaPubKey->buffer.data(), rsaPubKey->buffer.size()), rsaParms->exponent);
std::string strPemText = Botan::X509::PEM_encode(rsaPublicKey);
cout << "public format Text: " << strPemText.c_str() << endl;
|
72,441,818 | 72,442,751 | CMake cannot link executable -ljsoncpp: no such file using github submodules | I am working in a project which uses jsoncpp for parsing and cmake for compilation. I added the jsoncpp official git repository as a submodule to my project with git submodule add REPO_URL external/jsoncpp, so as to keep every dependency together.
When running cmake -B out/build, it works normally. But when I do make, I get the following error:
/usr/bin/ld: cannot find -ljsoncpp: No such file or directory.
The files are organized the following way:
- root
- out/build
- external
- jsoncpp (cloned repo)
- include
foo.h
bar.h
- src
foo.cpp
bar.cpp
main.cpp
CMakeLists.txt
The CMakeLists.txt is like this:
cmake_minimum_required(VERSION 3.22.1)
project(ants)
# ".cpp" files in folder "src" into cmake variable "SOURCE"
file(GLOB SOURCE "src/*.cpp")
# Executable
add_executable(${PROJECT_NAME} ${SOURCE})
# Directory where cmake will look for include files
include_directories(include)
# Tells cmake to compile jsoncpp
add_subdirectory(external/jsoncpp)
# Tells cmake where to look for jsoncpp include files
target_include_directories(${PROJECT_NAME}
PUBLIC external/jsoncpp/include
)
target_link_libraries(${PROJECT_NAME} jsoncpp)
| The jsoncppConfig.cmake defines property INTERFACE_INCLUDE_DIRECTORIES for targets jsoncpp_lib and jsoncpp_lib_static.
You need to query the target property and set it manually:
get_target_property(JSON_INC_PATH jsoncpp_lib INTERFACE_INCLUDE_DIRECTORIES)
include_directories(${JSON_INC_PATH})
Linking is done via:
target_link_libraries(${PROJECT_NAME} jsoncpp_lib)
Source.
Try this:
cmake_minimum_required(VERSION 3.22.1)
project(ants)
# ".cpp" files in folder "src" into cmake variable "SOURCE"
file(GLOB SOURCE "src/*.cpp")
# Executable
add_executable(${PROJECT_NAME} ${SOURCE})
# Directory where cmake will look for include files
include_directories(include)
# Tells cmake to compile jsoncpp
add_subdirectory(external/jsoncpp)
get_target_property(JSON_INC_PATH jsoncpp_lib INTERFACE_INCLUDE_DIRECTORIES)
include_directories(${JSON_INC_PATH})
target_link_libraries(${PROJECT_NAME} jsoncpp_lib)
|
72,441,942 | 72,442,369 | Keep track of boolean variable when class is called | I have a class named Colorblind which has getter and setter methods for a boolean variable called bool toggleColorBlind = false. I have multiple other classes such as Menu which a user can toggle the boolean variable and set it to true.
When I try to get the variable from another class, like Game, the boolean variable resets to its initial value when I instantiate the class and use the getToggleColorBlind() method within the class.
What can I do to prevent the boolean from resetting to its initial value and keep track of it when the class is instantiated and used? Could this be done a better way by using static or something?
Code example:
#include "Colorblind.h"
bool Colorblind::getToggleColorBlind()
{
return mToggleColorBlind;
}
void Colorblind::setToggleColorBlind(bool state)
{
mToggleColorBlind = state;
}
class Colorblind
{
public:
Colorblind();
bool toggleColorBlind(){return mToggleColor;}
bool getToggleColorBlind();
void setToggleColorBlind(bool state);
private:
bool mToggleColorBlind = false;
};
Now the Menu is where a user can enable/disable colorblind mode which works as expected.
Colorblind colorblind;
while (std::getline(cin, command)) {
if (command == "toggle colorblind") {
bool isToggled = colorblind.getToggleColorBlind();
if (isToggled == true) {
colorblind.setToggleColorBlind(false);
} else {
colorblind.setToggleColorBlind(true);
}
{
}
Now my problem is when I try to access the mToggleColorBlind by doing Colorblind colorblind; colorblind.getToggleColorBlind() from any class such as Game to set colors etc.. The value is lost, how can I keep track of this.
| If you goal is to share the same toggleColorBlind across all the instance of different classes like Menu and Game, then you can make toggleColorBlind a static data member as shown below. Making it a static data member would allow you use it without any instance of ColorBlind. This is because a static data member is not associated with any object of the corresponding class ColorBlind.
C++17
Here we use inline keyword for static data member.
class ColorBlind
{
public:
inline static bool toggleColorBlind = false;
//^^^^^^ ^^^^^^------------------------------------->note inline and static used here
};
class Menu
{ public:
//method that toggles
void invertColorBlind() const
{
ColorBlind::toggleColorBlind = !ColorBlind::toggleColorBlind;
std::cout<<"changed to: "<<ColorBlind::toggleColorBlind<<std::endl;
}
};
class Game
{
public:
void invertColorBlind() const
{
ColorBlind::toggleColorBlind = !ColorBlind::toggleColorBlind;
std::cout<<"changed to: "<<ColorBlind::toggleColorBlind<<std::endl;
}
};
int main()
{
std::cout<<"Initially toggleColorBlind is: "<<ColorBlind::toggleColorBlind<<std::endl; //prints 0
Menu m;
//lets change toggleColorBlind using an instance of Menu
m.invertColorBlind(); //prints 1
//toggle again
m.invertColorBlind(); //prints 0
Game g;
//lets change toggleColorBlind using an instance of Game
g.invertColorBlind(); //print 1
}
The output of the program can be seen here:
Initially toggleColorBlind is: 0
changed to: 1
changed to: 0
changed to: 1
C++11
Prior to C++17, we could not use inline while defining a static data member inside class. So here we will provide an out-of-class definition for the static data member.
class ColorBlind
{
public:
static bool toggleColorBlind;;
//^^^^^^------------------------------------->note only the static used here
};
//define it outside class
bool ColorBlind::toggleColorBlind = false;
Working demo
|
72,442,114 | 72,442,779 | insertion at the end of linked list function not working | I don't know where I am wrong, when I debugged the code I found out that the 'new node' address is 'new node' address, basically the new node is referring to itself
void insertend(struct node *parent, int item)
{
while (parent->addr != NULL)
parent = parent->addr;
struct node new_node;
new_node.a = item;
parent->addr = &new_node;
parent->addr->addr = NULL;
}
|
void insertend(struct node *parent, int item)
{
while (parent->addr != NULL)
parent = parent->addr;
struct node new_node;
new_node.a = item;
parent->addr = &new_node;
parent->addr->addr = NULL;
}
The lifetime of new_node is limited to the function. Once that function returns, it is no longer valid.
In order to circumvent this, it is necessary to dynamically allocate memory for new_node. Of course, as already pointed out, this means explicitly deallocating the memory eventually.
Note: as this is C++ rather than C, we do not need to add struct to the front of the type in use, and NULL is better spelled nullptr.
void insertend(node *parent, int item)
{
while (parent->addr != nullptr)
parent = parent->addr;
node *new_node = new node;
new_node.a = item;
parent->addr = new_node;
parent->addr->addr = nullptr;
}
As C++ structs are just classes with default public access, it's also worth noting we could implement this as a member function. Something like:
template <typename T>
struct Node {
T value;
Node<T> *next;
void append(T val) {
Node<T> * temp = this;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = new Node<T>;
temp->next->value = val;
temp->next->next = nullptr;
}
};
int main() {
auto n = Node<int>();
n.value = 27;
n.append(42);
n.append(34);
for (Node<int> *t = &n; t != nullptr; t = t->next) {
std::cout << t->value << std::endl;
}
return 0;
}
The next step would be implementing a constructor and destructor.
One more thing to keep in mind is that getting to the end of a list this way is O(n) time complexity. Doing it over and over again is costly. If you have Node::append return a pointer to the new Node, then you can call append on that.
template <typename T>
struct Node {
T value;
Node<T> *next;
Node<T> *append(T val) {
Node<T> * temp = this;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = new Node<T>;
temp->next->value = val;
temp->next->next = nullptr;
return temp->next;
}
};
int main() {
auto n = Node<int>();
n.value = 27;
auto n2 = n.append(42);
n2 = n2->append(34);
n2 = n2->append(15);
for (Node<int> *t = &n; t != nullptr; t = t->next) {
std::cout << t->value << std::endl;
}
return 0;
}
|
72,442,534 | 72,442,704 | C++ Compile time index/tuple access for tensor | I have a compile time tensor class. Now i would like to implement index access like this:
std::array<std::array<std::array<int, 3>, 2>, 1> myTensor;
template <class... Indices>
auto get(Indices... indices) {
return myTensor[indices][...];
}
int main() {
myTensor[0][1][2] = 3;
std::cout << get(0, 1, 2) << std::endl;
}
But this sadly does not compile. Does anyone have an idea of how i could implement this?
It also needs to work when my tensor is const. I would also be fine using tuple instead of variadic template. I can use the most modern compiler/cpp standard if needed.
| You cannot fold over [] (for multidimensional indexing). You can achieve this with a pair of functions:
// This is written as generically as possible, but can be
// pared down by removing forwarding in your use case
template <class Container>
constexpr decltype(auto) get_of(Container&& c) noexcept {
return std::forward<Container>(c);
}
template <class Container, class Index, class... Indices>
constexpr decltype(auto) get_of(Container&& c, Index&& index, Indices&&... indices) {
return ::get_of(std::forward<Container>(c)[std::forward<Index>(index)], std::forward<Indices>(indices)...);
}
// Your attempt with `myTensor[indices][...]` becomes `get_of(myTensor, indices...)`
template <class... Indices>
decltype(auto) get(Indices... indices) {
return get_of(myTensor, indices...);
}
And if you are using C++2b, you can use operator[] with multiple arguments, which might make it easier to use:
struct tensor_type {
std::array<std::array<std::array<int, 3>, 2>, 1> myTensor;
decltype(auto) operator[](auto... indices) {
return get_of(myTensor, indices...);
}
};
int main() {
tensor_type t;
t[0][1][2] = 3;
std::cout << t[0, 1, 2] << '\n';
}
|
72,442,797 | 72,442,872 | Why this code is printing "YES" infinite number of times while it should have printed "NO" one time | for s="0" and k=20 this code is printing YES infinite number of times but the for loop condition (0<=1-20) is not true. it should print NO. Please help me.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
int k;
cin>>k;
for(int i=0;i<=s.size()-k;++i){
cout<<"YES"<<endl;
}
cout<<"NO"<<endl;
return 0;
}
| The short answer is: unsigned integer underflow.
To see it more clearly, let's assign the values to variables of type size_t (which is the type that s.size() returns):
const size_t ssize = s.size();
const size_t ssize_minus_k = ssize-k;
cout << "ssize=" << ssize << " ssize_minus_k=" << ssize_minus_k << endl;
for(int i=0;i<=ssize_minus_k;++i){
cout<<"YES"<<endl;
}
.... with the above lines, the output of the program looks like this:
$ ./a.out
0
20
ssize=1 ssize_minus_k=18446744073709551597
YES
YES
[...]
Now to fix the problem, let's change the type of our variables from size_t to ssize_t (note the extra s, meaning "signed"):
const ssize_t ssize = s.size();
const ssize_t ssize_minus_k = ssize-k;
cout << "ssize=" << ssize << " ssize_minus_k=" << ssize_minus_k << endl;
for(int i=0;i<=ssize_minus_k;++i){
cout<<"YES"<<endl;
}
.... and now we get behavior more like what we were expecting:
$ ./a.out
0
20
ssize=1 ssize_minus_k=-19
NO
|
72,442,899 | 72,443,651 | c++ template structure about iterator_traits | I'm studying about iterator and I found some source code on github.
I realize what this code do but cannot find how.
template <class T>
struct _has_iterator_category
{
private:
struct _two { char _lx; char _lxx; };
template <class U> static _two _test(...);
template <class U> static char _test(typename U::iterator_category * = 0);
public:
static const bool value = sizeof(_test<T>(0)) == 1;
};
I think this code check if T has iterator_category, but I cannot figure few things about how and why this works.
Why this code use two template? what class U template does?
Is _test(...) function or constructor? And what is (...) means?
2-1. If _test is function, is this code doing function overloading? then how can be overloaded with different return type?
2-2. If _test is constructor, then is char a class in c++?
What does * = operator do in (typename U::iterator_category * = 0)? Is it multiplying iterator_category or make 0 of iterator_category pointer?
what sizeof(_test<T>(0)) == 1; means? Is it return true if sizeof(_test<T>(0)) is 1?
I searched a lot of document for iterator_traits and other things, but failed to interpret this code.
| First thing first, this code is completely interpretable on it's own, if you know C++. No documentation on external components is required. It's not depending on anything. You have asked questions which suggest some gaps in basic C++ syntax understanding.
1. Template definition _test is a template member of class template _has_iterator_category. It's a template defined within template, so even if you instantiate _has_iterator_category, you still have to instantiate _test later, it got a separate template parameter.
2. Technically, it's neither. Because a class template isn't a type and a function template, which _test is, is not a function.
Constructor's name always matched the most nested enclosing class scope, i.e. _has_iterator_category in here. _has_iterator_category doesn't have a constructor declared.
It's a template of function. There are two templates, for different arguments, with different argument type. If both templates can be instantiated through successful substitution of U with concrete type, the function is overloaded.
3. It's not operator * =, operators cannot have a whitespace in them. It's * and =. This is a nameless version of argument list which could be written otherwise:
template <class U> static char _test(typename U::iterator_category *arg = 0);
= 0 is default value of function parameter arg. As arg is not being used in this context, its name can be skipped.
The single parameter of function's signature got type U::iterator_category *. typename is a keyword required by most but recent C++ standards for a nested type dependant on template parameter. This assumes that U must have a nested type
iterator_category. Otherwise the substitution of template parameters would fail.
template <class U> static _two _test(...);
Here function signature is "variadic". It means that function may take any number of arguments after substitution of template parameters. Just like printf.
4. sizeof(_test<T>(0)) == 1 equals to true if size of _test<T>(0) result is equal to 1.
The whole construction is a form of rule known as SFINAE - Substitution Failure Is Not An Error. Even if compiler fails to substitute one candidate, it would still try other candidates. The error would diagnosed when all options are exhausted.
In this case the expression sizeof(_test<T>(0)), which attempts to substitute U with T. It's the reason why _test is made into a nested template. The class is valid, but now we check the function.
If type-id T::iterator_category is valid, then substitution will be successful, as the resulting declaration will be valid. _test(...) can be successful too, but then we go to overload choice rules.
A variadic argument always implies type conversion, so there is no ambiguity and _test(...) will be discarded.
If T::iterator_category is not a valid type, _two _test(...) is the only instance of _test().
Assuming that sizeof(char) equals to 1, the constant value is initialized with true if return value of expression would be _test<T>(0) got same size as char. Which is only true if T::iterator_category exists.
Essentially this constructs checks, if class T contains nested type T::iterator_category in somewhat clumsy and outdated ways. But it is compatible with very early C++ standards as it doesn't use nullptr or <type_traits> header.
|
72,444,600 | 72,444,739 | Remove strings that contain digits and convert others in upper case and separate them with comma | I've almost finished this task but have a little trouble in result. Here's the problem description:
Given a vector of strings, please implement the following 2 functions to process and output it:
process(): remove strings that contain digits and convert others in upper case
output(): print the strings and separate them with comma.
Hints:
If possible, manipulate the vector elements in place to avoid copying vector.
It is encouraged to leverage STL functions/algorithms.
Expected Output:
==========================================
Before: abc, 123, 456, xyz
After: ABC, XYZ
But my code caused the input is not as expected
before process: abc, 123, 456, xyz,
after process: ABC, XYZ,
Please tell me how to remove the comma in the end of string in both case before/after process
Here's my code:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <vector>
void process(std::vector<std::string>& v)
{
// Remove strings that contain digits
for(std::string &s : v)
s.erase(std::remove_if(std::begin(s), std::end(s),
[](unsigned char ch) { return std::isdigit(ch); }),
s.end());
// Convert other characters into upper case
// std::toupper has several overloads
// template <class charT> charT toupper(charT, const locale&)
// int toupper(int ch)
// So taking its address might be complicated.
// We can use lambda to let compiler found the right overload:
// (In addition, as char might be signed or not, and toupper expects unsigned char value (or EOF))
for(std::string &s : v)
{
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c){ return std::toupper(c); });
}
std::cout << '\n';
}
void output(std::vector<std::string>& v)
{
for(std::string &str : v)
if(str != "\0")
std::cout << str << ", ";
}
int main()
{
std::vector<std::string> v = { "abc", "123", "456", "xyz" };
std::cout << "Before: "; output(v);
process(v);
std::cout << "After: "; output(v);
return 0;
}
| Sometimes, good old syntax is a good thing.
void output(std::vector<std::string>& v) {
// clean array
size_t n = v.size();
while(n--) if(v[n] == '\0') v.erase(v.begin() + n);
// print words
for(size_t i = 0; i < v.size(); ++i) {
std::cout << v[i];
if(i < (v.size() - 1) std::cout << ", ";
}
}
another method
void output(std::vector<std::string>& v) {
// clean array
size_t n = v.size();
while(n--) if(v[n] == '\0') v.erase(v.begin() + n);
// print words
size_t max = v.size() - 1;
for(size_t i = 0; i < max; ++i)
std::cout << v[i] << ", ";
std::cout << v[max];
}
|
72,444,766 | 72,444,949 | Is there a way of creating a shorthand map to be passed to a function in C++? | I wonder if there is a way of constructing a temporary map to be passed so that the following implementation is possible:
void func(map<string,int> & input) {
cout << input["m1"] << endl;
cout << input["m2"] << endl;
}
func ( map<string,int>{{"m1",1},{"m2",2}} ; // causing error when compiled
| The problem is that you're trying to bind an rvalue expression to an lvalue reference to non-const std::map.
To solve this you can add a low-level const in the parameter and use std::map::find as shown below:
void func(const std::map<string, int>& input) {
auto it1 = input.find("m1");
if(it1!=input.end())
{
cout << it1->second << endl;
}
else
{
std::cout<<"element cannot be found"<<std::endl;
}
//do the same for other key "m2"
}
int main()
{
func({{"m1", 1}, {"m2", 2}});
return 0;
}
Demo
Note if you want to just print all the elements of the map you can use structure binding with C++17 as shown below:
void func(const std::map<string, int>& input) {
for(const auto&[key, value]: input)
{
std::cout<<key<<" --> "<<value<<std::endl;
}
}
int main()
{
func({{"m1", 1}, {"m2", 2}});
return 0;
}
Demo C++17 & above
Note structure bindings are available from C++17, so if you're using C++11 or C++14 you can use the range-based for loop :
void func(const std::map<string, int>& input) {
for(const auto&element: input)
{
std::cout<<element.first<<" --> "<<element.second<<std::endl;
}
}
Demo Prior C++17
|
72,444,998 | 72,445,228 | Preprocessing multiple source files with one command using g++ | Question
I have three files in my current working directory:
hello.cpp
goodbye.cpp
prog.cpp
I would like to only preprocess hello.cpp and goodbye.cpp and dump the output in files hello.i and goodbye.i. Is there a way to achieve this using g++ in a Ubuntu Linux command line using one command? The reason I would like to call g++ only once is because I would eventually like to include this command in my own Makefile.
What I've tried
I basically did the following:
g++ -E -o goodbye.i hello.i goodbye.cpp hello.cpp
Which, unsurprisingly, failed with the following error:
g++ : fatal error: cannot specify '-o' with '-c', '-S' or '-E' with multiple files
compilation terminated
I also tried g++ -E goodbye.cpp hello.cpp, which only reminded me that the preprocessor dumps to stdout by default. I do, for the purposes of this exercise, need for g++ to dump the result into an actual *.i file...
What I'm trying to avoid
From the comments, it seems to me that I can provide a further clarification. I'm trying to avoid having multiple commands in my Makefile, as each separate .cpp file would generate a separate command:
all: preprocess_hello preprocess_goodbye
preprocess_hello:
g++ -E -o hello.i hello.cpp
preprocess_hello:
g++ -E -o goodbye.i goodbye.cpp
Obviously, this is not ideal, because every new file I add would require adding a new command and updating the all target.
| You can use a pattern rule so Make knows how to generate a .i file from a .c file:
%.i: %.cpp
g++ -E -o $@ $<
and then if your makefile ever requires hello.i, Make will know that it can use the command g++ -E -o hello.i hello.cpp
E.g. if you have all: hello.i goodbye.i and run make all it will know that it needs hello.i and goodbye.i and it will make them.
If you have a list of .cpp files and you need to convert it to a list of .i files (e.g. if you want to do all: $(CPPFILES) but it doesn't work because those are the .cpp files and not the .i files) you can use patsubst:
all: $(patsubst %.cpp,%.i,$(CPPFILES))
You can even use wildcard to get the list of cpp files. To make all depend on all the .i files for all the .cpp files in the current directory, you could use
all: $(patsubst %.cpp,%.i,$(wildcard *.cpp))
|
72,445,056 | 72,487,420 | How to compose a string literal from constexpr char arrays at compile time? | I'm trying to create a constexpr function that concatenates const char arrays to one array. My goal is to do this recursively by refering to a specialized variable template join that always joins two const char*'s . But the compiler doesn't like it and throws an error message that I can't get behind.
I've already checked out this topic but it unfortunately doesn't have a straight up answer.
Code:
#include <type_traits>
#include <cstdio>
#include <iostream>
constexpr auto size(const char*s)
{
int i = 0;
while(*s!=0) {
++i;
++s;
}
return i;
}
template <const char* S1, typename, const char* S2, typename>
struct join_impl;
template <const char* S1, int... I1, const char* S2, int... I2>
struct join_impl<S1, std::index_sequence<I1...>, S2, std::index_sequence<I2...>>
{
static constexpr const char value[]{ S1[I1]..., S2[I2]..., 0 };
};
template <const char* S1, const char* S2>
constexpr auto join
{
join_impl<S1, std::make_index_sequence<size(S1)>, S2, std::make_index_sequence<size(S2)>>::value
};
template <const char* S1, const char* S2, const char*... S>
struct join_multiple
{
static constexpr const char* value = join<S1, join_multiple<S2, S...>::value>::value;
};
template <const char* S1, const char* S2>
struct join_multiple<S1, S2>
{
static constexpr const char* value = join<S1, S2>;
};
constexpr const char a[] = "hello";
constexpr const char b[] = "world";
constexpr const char c[] = "how is it going?";
int main()
{
// constexpr size_t size = 100;
// char buf[size];
// lw_ostream{buf, size};
std::cout << join_multiple<a, b, c>::value << std::endl;
}
Error:
<source>:33:82: error: qualified name refers into a specialization of variable template 'join'
static constexpr const char* value = join<S1, join_multiple<S2, S...>::value>::value;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
<source>:25:16: note: variable template 'join' declared here
constexpr auto join
^
<source>:33:34: error: default initialization of an object of const type 'const char *const'
static constexpr const char* value = join<S1, join_multiple<S2, S...>::value>::value;
^
= nullptr
2 errors generated.
ASM generation compiler returned: 1
<source>:33:82: error: qualified name refers into a specialization of variable template 'join'
static constexpr const char* value = join<S1, join_multiple<S2, S...>::value>::value;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
<source>:25:16: note: variable template 'join' declared here
constexpr auto join
^
<source>:33:34: error: default initialization of an object of const type 'const char *const'
static constexpr const char* value = join<S1, join_multiple<S2, S...>::value>::value;
^
= nullptr
2 errors generated.
Execution build compiler returned:
What am I missing?
| As alternative, to avoid to build the temporary char arrays, you might work with types (char sequences) and create the char array variable only at the end, something like:
constexpr auto size(const char*s)
{
int i = 0;
while(*s!=0) {
++i;
++s;
}
return i;
}
template <const char* S, typename Seq = std::make_index_sequence<size(S)>>
struct as_sequence;
template <const char* S, std::size_t... Is>
struct as_sequence<S, std::index_sequence<Is...>>
{
using type = std::integer_sequence<char, S[Is]...>;
};
template <typename Seq>
struct as_string;
template <char... Cs1>
struct as_string<std::integer_sequence<char, Cs1...>>
{
static constexpr const char c_str[] = {Cs1..., '\0'};
};
template <typename Seq1, typename Seq2, typename... Seqs>
struct join_seqs
{
using type = typename join_seqs<typename join_seqs<Seq1, Seq2>::type, Seqs...>::type;
};
template <char... Cs1, char... Cs2>
struct join_seqs<std::integer_sequence<char, Cs1...>, std::integer_sequence<char, Cs2...>>
{
using type = std::integer_sequence<char, Cs1..., Cs2...>;
};
template <const char*... Ptrs>
const auto join =
as_string<typename join_seqs<typename as_sequence<Ptrs>::type...>::type>::c_str;
Demo
|
72,445,523 | 72,463,675 | How to use an executor from a boost::asio object to dispatch stuff into the same execution thread? | Ok, I don't have enough code yet for a fully working program, but I'm already running into issues with "executors".
EDIT: this is Boost 1.74 -- Debian doesn't give me anything more current. Which causes problems elsewhere, but I hope it had working executors back then as well :-)
Following one of the beast examples, I'm assigning a "strand" to a number of objects (a resolver and a stream) to be slightly more future-proof in case I need to go a multithreaded-route. But that's not actually the problem here, just the reason why I used a strand.
Now, I have this object that has a number of asio "subobjects" which are all initialized with that executor. No issues there, at least on the compiler side (I don't know whether the code does the intended stuff yet... it's heavily based on a beast example, though, so it's not completely random).
So, I want to send data to that object now. The assumption here is that the entire executor stuff is kind of pointless if I just randomly manipulate stuff from the "outside", so I wanted to "dispatch" my changes to the executor to it plays nicely with the async stuff that might be going on, especially when/if threads come into play. And since all the asio objects know their executor, I figured I wouldn't need to remember it myself.
Here some random self-contained example that shows the problem I'm having.
#include <boost/asio.hpp>
/************************************************************************/
class Test
{
private:
boost::asio::ip::tcp::resolver resolver;
public:
Test(boost::asio::any_io_executor executor)
: resolver(executor)
{
}
public:
void doSomething()
{
std::function<void(void)> function;
// Doesn't compile: no "dispatch" member
resolver.get_executor().dispatch(function);
// Doesn't compile: "target" is a template, needs a type
resolver.get_executor().target()->dispatch(function);
// Compiles, but I don't like having to know that it's a strand?
// How can the asio objects use the executor without me telling them the type?
// NOTE: I don't know whether it does the right thing!
resolver.get_executor().target<boost::asio::io_context::strand>()->dispatch(function);
}
};
/************************************************************************/
void test()
{
boost::asio::io_context ioContext;
Test test(boost::asio::make_strand(ioContext));
}
It's actually all in the "doSomething()" function: how do I "dispatch" something to the same executor that some asio object uses, without having to know exactly what that executor is?
Yes, I can do the workaround and pass the "strand" object instead of any_executor, and store that with the other stuff so I have something to call directly. But since every asio object has an executor and also manages to use it properly... I should be able to do the same thing, no?
| Post, defer and dispatch are free functions:
boost::asio::dispatch(resolver.get_executor(), function);
Live: http://coliru.stacked-crooked.com/a/c39d263a99fbe3fd
#include <boost/asio.hpp>
#include <iostream>
struct Test {
Test(boost::asio::any_io_executor executor) : resolver(executor) {}
void doSomething() {
boost::asio::dispatch(resolver.get_executor(), [] {std::cout << "Hello world\n";});
}
private:
boost::asio::ip::tcp::resolver resolver;
};
int main() {
boost::asio::io_context ioContext;
Test test(make_strand(ioContext));
test.doSomething();
ioContext.run();
}
Prints
Hello world
|
72,445,583 | 72,583,056 | Why pragma comment(linker,"/export ...") unresolved external symbol | The header file just like below
#define CoverWinAPI extern "C" __declspec(dllexport)
CoverWinAPI BOOL RunDll();
CoverWinAPI void ReplaceIATEntryInOneMod(PCSTR pszCalleeModName,PROC pfnCurrent,PROC pfnNew,HMODULE hmodCaller);
#pragma comment(linker,"/export:MyCreateWindowExW=_MyCreateWindowExW@48")
CoverWinAPI HWND WINAPI MyCreateWindowExW(
_In_opt_ DWORD dwExStyle,
_In_opt_ LPCWSTR lpClassName,
_In_opt_ LPCWSTR lpWindowName,
_In_ DWORD dwStyle,
_In_ int X,
_In_ int Y,
_In_ int nWidth,
_In_ int nHeight,
_In_opt_ HWND hWndParent,
_In_opt_ HMENU hMenu,
_In_opt_ HINSTANCE hInstance,
_In_opt_ LPVOID lpParam);
when I don't use #pragma comment ,the export funtion name is _MyCreateWindowExW@48.
But when I use #pragma comment(linker,"/export:MyCreateWindowExW=_MyCreateWindowExW@48") , MSVC compile fail and show that unresolved external symbol _MyCreateWindowExW@48. What cause this error?
| The problem you encountered is due to the way function names are decorated by the compiler.
_MyCreateWindowExW@48 is a x86-style decorated name, valid for x86 build only, its x64 counterpart is simply MyCreateWindowExW (x64 has only one calling convention which resembles __cdecl in that the caller is the one responsible for managing the stack allocation).
Contrary to the official documentation, neither export #pragma nor /EXPORT linker option work with undecorated names, they both expect the name to be fully decorated. This is mentioned here.
Small note
There are several ways to export from Dll, such as:
__declspec(dllexport)
#pragma comment(linker,"/export:...") OR link.exe /EXPORT
DEF file
Using only one of them is usually enough, so in your example __declspec(dllexport) is superfluous, even more so considering that it exports a decorated name, which is not what you wanted.
Solution #1 (IMO cumbersome)
Use #ifdef to provide appropriate decorated name for each platform:
#define CoverWinAPI extern "C"
CoverWinAPI BOOL RunDll();
CoverWinAPI void ReplaceIATEntryInOneMod(PCSTR pszCalleeModName, PROC pfnCurrent, PROC pfnNew, HMODULE hmodCaller);
#ifndef _WIN64
#pragma comment(linker,"/export:MyCreateWindowExW=_MyCreateWindowExW@48")
#else
#pragma comment(linker,"/export:MyCreateWindowExW")
#endif
CoverWinAPI HWND WINAPI MyCreateWindowExW(...);
Solution #2 (suggested)
Add a DEF file to your project:
LIBRARY CoverWinAPI
EXPORTS
MyCreateWindowExW
RunDll
ReplaceIATEntryInOneMod
Then your declarations could be rewritten like so:
#define CoverWinAPI WINAPI
BOOL CoverWinAPI RunDll();
void CoverWinAPI ReplaceIATEntryInOneMod(PCSTR pszCalleeModName, PROC pfnCurrent, PROC pfnNew, HMODULE hmodCaller);
HWND CoverWinAPI MyCreateWindowExW(...);
This works because apparently linker does try to match DEF file entries vs. both decorated and undecorated names.
|
72,445,864 | 72,446,064 | how to reduce the amount of functions that defines pointer function | i'm implementing some pointer functions/Callbacks in my code as follow:
typedef WndDyn* (Edit_t)(Point2d* pThis, const EditParams& EditParams);
Edit_t g_Edit_CB{ nullptr };
typedef WndDyn* (*Show_t)(const Point2d* pThis, const EditParams& EditParams);
Show_t g_Show_CB{ nullptr };
// Punkt3d
typedef WndDyn* (*Edit3d_t)(Point3d* pThis, const EditParams& EditParams);
Edit3d_t g_Edit3d_CB{ nullptr };
typedef WndDyn* (*Show3d_t)(const Point3d* pThis, const EditParams& EditParams);
Show3d_t g_Show3d_CB{ nullptr };
.
.
// Vector2d
.
.
After a few moments I realized that I am repeating the pointer function and I am only changing my element which is Point_2d/Point_3d/....
Could someone help me to reduce the functions. I'm thinking about implementing virtual pure functions, but I usually implement them with functions and not pointer functions, so I have no idea how to do it. I would be very grateful if someone could help me.
Thank you in advance
| Since C++11 (which I assume you have available as you're using nullptr), you can use an alias template:
template <typename T>
using EditParamsCallback_t = WndDyn* (*)(T, const EditParams&);
int main() {
using Edit_t = EditParamsCallback_t<Point2d*>;
Edit_t g_Edit_CB{nullptr};
using Show_t = EditParamsCallback_t<const Point2d*>;
Show_t g_Show_CB{nullptr};
// Punkt3d
using Edit3d_t = EditParamsCallback_t<Point3d*>;
Edit3d_t g_Edit3d_CB{nullptr};
using Show3d_t = EditParamsCallback_t<const Point3d*>;
Show3d_t g_Show3d_CB{nullptr};
// Vector2d
}
|
72,446,085 | 72,446,833 | VSCode - autocomplete for loops | I used to write C code with Visual Studio, and whenever I wrote "for" and then pressed TAB, it was automatically completed to an entire for loop, i.e.
for (size_t i = 0; i < length; i++)
{
}
Is there a way to enable that in VSCode as well? Even by using some extension?
Thanks!
|
Is there a way to enable that in VSCode as well?
Yes, you can add snippets and customize them according to your needs if the corresponding snippet is not already available, as shown below for the for loop shown in your question.
Step 1
Go to Files -> Preferences -> User Snippets
Step 2
After clicking on the User Snippets you will be prompted with a menu with different options as shown in the screen shot attached. Click on the option saying: New Global Snippets File
Step 3
When you click on New Global Snippets File, a file will open where you can add your required snippet. Since you've given the for loop that you want in C++, I will write the content that you want to place in that file:
{
"For Loop": {
"prefix": ["for", "for-const"],
"body": ["for (size_t i = ${1:0} ;i < ${2:length}; i++)", "{\t${0://add code here}", "}"],
"description": "A for loop."
}
}
Step 4
Save this file with the content shown above and then you will be able to use this snippet. For example, next time you write for you will be prompted with different options and you can press TAB for selecting that option and that snippet will be used at that point, as shown in the below screenshot :
|
72,446,418 | 72,469,460 | Flutter Xcode Error Undefined symbol: _MDFInsetsFlippedHorizontally and Undefined symbol: _MDFRectFlippedHorizontally | I am struggling with these for days. Searching for answers online but still to no avail.
Details of the error:
List of pod files: (I assume this is related to MDFInternationalisation?)
This is my code in podfile:
# platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
I tried this solution https://github.com/material-components/material-components-ios/issues/10203 but error still persists. I also tried installing the latest xcode version.
Please please help me. I have been stucked for days and it is extremely frustrating. I am a flutter dev so I am quite a noob in ios. Hope to get any guidance. Thank you!
| After trying out multiple solutuions, this is my solution. Simply add this pod 'MDFInternationalization','~>2.0 to your podfile, nothing more. There are some solutions on the internet that require us to change post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) end end It is not required. just add pod md internationalisation and make sure you specify 2.0.
After that, pod install, flutter clean and flutter run.
|
72,446,709 | 72,447,648 | Accessing modelData inside nested delegates | I have a scenario where in I need to access the modelData inside a repeater which part of a listview's delegate. I am unable to differentiate between listview's modelData and Repeater's modelData.
ListView
{
id: listViewData
model: listViewData //here listViewData is QObjectListModel
delegate:
ColumnLayout
{
Rectangle
{
TextArea
{
text: modelData.somePropertyA[index] // This works fine, no issues
....
}
Column
{
Repeater
{
id: repeaterData
model: modelData.getCount(modelData.somePropertyB[index]) // here modelData is referencing to listViewData's modelData.
Text
{
text: repeaterData.modelData.someFunction(listViewData.modelData)
//So my concern here is, how do i differently access listViewData's modelData and repeaterData's modelData. I tried referencing by using id name as you can see. But i am unable to use in this way, it says undefined.
}
}
}
}
}
}
| You can bind the outer model data to some delegate property to create a kind of alias, for example:
Column {
spacing: 5
Repeater {
model: ["A","B","C"]
delegate: Row {
spacing: 5
property var storedValue: modelData
Repeater {
model: ["1","2","3"]
delegate: Text {
text: modelData + storedValue
}
}
}
}
}
|
72,447,160 | 72,454,370 | ASIO: Is it defined behavior to run a completion handler in a different thread? | In the following example, the timer was associated with the io_context executor. But then, the handler is told to execute in the thread-pool. The reason is, because the handler actually executes blocking code, and I don't want to block the run function of the io_context.
But the documentation states
Handlers are invoked only by a thread that is currently calling any overload of run(), run_one(), run_for(), run_until(), poll() or poll_one() for the io_context.
As the code shows, the handler is invoked by the thread_pool, outside of run. Is this behavior well-defined? Does it work also for sockets?
#include <boost/asio.hpp>
#include <iostream>
int main() {
using namespace boost::asio;
thread_pool tp(4);
io_context ioc;
deadline_timer dt(ioc, boost::posix_time::milliseconds(500));
dt.async_wait(bind_executor(tp, [&](boost::system::error_code){
std::cout << "running in tp: " << tp.get_executor().running_in_this_thread() << std::endl;
std::cout << "running in ioc: " << ioc.get_executor().running_in_this_thread() << std::endl;
exit(0);
}));
auto wg = make_work_guard(ioc);
ioc.run();
}
running in tp: 1
running in ioc: 0
Godbolt link.
| First things first.
You can run a handler anywhere you want. Whether it results in UB depends on what you do in the handler.
I'll interpret your question as asking "Does the observed behaviour contradict the documented requirements/guarantees for handler invocation?"
Does This Contradict Documentation?
It does not.
You have two different execution contexts. One of them is io_context (which you linked to the documentation of), and the other is thread_pool.
You've asked to invoke the handler on tp (by binding the handler to its executor).
Therefore, the default executor that deadline_timer was bound to on construction is overruled by the handler's associated executor.
You're confusing yourself by looking at the documentation for io_context that doesn't govern this case: The completion to the deadline-timer is never posted to the io_context. It's posted to the thread_pool's context, as per your specific request.
As expected, the handler is invoked on a thread running the execution context tp.
Simplify And Elaborate
Here's a simplified example that uses post directly, instead of going through an arbitrary async initiation function to do that.
In addition it exercises all the combinations of target executor and associated executors, if any.
Live On Coliru
#include <boost/asio.hpp>
#include <iomanip>
#include <iostream>
namespace asio = boost::asio;
int main() {
std::cout << std::boolalpha << std::left;
asio::io_context ioc;
asio::thread_pool tp(4);
auto xioc = ioc.get_executor();
auto xtp = tp.get_executor();
static std::mutex mx; // prevent jumbled output
auto report = [=](char const* id, auto expected) {
std::lock_guard lk(mx);
std::cout << std::setw(11) << id << " running in tp/ioc? "
<< xtp.running_in_this_thread() << '/'
<< xioc.running_in_this_thread() << " "
<< (expected.running_in_this_thread() ? "Ok" : "INCORRECT")
<< std::endl;
};
asio::post(tp, [=] { report("direct tp", xtp); });
asio::post(ioc, [=] { report("direct ioc", xioc); });
asio::post(ioc, bind_executor (tp, [=] { report("bound tp.A", xtp); }));
asio::post(tp, bind_executor (tp, [=] { report("bound tp.B", xtp); }));
asio::post( bind_executor (tp, [=] { report("bound tp.C", xtp); }));
asio::post(ioc, bind_executor (ioc, [=] { report("bound ioc.A", xioc); }));
asio::post(tp, bind_executor (ioc, [=] { report("bound ioc.B", xioc); }));
asio::post( bind_executor (ioc, [=] { report("bound ioc.C", xioc); }));
// system_executor doesn't have .running_in_this_thread()
// asio::post([=] { report("system", asio::system_executor{}); });
ioc.run();
tp.join();
}
Prints e.g.
direct tp running in tp/ioc? true/false Ok
direct ioc running in tp/ioc? false/true Ok
bound tp.C running in tp/ioc? true/false Ok
bound tp.B running in tp/ioc? true/false Ok
bound tp.A running in tp/ioc? true/false Ok
bound ioc.C running in tp/ioc? false/true Ok
bound ioc.B running in tp/ioc? false/true Ok
bound ioc.A running in tp/ioc? false/true Ok
Note that
the bound executor always prevails
there's a fallback to system executor (see its effect)
For semantics of post see the docs or e.g. When must you pass io_context to boost::asio::spawn? (C++)
|
72,447,454 | 72,514,888 | Failed to receive UDP stream using OpenCV GStreamer | I am trying to transmit RGB raw data over the network via UDP and on the receiving side, I want to do some image processing on the data using OpenCV C++.
Sender Pipeline
gst-launch-1.0 -v k4asrc serial=$k4a_serial timestamp-mode=clock_all enable-color=true ! rgbddemux name=demux demux.src_color ! rtpvrawpay ! udpsink host=192.168.100.46 port=9001
Receiver:
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
VideoCapture cap("udpsrc port=9001 ! application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=RAW, sampling=(string)RGB, width=(string)1280, height=(string)720, payload=96 ! rtpvrawdepay ! videoconvert ! queue ! appsink", CAP_GSTREAMER);
if (!cap.isOpened()) {
cerr << endl <<"VideoCapture not opened !!!" << endl;
exit(-1);
}
while (true) {
Mat frame;
cap.read(frame);
imshow("receiver", frame);
if (waitKey(1) == 27) {
break;
}
}
return 0;
}
I get the following output in the terminal:
[ INFO:0@0.005] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\videoio_registry.cpp (223) cv::`anonymous-namespace'::VideoBackendRegistry::VideoBackendRegistry VIDEOIO: Enabled backends(8, sorted by priority): FFMPEG(1000); GSTREAMER(990); INTEL_MFX(980); MSMF(970); DSHOW(960); CV_IMAGES(950); CV_MJPEG(940); UEYE(930)
[ INFO:0@0.005] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\backend_plugin.cpp (383) cv::impl::getPluginCandidates Found 2 plugin(s) for GSTREAMER
[ INFO:0@0.005] global c:\build\master_winpack-build-win64-vc15\opencv\modules\core\src\utils\plugin_loader.impl.hpp (67) cv::plugin::impl::DynamicLib::libraryLoad load C:\opencv\build\x64\vc15\bin\opencv_videoio_gstreamer455_64d.dll => FAILED
[ INFO:0@0.006] global c:\build\master_winpack-build-win64-vc15\opencv\modules\core\src\utils\plugin_loader.impl.hpp (67) cv::plugin::impl::DynamicLib::libraryLoad load opencv_videoio_gstreamer455_64d.dll => FAILED
VideoCapture not opened !!!
C:\Users\username\g-streamer\gst_sample\gst-udp-03\out\build\x64-Debug\gstreamer_udp_03.exe (process 21264) exited with code -1.
Press any key to close this window . . .
Why does the opencv_videoio_gstreamer455_64d.dll load fail? I checked and it is already in the provided path.
When I try the same Pipeline in the terminal, I can see the expected video.
Terminal Receiver Pipeline:
gst-launch-1.0 udpsrc port=9001 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)RAW, sampling=(string)RGB, width=(string)1280, height=(string)720, payload=(int)96" ! rtpvrawdepay ! videoconvert ! queue ! autovideosink sync=false
System:
Sender-PC = Ubuntu 18.04
Receiver-PC = Windows 10
Python = 3.7.9
OpenCV = 4.5.5
| SOLVED after several tries. Hope it helps someone else.
I reinstalled everything. Built another version of OpenCV and it's working as expected. Also had to change the Pipeline a bit to add all the CAPS information.
Sender Pipeline
gst-launch-1.0 -v k4asrc serial=$k4a_serial timestamp-mode=clock_all enable-color=true ! rgbddemux name=demux demux.src_color ! rtpvrawpay ! udpsink host=192.168.100.46 port=9001
Receiver:
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
// Receiving Pipeline
VideoCapture cap("udpsrc port=9001 ! application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)RAW, sampling=(string)RGB, depth=(string)8, width=(string)1280, height=(string)720, colorimetry=(string)SMPTE240M, payload=(int)96, ssrc=(uint)597927397, timestamp-offset=(uint)407659256, seqnum-offset=(uint)20318, a-framerate=(string)30 ! rtpvrawdepay ! videoconvert ! appsink", CAP_GSTREAMER);
if (!cap.isOpened()) {
cerr << endl <<"VideoCapture not opened !!!" << endl;
exit(-1);
}
while (true) {
Mat frame;
cap.read(frame);
imshow("receiver", frame);
if (waitKey(1) == 27) {
break;
}
}
// When everything done, release the video capture object
cap0.release();
cap1.release();
// Closes all the frames
destroyAllWindows();
return 0;
}
System:
Sender-PC = Ubuntu 18.04
Receiver-PC = Windows 10
OpenCV = 4.2.0
Gstreamer = 1.20.1
Python = 3.8.9
|
72,447,518 | 72,448,542 | Print all subarrays in less than O(n^3) time complexity | To print all the subarrays (contiguous subsequences) of a given array, one requires three nested
for loops. Is there a way to reduce the time complexity of O(n^3) using map in C++ STL?
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio (false);
cin.tie(NULL);
cout.tie(NULL);
vector<int> v;
int n;
cin>>n; // the size of the array
for(int i=0;i<n;i++)
{
int x;
cin>>x;
v.push_back(x);
}
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
for(int k=i;k<=j;k++)
cout<<v[k]<<" ";
cout<<endl;
}
}
return 0;
}
| If you must iterate all elements then you must iterate all elements... No further reduction possible. Reducing time complexity is all about finding ways in which you don't need to iterate all elements.
|
72,447,590 | 72,447,697 | Perform different actions with predefined probability based on random value between 0 and 99 | I'm working on a project where I run actions randomly with a certain probability.
I basically have four actions. Action A has a probability of 40%, Action B has a probability of 40%, Action C has a probability of 15% and Action D has a probability of 5%.
My approach was to generate a random number (int) between 0 and 99 (100 possible integer values). Then run the actions accordingly, but the numbers don't add up for me.
The code is basically:
// values starting from 0 up to 99
randNumber=random(100);
// Probability of 40% (will enter for values including 59 up to 99 (40 numbers))
if (randNumber >= 59)
{
actionA();
}
// Probability of 40% (will enter for values including 18 up to 58 (40 numbers))
else if (randNumber >=18)
{
actionB();
}
// Probability of 15% (will enter for values including 2 up to 17 (15 numbers))
else if (randNumber >=2)
{
actionC();
}
// Remaining probability of what should be 5% (will enter for values including 0 to 1 (2 numbers)) ???
else
{
actionD();
}
Where am I going wrong? With values from 0 to 99, I should have 100 possible numbers. However, the last probability of the last 5% does not add up.
Source of random(): https://www.arduino.cc/reference/en/language/functions/random-numbers/random/
| It actually depends on the source of random(int) function, you are not showing on your question, but I think your problem is more math-related than C++-related, if actually random(int) is uniform between 0 and 99 included.
How many are >=59? I am quite sure there are 41, not 40, therefore you are giving a probability equal to 41%, not 40% (99 - 59 + 1 for the >=). And 18<= x < 59 is quite the same, there actually are 41.
At the end of the day, you do not have numbers because every interval is 1 too much.
Try removing the equal from that >= and rethink about your intervals accordingly, (59, 19 and so on)
|
72,447,643 | 72,528,311 | In C++, (how) can I make a local variable available in other classes during the lifetime of this variable | I am writing a DLL that does chemical calculations. At the entry point (let's say a method called entryPoint()), I get the number of chemical components (componentCount) participating in the reaction and their input concentrations as an array with length componentCount.
To define the reactions, I use a Component enum, which (using operator overloading) enables me to write things like Component::H + Component::O2 >> Component::H2O to define a reaction.
To actually calculate the reaction results, I need to map each enum to the index in the concentrations array. This mapping is not static, but defined by the program calling my DLL and can change between calls to the entry point.
I created a ComponentMapping class which can calculate the mapping (using UUIDs) and then provides a int index(Component) and a Component component(int) member function.
My Problem is, that I need to use this mapping in a lot of places during the runtime of the entryPoint() function. Normally I would write something like this
void entryPoint(int componentCount, double[] concentrations) {
// somewhat expensive instanciation, which uses UUIDs to generate mapping
ComponentMapping mapping{componentCount};
Reaction reaction1{mapping, Component::H + Component::O2 >> Component::H2O};
// and so on...
}
passing the mapping to anything that needs it. However, like I said, I need to use the mapping in a lot of places and always passing it to every instance and function that uses it somewhere down the call chain would be very tedious.
So what I would like is the ability to make that mapping available in other contexts. Of course I could just use a singleton, but this means I (and especially also other devs working on the same project) need to remember to update the mapping at the beginning of each entry point (there are multiple). Is there any alternative or modification of the singleton pattern which scopes the lifetime of the mapping to that of the entryPoint() function?
| So, I came up with my own solution, in case anyone is interested:
I created a LifetimeScope class, which can be used to initialize temporarily scoped Singletons and looks as follows:
class LifetimeScope {
public:
LifetimeScope() = default;
LifetimeScope(const LifetimeScope&) = delete;
LifetimeScope(LifetimeScope&&) = delete;
LifetimeScope& operator=(const LifetimeScope&) = delete;
LifetimeScope& operator=(LifetimeScope&&) = delete;
~LifetimeScope() {
for (auto& f : m_onScopeEndFunctions) {
f();
}
}
void onScopeEnd(void (*f)()) {
m_onScopeEndFunctions.push_back(f);
}
private:
std::vector<void (*)()> m_onScopeEndFunctions;
Now Singleton classes (e.g. the ComponentMapping) can look like this:
class ComponentMappipng {
public:
void destroy() {
delete m_instance;
m_instance = nullptr;
}
void create(LifetimeScope& scope) {
assert(!s_instance);
s_instance = new ComponentMapping();
scope.onScopeEnd(destroy);
}
ComponentMapping& instance() {
assert(s_instance);
return *s_instance;
}
// instance methods
private:
// instance fields
static ComponentMapping* s_instance;
}
The entry point then looks like this:
void entryPoint() {
LifetimeScope scope();
ComponentMapping::create(scope);
// stuff that uses the componentMapping
}
At the end of the function, the componentMapping will be distroyed, so it cannot be accidentally used in an invalid scope.
|
72,447,710 | 72,448,195 | override malloc and new calls in cpp program | I want to call my custom malloc/new calls instead of standard library functions.
1. for malloc, I have this short program
#include <stdio.h>
#include <stdlib.h>
void *__real_malloc(size_t size);
void *__wrap_malloc(size_t size)
{
void *ptr = __real_malloc(size);
printf("malloc(%ld) = %p\n", size, ptr);
return ptr;
}
int main(void) {
int* ptr = (int*) malloc(sizeof(int));
return 0;
}
I use the following command to compile
g++ -Wl,--wrap,malloc main.cpp
But getting below error
/usr/bin/ld: /tmp/ccnB04KY.o: in function `__wrap_malloc(unsigned long)':
b3.cpp:(.text+0x18): undefined reference to `__real_malloc(unsigned long)'
/usr/bin/ld: /tmp/ccnB04KY.o: in function `main':
b3.cpp:(.text+0x54): undefined reference to `__wrap_malloc'
collect2: error: ld returned 1 exit status
This works with gcc for .c files but not with g++ and .cpp files. What's the issue?
2. Also I cant figure out how to overide new calls?
| Why does g++ not work with -Wl,--wrap,malloc?
g++ is for C++, and C++ ABI is different from C ABI. So you need to add extern "C" around __real_malloc and __wrap_malloc:
extern "C" {
void *__real_malloc(size_t size);
void *__wrap_malloc(size_t size) {
void *ptr = __real_malloc(size);
printf("malloc(%ld) = %p\n", size, ptr);
return ptr;
}
}
C++ rewrites names to some kind of random (at least it seems so) strings to avoid conflicts, while C often simply inserts _ before the "C" name to create a name in assembly. (This naming convention is called _cdecl, and is used most commonly.) extern "C" forces C++ compiler to generate names according to C's convention. See https://en.wikipedia.org/wiki/Name_mangling for more information.
How to override new?
You can override new specifically for a class, or provide a global new. See https://en.cppreference.com/w/cpp/memory/new/operator_new.
|
72,447,799 | 72,448,115 | Emplacing an instance with constant fields fails to compile (C++) | I have an example_class with two constant fields. When I try to emplace an object of that class into a std::vector, I get various errors such as "error: object of type 'example_class' cannot be assigned because its copy assignment operator is implicitly deleted". Does anyone know what is going on here? If I remove the const in example class, the code compiles without problems.
#include <vector>
#include <iostream>
using namespace std;
class example_class {
public:
example_class(int v1, int v2) : val1(v1), val2(v2) {}
private:
const int val1, val2;
};
int main() {
vector<example_class> *vec = new vector<example_class>();
vec->emplace(vec->begin() + 1, 13131, 12313);
return 0;
}
| By trying to use the std::vector<T>::emplace in this case we get something like: error: use of deleted function ‘Foo& Foo::operator=(Foo&&)’ which follows from the fact that...
...if the required location (e.g. vec.begin()) has been occupied by an existing element, the
inserted element is constructed at another location at first, and then
move assigned into the required location - More here
The example_class cannot be move assigned due to presence of const data members.
You still can construct elements directly in the vec by making sure that you not trying to construct them in place of any already existing element - by using `emplace_back().
More importantly, note that in vec.begin()+1 you try to access beyond the currently allocated memory for the vec (which is empty, meaning vec.begin() == vec.end()). It's the same as assuming that subscripting an element after the end of a vector will add an element to it - which is wrong.
|
72,448,497 | 72,450,520 | JVMTI Invoke toString(); on an Java object from C++ code | So, I was trying to invoke the toString(); method on an object (in this case an enum). This immediately crashed my application. I am assuming that, since the toString(); method isn't declared directly in the enum but inherited from the Object class (Enum in this case) it is not able to find the method and therefore causes an error.
bool is_miss() {
// the enum I want to invoke toString() on, the type() method works just fine and returns the jobject
jobject rt_type = type();
// I assume that this is where i'm doing something wrong
// Edit: My assumption was right, this is the line that causes the crash
jmethodID method = m_jenv->GetMethodID(m_jenv->GetObjectClass(rt_type), "toString", "()Ljava/lang/String;");
jstring str = (jstring)m_jenv->CallObjectMethod(rt_type, method);
jboolean is_copy = jboolean{ true };
return std::string(m_jenv->GetStringUTFChars(str, &is_copy));
}
How m_jenv is declared:
JNIEnv* m_jenv;
And it's initialization:
// ... other code ...
jsize count;
if (JNI_GetCreatedJavaVMs(&m_jvm, 1, &count) != JNI_OK || count == 0) {
return;
}
jint res = m_jvm->GetEnv((void**)&m_jenv, JNI_VERSION_1_6);
if (res == JNI_EDETACHED) {
res = m_jvm->AttachCurrentThread((void**)&m_jenv, nullptr);
}
if (res != JNI_OK) {
return;
}
// ... other code ...
However, the initialization works and the m_jenv field is accessed through a global variable holding a class that holds the JNIEnv* field. It's accessed by countless methods, even within the class of the is_miss() method and it's only this method causing an error.
How would I invoke the toString method on a enum (or Java object in general) via JVMTI?
| I have been experimenting a bit, and now that I found a solution it makes sense why it didn't work.
Instead of trying to find the toString() method in the class directly, I passed the class found at the classpath of java/lang/Enum (or java/lang/Object for non-enum types) to the getMethodID() function.
jmethodID method = m_jenv->GetMethodID(m_jenv->FindClass("java/lang/Enum"), "toString", "()Ljava/lang/String;");
And then just passed my jobject to CallObjectMethod().
jobject result = m_jenv->CallObjectMethod(rt_type, method);
|
72,448,770 | 72,448,850 | C++ get and set item in map as value inside unordered_map? | std::unordered_map<string, tuple<int, vector<int>>> combos;
I want to retrieve items inside tuple and also to increase or set their value.
e.g.
if(v_intersection.size()==5){
string stringval = join(v_intersection, ",");
if (combos.find(stringval) == combos.end()) // if key is NOT present already
{
combos[stringval]get<0>(combos[stringval]) = 1; // initialize the key with value 1
}
else
{
combos[stringval]++; // key is already present, increment the value by 1
}
}
I want to set int (the first parameter of tuple) to 1 and also increase it by 1 when needed.
It is not inside a for loop but in a if conditional clause.
How to do that?
I tried combos[stringval]get<0>(combos[stringval]) = 1; but it is not working.
What if I want to add items inside the vector from that map? How to do it?
Also, if you have any idea on how to do this using something else other than nested maps with tuples, please give to me your advise.
Thank you in advance!
It is not duplicate, please check it out. There are some topics but asking for something else not nested maps with tuples as values.
| std::get(std::tuple) is a free function that takes a tuple as parameter. So you have to call it like so: get<INDEX>(some_tuple).
Knowing this, answering your question is just a matter of passing the tuple from the map to that function.
I want to set int (the first parameter of tuple) to 1
std::get<0>(combos[stringval]) = 1;
and also increase it by 1 when needed.
std::get<0>(combos[stringval])++;
|
72,448,817 | 72,449,889 | C# Matrix4x4 equivalent of DirectX::XMMatrixPerspectiveLH | I was trying to port some c++ code to C#, everything works except the perspective.
In c++ the code looks like this, which worked without distortion.
DirectX::XMMatrixTranspose(
DirectX::XMMatrixRotationZ(100) *
DirectX::XMMatrixRotationX(200) *
DirectX::XMMatrixTranslation(0,0,4) *
DirectX::XMMatrixPerspectiveLH(DirectX::XMConvertToRadians(180),pAdapter->aspectRatio,0.5f,10)
and the C# code like this
Matrix4x4.Transpose(
Matrix4x4.CreateRotationZ(100) *
Matrix4x4.CreateRotationX(200) *
Matrix4x4.CreateTranslation(0, 0, 4) *
Matrix4x4.CreatePerspective(1.39626f, 1.7777777777777777777777777777778f, 0.5f,10)
);
I would assume both of these would do the exact same, but the C# code doesn't appear at all, when i remove the perspecitve it renders but everything is strecthed as expected.
I tried to remake the source of dxmath which resulted in this, it now renders as further away but its still stretched.
Matrix4x4 perspective = new Matrix4x4();
float ViewWidth = 1.39626f;
float ViewHeight = 1.7777777777777777777777777777778f;
float NearZ = 0.5f;
float FarZ = 10.0f;
float TwoNearZ = NearZ + NearZ;
float fRange = FarZ / (NearZ - FarZ);
perspective.M11 = TwoNearZ / ViewWidth;
perspective.M22 = TwoNearZ / ViewHeight;
perspective.M33 = fRange;
perspective.M43 = -fRange * NearZ;
data.matrix = perspective * data.matrix;
Im not really sure what the problem is, i read in another post that matrix4x4 is right handed so i tried the same with that one but it didn't render at all. Any help is appreciated.
| The perspective matrix you use appear strange. I suggest you to use the more classical implementation from OpenGL documentation. Also, notice that you don't explicitly set the M44 value of your perspective matrix to 0.0f while this value is set to 1.0f for default identity matrix. This result in a wrong perspective matrix.
float frustumDepth = farDist - nearDist;
float oneOverDepth = 1 / frustumDepth;
perspective.M22 = (float)(1.0f / Math.Tan(0.5f * fovRadians));
perspective.M11 = 1.0f * perspective.M22 / aspectRatio;
perspective.M33 = farDist * oneOverDepth;
perspective.M34 = 1.0f;
perspective.M43 = (farDist * nearDist) * oneOverDepth;
perspective.M44 = 0.0f; //< replace 1.0f to 0.0f
|
72,449,160 | 72,449,192 | How to pick up a random value from an enum class? | hello,
Been recently into C++ (C++14 to be precise), and I'me trying to get my way with enums, still have a bit of trouble figuring things out
Currently, trying to get a random value from an enum class that was constructed as such:
enum class Niveau {
#define NIVEAU_DEF(NOM,VALEUR) NOM = VALEUR,
#include "niveau.def"
#undef NIVEAU_DEF
};
And here is the content of "niveau.def"
NIVEAU_DEF(I, 1)
NIVEAU_DEF(II, 2)
...
NIVEAU_DEF(IX, 9)
NIVEAU_DEF(X, 10)
Is it possible to pick up a random one of those enumerations using a method ? Or does this way of constructing an enum doesn't allow it?
| Since you have a XMacro already, you can just reuse it to create an array of the values and pick from it:
const Niveau niveau_vals[] = {
#define NIVEAU_DEF(NOM,VALEUR) Niveau::VALEUR,
#include "niveau.def"
#undef NIVEAU_DEF
};
In newer versions of the language, you can make it a nice constexpr with std::array.
constexpr std::array niveau_vals = {
#define NIVEAU_DEF(NOM,VALEUR) Niveau::VALEUR,
#include "niveau.def"
#undef NIVEAU_DEF
};
|
72,449,410 | 72,449,983 | Using FRIEND_TEST to test private functions of a class in another namespace | I'm trying to use GTest's FRIEND_TEST() macro to enable testing of some private functions from another namespace. However, I can't get past some errors, though I must be missing something simple.
I have Tests.cpp where I would like to test private functionality of MyClass:
namespace a::b::tests
{
class MyTests : public ::testing::Test { ... };
TEST_F(MyTests, Test1)
{
// Test private functions of MyClass instance from MyClass.cpp
...
}
}
In MyClass.h, implemented in MyClass.cpp, I have:
namespace a::b
{
class MyTests_Test1_Test; // Forward declaration.
class MyClass
{
private:
FRIEND_TEST(a::b::tests::MyTests, Test1);
...
};
}
However, this fails with compile-time errors 'a::b::tests' has not been declared and error: friend declaration does not name a class or function.
If I try to forward-declare the namespace by adding using a::b::tests; in MyClass.h, the error remains.
How can I properly make MyTests a friend class of MyClass here?
| Turns out I had to do forward declarations like this, in MyClass.h:
namespace a::b::tests
{
class MyTests;
class MyTests_Test1_Test;
}
namespace a::b
{
class MyClass
{
private:
FRIEND_TEST(a::b::tests::MyTests, Test1);
...
};
}
|
72,449,667 | 72,458,204 | How to get an image char array by using libpng? | Although I have successfully utilized stb_image/CImg/lodepng open source to get a char array, the memory usage is too huge that I can't implement it in a low power embedded system.
Therefore, I try to use libpng to read a png type image, and get a char array.
However, I am completely not familiar with libpng......
Anyone can help?
According to some website sample programs, I write the following function. But I encounter Segmentation Fault, I think that I have problem dealing with the variables, raw_pointers and image. Anyone can review my code and give me some suggestions?
unsigned char* read_png_file(const char *filename)
{
FILE *fp = fopen(filename, "rb");
int bit_depth;
int color_type;
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info = png_create_info_struct(png);
png_init_io(png, fp);
png_read_info(png, info);
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
color_type = png_get_color_type(png, info);
bit_depth = png_get_bit_depth(png, info);
int numchan = 4;
// Set up row pointers
row_pointers = (unsigned char**) malloc(sizeof(unsigned char) * height);
for (int y=0; y<height; y++)
row_pointers[y] = (unsigned char*) malloc(sizeof(unsigned char) * width);
png_read_image(png, row_pointers);
// Put row pointers data into image
unsigned char * image = (unsigned char *) malloc (numchan*width*height);
for (unsigned int i=0;i<height;i++)
for (unsigned int j=0;j<width;i++)
*image++ = row_pointers[j][i];
fclose(fp);
cout << height << ", " << width << ", " << bit_depth << ", " << numchan << endl;
return image;
}
| I successfully use libpng to get a char array.
However, the memory usage is up to 915.1KB which is higher than stb_image !!! (Use Valgrind)
Ah... Could anyone tell me some directions to optimize the memory usage?
unsigned char* read_png_file(const char *filename)
{
FILE *fp = fopen(filename, "rb");
png_byte bit_depth;
png_byte color_type;
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info = png_create_info_struct(png);
png_init_io(png, fp);
png_read_info(png, info);
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
color_type = png_get_color_type(png, info);
bit_depth = png_get_bit_depth(png, info);
if(color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png);
if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand_gray_1_2_4_to_8(png);
if(png_get_valid(png, info, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png);
if(color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE)
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
if(color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
png_read_update_info(png, info);
int numchan = 4;
// Set up row pointer
png_bytep *row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height);
unsigned int i, j;
for (i = 0; i < height; i++)
row_pointers[i] = (png_bytep)malloc(png_get_rowbytes(png,info));
png_read_image(png, row_pointers);
// Put row pointers data into image
unsigned char *image = (unsigned char *) malloc (numchan*width*height);
int count = 0;
for (i = 0 ; i < height ; i++)
{
for (j = 0 ; j < numchan*width ; j++)
{
image[count] = row_pointers[i][j];
count += 1;
}
}
fclose(fp);
for (i = 0; i < height; i++)
free(row_pointers[i]) ;
free(row_pointers) ;
return image;
}
|
72,450,588 | 72,450,631 | co_await inside catch no longer compiling with GCC12 | I have a code that looks like this:
auto func() -> asio::awaitable<void> {
try {
co_await async_operation();
} catch(boost::system::system_error const& e) {
co_return co_await another_async_operation();
}
}
This code worked perfectly with GCC 11, but with GCC 12 it won't compile:
file.cpp:3:19: error: await expressions are not permitted in handlers
3 | co_return co_await another_async_operation();
| ^~~~~~~~
Why is that and how can I fix it?
| This is explicitly forbidden in [expr.await]/2:
An await-expression shall appear only in a potentially-evaluated expression within the compound-statement of a function-body outside of a handler ([except.pre]).
The error message here is pretty clear: you can't await in an exception handler. That it compiled before is a bug, this was always the rule (P0912R5).
|
72,450,718 | 72,450,949 | Store pointers to copies of the parameter pack in a tuple | I want to store pointers to copies of parameter pack arguments in a tuple. Here is the code:
struct FDead {};
struct FAlive {};
struct FBossDead final : FDead {};
struct FBossAlive final : FAlive {};
template<typename... TStates>
struct TContext
{
using FTuple = std::tuple<TStates*...>;
template<typename... TSubStates>
explicit TContext(TSubStates&&... InStates)
{
static_assert(sizeof...(TStates) == sizeof...(TSubStates));
// FIXME: Check if TSubStates are actually sub-types of TStates
//static_assert(((std::is_base_of_v<TStates, TSubStates> || ...) && ...));
States = FTuple{(new TSubStates{ InStates }, ...)};
}
FTuple States;
};
void Test()
{
TContext<FAlive, FDead> Context
{
FBossAlive{},
FBossDead{}
};
}
As you can see, FBossDead extends FDead, and FBossAlive extends FAlive. TContext is created with base types as template arguments but then I'm sending their subtypes that I want to copy and then store pointers to them in the States tuple.
I am getting this compilation error though:
[C2440] '<function-style-cast>': cannot convert from 'initializer list' to 'std::tuple<PCF::SubClass::FAlive *,PCF::SubClass::FDead *>'
I believe that's because of this fold expression:
(new TSubStates{ InStates }, ...)
that evaluates to a initializer_list, not a tuple (because of the comma, I believe) but I have no idea how to fix this problem. Any help will be much appreciated!
n.b. I need to store copies, I can not change the constructor signature to accept a pack of pointers.
| You don't need a fold expression here. A regular parameter pack expansion will do the trick just fine.
Also, while not strictly necessary for your example as posted, using std::forward<> when dealing with Forwarding References (which InStates is) is a good habit to get into.
States = FTuple{ new TSubStates{ std::forward<TSubStates>(InStates) }... };
But you might as well do it in the initializer list:
template<typename... TSubStates>
explicit TContext(TSubStates&&... InStates)
: States{ new TSubStates{ std::forward<TSubStates>(InStates) }... } {
// FIXED: Check if TSubStates are actually sub-types of TStates
// But this is redundant, as the pointer assignment itself would fail.
static_assert((std::is_base_of_v<TStates, TSubStates> && ...));
}
|
72,450,903 | 72,451,102 | vector<unique_ptr<Base> > using initialization list of Derived | I have a follow-up question to this one:
vector<unique_ptr<A> > using initialization list
I would like to achieve essentially the same goal as in the referenced question, but this time using polymorphic classes. That is, I would like to create a std::vector<std::unique_ptr<Base>> using an initialization list.
#include <vector>
#include <memory>
#include <iterator>
#include <iostream>
template<class T>
struct movable_il {
mutable T t;
operator T() const&& { return std::move(t); }
movable_il( T&& in ): t(std::move(in)) {}
};
template<class T, class A=std::allocator<T>>
std::vector<T,A> vector_from_il( std::initializer_list< movable_il<T> > il ) {
std::vector<T,A> r( std::make_move_iterator(il.begin()), std::make_move_iterator(il.end()) );
return r;
}
// Example with class hierarchy
class Base
{
public:
Base(int in) : x(in) {}
virtual ~Base() = default;
virtual void print() const = 0;
protected:
int x;
};
class Derived1 : public Base
{
public:
Derived1(int in) : Base(in) {}
virtual ~Derived1() = default;
virtual void print() const override { std::cout << "Derived1: " << x << std::endl; }
};
class Derived2 : public Base
{
public:
Derived2(int in) : Base(in) {}
virtual ~Derived2() = default;
virtual void print() const override { std::cout << "Derived2: " << x << std::endl; }
};
int main()
{
{
auto v = vector_from_il< std::unique_ptr<Base> >({
std::make_unique<Derived1>(7),
std::make_unique<Derived2>(3)
});
for (const auto & val : v)
val->print();
}
return 0;
}
the compiler (GCC 7.4.0 on Ubuntu 18) error message is:
template argument deduction/substitution failed:
cannot convert '{std::make_unique(_Args&& ...)
[with _Tp = Derived1;
_Args = {int};
typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<Derived1, std::default_delete<Derived1> >](),
std::make_unique(_Args&& ...)
[with _Tp = Derived2;
_Args = {int};
typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<Derived2, std::default_delete<Derived2> >]()}'
(type '<brace-enclosed initializer list>') to type 'std::initializer_list<movable_il<std::unique_ptr<Base> > >'
I assume the error is related to the fact that no conversions are taken into account during template argument deduction, so maybe this is just not possible to do.
| Adding extra constructor
template <typename U>
movable_il(U&& in): t(std::forward<U>(in)) {}
fixes compilation.
Demo.
|
72,451,130 | 72,451,307 | Why don't we add parenthesis when writing comparator in c++? | Here is a code explaining what I mean.
static bool comparator(int a, int b) {
if(a > b) return false;
return true;
}
sort(arr.begin(), arr.end(), comparator); // why don't we write comparator()
| If you will write
sort(arr.begin(), arr.end(), comparator());
then it means that the argument expression of the function std::sort comparator() must be evaluated. But neither arguments are supplied to the function call comparator(). So the compiler will issue an error message.
On the other hand, if you will write
sort(arr.begin(), arr.end(), comparator);
then the function designator comparator is implicitly converted to a pointer to the function and the function std::sort within itself will call the function using the pointer and supplying two arguments to it.
|
72,451,615 | 72,451,785 | Is function trailing return type evaluated when requires clause fails | Simple code as below or as on godbolt doesn't compile with clang but compiles fine with gcc and Visual Studio.
The trailing return type decltype(foo(t)) of baz(T t) is not evaluated when SFINAE fails with clang, gcc and Visual Studio.
However, the trailing return type decltype(foo(t)) of bar(T t) is still evaluated when requires clause fails with clang. The trailing return type is not evaluated when requires clause fails with gcc and Visual Studio. Which compiler is correct on this?
Thank you.
#include <utility>
#include <type_traits>
template<typename T>
auto foo(T) {
static_assert(std::is_integral<T>::value); // clang error: static_assert failed due to requirement 'std::is_integral<double>::value'
return 5;
}
template<typename T> requires std::is_integral<T>::value
auto bar(T t) -> decltype(foo(t)) {
return foo(t);
}
template<typename T> requires (!std::is_integral<T>::value)
auto bar(T) {
return 1.5;
}
template<typename T, std::enable_if_t<std::is_integral<T>::value>* = nullptr>
auto baz(T t) -> decltype(foo(t)) {
return foo(t);
}
template<typename T, std::enable_if_t<!std::is_integral<T>::value>* = nullptr>
auto baz(T) {
return 1.5;
}
int main()
{
bar(5.); // fails with clang, works with gcc and VS
baz(5.); // works with clang, gcc and VS
}
| This is CWG 2369, which clang does not appear to implement yet.
The example in that issue (which can now be found in [temp.deduct.general]/5) doesn't compile on clang, but does on gcc.
template <class T> struct Z {
typedef typename T::x xx;
};
template <class T> concept C = requires { typename T::A; };
template <C T> typename Z<T>::xx f(void *, T); // #1
template <class T> void f(int, T); // #2
struct A {} a;
struct ZZ {
template <class T, class = typename Z<T>::xx> operator T *();
operator int();
};
int main() {
ZZ zz;
f(1, a); // OK, deduction fails for #1 because there is no conversion from int to void*
f(zz, 42); // OK, deduction fails for #1 because C<int> is not satisfied
}
|
72,451,826 | 72,452,056 | C++ pass a non const string by reference with default value | So I am working on a codebase where this someFunc is called at a lot of places and I can't afford to change it by adding this new variable at all places where this function is called. And that too when that variable is not needed at all the place where someFunc is called.
So I have a requirement where I need to have a function definition having a string which is pass by reference and we are able to mutate the value of the same.
Pass by reference: because that string variable is used by the caller
Default value : Because this func is called at lot of place, can't change everywhere.
Non const : Because I want to mutate it
This is what I have tried :
ExceptionClass ClassName::someFunc(int a, float b, map<int, string> c, const string &d = "")
The problem with this approach is I am unable to change the value of d inside my function. Getting following error :
How do I use something that fulfills my requirement?
| You can get the equivalent behavior that you are describing by using a separate overload instead of a default value:
class ClassName {
public:
ExceptionClass someFunc(int a, float b, map<int, string> c, string &d);
ExceptionClass someFunc(int a, float b, map<int, string> c) {
string d = "";
return someFunc(a, b, c, d);
}
};
|
72,452,428 | 72,452,488 | c++ structured bindings: What is the standard order of destruction? | Is there any definition of the order of destruction of objects returned from a method that can be put into a structured binding statement? cppreference doesn't seem to mention destruction order, and a quick test on godbolt reveals something other than what I expected.
#include <iostream>
#include <tuple>
struct A{
A()=default;
~A(){ std::cout << "~A()" << std::endl; }
};
struct B{
B()=default;
~B(){ std::cout << "~B()" << std::endl; }
};
struct C{
C()=default;
~C(){ std::cout << "~C()" << std::endl; }
};
auto MakeStuff()
{
auto a = A{};
auto b = B{};
auto c = C{};
return std::make_tuple(std::move(c), std::move(b), std::move(a));
}
int main()
{
auto&& [c, b, a] = MakeStuff();
std::cout << "Results now: " << std::endl;
}
Results:
Program returned: 0
~C()
~B()
~A()
Results now:
~C()
~B()
~A()
I guess structured binding constructs the objects in the [brackets] from right to left, seeing as how the destructors invoked as c first, then b, then a. Is this standard behavior, or am I relying on something implementation-specific here?
Thank you.
| Structured binding changes absolutely nothing about the language in terms of order of construction/destruction. Structured binding is a fiction, a linguistic shorthand that turns get<I>(unnamed_object) or unnamed_object.some_name into some_name. In this fiction, unnamed_object is the actual object which is generated by the expression and captured by the auto[] structured binding declaration.
That object works exactly like any other C++ object. The order of subobject declarations in the class (if it is a class) determines the order of construction and destruction, just like any other C++ object.
Now, when it comes to std::tuple, the order of its subobject declaration is unspecified; it is allowed to vary from implementation to implementation. Again, structured binding has nothing to do with that. So the order of destruction can be whatever your particular implementation wants it to be.
|
72,452,681 | 72,452,682 | Copyable C++ coroutine with data | I have written a forward iterator that iterates over the nodes of a graph in order of a (preorder/postorder/inorder) DFS spanning tree. Since it is quite complicated compared to writing a simple DFS and calling a callback for each encountered node, I thought I could use C++20 coroutines to simplify the code of the iterator.
However, C++20 coroutines are not copyable (much less so if they are stateful) but iterators should better be copyable!
Is there any way I could still use some coroutine-like code for my iterator?
Note: I want all iterators to iterate independently from each other. If I copy an iterator and then call ++ on it, then only the iterator should have advanced, but not its copy.
| I figured that, with the Miro Knejp "goto-hack", something resembling copyable co-routines is possible as follows (this toy example just counts "+1" "*2" until a certain value but it illustrates the point).
(1) this is just a simple wrapper for the actual function
template<class Func, class Data>
struct CopyableCoroutine {
Data data;
Func func;
CopyableCoroutine(const Data& _data, const Func& _func): data(_data), func(_func) {}
bool done() const { return data.done(); }
template<class... Args> decltype(auto) operator()(Args&&... args) {
return func(data, std::forward<Args>(args)...);
}
};
(2) this is where the magic happens
struct my_stack {
int n;
int next_label_idx = 0;
bool done() const { return n > 30; }
};
int wierd_count(my_stack& coro_data) {
static constexpr void* jump_table[] = {&&beginning, &&before_add, &&after_add, &&the_end};
goto* jump_table[coro_data.next_label_idx];
beginning:
while(coro_data.n <= 32) {
coro_data.next_label_idx = 1;
return coro_data.n;
before_add:
coro_data.next_label_idx = 2;
++coro_data.n; // odd steps: add one
return coro_data.n;
after_add:
coro_data.next_label_idx = 3;
coro_data.n *= 2; // even steps: multiply 2
}
the_end:
return -1;
}
play with it here.
NOTE: unfortunately, this "dirty hack" requires some extra work and I would be super happy if that could be avoided somehow. I'd really love to see C++ native coroutines that can be copied if the user promises that its stack is copyable.
|
72,453,622 | 72,453,783 | the child class always have access to the public members of its parent, why and how it is possible? | why does a child class have access to members of a parent class?
and why parent class cannot access the members of child class?
I was preparing for my exams and saw this reasoning question in one of my past papers. this seems quite vague to me , I was confused what will be the proper answer to this question.
it will be quite helpful, if anyone of you guys can provide proper explanation that why parent has no knowledge about child class.
class parent{
public :
void access(){}
};
class child:public parent{
};`
| Using public inheritance, your derived class will have access to protected and public fields and methods declared in the base class. However, your base class doesn't know about your derived class at all. Inheritance only works one way. You basically extend the functionality of a class.
You can think of it as putting a smaller box into a larger one. Each box knows what's inside it, but it doesn't know what's outside of it. The base class is the smaller box, the derived one is the larger box.
|
72,453,646 | 72,453,704 | Does delete delete every element in a vector and free the memory? | vector<int>* v = new vector<int>;
for (int i = 0; i < 100; i++) {
(*v).push_back(i);
}
delete v;
Do I delete every element of the vector and free the memory? If not how do I free the memory?
| An allocating new expression allocates memory, constructs a dynamic object into that memory, and returns a pointer to that object. When you pass such pointer to delete, the pointed object is destroyed and the memory is deallocated.
When an instance of a class, such as a vector is destroyed, its destructor is called. The destructor of vector destroys all elements of the vector.
Sidenote 1: It's rarely useful to use allocating new and delete. When you need dynamic storage, prefer to use RAII constructs such as containers and smart pointers instead.
Sidenote 2: You should avoid unnecessary use of dynamic memory in general. It's quite rare to need singular dynamic vector such as in your example. I recommend following instead:
std::vector<int> v(100);
std::ranges::iota(v, 0);
Sidenote 3: Avoid using (*v).push_back. It's hard to read. Prefer using the indirecting member access operator aka the arrow operator instead: v->push_back
|
72,453,747 | 72,453,776 | how to swap arrays without copying elements | I'd like to swap two integer arrays without copying their elements :
int Z1[10],Z2[10];
std::swap(Z1,Z2); // works
//int *tmp;*tmp=*Z1;*Z1=*Z2;*Z2=*tmp; // doesn't work
[ expressions involving Z1,Z2 ]
In the third line I commented out what I tried and didn't work
Is there a way to do this by swapping pointers instead...
|
how to swap arrays without copying elements
By virtue of what swapping is, and what arrays are, it isn't possible to swap arrays without copying elements (to be precise, std::swap swaps each element and a swap is conceptually a shallow copy).
What you can do is introduce a layer of indirection. Point to the arrays with pointers. Then, swapping the pointers will swap what arrays are being pointed without copying elements:
int* ptr1 = Z1;
int* ptr2 = Z2;
std::swap(ptr1, ptr2); // now ptr1 -> Z2, ptr2 -> Z1
|
72,454,299 | 72,459,974 | Why does static_cast of an enum class stored in a bit-field change the result? | Given an enum class stored in a bit-field:
#include <cstdint>
#include <iostream>
enum class Orientation: uint8_t
{
NORMAL = 0,
CLOCKWISE = 1,
ANTICLOCKWISE = 2
};
inline Orientation operator+(const Orientation& lvalue, const Orientation& rvalue)
{
switch(lvalue)
{
case Orientation::NORMAL: return rvalue;
case Orientation::CLOCKWISE:
switch (rvalue)
{
case Orientation::CLOCKWISE: return Orientation::ANTICLOCKWISE;
case Orientation::ANTICLOCKWISE: return Orientation::NORMAL;
case Orientation::NORMAL: return Orientation::CLOCKWISE;
}
__builtin_unreachable();
case Orientation::ANTICLOCKWISE:
switch (rvalue)
{
case Orientation::CLOCKWISE: return Orientation::NORMAL;
case Orientation::ANTICLOCKWISE: return Orientation::CLOCKWISE;
case Orientation::NORMAL: return Orientation::ANTICLOCKWISE;
}
__builtin_unreachable();
}
__builtin_unreachable();
}
class Puzzle {
private:
Orientation or1_ : 2;
Orientation or2_ : 2;
public:
Puzzle(
const Orientation or1,
const Orientation or2
) :
or1_(or1),
or2_(or2)
{}
bool checkPolarity() const
{
return (or1_ + or2_)
== Orientation::NORMAL;
}
bool checkPolarityWithCast() const
{
return (static_cast<Orientation>(or1_) + static_cast<Orientation>(or2_))
== Orientation::NORMAL;
}
};
int main()
{
Puzzle puzzle(
Orientation::ANTICLOCKWISE,
Orientation::CLOCKWISE
);
std::cout << "No cast: " << puzzle.checkPolarity() << '\n';
std::cout << "Cast: " << puzzle.checkPolarityWithCast() << '\n';
}
In x86-64 gcc 8.4, 8.5, 9.3, 9.4 and 9.5 the output is:
No cast: 0
Cast: 1
But from gcc 10, the output is:
No cast: 1
Cast: 1
Why does the static_cast make a difference to the output? Is it a bug in the compiler that was fixed from g++ 10?
godbolt here
| With G++8.4, the assembly code for Puzzle.checkPolarity() is:
Puzzle::checkPolarity() const:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
movzx eax, BYTE PTR [rax]
and eax, 3
mov edx, eax
mov rax, QWORD PTR [rbp-8]
movzx eax, BYTE PTR [rax]
shr al, 2
and eax, 3
add eax, edx
test al, al
sete al
pop rbp
ret
And, as commented by Goswin von Brederlow
Because g++ 8.4 and 9.3 don't call the custom operator+. I guess they do integer promotion for the + and then the equality is false.
As commented by Yksisarvinen
Looks like a fixed bug indeed: gcc.gnu.org/bugzilla/show_bug.cgi?id=92859
However, that bug report states:
Comment 5 Jason Merrill 2019-12-19 14:23:49 UTC
Fixed for 8.4/9.3/10.
and it appears that it has not entirely been fixed as it is still appearing to be bugged in x86-64 gcc 8.4, 8.5, 9.3, 9.4 and 9.5 but the fix does appear to have worked from version 10.
|
72,454,890 | 72,455,025 | Assembly showing a lot of repeating code? | So I'm working on some binary to assembly to c++ code. It's for a project.
When I disassemble the binary I'm getting a lot of repeating assembly code and I'm not sure what it's doing. It's almost like it's just pointing it's way down.
0x0000000000000000 <+0>: push %rbp
0x0000000000000001 <+1>: mov %rsp,%rbp
0x0000000000000004 <+4>: lea 0x0(%rip),%rsi # 0xb <main+11>
0x000000000000000b <+11>: lea 0x0(%rip),%rdi # 0x12 <main+18>
0x0000000000000012 <+18>: callq 0x17 <main+23>
0x0000000000000017 <+23>: callq 0x1c <main+28>
0x000000000000001c <+28>: mov %eax,0x0(%rip) # 0x22 <main+34>
0x0000000000000022 <+34>: mov 0x0(%rip),%eax # 0x28 <main+40>
0x0000000000000028 <+40>: cmp $0x1,%eax
0x000000000000002b <+43>: je 0x40 <main+64>
0x000000000000002d <+45>: lea 0x0(%rip),%rsi # 0x34 <main+52>
0x0000000000000034 <+52>: lea 0x0(%rip),%rdi # 0x3b <main+59>
0x000000000000003b <+59>: callq 0x40 <main+64>
0x0000000000000040 <+64>: mov 0x0(%rip),%eax # 0x46 <main+70>
0x0000000000000046 <+70>: cmp $0x1,%eax
So the repeating code is the "lea" and "callq". Based on the way I'm reading it, it's just pointing to the next line down. For example, the first lea ends with #0xb <main+11> which is the line right below it, and that one points to the line below it, and so on. Can anyone help with what I'm looking at?
There's at least a hundred extra lines in the project, so I'm not looking for a free A, I just need help understanding.
Edit: I am working with a .o file without access to the original .cpp file and the task is to use GDB and Bless to help me read the Assembly output and reassemble it into a .cpp file that works the same as the original code.
|
So the repeating code is the "lea" and "callq".
The addresses suggest that you are disassembling .o file, not an executable (you should always show the command you used when asking about its output).
Try objdump -dr foo.o instead -- the picture should become much clearer.
P.S. GDB isn't really the right tool for looking at .o files anyway.
Update:
I tried the objdump -dr Project1.o and got pretty much the same output
Look closer: it's not the same output. objdump will display relocations, which show where he CALL will actually go to.
You should also be able to link Project1.o into an executable (something like gcc Project1.o -o Project1), and run gdb Project1 and then disas main. You will see that that disassembly makes more sense, and also matches the output of objdump.
|
72,454,912 | 72,455,210 | vector is returning a size() of 0 | I am new to C++ programming and I am having trouble with the following code:
#include <iostream>
#include <vector>
using namespace std;
class Absolute {
public:
vector<int> nums;
Absolute(vector<int> nums) {
nums = nums; //<--- this size is not 0
}
vector<int> getNums() { return nums; }
int addr() {
int total = 0;
for(int i=0; i<nums.size(); i++) { //<--- nums.size() here is 0 even though it should not be
total += nums[i];
}
return total;
}
};
int main() {
vector<int> numbers = {1, 3, 3, 4, 5, 6, 7, 8}; //<--- passing this to addNums but still returns size of 0
Absolute addNums = Absolute(numbers);
cout << addNums.addr() << endl;
return 0;
}
My goal is to add up all the numbers in the vector together using the addr() method, but for some reason the size of the vector is 0 inside of the addr() method, so I end up printing these very large numbers:
15152333321
What is going on here? Could it be that it's not being initialized with the vector in the first place?
| In this code:
Absolute(vector<int> nums)
{
nums = nums;
}
You encounter what I call "Highlander's Law" (There can be only one). In this function, nums refers to the parameter nums, not the member nums. The member nums is shadowed, hidden, by the parameter. So nums = nums; means assign the parameter to itself. The member nums is unchanged and stays at size 0.
Fix: You can change the name of one of the variables so that they do not collide. You can be extra explicit with this->nums = nums, but there's a better and faster option: Use the member initializer list and initialize the member nums with the correct value rather than initialize it to a default and then assign it.
Absolute(vector<int> nums): nums(nums)
{
}
You can use the same name here because there is no ambiguity. The member nums is being initialized, so it must be the left-most nums. It is initialized to the parameter nums because the parameter is the current holder of the identifier nums.
Side note: Consider passing by reference and save yourself a copy:
Absolute(const vector<int> & nums): nums(nums)
{
}
|
72,455,343 | 72,455,849 | Unable to get a jstring from R.string.* via JNI in a native C application | I'm working on a native c/c++ app, that uses string resources via the strings.xml file.
Attempting to use AAssetManager to load the "strings.xml" file, has no effect. Returns the same error
I've tried looking for various other implementations, but none have worked
Android API level (Project): 25
Android API level (Device): 30
The code I've attempted to use so far is the following:
JNIEnv* jni;
g_App->activity->vm->AttachCurrentThread(&jni, NULL);
jclass rcl = jni->FindClass("com.avetharun.rosemary.R$string");
// attempted the above as well as "... R.string" instead of "... R$string"
jfieldID fid = jni->GetStaticFieldID(rcl, "app_name", "s");
// attempted the above as well as "Ljava/lang/String;" instead of "s"
jstring jstr = (jstring)jni->GetObjectField(rcl, fid);
const char* str = jni->GetStringUTFChars(jstr, 0);
Directory tree:
assets
- test.txt
res
- values
- - strings.xml
strings.xml :
<string name="app_name">Rosemary Project</string>
Running this causes an error: 0x0000007f1881daac in __rt_sigtimedwait () from libc.so, as well as "Sequence contains more than one element"
| You're looking for it in the wrong way. The value at R.string.some_string isn't the string itself- it's an integer that references the string. To get the actual string, you need to call Context.getResources().getString(), passing in the id you want to getString.
It's set up this way for resource localization. The R class holds ids used to reference the strings, and can be used at any time. The Resources class holds a map of those ids to the actual strings, and different instances of Resources will be created for different locales, screen sizes, orientations, etc.
|
72,456,118 | 72,907,523 | Why does clang give a warning: unterminated ‘#pragma pack (push, …)’ at end of file? | I create a main.cpp in my vscode with clangd enabled, and put the following code in it.
clangd warns the first line with the warning message:
warning: unterminated ‘#pragma pack (push, …)’ at end of file
The whole content of main.cpp:
#pragma pack(push) // warning on this line
#pragma pack(1)
struct A
{
int a;
short b;
char c;
};
#pragma pack(pop)
See also: https://releases.llvm.org/13.0.0/tools/clang/docs/DiagnosticsReference.html#wpragma-pack
I think it's a very common usage of #pragma pack(push), I don't understand why the warning is generated.
More strange to me, if I add a semicolon before the first line, the warning disappears.
; // Add a semicolon
#pragma pack(push) // The warning disappears
#pragma pack(1)
struct A
{
int a;
short b;
char c;
};
#pragma pack(pop)
What's the reason behind?
| This is a known bug in clangd, tracked in https://github.com/clangd/clangd/issues/1167.
Please see that issue for an explanation of why this currently happens and a potential workaround.
|
72,456,580 | 72,458,056 | Broadcasting Row and Column Vector in Eigen C++ | I have following Python Code written in NumPy:
> r = 3
> y, x = numpy.ogrid[-r : r + 1, -r : r + 1]
> mask = numpy.sqrt(x**2 + y**2)
> mask
array([[4.24264, 3.60555, 3.16228, 3.00000, 3.16228, 3.60555, 4.24264],
[3.60555, 2.82843, 2.23607, 2.00000, 2.23607, 2.82843, 3.60555],
[3.16228, 2.23607, 1.41421, 1.00000, 1.41421, 2.23607, 3.16228],
[3.00000, 2.00000, 1.00000, 0.00000, 1.00000, 2.00000, 3.00000],
[3.16228, 2.23607, 1.41421, 1.00000, 1.41421, 2.23607, 3.16228],
[3.60555, 2.82843, 2.23607, 2.00000, 2.23607, 2.82843, 3.60555],
[4.24264, 3.60555, 3.16228, 3.00000, 3.16228, 3.60555, 4.24264]])
Now, I am making the mask in Eigen where I need to broadcast row and column vector. Unfortunately, it is not allowed so I made the following workaround:
int len = 1 + 2 * r;
MatrixXf mask = MatrixXf::Zero(len, len);
ArrayXf squared_yx = ArrayXf::LinSpaced(len, -r, r).square();
mask = (mask.array().colwise() + squared_yx) +
(mask.array().rowwise() + squared_yx.transpose());
mask = mask.cwiseSqrt();
cout << "mask" << endl << mask << endl;
4.24264 3.60555 3.16228 3 3.16228 3.60555 4.24264
3.60555 2.82843 2.23607 2 2.23607 2.82843 3.60555
3.16228 2.23607 1.41421 1 1.41421 2.23607 3.16228
3 2 1 0 1 2 3
3.16228 2.23607 1.41421 1 1.41421 2.23607 3.16228
3.60555 2.82843 2.23607 2 2.23607 2.82843 3.60555
4.24264 3.60555 3.16228 3 3.16228 3.60555 4.24264
It works. But I wonder if there is another and shorter way to do it. Therefore my question is how to broadcast Row and Column Vector in Eigen C++?
System Info
Tool
Version
Eigen
3.3.7
GCC
9.4.0
Ubuntu
20.04.4 LTS
| I think the easiest approach (as in: most readable), is replicate.
int r = 3;
int len = 1 + 2 * r;
const auto& squared_yx = Eigen::ArrayXf::LinSpaced(len, -r, r).square();
const auto& bcast = squared_yx.replicate(1, len);
Eigen::MatrixXf mask = (bcast + bcast.transpose()).sqrt();
Note that what you do is numerically unstable (for large r) and the hypot function exists to work around these issues. So even your python code could be better:
r = 3
y, x = numpy.ogrid[-r : r + 1, -r : r + 1]
mask = numpy.hypot(x, y)
To achieve the same in Eigen, do something like this:
const auto& yx = Eigen::ArrayXf::LinSpaced(len, -r, r);
const auto& bcast = yx.replicate(1, len);
Eigen::MatrixXf mask = bcast.binaryExpr(bcast.transpose(),
[](float x, float y) noexcept -> float {
return std::hypot(x, y);
});
Eigen's documentation on binaryExpr is currently broken, so this is hard to find.
To be fair, you will probably never run into stability issues in this particular case because you will run out of memory first. However, it'd still like to point this out because seeing a naive sqrt(x**2 + y**2) is always a bit of a red flag. Also, in Python hypot might still worth it from a performance point because it reduces the number of temporary memory allocations and function calls.
BinaryExpr
The documentation on binaryExpr is missing, I assume because the parser has trouble with Eigen's C++ code. In any case, one can find it indirectly as CwiseBinaryOp and similarly CwiseUnaryOp, CwiseNullaryOp and CwiseTernaryOp.
The use looks a bit weird but is pretty simple. It takes a functor (either a struct with operator(), a function pointer, or a lambda) and applies this element-wise.
The unary operation makes this pretty clear. If Eigen::Array.sin() didn't exist, you could write this:
array.unaryExpr([](double x) -> double { return std::sin(x); }) to achieve exactly the same effect.
The binary and ternary versions take one or two more Eigen expressions as the second and third argument to the function. That's what I did above. The nullary version is explained in the documentation in its own chapter.
Use of auto
Eigen is correct to warn about auto but only in that you have to know what you do. It is important to realize that auto on an Eigen expression just keeps the expression around. It does not evaluate it into a vector or matrix.
This is fine and very useful if you want to compose a complex expression that would be hard to read when put in a single statement. In my code above, there are no temporary memory allocations and no floating point computations take place until the final expression is assigned to the matrix.
As long as the programmer knows that these are expressions and not final matrices, everything is fine.
I think the main take-away is that use of auto with Eigen should be limited to short-lived (as in: inside a single function) scalar expressions. Any coding style that uses auto for everything will quickly break or be hard to read with Eigen. But it can be used safely and make the code more readable in the process without sacrificing performance in the same way as evaluating into matrices would.
As for why I chose const auto& instead of auto or const auto: Mostly force of habit that is unrelated to the task at hand. I mostly do it for instances like this:
const Eigen::Vector& Foo::get_bar();
void quz(Foo& foo)
{
const auto& bar = foo.get_bar();
}
Here, bar will remain a reference whereas auto would create a copy. If the return value is changed, everything stays valid.
Eigen::Vector Foo::get_bar();
void quz(Foo& foo)
{
const auto& bar = foo.get_bar();
}
Now a copy is created anyway. But everything continues to work because assigning the return value to a const-reference extends the lifetime of the object. So this may look like a dangling pointer, but it is not.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.