question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,250,816 | 71,968,603 | CMake - How to handle dependencies of imported library targets with TARGET_RUNTIME_DLLS | In my project I rely on some third party shared library named foo.
foo itself is relying on some other third party dll (let's call it bar.dll), which is however neither used by my project nor exposed in the headers of foo.
The foo target is created and linked to my project as follows
add_library(foo SHARED IMPORTED)
set_target_properties(foo PROPERTIES
IMPORTED_LOCATION "${foo_dll_path}"
IMPORTED_IMPLIB "${foo_lib_path}"
)
target_link_libraries(my_project PUBLIC foo)
Later on a post build event is triggered to create hard links to all dependent 3rd party libraries via $<TARGET_RUNTIME_DLLS:my_project> generator expression.
How can bar.dll be introduced in this setup to be visible in $<TARGET_RUNTIME_DLLS:my_project>?
So far I tried to add bar.dll as yet another imported target via add_library(bar UNKNOWN IMPORTED) and add_library(bar SHARED IMPORTED) and setting IMPORTED_LOCATION on bar accordingly, which however does create linker errors.
Example:
add_library(bar UNKNOWN IMPORTED)
set_target_properties(bar PROPERTIES
IMPORTED_LOCATION "${bar_dll_path}"
)
target_link_libraries(foo INTERFACE bar)
In case of UNKNOWN the linker will use bar.dll as linker input, which of course fails, in case of SHARED IMPORTED CMake demands that IMPORTED_IMPLIB is set, but neither do I have the import library for bar.dll nor do I want to link my_project against it.
Any other suggestions how to deal with this?
| Since there seems to be no proper solution to this issue I came up with a (possibly fragile) workaround involving a meta target:
# same as before
add_library(foo_real SHARED IMPORTED)
set_target_properties(foo_real PROPERTIES
IMPORTED_LOCATION "${foo_dll_path}"
IMPORTED_IMPLIB "${foo_lib_path}"
)
# add SHARED IMPORTED target with the importlib pointing to foo_reals importlib location
add_library(bar SHARED IMPORTED)
set_target_properties(bar PROPERTIES
IMPORTED_LOCATION "${bar_dll_path}"
IMPORTED_IMPLIB "${foo_lib_path}" # same lib path as for imported target foo
)
# add meta target to combine both
add_library(foo INTERFACE IMPORTED)
target_link_libraries(foo INTERFACE foo_real bar)
# finally link the meta target to the final project
target_link_libraries(my_project PUBLIC foo)
This workaround will cause CMake to generate a build script passing foo.lib multiple times to the linker which does not seem to cause problems with the current MSVC Toolset. Also bar.dll will now be part of TARGET_RUNTIME_DLLS as intended.
|
71,251,192 | 71,251,296 | C++ interpreting/mapping getch() output | Consider this program:
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
std::string input;
std::cin >> input;
}
The user can input any string (or single character) and the program is going to output it as is (upper/lower case or symbols like !@#$%^&* depending on modifiers).
So, my question is: what is the best way to achieve the same result using <conio.h> and _getch()? What's the most straightforward way to map the _getch() keycodes to the corresponding symbols (also depending on the current system's locale)?
What I tried was:
while (true) {
const int key = _getch();
const char translated = VkKeyScanA(key); // From <Windows.h>
std::cout << translated;
}
Although this correctly maps the letters, they're all capitalized and this doesn't map any symbols (and doesn't take modifiers into account). For example:
It outputs ╜ when I type _ or -
It outputs █ when I type [ or {
A cross platform solution would be appreciated.
| The following code works:
// Code 1 (option 1)
while (true)
{
const int key = _getch(); // Get the user pressed key (int)
//const char translated = VkKeyScanA(key);
std::cout << char(key); // Convert int to char and then print it
}
// Code 2 (option 2)
while (true)
{
const char key = _getch(); // Get the user pressed key
//const char translated = VkKeyScanA(key);
std::cout << key; // Print the key
}
|
71,251,287 | 71,251,537 | using struct in sets | I am trying to make a set of sets, what is the correct to method to do that in C++. What i am trying to achieve is something like this
One = { {"DDD", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64},{"JJ", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64},
{"kk", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64}, {"LL", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64} };
I tried like this
#include <set>
#include <iostream>
#include <algorithm>
#include <cstring>
struct Config
{
const char* lbl;
const char* desc;
std::uint8_t se_2A;
std::uint8_t se_2B;
std::uint8_t se_2C;
std::uint8_t se_2D;
std::uint8_t se_2E;
std::uint8_t su_2A;
std::uint8_t su_2B;
std::uint8_t su_2C;
std::uint8_t su_2D;
std::uint8_t su_2E;
std::size_t total_size;
};
inline bool operator<(const Config& lhs, const Config& rhs)
{
return lhs < rhs;
}
int main(){
Config b1 = {"DDD", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64};
Config b2 = {"JJ", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64};
Config b3 = {"kk", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64};
Config b4 = {"LL", "Numbers", 0xf, 0xf, 0xf, 0x0,0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 64};
std::set<Config> newConfig;
std::set<std::set<Config>> One;
newConfig.insert(b1);
newConfig.insert(b2);
}
But gives me this error
Program received signal SIGSEGV, Segmentation fault.
0x00005555555555b9 in operator< (
lhs=<error reading variable: Cannot access memory at address 0x7fffff7feff8>, rhs=<error reading variable: Cannot access memory at address 0x7fffff7feff0>)
at main.cpp:32
Whats the correct to way to do this or fix the error?
|
inline bool operator<(const Config& lhs, const Config& rhs)
{
return lhs < rhs;
}
This operator< calls the operator< which calls the operator< which the operator< which the operator< which calls... can you spot the problem? The recursion is infinite and will eventually overflow the stack.
What you're probably intending to do is to compare the members of one side to the members of the other side. That said, it's easier to let the compiler do the work (C++20 or later required):
struct Config
{
... members ...
friend auto operator<=>(const Config&, const Config&) = default;
};
Another issue that comparing pointers to strings isn't comparing the contents of the string. It might not cause problems in this trivial example, but "Numbers" in this translation unit doesn't necessarily have the same address as "Numbers" in another translation unit. And an automatic array such as char str[] = "Numbers"; definitely wouldn't have the same address.
To compare the strings by their content, you could use std::string_view instead:
struct Config
{
std::string_view lbl;
std::string_view desc;
|
71,251,402 | 71,251,508 | Initialize priority_queue without constructor | I have a priority_queue with custom comparator:
using A = ...
class A {
public:
A() {
auto cmp = [](DataPair left, DataPair right) {
return left.second > right.second;
};
std::priority_queue<DataPair, std::vector<DataPair>, decltype(cmp)> q(cmp);
q_ = q;
}
private:
std::priority_queue<DataPair, std::vector<DataPair>, decltype(cmp)> q_;
};
Is there a way to initialize priority_queue without constructor ?
| You cannot use decltype(cmp) for the member type when cmp is local to the constructor. You can move the definition of the comparator out of the constructor and use the default constructor of priority_queue which default constructs the comparator:
struct cmp {
bool operator()(const DataPair& left,const DataPair& right) {
return left.second > right.second;
}
};
class A {
public:
private:
std::priority_queue<DataPair, std::vector<DataPair>, cmp> q_;
};
|
71,252,104 | 71,257,285 | Why is there no (implicit) conversion from std::tuple<Ts...>& to std::tuple<Ts&...>? |
As the title states, is there a specific reason why there is no (implicit) conversion from std::tuple<Ts...>& to std::tuple<Ts&...>?
In contrast, the tuple implementation of EASTL provides this conversion.
#include <EASTL/tuple.h>
#include <tuple>
#include <type_traits>
int main()
{
using TupleRef = std::tuple<int, float>&;
using RefTuple = std::tuple<int&, float&>;
using EATupleRef = eastl::tuple<int, float>&;
using EARefTuple = eastl::tuple<int&, float&>;
// static_assert(std::is_convertible_v<TupleRef, RefTuple>); // fails to compile
static_assert(std::is_convertible_v<EATupleRef, EARefTuple>);
return 0;
}
What do I have to change/add, if I reimplemented the STL tuple implementation?
Here is a link to godbolt show-casing the problem: https://godbolt.org/z/zqfrETKEz
PS: I used the c++17 flag in godbolt since EASTL does not compile with the c++20 flag, but I am also interested in a c++20 solution.
| There will be in c++23, as a result of the zip paper (P2321).
Generally speaking, it is typical for overload sets to have one overload taking T const& and another overload taking T&&, it's not often that T& is needed as a distinct 3rd option (and T const&& even less so). This is one of those cases that originally had just the two, but then really does need at least the 3rd.
I'm not sure if you had a particular motivation for needing tuple<int>& to be convertible to tuple<int&>, but zip needs that to work, which is why it changed.
|
71,252,342 | 71,252,459 | Conversion error while trying to use CreateProcess Windows API | I am trying to run a C++ program that creates a process:
int main()
{
HANDLE hProcess;
HANDLE hThread;
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD dwProcessId = 0;
DWORD dwThreadId = 0;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
BOOL bCreateProcess = NULL;
bCreateProcess = CreateProcessW(L"C:\\Windows\\System32\\notepad.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (bCreateProcess == FALSE) {
cout << "Create Process Failed & Error No. " << GetLastError() << endl;
}
cout << "Process Creation Successful!" << endl;
cout << "Process ID: " << pi.dwProcessId << endl;
cout << "Thread ID: " << pi.dwThreadId << endl;
cout << "GetProcessID: " << GetProcessId(pi.hProcess) << endl;
cout << "GetThreadID: " << GetThreadId(pi.hThread) << endl;
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}
However, I returns the following error:
main.cpp(19): error C2664: 'BOOL CreateProcessW(LPCWSTR,LPWSTR,LPSECURITY_ATTRIBUTES,LPSECURITY_ATTRIBUTES,BOOL,DWORD,LPVOID,LPCWSTR,LPSTARTUPINFOW,LPPROCESS_INFORMATION)': cannot convert argument 9 from 'LPSTARTUPINFOW *' to 'LPSTARTUPINFOW'
main.cpp(27): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
C:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\um\processthreadsapi.h(372): note: see declaration of 'CreateProcessW'
I am compiling it on Windows 10 using the following command:
cl.exe /EHsc main.cpp
Also, if you could please suggest some tutorials (courses, book, youtube channels, blogs, etc.) for Windows system programming.
| It seems you are compiling with Ansi strings rather than Wide strings, so STARTUPINFO becomes STARTUPINFOA, which is incompatible with CreateProcessW().
When I compile your code, I get error cannot convert argument 9 from 'STARTUPINFO *' to 'LPSTARTUPINFOW', which makes more sense than the error you posted.
Either change the compiler options or write STARTUPINFOW si; in your code.
|
71,252,430 | 71,256,817 | How to add a String Value/ Name Data pair in Windows Registry Editor key using C++ and Windows Registry API's | I want to add a string name and its value to the Windows Registry using C++ code, to stop browsers other than Firefox stop running. I plan to do the Windows Registry editing in a loop for all browsers, but for now I am implementing it for Chrome only.
My current code below is adding a value to the Default string, and it is not working, but I want to create a Debugger string and set it to "ntsd -c q" in the chrome.exe subkey, as shown in the picture below.
Here is my code, which is adding "ntsd -c q" for the Default string and not creating a new Debugger string. I am not able to clearly understand from Microsoft's documentation about how to achieve this using C/C++. I have seen some solutions that do it via the command line, but co-workers are very ethical and they don't prefer that way.
#include <Windows.h>
#include <iostream>
int main()
{
HKEY hkey;
LSTATUS ReturnValue = 0;
LPCTSTR Directory = TEXT("SOFTWARE\\Microsoft\\Windows\ NT\\CurrentVersion\\Image\ File\ Execution\ Options\\chrome.exe");
ReturnValue = RegOpenKeyEx(HKEY_LOCAL_MACHINE, Directory, 0, KEY_ALL_ACCESS, &hkey);
if (ERROR_SUCCESS != ReturnValue)
{
printf("RegOpenKeyEx failed\n");
printf("%d\n", GetLastError());
return -1;
}
//LPCSTR value = "Debugger";
//ReturnValue = RegQueryValueEx(HKEY_LOCAL_MACHINE, Directory, NULL, NULL, value, sizeof(value));
LPCSTR Value = "ntsd\ -c\ q\0";
ReturnValue = RegSetValueA(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\ NT\\CurrentVersion\\Image\ File\ Execution\ Options\\chrome.exe",REG_SZ, Value, sizeof(Value));
if (ERROR_SUCCESS != ReturnValue)
{
printf("RegStatusValueA failed\n");
printf("%d\n", GetLastError());
return -1;
}
ReturnValue = RegCloseKey(hkey);
if (ERROR_SUCCESS != ReturnValue)
{
printf("RegCloseKey failed\n");
printf("%d\n", GetLastError());
return -1;
}
return 0;
}
| KEY_ALL_ACCESS requires admin rights. All you really need in this situation is KEY_SET_VALUE instead. Don't ask for more permissions than you actually need. But, you do still need admin rights to write to HKEY_LOCAL_MACHINE to begin with. So make sure you are running your code as an elevated user.
In any case, your string literals have a few \ that don't belong. But more importantly, your use of RegSetValueA() is completely wrong for this task. It is a deprecated API that can only write to the (Default) string and nothing else (and, you are not even calling it correctly anyway, you would need strlen(Value)+1 instead of sizeof(Value) - not that it matters because that parameter is ignored anyway).
In order to create your Debugger string value, you need to use RegSetValueEx() instead, eg:
#include <Windows.h>
#include <iostream>
int main()
{
HKEY hkey;
LPCTSTR Directory = TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\chrome.exe");
LSTATUS ReturnValue = RegOpenKeyEx(HKEY_LOCAL_MACHINE, Directory, 0, KEY_SET_VALUE, &hkey);
if (ERROR_SUCCESS != ReturnValue)
{
printf("RegOpenKeyEx failed: %u\n", GetLastError());
return -1;
}
LPCTSTR Value = TEXT("ntsd -c q");
ReturnValue = RegSetValueEx(hkey, TEXT("Debugger"), 0, REG_SZ, (const BYTE*)Value, (lstrlen(Value)+1) * sizeof(TCHAR));
if (ERROR_SUCCESS != ReturnValue)
{
printf("RegSetValueExA failed: %u\n", GetLastError());
RegCloseKey(hkey);
return -1;
}
ReturnValue = RegCloseKey(hkey);
if (ERROR_SUCCESS != ReturnValue)
{
printf("RegCloseKey failed: %u\n", GetLastError());
return -1;
}
return 0;
}
|
71,252,474 | 71,252,547 | Is there a build command for meson? | Well I can init and build a meson with project as:
$ cd /tmp/
$ mkdir foobar; cd foobar
$ meson init --name foobar -l cpp --build
Using "foobar" (project name) as name of executable to build.
Sample project created. To build it run the
following commands:
meson builddir
ninja -C builddir
Building...
The Meson build system
Version: 0.53.2
Source dir: /tmp/foobar
Build dir: /tmp/foobar/build
Build type: native build
Project name: foobar
Project version: 0.1
C++ compiler for the host machine: c++ (gcc 9.3.0 "c++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0")
C++ linker for the host machine: c++ ld.bfd 2.34
Host machine cpu family: x86_64
Host machine cpu: x86_64
Build targets in project: 1
Found ninja-1.10.0 at /usr/bin/ninja
ninja: Entering directory `build'
[2/2] Linking target foobar.
But with a created project, I have reading the man page and the website but I can find a command such as $ meson build.
Yes I know there is:
$ cd build
$ ninja
But I think that there is --build in init command...is it other for build?
| Once you have configured your build you can do something like:
cd build
meson compile
or
meson compile -C build
See the docs @: https://mesonbuild.com/Running-Meson.html#building-from-the-source
|
71,252,828 | 71,253,083 | Base pointer offset adjustment for multiple inheritance question | I know base offset adjustment will happen in this situation
class Mother {
public:
virtual void MotherMethod() {}
int mother_data;
};
class Father {
public:
virtual void FatherMethod() {}
int father_data;
};
class Child : public Mother, public Father {
public:
virtual void ChildMethod() {}
int child_data;
};
Father *f = new Child;
During compilation, this code is equivalent to
Child *tmp = new Child;
Father *f = tmp ? tmp + sizeof(Mother) : 0;
My question is how this offset is determined in the compilation phase?
for example, in the following case
void fun(Father* f) {
// do something
}
we don't know what object the pointer will receive, how is it possible to determine whether or how much offset adjustment is needed during compilation.
I hope someone can answer my doubts, Thank you very much!
| The caller of a function knows exactly what types are involved and does the necessary adjustments.
That is,
Child c;
fun(&c);
behaves exactly the same as
Child c;
fun(static_cast<Father*>(&c));
but the conversion is implicit.
|
71,252,917 | 71,253,064 | c++ program not giving desired output | disclaimer: i am in 8th grade in school and we are learning the ancient and dead TURBO c++ as our first programming language. I have written around 50 simpler programs so far. here is the most intresting on i am working on.
i was writing a program to find sum of n natural number using classes and trying to make it 'failsafe'.
i am not getting the desired result. i am getting no errors and warnings from the compiler.
i am learning programming to understand logic and think like a programmer. Please do not judge me for using Turbo C++ i cannot do anything about it. I promise once i grow up then i will learn RUST.
here is my code:
#include<iostream.h>
#include<conio.h>
class summer
{
int n,s;
public:
int get();
void calc();
void show();
void define();
};
int summer::get()
{
cout<<"Enter a Natural Number: ";
cin>>n;
return n;
}
void summer::calc()
{
for(int i=1;i<=n;i++)
{
s=s+i;
}
}
void summer::show()
{
cout<<"Sum of all natural Numbers till "<<n<<" is "<<s;
}
void summer::define()
{
cout<<"\n\nA natural Number is a non decimal and non fractional number greater than 0";
}
void main()
{
clrscr();
summer obj;
int ch=obj.get();
if(ch>0)
{
obj.calc();
obj.show();
}
else
{
cout<<ch<<" is not a natural number";
obj.define();
}
getch();
}
cannot copy paste the output screen. please understand.
i input 5 and get output as 7888
| The problem is that the data member s has not been initialized and you're using that uninitialized data member which leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Solution
Since you're using Turbo, you can solve the problem by adding a parameterized constructor that initializes both the data members n and s to 0 as shown below:
//other code here as before
class summer
{
unsigned int n,s;//unsigned int used instead of int
public:
int get();
void calc();
void show();
void define();
//parameterized constructor
summer(): n(0), s(0) //uses constructor initializer list
{
}
};
//other code here as before
The output of the modified program can be seen here.
Some of the changes i made include:
Added a parameterized constructor to initialize data members n and s to 0 using constructor initializer list.
Made the data members n and s to be of type unsigned int.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
|
71,253,245 | 71,262,875 | Enqueue kernel from kernel leads to a misunderstood build error | I need to launch a kernel from another kernel so I read the OpenCL specs and did exactly as mentioned but I got a CL_BUILD_PROGRAM_FAILURE. Maybe my opencl version is less than 2.0 but I have downloaded OpenCL with CUDA so normally the version is upper than 2.0 right?
Here is my kernel code :
__kernel void funcB(__global int* a)
{
//blabla
}
__kernel void funcA(__global int* a, const size_t n)
{
//blabla
void (^funcB)(void) = ^{funcB(a);};
enqueue_kernel(get_default_queue(), CLK_ENQUEUE_FLAGS_WAIT_KERNEL,
ndrange_1d(n), funcB);
}
Do I also need to create a 'cl_kernel funcB' object in the host code ?? Or maybe import a header other than <CL/cl.h> ?
Thanks for the help.
| You can't use OpenCL 2.0/2.1/2.2 features on OpenCL 1.1/1.2/3.0 devices.
Nvidia GPUs only support the OpenCL C 1.2 language standard (you can query this with cl_device.getInfo<CL_DEVICE_OPENCL_C_VERSION>()). Nvidia recently "upgraded" to OpenCL version 3.0, but this is just a new name for version 1.2. OpenCL 2.0/2.1/2.2 features are still not supported.
|
71,253,815 | 71,254,011 | How can I get double(or bytes) data through PQgetvalue in an efficient way? | I create a table with 3 columns: int8, double and bytea. When query a row of data, I use PQgetvalue to get each column value in a row. But PQgetvalue return a char*, I have to convert text value to corresponding type, like atoi or strtod etc.
Is there is a more efficient way to get actual data, avoid converting data every time?
| There is not much overhead in converting a char * to a number. But you can use binary mode by calling PQexecParams with 1 as the last argument.
To retrieve binary data, you have to use PQgetlength and PQgetisnull to get size and NULLness of the datum. Also, the data will be in the binary format used by the database server, so the representation of a double could be different if both machines have a different hardware architecture (although IEEE is used pretty much everywhere).
|
71,253,945 | 71,254,648 | asio socket, split incoming data at a delimitator? | I am reading data from a asio socket in c++.
I need to parse the incoming data as json. To do this, i need to get a single json string entry. I am adding a character ';' at the end of the json string, now i need to split at that character on read. i am trying this:
int main()
{
asio::io_service service;
asio::ip::tcp::endpoint endpoint(asio::ip::address::from_string("127.0.0.1"), 4444);
asio::ip::tcp::socket socket(service);
std::cout << "[Client] Connecting to server..." << std::endl;
socket.connect(endpoint);
std::cout << "[Client] Connection successful" << std::endl;
while (true)
{
std::string str;
str.resize(2048);
asio::read(socket, asio::buffer(str));
std::string parsed;
std::stringstream input_stringstream(str);
if (std::getline(input_stringstream, parsed, ';'))
{
std::cout << parsed << std::endl;
std::cout<<std::endl;
}
}
}
But it gives me random sections of the string.
The full message is: (for testing, not json formatted)
this is the message in full, no more no less ;
and I get:
full, no more no less
this is the message in full, no more no less
ull, no more no less
is is the message in full, no more no less
l, no more no less
is the message in full, no more no less
no more no less
Where am i going wrong here?
Thanks!
| I'd use read_until:
#include <boost/asio.hpp>
#include <iostream>
#include <iomanip>
namespace asio = boost::asio;
using asio::ip::tcp;
int main()
{
asio::io_service service;
tcp::socket socket(service);
socket.connect({{}, 4444});
std::string str;
while (auto n = asio::read_until(socket, asio::dynamic_buffer(str), ';')) {
std::cout << std::quoted(std::string_view(str).substr(0, n - 1)) << std::endl;
str.erase(0, n);
}
}
For example with a sample server:
paste -sd\; /etc/dictionaries-common/words | netcat -l -p 4444
Output is:
"A"
"A's"
"AMD"
"AMD's"
"AOL"
"AOL's"
"Aachen"
"Aachen's"
"Aaliyah"
"Aaliyah's"
"Aaron"
"Aaron's"
"Abbas"
"Abbas's"
"Aberdeen's"
...
"zucchinis"
"zwieback"
"zwieback's"
"zygote"
"zygote's"
"zygotes"
"Ångström"
"Ångström's"
"éclair"
"éclair's"
"éclairs"
"éclat"
"éclat's"
"élan"
"élan's"
"émigré"
"émigré's"
"émigrés"
"épée"
"épée's"
"épées"
"étude"
"étude's"
Additional hints
You can use any dynamic buffer. Here's streambuf:
for (asio::streambuf buf; auto n = asio::read_until(socket, buf, ';');) {
std::cout << std::string_view(
asio::buffer_cast<char const*>(buf.data()), n)
<< std::endl;
buf.consume(n);
}
Or, hybrid, showing that dynamic_string_buffer models the same concept as streambuf:
std::string str;
for (auto buf = asio::dynamic_buffer(str);
auto n = asio::read_until(socket, buf, ';');) {
std::cout << std::string_view(
asio::buffer_cast<char const*>(buf.data()), n)
<< std::endl;
buf.consume(n);
}
Or also:
std::vector<unsigned char> vec;
for (auto buf = asio::dynamic_buffer(vec);
auto n = asio::read_until(socket, buf, ';');) {
std::cout << std::string_view(
asio::buffer_cast<char const*>(buf.data()), n)
<< std::endl;
buf.consume(n);
}
|
71,254,196 | 71,254,270 | C++ empty iterator with {} | I found this answer on stack overflow for reading a stream into a string. The code std::string s(std::istreambuf_iterator<char>(stream), {}); works just fine for what I was doing, but I was really confused about the {}. As far as I can tell this is using the std::string constructor that uses a begin and end iterator, but I've never seen an iterator defined with {}. What does that mean and how is it achieving the same thing as std::istreambuf_iterator<char> eos;?
| {} is a braced initialiser list in this context. It is a list of initialisers used to initialise an object. It is used to initialise a temporary object.
In this case, the list of initialisers is empty. In such case, the object will be value initialised. In case of a non-trivially-default-constructible class such as std::istreambuf_iterator value initialisation means that the default constructor will be used.
A default consturcted std::istreambuf_iterator is a sentinel that represents end of stream. This is a feature specific to stream iterators and not to all other iterators.
|
71,254,242 | 71,255,972 | Variadic Templates: how to "look ahead" in the arguments | I am implementing a printf version which can also handle std::string arguments.
At the heart of it there are these functions:
// use sprintf to transform the single format string with the value t
template<typename T>
std::string simpleFormat(const std::string sFormat, const T t) {
size_t required = snprintf(NULL, 0, sFormat.c_str(), t);
char sTemp[required+1];
sprintf(sTemp, sFormat.c_str(), t);
return std::string(sTemp);
}
// termination of recursion
std::string recursiveFormat(stringvec &vParts, stringvec &vFormats, uint i) {
return vParts[i];
}
// recursively walk through arguments
template<typename T, typename... Args>
std::string recursiveFormat(stringvec &vParts, stringvec &vFormats, uint i, T value, Args... args) {
std::string sRes = "";
if (i < vFormats.size()) {
sRes += vParts[i];
sRes += simpleFormat(vFormats[i], value);
sRes += recursiveFormat(vParts, vFormats, i+1, args...);
}
return sRes;
}
This works very well. However, to handle a format strings with an asterisk, like for instance in printf("%0*d", width, value) this approach doesn't work.
I tried by adding two functions
// get the next argument and return it
template<typename U, typename... Args>
U fetchNextParam(const U value2, Args... args) {
return value2;
}
// handle the star by providing sprintf with two values
template<typename T, typename U>
std::string starFormat(const std::string sFormat, const T value1, const U value2) {
size_t required = snprintf(NULL, 0, sFormat.c_str(), value1, value2);
char sTemp[required+1];
sprintf(sTemp, sFormat.c_str(), value1, value2);
return std::string(sTemp);
}
and modify the recursiveFormat() function like this:
template<typename T, typename... Args>
std::string recursiveFormat(stringvec &vParts, stringvec &vFormats, uint i, T value, Args... args) {
std::string sRes = "";
if (i < vFormats.size()) {
sRes += vParts[i];
//--- trying to handle star
if (vFormats[i].find('*') != std::string::npos) {
auto value2 = fetchNextParam(args...);
sRes += starFormat(vFormats[i], value, value2);
} else {
sRes += simpleFormat(vFormats[i], value);
}
sRes += recursiveFormat(vParts, vFormats, i+1, args...);
}
return sRes;
}
However, this code won't compile: i get the compiler message:
sptest.cpp: In instantiation of ‘std::string recursiveFormat(stringvec&, stringvec&, uint, T, Args ...) [with T = double; Args = {}; std::string = std::__cxx11::basic_string<char>; stringvec = std::vector<std::__cxx11::basic_string<char> >; uint = unsigned int]’:
sptest.cpp:114:32: recursively required from ‘std::string recursiveFormat(stringvec&, stringvec&, uint, T, Args ...) [with T = int; Args = {double}; std::string = std::__cxx11::basic_string<char>; stringvec = std::vector<std::__cxx11::basic_string<char> >; uint = unsigned int]’
sptest.cpp:114:32: required from ‘std::string recursiveFormat(stringvec&, stringvec&, uint, T, Args ...) [with T = int; Args = {int, double}; std::string = std::__cxx11::basic_string<char>; stringvec = std::vector<std::__cxx11::basic_string<char> >; uint = unsigned int]’
sptest.cpp:124:36: required from here
sptest.cpp:107:41: error: no matching function for call to ‘fetchNextParam()’
107 | auto value2 = fetchNextParam(args...);
| ~~~~~~~~~~~~~~^~~~~~~~~
sptest.cpp:58:3: note: candidate: ‘template<class U, class ... Args> U fetchNextParam(U, Args ...)’
58 | U fetchNextParam(const U value2, Args... args) {
| ^~~~~~~~~~~~~~
sptest.cpp:58:3: note: template argument deduction/substitution failed:
sptest.cpp:107:41: note: candidate expects at least 1 argument, 0 provided
107 | auto value2 = fetchNextParam(args...);
| ~~~~~~~~~~~~~~^~~~~~~~~
What must i do to get the functionality to look "one ahead" in the variadic arguments?
| You can also provide fetchNextParam(/*empty parameter*/)
// it's type need to return something since you store the value into value2
int fetchNextParam(){throw std::runtime_error("Wrong number of argument");}
|
71,254,325 | 71,255,679 | Do Compilers Un-Inline? | It is fairly common knowledge that the most powerful tool in a compilers tool-belt is the inlining of functions into their call sites. But what about doing the reverse? If so, is it done? And when? For example given:
void foo(int x)
{
auto y = bar(x);
baz(y);
}
void bop()
{
int x;
auto y = bar(x);
baz(y);
}
Does it ever make sense for the compiler to abstract this out to
void qux(int x)
{
auto y = bar(x);
baz(y);
}
void foo(int x)
{
qux(x);
}
void bop()
{
int x;
qux(x);
}
| Yes, for example LLVM has a MachineOutliner optimization pass.
|
71,254,607 | 71,256,997 | Strict alternation for pthreads, c++ | I'm new in c++ and trying to get understand a piece of code now. It is about strict alternation for Pthreads.
line 1: #include <iostream>
line 2: #include <pthread.h>
line 3: #include <stdlib.h>
line 4:
line 5: int count;
line 6: int turn = 0;
line 7:
line 8: void* function(void* arg){
line 9: int actual_arg = *((int*) arg);
line 10: for(unsigned int i = 0; i < 10; ++i) {
line 11: while(turn != actual_arg);
line 12: count++
line 13: std::cout << "Thread #" << actual_arg << " count = " << count << std::endl;
line 14: if(actual_arg==0){
line 15: turn =1;
line 16: }else {
line 17: turn =0;
line 18: }
line 19: int max = rand() % 100000;
line 20: for(int x = 0; x < max; x++);
line 21: }
line 22: pthread_exit(NULL);
line 23: }
My question is:
Why the first for loop use unsigned int(line 10), is that because of the declaration of the pointer value arg in line 9?
What is line 11? I kind of know it is about checking thread in actual_arg, however, I am still confused for that line.
For lines 14 to 18, since the turn value will only be 1 or 0 so we use an if statement to check the value here?
The last one is for lines 19 and 20, are we really need those codes? what is that for then?
Thank you for answering these questions, and very grateful if you can help me interpret this code in detail.
|
Why the first for loop use unsigned int(line 10), is that because of the declaration of the pointer value arg in line 9?
No particular reason. int or short or unsigned long long or any other integer type would have worked fine for the purpose. I can't speak to the decision process of the author of that code as far as choosing unsigned int in particular. I would have used int, myself, but there's nothing particularly wrong with using unsigned int.
What is line 11? I kind of know it is about checking thread in actual_arg, however, I am still confused for that line.
It loops until the condition turn != actual_arg evaluates to 0 (false). That appears to be intended to make the thread busy-wait until its turn comes, but
That's hideous, and
It contains a data race, and therefore might very well not work at all.
A more appropriate thing to do here would be to use a condition variable to help the thread suspend operation until its turn arrives. That would also involve a mutex, which would, among other things, serve to protect the shared data and therefore avoid the data race.
For lines 14 to 18, since the turn value will only be 1 or 0 so we use an if statement to check the value here?
Basically, yes. That code appears intended to set turn to indicate that it is now the other thread's turn, but this involves another data race. The turn variable must be protected from concurrent access by multiple threads via a mutex or a similar synchronization object.
The last one is for lines 19 and 20, are we really need those codes? what is that for then?
The intention appears to be make the thread spend a random amount of time before looping back around to try to take another turn. Perhaps this is intended to simulate a bona fide computational workload. However, this is not certain to be effective, as a compiler could easily optimize out the whole for loop. In the event that it is effective, it is extremely wasteful.
Overall, I concur with your other answer: the code presented is awful. Throw it away. Do not take it as a good example of anything.
|
71,254,831 | 71,254,933 | const char * is incompatible with parameter of type char *, initgraph() | I have been going through this: https://www.geeksforgeeks.org/draw-circle-c-graphics/ and for some reason it seems to not be working, I'm using vs 2019, I have the dependency's, no errors there, it seems its just the two quotes in initgraph(&gd, &gm, "");
error: E0167 argument of type "const char *" is incompatible with parameter of type "char *"
| The third argument to initgraph should be a char* but in C++, "" is a const char[1].
void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);
You can get around that problem by creating a char[1] and use that as an argument instead:
char pathtodriver[] = "";
initgraph(&gd, &gm, pathtodriver);
|
71,255,783 | 71,256,150 | Creating matrix using array | I made an array matrix and used for loops, the problem is that it only displays my last input. Please refer to the sample result below.
#include<iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
int a[x][y], i, j;
cout<<"Enter number of Columns: ";
cin>>y;
cout<<"Enter number of Rows: ";
cin>>x;
cout<<endl;
for(i=0; i<x; i++)
{
cout<<endl;
cout<<"Enter values or row/s: ";
cout<<endl;
for(j=0; j<y; j++)
{
cout<<endl;
cout<<"Row "<< i+1 << ": ";
cin >> a[i][j];
}
}
cout<<endl;
cout<<"Entered Matrix is: ";
cout<<endl;
for(i=0; i<x; i++)
{
for(j=0; j<y; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
SAMPLE RESULT:
Enter number of Columns: 3
Enter number of Rows: 2
Enter values or row/s:
Row 1: -1
Row 1: -2
Row 1: -3
Enter values or row/s:
Row 2: 4
Row 2: 5
Row 2: -6
Entered Matrix is:
4 5 -6
4 5 -6
| Just change declaration of array like this:
int[x][y] to int[10][10]
|
71,256,115 | 71,256,831 | How do I write a function that modifies a list such that all odd elements get duplicated and all even elements removed? | I'm trying to write a function that modifies an array list by removing even numbers and duplicating odd numbers.
My code works just fine in removing the even numbers. However, it only duplicates some odd numbers.
For eg. my list contains: 12 11 13 14 15 13 10
The list L after L.duplicateORremove() should contain:
11 11 13 13 15 15 13 13
But this is what I get: 11 13 13 15 13 13
I'd like some help in figuring out why I'm getting this result.
This is my code so far:
template <class Type>
void arrayListType <Type>::duplicateORremove()
{
for(int i=0; i<length; i++)
{
if(list[i]%2==0)
{
for (int j = i; j < length - 1; j++)
list[j] = list[j + 1];
length--;
}
else
{
for (int j = length; j > i; j--)
list[j] = list[j - 1];
list[i+1] = list[i];
i++;
length++;
}
}
}
This is how my class definition and main look like:
template < class Type >
class arrayListType {
public:
arrayListType(int size = 100);
~arrayListType();
void insertEnd(const Type & insertItem);
void print() const;
void duplicateORremove();
protected:
Type * list; //array to hold the list elements
int length; //stores length of list
int maxSize; //stores maximum size of the list
};
template < class Type >
arrayListType < Type > ::arrayListType(int size) {
if (size < 0) {
cerr << "The array size must be positive. Creating " <<
"an array of size 100. " << endl;
maxSize = 100;
} else
maxSize = size;
length = 0;
list = new Type[maxSize];
assert(list != NULL);
}
template < class Type >
arrayListType < Type > ::~arrayListType() {
delete[] list;
}
template < class Type >
void arrayListType < Type > ::insertEnd(const Type & insertItem) {
if (length >= maxSize)
cerr<<"Cannot insert in a full list" << endl;
else {
list[length] = insertItem;
length++;
}
}
template < class Type >
void arrayListType < Type > ::print() const {
for (int i = 0; i < length; i++)
cout << list[i] << " ";
cout << endl;
}
int main()
{
arrayListType <int> L;
L.insertEnd(12);
L.insertEnd(11);
L.insertEnd(13);
L.insertEnd(14);
L.insertEnd(15);
L.insertEnd(13);
L.insertEnd(10);
cout << "List L before L.duplicateORremove() contains:" << endl;
L.print();
L.duplicateORremove();
cout << "List L after L.duplicateORremove() contains:" << endl;
L.print();
| #include <iostream>
using namespace std;
void duplicateORremove(int list[], int length) {
for(int i=0; i<length; i++)
{
if(list[i]%2==0)
{
for (int j = i; j < length - 1; j++)
list[j] = list[j + 1];
length--;
i-=1;
}
else
{
for (int j = length; j > i; j--)
list[j] = list[j - 1];
list[i+1] = list[i];
i++;
length++;
}
}
for (int i=0; i<length; i++) {
cout << list[i];
cout << " ";
}
}
int main()
{
int arrlist[] = {12, 11, 13, 14, 15, 13, 10};
duplicateORremove(arrlist, 7);
return 0;
}
You are not resetting the 'i' value to traverse from the previous state when an even number is found. Because of that odd number taking place of an even number is skipped while looping, and, hence you will end up with a result that has some values missing in the result. And the count of missing values will be equal to the count of even number in your input.
Just add that reset condition and it will work.
Link to run the above code: Online cpp compiler
|
71,256,813 | 71,257,473 | How should I initialize linked list in C++? | I have an array which I have to initialize into a list
What I try to do
#include <stdio.h>
#include <string.h>
struct data_t
{
unsigned int id_;
char name_ [50];
};
struct node_t
{
node_t * next_;
data_t data_;
};
void initialize(node_t **, const char **, const unsigned int);
int main()
{
node_t * first = NULL;
const char * data [3] = {"Alpha", "Bravo", "Charlie"};
initialize(&first, data, 3);
return 0;
}
void initialize(node_t ** head, const char ** data, const unsigned int n) {
node_t * current = NULL;
node_t * previous = NULL;
for (size_t i = 0; i < n; i++)
{
current = new node_t;
current->next_ = previous;
current->data_.id_ = i+1;
strcpy(current->data_.name_, data[i]);
if (i == 1)
{
*head = previous;
previous->next_ = current;
} else {
previous = current;
}
}
};
next_ just loops and changes between 2 values. I tried many different options but nothing works. Please help.
Why is this happening?
| You need to do something special in the case of 'first' vs 'not first', you knew this but had it wrong.
On the first one (i==0) you need to set head so the caller gets the pointer to the first node
on subsequent ones you have to set the prior ones next pointer to point at current. For the first one there is no prior
Plus you set the current->next to point to previous, thats wrong too, that made your loop
So this is what you need
for (size_t i = 0; i < n; i++)
{
current = new node_t;
current->next_ = NULL; <<<======
current->data_.id_ = i + 1;
strcpy(current->data_.name_, data[i]);
if (i == 0)
*head = current;
else
previous->next_ = current;
previous = current;
}
|
71,257,551 | 71,257,714 | why does std::sort not require the user to specify the templated types? | If I understand correctly, in the Standard Library, there exists this definition of std::sort():
template< class RandomIt >
constexpr void sort( RandomIt first, RandomIt last );
Suppose I have such a vector that I wish to sort:
std::vector<int> data {9, 7, 5, 3, 1};
If this is the case, then why can I just write:
std::sort(data.begin(), data.end());
as opposed to requiring:
std::sort<std::vector<int>::iterator>(data.begin(), data.end());
If possible, could someone provide a generic explanation? I think I've definitely seen more than one instance of this where the template type almost seems to be automatically deduced... or is it being automatically deduced...?
|
or is it being automatically deduced...?
Yes.
When a template parameter is used for a function parameter, the template argument can be deduced from the argument passed to the function. So, in this case RandomIt is deduced from the arguments data.begin() and data.end().
|
71,258,146 | 71,269,964 | Unreal Engine: I cant login with EOS | I am giving a shot at trying out EOS. I am running into an error while trying to log in. I have a product and application set up in the online dev portal. Dont know if I have everything right though. I entered all the IDs and secret values into their appropriate places in the EOS plugin area in settings.
I have this in my DefaultEngine.ini
[OnlineSubsystemEOS]
bEnabled=true
[OnlineSubsystem]
DefaultPlatformService=EOS
[/Script/Engine.GameEngine]
+NetDriverDefinitions=. (DefName="GameNetDriver",DriverClassName="OnlineSubsystemEOS.NetDriverEOS",DriverClassNameFallback="OnlineSubsystemUtils.IpNetDriver")
[/Script/OnlineSubsystemEOS.NetDriverEOS]
bIsUsingP2PSockets=true
And this is how I am logging in
FOnlineAccountCredentials Credentials;
Credentials.Id = FString();
Credentials.Token = FString();
Credentials.Type = FString("accountportal");
Identity->OnLoginCompleteDelegates->AddUObject(this, &UEOSLibrary::OnLoginComplete);
Identity->Login(0, Credentials);
When I hit login I get a webpage that opens and asks if I want to allow access. I hit accept and what happens is the callback is never called to indicate completion. And the logs indicate that I might be missing something. What verification code and where??
LogEOSSDK: LogEOSAuth: NewClientToken: Client ClientId: xyz...kJK Access[Expires: 2022.02.22-22.32.12 Remaining: 7200.67] State: Valid
LogEOSSDK: LogEOSAuth: xyz...kJK result: eyJ...cwQ
LogEOSSDK: LogEOSAuth: Launching platform browser for account portal
LogEOSSDK: Warning: LogEOS: Error response received from backend. ServiceName=[OAuth], OperationName=[TokenGrant], Url=[<Redacted>], HttpStatus=[400], ErrorCode=[errors.com.epicgames.account.oauth.authorization_pending], NumericErrorCode=[1012], ErrorMessage=[The authorization server request is still pending as the end user has yet to visit and enter the verification code.], CorrId=[EOS-cuMGvKq4S3GvWUBNVjIbnw-ZJtD_z3YTx62TxiNJ8Yr2g-ug4LfijbR8Cx2eeMp7E3fA]
LogEOSSDK: LogEOSAuth: NewUserToken: User ClientId: xyz...kJK AccountId: 5f2...f59 Access[Expires: 2022.02.22-22.32.23 Remaining: 7200.31] Refresh[Expires: 2022-08-21T20:32:23.313Z Remaining: 15552000.31] State: Valid
LogEOSSDK: LogEOSAuth: GenerateUserAuth success
LogEOSSDK: LogEOSAuth: login/queryuserinfo success
LogEOSSDK: LogEOSAuth: Login Tasks Complete: 0
LogEOSSDK: LogEOSPresence: Updating Presence to Online. LocalUserId=[5f2...f59] RichText=[]
| Turns out you cant be running the game for it to work. Which is what I was doing. Running as a standalone game I was able to successfully log in.
|
71,258,316 | 71,259,992 | C++ gdb pretty printing in Ubuntu 18.04 visual studio code | I am trying to make pretty printing to work on Ubuntu 18.04 from visual studio code 1.64.2.
I tried to follow instructions initially from here and then the answer by Devymex as detailed in here.
Then further digging up revealed that the gdb pretty printing itself is not working as I tried to build, make, and run my code outside of VSCode. I had gcc 7.5 preinstalled on Ubuntu 18.04 and then I installed 11.2. But nothing worked.
The code I am trying to run
#include <string>
#include <iostream>
std::string str = "hello world";
int main ()
{
std::cout << str << std::endl;
return 0;
}
The output I get while debugging with gdb
Additionally, I tried to check which pretty-printer is configured or set up by typing info pretty-printer from within (gdb). But it appears that the appropriate pretty printer is not configured.
I tried reinstalling gcc 11.2 from the source by configuring with python using both python 2.7 and python 3.6.9 using the command ./configure --with-python and ./configure --with-python3. But nothing worked!
Can anyone please help me out?
| I found a solution as posted here. The gdb was not able to find the location where the python printers.py was located. The file was located under /usr/share/gcc/python/libstdcxx/v6/printers.py.
What I needed to do is create a .gdbinit file on my home directory including the following lines of code
python
import sys
sys.path.insert(0, '/usr/share/gcc/python')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)
end
Next source the file with source .gdbinit and then try again the info pretty-print. All the alternate options are now available. Subsequently, gdb debugging and vscode was able to show the contents of the C++ STL containers.
|
71,258,987 | 71,259,305 | compiler gives invalid operands to binary expression error even if there is an overloaded stream insertion operator | I'm trying to learn operator overloading and I get a below error
error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Coefficient')
cout << (c + 4) << endl ;
I mentioned the line that causes the compiler to give an error. (last line in the main)
#include <iostream>
#include <ostream>
using namespace std ;
class Coefficient {
private:
double myValue ;
mutable int myAccesses ;
public:
Coefficient (double initVal) {
myValue = initVal ;
myAccesses = 0 ;
}
double GetValue (void) const {
myAccesses++ ;
return myValue ;
}
bool operator= (double v) {
myAccesses++ ;
if (v < 0 || v > 1) {
return false ;
}
myValue = v ;
return true ;
}
bool operator+= (double addval) {
return addValue(addval) ;
}
bool operator-= (double subval) {
return addValue(-subval) ;
}
bool operator= (char * str) {
if(!strcmp(str, "default")) {
return operator=(0.5) ;
} else if (!strcmp(str, "max")) {
return operator=(0.0) ;
} else if (!strcmp(str, "min")) {
return operator=(1.0) ;
} else {
return false ;
}
}
Coefficient operator+ (double d) {
Coefficient sum{ this->myValue + d} ;
return sum ;
}
private:
bool addValue (double v) {
myAccesses++ ;
if (myValue + v < 0 || myValue + v> 1) {
return false ;
}
myValue += v ;
return true ;
}
} ;
Coefficient operator+ (double leftval, Coefficient rightval) {
return rightval + leftval ;
}
ostream & operator<< (ostream & output, Coefficient & holder) {
output << (holder.GetValue()) ;
return output ;
}
int main (void) {
Coefficient c{0.5} ;
cout << c << "\t";
c = 0.75 ;
cout << c << endl ;
c = const_cast<char *>("max") ;
cout << c << endl ;
c = const_cast<char *>("default") ;
cout << c << endl ;
c = (c + 4) ;
cout << c << endl ;
cout << (c + 4) << endl ; // compiler gives error because of this line
}
I do overload the stream insertion operator and addition operator, and when I delete the last line, I can use my custom class with stream insertion operator and it prints a value.
As you can see at the end of the main, when I assigned the result of the summation to the variable, and then use the variable with stream insertion operator, I could print the value. But when I tried to use summation without assigning the variable, it gives an error.
Why does the compiler give that error? Why the compiler does not find proper overloaded function without assigning to the variable?
I am using mac os big sur. I use clang version 13.0.0
| The definition of your stream output operator accepts a reference to a Coefficient:
ostream & operator<< (ostream & output, Coefficient & holder) {
output << holder.GetValue();
return output;
}
This works in the naive case, when you have some variable of type Coefficient and you output it.
cout << c; //<-- c is an lvalue
But there's a subtle thing going on here. The reference is what's called an lvalue -- that is, something that can be modified. The reason why this works is because you're allowed to modify c because it's non-const and exists in the stack in your main function.
Now, consider the problem call:
cout << (c + 4); //<-- (c + 4) is an rvalue
The way c + 4 was created was via a value returned from your operator+ overload. The return value is a temporary, because it's not actually being stored in a variable anywhere. Instead, it's created as a temporary that is used as an operand. The temporary is what's called an rvalue. The C++ standard prevents a program from holding non-const references to rvalues (a slight exception to this being rvalue references, which you are not using here and are not appropriate for this problem).
And so, the compiler error here is an overload resolution issue. You made a temporary value with c + 4 but there is no function that can take it as an argument, nor is there any way to automatically convert it to match any other operator overload.
To correct the issue, you need to either copy it (make the parameter a non-reference), or pass it as a const reference. Usually, the latter is preferable:
ostream & operator<< (ostream & output, const Coefficient & holder) {
output << holder.GetValue();
return output;
}
This will fix the overload resolution problem, and since you have already correctly declared .GetValue() as const there should be no other issues. But, if you had not made that GetValue function const, you would get an error.
Basic rules of thumb for const-correctness:
if a function will not modify a parameter passed as a reference, make the reference const.
if a member function will not modify the object, make the function const.
|
71,259,085 | 71,259,127 | How to pass values within functions in linked lists C++ | I created this code to calculate the sum of the values in a linked list entered by the user, and the expected output is to print the sum but it gives the last value and prints the wrong number of records in linked list
Enter a number : 5
Enter [Y] to add another number : Y
Enter a number : 1
Enter [Y] to add another number : N
List of existing record : 5
1
My code is as below, however it does not print my expected output :
#include <iostream>
using namespace std;
class Node {
public:
int no;
Node* next; //missing code
};
Node* createNode(int num) {
Node* n = new Node();
n->no = num;
n->next = NULL;
return n;
}
void addValue(int no, Node** h) {
//insert first node into linked list
Node* y = createNode(no), * p = *h;
if (*h == NULL)
*h = y;
//insert second node onwards into linked list
else {
while (p->next != NULL) //while not the end
p = p->next; // go next
p->next = y;
}
}
void display(Node* x) {
while (x != NULL) {
cout << x->no << " " << endl;
x = x->next;
}
}
double sumNodes(Node** h) {
double* sum = 0;
Node* x = *h;
while (x != NULL) {
*sum += x->no;
x = x->next;
}
return *sum;
}
int main() {
int num = 0; char choice;
Node* head = NULL;
double s;
do {
cout << "Enter a number : ";
cin >> num;
addValue(num, &head);
cout << "Enter [Y] to add another number : ";
cin >> choice;
} while (choice == 'Y');
cout << "List of existing record : ";
display(head);
cout << endl << endl;
s = sumNodes(&head);
cout << "Sum = " << s << endl;
return 0;
}
| In sumNodes(), you are declaring sum as a null pointer and then dereferencing it, which invokes undefined behavior.
double sumNodes(Node** h) {
double* sum = 0; // <-- null pointer
Node* x = *h;
while (x != NULL) {
*sum += x->no; // <-- dereference
x = x->next;
}
return *sum; // <-- dereference
}
There is no need to use a pointer at all. Instead, write:
double sumNodes( const Node** h) {
double sum = 0;
const Node* x = *h;
while (x != NULL) {
sum += x->no;
x = x->next;
}
return sum;
}
|
71,259,123 | 71,259,236 | Passing a lambda function to a template method | I have the following templated method:
auto clusters = std::vector<std::pair<std::vector<long>, math::Vector3f>>
template<class T>
void eraserFunction(std::vector<T>& array, std::function<int(const T&, const T&)> func)
{
}
And I have a function that looks like
auto comp1 = [&](
const std::pair<std::vector<long>, math::Vector3f>& n1,
const std::pair<std::vector<long>, math::Vector3f>& n2
) -> int {
return 0;
};
math::eraserFunction(clusters, comp1);
However, I get a syntax error saying:
116 | void eraserFunction(std::vector<T>& array, std::function<int(const T&, const T&)> func)
| ^~~~~~~~~~~~~~
core.hpp:116:6: note: template argument deduction/substitution failed:
geom.cpp:593:23: note: 'math::method(const at::Tensor&, const at::Tensor&, int, float, int, int, float)::<lambda(const std::pair<std::vector<long int>, Eigen::Matrix<float, 3, 1> >&, const std::pair<std::vector<long int>, Eigen::Matrix<float, 3, 1> >&)>' is not derived from 'std::function<int(const T&, const T&)>'
593 | math::eraserFunction(clusters, comp1);
| The function call tries to deduce T from both the first and second function parameter.
It will correctly deduce T from the first parameter, but fail to deduce it from the second parameter, because the second function argument is a lambda type, not a std::function type.
If deduction isn't possible from all parameters that are deduced context, deduction fails.
You don't really need deduction from the second parameter/argument here, since T should be fully determined by the first argument. So you can make the second parameter a non-deduced context, for example by using std::type_identity:
void eraserFunction(std::vector<T>& array, std::type_identity_t<std::function<int(const T&, const T&)>> func)
This requires C++20, but can be implemented easily in user code as well if you are limited to C++11:
template<typename T>
struct type_identity { using type = T; };
and then
void eraserFunction(std::vector<T>& array, typename type_identity<std::function<int(const T&, const T&)>>::type func)
std::identity_type_t<T> is a type alias for std::identity_type<T>::type. Everything left to the scope resolution operator :: is a non-deduced context, which is why that works.
If you don't have any particular reason to use std::function here, you can also just take any callable type as second template argument:
template<class T, class F>
void eraserFunction(std::vector<T>& array, F func)
This can be called with a lambda, function pointer, std::function, etc. as argument. If the argument is not callable with the expected types, it will cause an error on instantiation of the function body containing the call. You can use SFINAE or since C++20 a type constraint to enforce this already at overload resolution time.
|
71,259,534 | 71,259,859 | Converting WinHttp to WinInet API POST request | I am trying to convert some HTTP request code from using the WinHttp COM interface to using lower-level WinInet calls from <wininet.h>. The COM version is working but I am having difficulty translating the calls into the WinInet API.
This code works fine and gets the correct error response (as the request data is empty) to the POST request:
#import <winhttpcom.dll>
#include <iostream>
#include <string>
int main()
{
HRESULT hr = CoInitialize(NULL);
using namespace WinHttp;
IWinHttpRequestPtr pReq = NULL;
hr = pReq.CreateInstance(__uuidof(WinHttpRequest));
const char* pszReq = "";
if (SUCCEEDED(hr))
{
_bstr_t bstrMethod("POST");
_bstr_t bstrUrl("https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ldb9.asmx");
hr = pReq->Open(bstrMethod, bstrUrl);
pReq->SetRequestHeader(_bstr_t("Content-Type"), _bstr_t("text/*"));
_variant_t vReq(pszReq);
hr = pReq->Send(vReq);
if (SUCCEEDED(hr))
{
_bstr_t bstrResp;
hr = pReq->get_ResponseText(&bstrResp.GetBSTR());
if (SUCCEEDED(hr))
{
std::cout << std::string(bstrResp) << "\n";
}
}
}
CoUninitialize();
}
Saving the output as html, gives this rendering of the response (which is what I expect, since I haven't provided any request data, which would usually include an access token).
This is the code (amended after comments below, and should be reproducible) that I am using to try and replicate this result using wininet.h and the low-level Win32 calls (I realize I haven't closed the handles).
#include <windows.h>
#include <WinInet.h>
#include <iostream>
int main()
{
const char* pszReq = "";
const char* pszUrl = "https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ldb9.asmx";
char szHostName[256];
char szPath[256];
URL_COMPONENTSA comps = {};
comps.dwStructSize = sizeof(comps);
comps.lpszHostName = szHostName;
comps.dwHostNameLength = sizeof(szHostName);
comps.lpszUrlPath = szPath;
comps.dwUrlPathLength = sizeof(szPath);
if (!InternetCrackUrlA(pszUrl, strlen(pszUrl), 0, &comps)) return 1;
HINTERNET hOpen = InternetOpenA("XYZ",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
if (!hOpen) return 1;
HINTERNET hConnect = InternetConnectA(hOpen,szHostName,comps.nPort,
NULL,NULL,INTERNET_SERVICE_HTTP,0,NULL);
if (!hConnect) return 1;
const char * rgpszAcceptTypes[] = { "text/*", NULL };
HINTERNET hOpenReq = HttpOpenRequestA(hConnect,"POST",szPath,NULL, NULL,
rgpszAcceptTypes, 0,NULL);
if (!hOpenReq) return 1;
const char* pszHeader = "Content-Type: text/xml;charset=UTF-8";
//*** This line returns FALSE ***
BOOL bRet = HttpSendRequestA(hOpenReq, pszHeader, strlen(pszHeader), (LPVOID)pszReq, strlen(pszReq));
//*** LastError is ERROR_HTTP_INVALID_SERVER_RESPONSE
DWORD dwErr = GetLastError();
return 0;
}
All the WinInet handles are non-zero, suggesting the calls are working, but the last HttpSendRequestA() is returning FALSE immediately, with LastError set to ERROR_HTTP_INVALID_SERVER_RESPONSE.
Clearly the COM route hides a lot of intermediate working, and presumably some constants are defaulted to specific values. It may also be adding other header information, I suppose.
Perhaps someone can suggest where I am going wrong?
| There are some mistakes in your WinInet code:
the pszServerName value needs to be just the host name by itself, not a full URL. If you have a URL as input, you can parse it into its constituent pieces using InternetCrackUrlA().
the 3rd parameter of HttpOpenRequestA() is the requested resource relative to pszServerName. So, in your example, you need to use "/" to request the root resource.
the 1st parameter of HttpSendRequestA() needs to be hOpenReq, not hOpen. Also, you should not be including the null-terminators in your buffer sizes.
If you have not already done so, you should have a look at WinInet's documentation on HTTP Sessions.
With that said, try this:
#include <windows.h>
#include <WinInet.h>
#include <iostream>
const char * pszUrl = "https://someUrl";
const char * pszReq = "A string of request data";
const char* pszHeader = "Content-Type: text/xml;charset=UTF-8";
char szHostName[256];
char szPath[256];
URL_COMPONENTSA comps = {};
comps.dwStructSize = sizeof(comps);
comps.lpszHostName = szHostName;
comps.dwHostNameLength = sizeof(szHostName);
comps.lpszUrlPath = szPath;
comps.dwUrlPathLength = sizeof(szPath);
BOOL bRet = InternetCrackUrlA(pszUrl, strlen(pszUrl), 0, &comps);
if (!bRet) ...
HINTERNET hOpen = InternetOpenA("XYZ", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hOpen) ...
HINTERNET hConnect = InternetConnectA(hOpen, szHostName, comps.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
if (!hConnect) ...
HINTERNET hOpenReq = HttpOpenRequestA(hConnect, "POST", szPath, NULL, NULL, NULL, comps.nScheme == INTERNET_SCHEME_HTTPS ? INTERNET_FLAG_SECURE : 0, NULL);
if (!hOpenReq) ...
bRet = HttpSendRequestA(hOpenReq, pszHeader, strlen(pszHeader), pszReq, strlen(pszReq));
if (!bRet) ...
...
|
71,259,676 | 71,260,193 | CLion greys out include | Mycode
Why is #include "string.h" greyed out and does it still include it even though its greyed out. This is the only CPP source file in my project and so I know I'm not including it in another file. My TA said that its probably using the CPP version of string but later in the course it'll be a problem because we need to use the "string.h" version of string so I'd like to make sure its still including "string.h" even though its grey.
| It’s greyed out if clion detects that you aren’t directly using something from the referenced header.
It isn’t always correct in it’s detection process.
In this case, it is. There is a difference between string.h and <string> as an include.
|
71,259,725 | 71,259,909 | Why the program of linked lists in C++ only displays the maximum number and ignores minimum number? | I have written this code using C++ to display the max and min number of the linked list, when I run the code I can get the maximum number but I cannot get the minimum number and its value always zero:
#include <iostream>
using namespace std;
class Node {
public:
int a;
Node* next;
};
Node* createNode(int num) {
Node* n = new Node();
n->a = num;
n->next = NULL;
return n;
}
void addValue(int a, Node** h) {
Node* y = createNode(a), * p = *h;
if (*h == NULL)
*h = y;
else {
while (p->next != NULL)
p = p->next;
p->next = y;
}
}
void display(Node* x) {
while (x != NULL) {
cout << x->a << " ";
x = x->next;
}
}
double sumNodes(Node** h) {
double sum = 0;
Node* x = *h;
while (x != NULL) {
sum += x->a;
x = x->next;
}
return sum;
}
void minmax(Node* numH1, Node* numH2) {
double max = 0, min = 0;
while (numH1 != NULL) {
if (max < numH1->a)
max = numH1->a;
numH1 = numH1->next;
}
cout << "max: " << max << endl;
while (numH2 != NULL) {
if (min > numH2->a)
min = numH2->a;
numH2 = numH2->next;
}
cout << "min: " << min;
}
int main() {
int num = 0; char choice;
Node* head1 = NULL;
Node* head2 = NULL;
do {
cout << "Enter a number : ";
cin >> num;
addValue(num, &head1);
cout << "Enter [Y] to add another number : ";
cin >> choice;
} while (choice == 'Y');
cout << endl;
minmax(head1, head2);
return 0;
}
I have to use one function to display both maximum and minimum numbers from the linked lsit, not sure what went wrong exactly
| You must set min to a high value, if you set it to 0 then this is never true
if (min > numH2->a)
so do
#include <limits>
....
double max = 0, min = std::numeric_limits<double>::max();
or if you arent allowed to use limits (omg wtf)
double max = 0, min = 999999999;
actually here is DBL_MAX for you (which is what numeric_limits would give you)
double max = 0, min = 1.79769e+308;
also becuase this is a double (signed) max should be set to smallest possible
double max = 2.22507e-308; // DBL_MIN
double min = 1.79769e+308; // DBL_MAX
|
71,260,420 | 71,260,486 | C++ Structures, file does not compile, vector array has issues | I do not understand what is wrong but it seems like the problem lies with the vector, but after searching on the internet I could not solve this issue.
The error from the compiler looks like this:
main.cpp:25:21: error: expected primary-expression before ‘&’ token
25 | getdata(student &s,file);
| ^
main.cpp:26:23: error: expected primary-expression before ‘&’ token
26 | printdata(student &s,file);
| ^
main.cpp: In function ‘void getdata(student&, std::fstream)’:
main.cpp:36:15: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
36 | cin>>s[i].name;
| ^
main.cpp:38:15: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
38 | cin>>s[i].sno;
| ^
main.cpp:40:15: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
40 | cin>>s[i].mark;
| ^
main.cpp:44:34: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
44 | file<<"Student name: "<<s[i].name<<endl;
| ^
main.cpp:45:36: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
45 | file<<"Student number: "<<s[i].snum<<endl;
| ^
main.cpp:46:33: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
46 | file<<"term mark: "<<s[i].mark<<endl;
| ^
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct student
{
string name;
int snum;
double mark;
};
void getdata(student &s,fstream file);
void printdata(student &s,fstream file);
int main ()
{
fstream file;
int number;
vector <student> s(3);
cout<<"Enter number of students to account for: "<<endl;
cin>>number;
getdata(student &s,file);
printdata(student &s,file);
}
void getdata(student &s, fstream file)
{
file.open("Students.txt",ios::out);
for(int i=0; i<3; i++)
{
cout<<"Enter your name: "<<endl;
cin>>s[i].name;
cout<<"Enter your student number: "<<endl;
cin>>s[i].sno;
cout<<"Enter your term mark: "<<endl;
cin>>s[i].mark;
cout<<endl;
file<<"----------------------"<<endl;
file<<"Student name: "<<s[i].name<<endl;
file<<"Student number: "<<s[i].snum<<endl;
file<<"term mark: "<<s[i].mark<<endl;
file<<"----------------------"<<endl;
}
file.close();
}
void printdata(student &s, fstream file)
{
file.open("Students.txt",ios::in);
string read;
while(getline(cin,read))
{
cout<<read<<endl;
}
file.close();
}
| These are not valid function calls:
getdata(student &s,file);
printdata(student &s,file);
They should be:
getdata(s,file);
printdata(s,file);
That will cause other errors because your functions clearly expect a vector<student>, but only take a student.
You also cannot pass fstream objects by value. They must be references.
Change your function parameter lists to look like this:
void getdata(vector<student> &s, fstream &file);
void printdata(vector<student> &s, fstream &file);
There's also a typo with the member .sno which you meant .snum
Fix all this and your program will compile, then you can at least start debugging it to see if it even works.
|
71,262,277 | 71,299,743 | Is there a way make a std::string that references an externally provided buffer but not own it? | Basically if one has a preloaded buffer for a null terminated string and the length to be referenced, and wants to pass a reference to it into a method that takes a std::string & but not copy the string or have it owned, is it possible to do so ?
This would only have a limited lifespan that is managed in such a way that it is only valid while the buffer is valid.
| Basically, the answer is no for the non owning string.
However, if the non owning criteria is not that important what you could do is to use your own allocator to reference a particular buffer.
What you also can do, is to use std::pmr::string which allows you to give a custom memory_resource.
The idea is as following :
#include <string>
#include <memory_resource>
#include <array>
#include <utility>
#include <iostream>
template<std::size_t size>
class StackBufferResource {
public:
auto as_resource() {return &m_resource;}
auto address() {return m_buffer.data();}
private:
std::array<std::byte, size> m_buffer{};
std::pmr::monotonic_buffer_resource m_resource{m_buffer.data(), size};
};
int main() {
StackBufferResource<512> buffer;
std::pmr::string myString("My name is Antoine and I am not sure for this answer", buffer.as_resource());
std::cout << myString << "\n";
std::cout << (const char*)buffer.address() << std::endl;
}
std::pmr::monotonic_buffer_resource is a memory_resource object which continually grows. It means that a deallocation is a kind of "no op".
What is nice with such a thing is that you can give the same thing to a std::pmr::vector.
However, you may pay the attention to the following points :
std::pmr::string use char. Since it is a trivial object, I think (I am not sure though) that it is safe to access the buffer memory after the string got destroyed.
If it was a type not trivially destructible, I think it would be possible to see garbage values.
|
71,262,437 | 71,270,477 | unresolved external symbol while loading HDF5 library via vcpkg to C++ vscode project | I am using visual studio project 2019- and vcpkg in order to load data to CUDA 11.6 C++ visual studio project.
at the begining of the file i have :
// #define H5_BUILT_AS_DYNAMIC_LIB
#include <H5Cpp.h>
and it do not give any errors - so I assume it was correctly loaded and integrated by by vcpkg. Also as visible at the end of the post H5 files are visible in external dependencies list of a solution explorer.
simple code that leads to error is shown below
H5::H5File file(FILE_NAME, H5F_ACC_RDONLY);
H5::DataSet dset = file.openDataSet(DATASET_NAME);
error (set of unresolved external symbol errors) - it appears in compile time.
If I will uncomment #define H5_BUILT_AS_DYNAMIC_LIB 1 the error discussed above disappears but new shows (in runtime) -
hdf5_cpp_D.dll not found ...
Exactly the same code worked perfectly well on my cmake CUDA C++ project, but for various reasons I need to switch to visual studio project.
Minimal example giving error
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
//#define H5_BUILT_AS_DYNAMIC_LIB 1
#include <H5Cpp.h>
#include <stdio.h>
void loadHDFIntoBoolArr(H5std_string FILE_NAME, H5std_string DATASET_NAME, bool*& data) {
H5::H5File file(FILE_NAME, H5F_ACC_RDONLY);
H5::DataSet dset = file.openDataSet(DATASET_NAME);
/*
* Get the class of the datatype that is used by the dataset.
*/
H5T_class_t type_class = dset.getTypeClass();
H5::DataSpace dspace = dset.getSpace();
int rank = dspace.getSimpleExtentNdims();
hsize_t dims[2];
rank = dspace.getSimpleExtentDims(dims, NULL); // rank = 1
printf("Datasize: %d \n ", dims[0]); // this is the correct number of values
// Define the memory dataspace
hsize_t dimsm[1];
dimsm[0] = dims[0];
H5::DataSpace memspace(1, dimsm);
data = (bool*)calloc(dims[0], sizeof(bool));
dset.read(data, H5::PredType::NATIVE_HBOOL, memspace, dspace);
file.close();
}
void loadHDF() {
const int WIDTH = 512;
const int HEIGHT = 512;
const int DEPTH = 826;
const H5std_string FILE_NAMEonlyLungsBoolFlat("C:\\Users\\1\\PycharmProjects\\pythonProject3\\mytestfile.hdf5");
const H5std_string DATASET_NAMEonlyLungsBoolFlat("onlyLungsBoolFlat");
// create a vector the same size as the dataset
bool* onlyLungsBoolFlat;
loadHDFIntoBoolArr(FILE_NAMEonlyLungsBoolFlat, DATASET_NAMEonlyLungsBoolFlat, onlyLungsBoolFlat);
}
int main()
{
loadHDF();
return 0;
}
vcpk commands used
.\vcpkg install hdf5
.\vcpkg install hdf5[cpp]
.\vcpkg integrate install
| The solution in my situation was simple just reinstall windows - on fresh installation I did steps as mentioned at the begining and all works now
|
71,262,525 | 71,263,352 | NVidia thrust arbitrary transform with three-dimensional grid | I want to parallelize the following nested for loop on the GPU using NVidia thrust.
// complex multiplication
inline __host__ __device__ float2 operator* (const float2 a, const float2 b) {
return make_float2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
int main()
{
const int M = 100, N = 100, K = 100;
float2 A[M*N*K], E[M*N*K];
float vec_M[M], vec_N[N], vec_K[K];
for (int i_M = 0; i_M < M; i_M++)
{
for (int i_N = 0; i_N < N; i_N++)
{
for (int i_K = 0; i_K < K; i_K++)
{
unsigned int idx = i_M * (N * K) + i_N * K + i_K; // linear index
float2 a = A[idx];
float b = vec_M[i_M];
float c = vec_N[i_N];
float d = vec_K[i_K];
float arg1 = (b + c) / d;
float2 val1 = make_float2(cosf(arg1), sinf(arg1));
E[idx].x = a * val1; // calls the custom multiplication operator
}
}
}
return 0;
}
I could implement this as
thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(A.begin(), B.begin(), C.begin(), D.begin(), E.begin())),
thrust::make_zip_iterator(thrust::make_tuple(A.end(), B.end(), C.end(), D.end(), E.end())),
custom_functor());
similar to the example given in thrust/examples/arbitrary_transformation.cu.
However, to do that, I have to create the matrices B, C, and D, each of size M x N x K, even though three vectors of size M, N, and K are sufficient to represent the corresponding values. Creating these matrices requires (3 * M * N * K) / (M + N + K) more memory than just using the vectors.
Is there something like MATLAB's meshgrid() function that allows to create a 3D grid using three vectors without actually storing these matrices? In my mind the pseudo code would look like this:
thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(A.begin(), meshgrid(vec_M.begin(), vec_N.begin(), vec_K.begin()), E.begin())),
thrust::make_zip_iterator(thrust::make_tuple(A.end(), meshgrid(vec_M.end(), vec_N.end(), vec_K.end()), E.end())),
custom_functor());
| You can simply collapse the nested loop into a single loop and use for_each with a counting iterator. In the functor, you need to calculate the three indices from the single loop variable.
#include <iostream>
#include <thrust/for_each.h>
#include <thrust/iterator/counting_iterator.h>
struct Op{
int N;
int M;
int K;
Op(int n, int m, int k) : N(n), M(m), K(k){}
void operator()(int x){
const int k = x % K;
const int m = (x / K) % M;
const int n = (x / (K * M));
std::cerr << "x = " << x << " (" << n << ", " << m << ", " << k << ")\n";
}
};
int main(){
const int N = 2;
const int M = 3;
const int K = 2;
Op op{N,M,K};
std::cerr << "with nested loops\n";
for(int n = 0; n < N; n++){
for(int m = 0; m < M; m++){
for(int k = 0; k < K; k++){
std::cerr << "(" << n << ", " << m << ", " << k << ")\n";
}
}
}
std::cerr << "\n";
std::cerr << "with single loop\n";
for(int x = 0; x < N * M * K; x++){
op(x);
}
std::cerr << "\n";
std::cerr << "with thrust\n";
auto xIterator = thrust::make_counting_iterator(0);
thrust::for_each(thrust::seq, xIterator, xIterator + N*M*K, op);
}
Output
with nested loops
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(0, 2, 0)
(0, 2, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
(1, 2, 0)
(1, 2, 1)
with single loop
x = 0 (0, 0, 0)
x = 1 (0, 0, 1)
x = 2 (0, 1, 0)
x = 3 (0, 1, 1)
x = 4 (0, 2, 0)
x = 5 (0, 2, 1)
x = 6 (1, 0, 0)
x = 7 (1, 0, 1)
x = 8 (1, 1, 0)
x = 9 (1, 1, 1)
x = 10 (1, 2, 0)
x = 11 (1, 2, 1)
with thrust
x = 0 (0, 0, 0)
x = 1 (0, 0, 1)
x = 2 (0, 1, 0)
x = 3 (0, 1, 1)
x = 4 (0, 2, 0)
x = 5 (0, 2, 1)
x = 6 (1, 0, 0)
x = 7 (1, 0, 1)
x = 8 (1, 1, 0)
x = 9 (1, 1, 1)
x = 10 (1, 2, 0)
x = 11 (1, 2, 1)
On a side note:
CUDA has a function sincosf which may be more efficient than calling both sin and cos with the same argument. https://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__SINGLE.html#group__CUDA__MATH__SINGLE_1g9456ff9df91a3874180d89a94b36fd46
|
71,263,721 | 71,263,844 | Virtual Inheritance: Interfaces and constructors | I am using C++11. I am trying to declare 2 interfaces: B and C, which each declare some functions to be implemented by the child classes. Both interfaces rely on variables and functions which are declared in the common A class. Even this relatively simple structure leads to the diamond heritance problem.(https://www.makeuseof.com/what-is-diamond-problem-in-cpp/)
I use virtual inheritance to link A and B/C, trying to implement something like this:
#edit 1
Modified the original code snippet to be a minimal reproducable example.
class T1{};
class A{
public:
A(const T1& param1);
void myfuna();
const T1 member1;
};
class B : public virtual A{
virtual void myfunb()=0;
};
class C: public virtual A{
virtual void myfunc()=0;
};
class Di: public B, public C{
Di(const T1& param1): A(param1){}
void myfunb() override;
void myfunc() override;
};
However, this code won't compile. The reason is that cpp interfaces aren't exactly speaking "interfaces" (I have a Java background), as they still have a default constructor which is called, even when virtual inheritance is used. This means that upon initialization of an instance of "D", these constructors are called:
A(param1,param2)
B()
C()
The B and C constructors in turn try to call the A() constructor, which is ill-defined (I get the "call to implicitly-delete default constructor" error). The culprit is the const field of A, which disables the default constructor.
I can't find an elegant way to remedy this problem. Am I missing something, is my design flawed or is this just a limitation of cpp?
| The solutions are:
Make B and C abstract classes.
Or define a default constructor for A.
Or call the non-default constructor of A in the constructors of B and C.
|
71,264,126 | 71,264,212 | boost::threadpool::pool::wait() doesn't stop | I was trying to write some Task-Management class with C++ boost::threadpool, condition_variable and mutex. It seems the program will stop at boost::threadpool::pool::wait(), but I don't know why this happens.
#include <boost/threadpool.hpp>
#include <condition_variable>
#include <iostream>
#include <mutex>
using namespace std;
enum {
Running,
Stopped,
Exiting
};
class C {
private:
int m_iStatus;
mutex m_mtx;
condition_variable m_cond;
boost::threadpool::pool m_tp;
public:
C() : m_iStatus(Stopped), m_tp(8) {}
void Start();
void Exit();
private:
bool Check();
void Dispatcher();
};
bool C::Check()
{
unique_lock<mutex> lk(m_mtx);
if (m_iStatus == Stopped)
m_cond.wait(lk);
if (m_iStatus == Exiting)
return false;
else
return true;
}
void C::Dispatcher()
{
if (!Check())
return;
unique_lock<mutex> lk(m_mtx);
// do something...
cout << "." << endl;
m_tp.schedule(bind(&C::Dispatcher, this));
}
void C::Start()
{
unique_lock<mutex> lk(m_mtx);
m_iStatus = Running;
m_tp.schedule(bind(&C::Dispatcher, this));
}
void C::Exit()
{
unique_lock<mutex> lk(m_mtx);
m_iStatus = Exiting;
m_cond.notify_all(); /* notify those waiting on m_cond */
m_tp.wait(); /* went wrong here */
}
int main()
{
C c;
c.Start();
/* wait for a moment */
Sleep(1000);
/* then call Exit */
c.Exit();
return 0;
}
| You enter the wait call while still holding the mutex. This will prevent other thread's from completing their work.
In your particular case, the m_cond condition variable is waiting on that same mutex, so the call to m_cond.wait(lk); will be unable to return as long as the mutex is still being held by the other thread.
One solution to this would be to relinquish the lock on the mutex between notifying the condition variable and waiting for the thread pool to complete:
{
unique_lock<mutex> lk(m_mtx);
m_iStatus = Exiting;
m_cond.notify_all(); /* notify those waiting on m_cond */
} // lock on m_mtx gets released here
m_tp.wait(); /* this should run fine now */
|
71,264,502 | 71,264,569 | What C library provides memcpy? | How to figure out what gcc library provides the symbol for memcpy?
memcpy is provided by the header file , but I don't know what library provides the symbol.
$ objdump -ax libboost_filesystem.so | grep memcpy
0000000000000000 F *UND* 0000000000000000 wmemcpy@@GLIBC_2.2.5
0000000000000000 F *UND* 0000000000000000 memcpy@@GLIBC_2.14
It is clear that this shared object needs to find an implementation of memcpy.
How do I go about getting this information?
It would be nice if I can query the compiler.
|
what gcc library provides the symbol for memcpy?
The C standard library provides memcpy.
There are some popular implementations of C standard library, on Linux it is most notably glibc (well, and musl on Alpine Linux).
How do I go about getting this information?
There are some approaches you can take. You can run something and see where it links to How to find which shared library exported which imported symbol in my binary? . You can index all libraries on your system (see man ld.so and /etc/ld.so.conf) and index all symbols in those libraries and query the symbol (this my script does that). Then you can query your system package manager to find out to which package the shared library belongs to.
|
71,265,806 | 71,265,902 | Can't find error with my code for sort 0 1 2? Segmentation fault | Could you please tell me what is the issue with my code? I am getting segmentation fault for this specific input (and more) but for few it running fine?
What is it that I am missing?
void sortArr(int a[], int n)
{
int x,y;
for(int i=0;i<n;i++)
{
if(a[i]==0)
{
x++;
}
else if(a[i]==1)
{
y++;
}
}
int i;
for(i=0;i<x;i++)
{
a[i]=0;
}
for(i=x;i<(x+y);i++)
{
a[i]=1;
}
for(i=(x+y);i<n;i++)
{
a[i]=2;
}
// Print the sorted array
printArr(a, n);
}
// Driver code
int main()
{
int arr[] = {0,2,1,2,0,2,2,0,0,1};
int n = sizeof(arr) / sizeof(int);
sortArr(arr, n);
return 0;
}
| Initialize your variables before using them:
int x = 0, y = 0;
If you don't initialize the variables, then they will have indeterminate values which may lead to undefined behavior, and in some cases, this can also cause errors. (For example with MSVC)
|
71,265,948 | 71,277,208 | Communication failure RFID reader and Arduino uno wifi rev 2 | All similar questions, don't solve my problem
its possible that Rfid ≪Mfrc522.H≫ Won't Work With New Arduino Uno Wifi Rev2 ¿? SPI interface is the same that Rev 3 ¿?
I have a problem with the RFID reader and Arduino uno wifi rev 2. When I connect and run the program, it says
Firmware Version: 0x0 = (unknown)WARNING: Communication failure, is the MFRC522 properly connected?
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9
#define SS_PIN 10
MFRC522 mfrc522(SS_PIN, RST_PIN);
void setup() {
Serial.begin(9600);
while (!Serial);
SPI.begin();
mfrc522.PCD_Init();
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
...more code...
}
The cables are connected correctly. (I'm sure, and it's welded)
has always been connected to a 3.3V output
I have followed the documentation as indicated.
I have tried with another motherboard and the same thing happens.
The arduino works correctly.
I have changed the cables in case they were defective.
Any Idea? Thanks!!
| I have solved the problem.
I will try to explain it as best as possible
The location of the SPI interface in Arduino wifi rev 2 is different from versions rev 3 and 1
"One of the significant differences between the Uno and the Uno WiFi Rev2 is that the Uno has the SPI bus pins broken out on pins 11-13 as well as on the 2x3 pin ICSP header. On the Uno WiFi Rev2, the SPI bus is only broken out on the 2x3 ICSP header. This means that if you had the MFRD522 connected to pins 11-13 on your Uno and you tried to use the same wiring on your Uno WiFi Ref2, it won't work."
So if your model is Arduino uno wifi rev 2 the wires connected to pins 11, 12, 13 will need to be moved to the ICSP pins.
(They are the 2x3 pins that are at the bottom of the arduino).
Due to this migration the SPI interface is located on those pins.
the rest of the connections do not touch them, leave them as in the previous image.
MISO (1)
SCK (3)
MOSI (4)
:)
|
71,267,644 | 71,267,851 | Conversion to signed type behavior when out of range | Converting an integer to a signed type when the source value can't be represented in the destination type is according to cppreference
implementation-defined (until C++20)
the unique value of the destination type equal to the source value modulo 2^n
where n is the number of bits used to represent the destination type (since C++20)
Also specified in GCC implementation-defined behavior, there is
For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.
I guess there are saying the same thing. My question is isn't the reduced/moduloed result still maybe out of range of the destination signed type? Say signed char c = 255, 255 modulo 2^8 is still 255, unchanged. How does this moduloed result fit into the destination type?
This answer shows a method to first invert the value and add 1, then prepend a signed bit. I'm not sure if that's what actually have been done.
What's the correct/standard way to interpret the emphasized part?
| Neither of these quotes are meant to say that the original value is taken, the modulo operation applied, and the result used as result of the conversion.
Instead they are meant to say that out of all values v representable in the destination type, the (unique) one for which the mathematical equality
s + m * 2^n = v
holds for some integer m, with s the source value, is chosen. It is said that s and v are congruent modulo 2^n if they satisfy this condition or sometimes also that they are equal modulo 2^n.
For s = 255 with signed target of width 8, 255 is not representable, but -1 is and v = -1 satisfies the equation with m = -1.
|
71,268,121 | 71,268,212 | How can I call this template function correctly in main() in cpp which uses chrono library to convert a number to a date? | How can I call this template function correctly in main() in cpp which uses chrono library to convert a number to a date?
#include <iostream>
#include <chrono>
#include <tuple>
//using namespace std;
// Returns year/month/day triple in civil calendar
// Preconditions: z is number of days since 1970-01-01 and is in the range:
// [numeric_limits<Int>::min(), numeric_limits<Int>::max()-719468].
template <class Int>
constexpr
std::tuple<Int, unsigned, unsigned>
civil_from_days(Int z) noexcept
{
static_assert(std::numeric_limits<unsigned>::digits >= 18,
"This algorithm has not been ported to a 16 bit unsigned integer");
static_assert(std::numeric_limits<Int>::digits >= 20,
"This algorithm has not been ported to a 16 bit signed integer");
z += 719468;
const Int era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097); // [0, 146096]
const unsigned yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365; // [0, 399]
const Int y = static_cast<Int>(yoe) + era * 400;
const unsigned doy = doe - (365*yoe + yoe/4 - yoe/100); // [0, 365]
const unsigned mp = (5*doy + 2)/153; // [0, 11]
const unsigned d = doy - (153*mp+2)/5 + 1; // [1, 31]
const unsigned m = mp < 10 ? mp+3 : mp-9; // [1, 12]
return std::tuple<Int, unsigned, unsigned>(y + (m <= 2), m, d);
}
int main(){
std::cout<< civil_from_days(15432)<<'\n';
}
which gives this or this (the same) compiler errors.
The code is from Howard Hinnant
| The call to the function is not the problem. The error you get (which you should have included in the question) is because there is no predefined output operator for tuples. Though, you can print the individual members:
int main(){
auto res = civil_from_days(15432);
std::cout<< std::get<0>(res)<<'\n';
std::cout<< std::get<1>(res)<<'\n';
std::cout<< std::get<2>(res)<<'\n';
}
|
71,269,922 | 71,270,211 | Overloading function where input has certain member function | I'm attempting to overload a function depending on whether the passed in sequence container has push_back as a member function.
#include <vector>
#include <forward_list>
#include <list>
#include <array>
#include <iostream>
template<class T, typename std::enable_if_t<std::is_member_function_pointer_v<decltype(&T::push_back)>, int> = 0>
void has_push_back(T p)
{
std::cout << "Has push_back" << std::endl;
}
template<class T, typename std::enable_if_t<!std::is_member_function_pointer_v<decltype(&T::push_back)>, int> = 0>
void has_push_back(T p)
{
std::cout << "No push_back" << std::endl;
}
int main() {
std::vector<int> vec = { 0 };
std::array<int, 1> arr = { 0 };
std::forward_list<int> f_list = { 0 };
has_push_back(vec);
has_push_back(arr);
has_push_back(f_list);
return 0;
}
This results in the following compiler error for each of the calls to has_push_back():
error C2672: 'has_push_back': no matching overloaded function found
error C2783: 'void has_push_back(T)': could not deduce template argument for '__formal'
Expected result:
Has push_back
No push_back
No push_back
| You could use expression SFINAE for this:
#include <iostream>
#include <vector>
#include <array>
#include <forward_list>
void has_push_back(...)
{
std::cout << "No push_back" << std::endl;
}
template<class T>
auto has_push_back(T&& t)
-> decltype(t.push_back(t.front()), void())
// ^^ expression SFINAE, only considered
// if the whole expression within decltype is valid
{
std::cout << "Has push_back" << std::endl;
}
int main() {
std::vector<int> vec = { 0 };
std::array<int, 1> arr = { 0 };
std::forward_list<int> f_list = { 0 };
has_push_back(vec);
has_push_back(arr);
has_push_back(f_list);
return 0;
}
Result:
Has push_back
No push_back
No push_back
https://godbolt.org/z/dbzafs1nY
&T::push_back may not be well formed when push_back is a template or overloaded. Instead, I check if a call with t.front() to push_back is valid or not. Of course this also requires the type to have a suitable front member.
|
71,269,953 | 71,270,820 | How can I reverse loop over a map by value? | I need to get the pairs of the map sorted by its values, i wonder if it is posible without an temporal declaration.
I know i can sort it if i make another map with the keys and values swaped, but i am searching for a better solution.
I can't sort the elements afterwards because i only need extract the chars and put them on an array for example.
std::map<char,int> list = {{'A',4},{'V',2},{'N',1},{'J',5},{'G',3}};
for(/* code here */){
std::cout << /* code here */ << std::endl;
}
Desired outout:
J 5
A 4
G 3
V 2
N 1
| This cannot be done with std::map.
This template has an optional template argument which allows for a custom sorting, but this sorting can only be done on the map's key:
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare.
This choice has been done as to not impose the map's value to be an orderable type.
As an alternative, you can use type std::vector<std::pair<char, int>> in combination with std::sort.
#include <vector>
#include <utility>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<std::pair<char,int>> list = {{'A',4},{'V',2},{'N',1},{'J',5},{'G',3}};
std::sort(begin(list), end(list), [](auto lhs, auto rhs) {
return lhs.second > rhs.second ? true : ( rhs.first > rhs.first );
});
for(auto const& pair : list) {
std::cout << pair.first << ", " << pair.second << '\n';
}
}
J, 5
A, 4
G, 3
V, 2
N, 1
Live demo
|
71,270,337 | 71,270,584 | Clang warns about potential memory leak when constructor involves recursion | I am writing a class where recursion is a must when writing its constructor, then clang analyzer complains about potential memory leak of this function, although I cannot see why and can guarantee that the recursion will always terminate.
Here is the code:
VeblenNormalForm::VeblenNormalForm(CantorNormalForm* _cnf) {
terms = vnf_terms();
_is_cnf = true;
if (!_cnf->is_zero()) {
for (int i = 0; i < _cnf->terms.size(); i++) {
terms.push_back(
phi(&ZERO, new VeblenNormalForm(get<0>(_cnf->terms[i]))) * get<1>(_cnf->terms[i])
);
}
}
}
The analysis given by clang is that it tries to enter the true branch for a few times and then claims there exist a potential memory leakage. Is it a real warning or just clang analyzer doing weird things?
| One problem is with exception safety. Your terms vector stores tuples of VeblenNormalForm*, which you allocate at least the second element with new.
Presumably you have corresponding deletes in your destructor, but if an exception is thrown from a constructor, the destructor will not be called.
In your case, you could allocate the first N elements correctly, but get an exception in N + 1st element. In that case, your first N elements will be leaked. terms will still get destructed properly, but since you only have raw pointers in it, nothing will be deleted properly.
You could fix this issue by making your tuple be a std::tuple<VeblenNormalForm*, std::shared_ptr<const VeblenNormalForm>>. In this case, even if you get an exception mid-construction, the smart pointers will correctly delete the well-constructed objects. This assumes the first pointer is pointing to some global variable, so it's still just a regular pointer. If that is also being dynamically allocated, you need to use a smart pointer for that as well.
Code-wise, it should look like this:
using phi = std::tuple<VeblenNormalForm*, std::shared_ptr<const VeblenNormalForm>>;
VeblenNormalForm::VeblenNormalForm(CantorNormalForm* _cnf) {
terms = vnf_terms();
_is_cnf = true;
if (!_cnf->is_zero()) {
for (int i = 0; i < _cnf->terms.size(); i++) {
terms.push_back(
phi(&ZERO, std::make_shared<VeblenNormalForm>(get<0>(_cnf->terms[i]))) * get<1>(_cnf->terms[i])
);
}
}
}
Note that these pointers point to const VeblenNormalForm. Sharing mutable data across different objects is very difficult to get right. If you can prove to yourself you will do it right, feel free to remove the const.
|
71,270,736 | 71,271,324 | How to append a temporary vector (defined at compile time) efficiently? | I have a std::vector<char> v that is created at runtime, and I would like to append {'a', 'k', 'e', 'e', 'f'} to it.
I could just do v.emplace_back on each individual letter, or I can create an l-value vector and store {'a', 'k', 'e', 'e', 'f'} and then use insert with iterators, but I don't like either of these approaches because the former requires additional lines (I have to do this in several parts of the code), and the letter requires creating an l-value vector (might be some efficiency issues)?
Is there a better way to do this? I'm essentially looking for a 1-2 liner, e.g., something like
v.emplace_back({'a', 'k', 'e', 'e', 'f'}); // doesn't work
I forgot to mention that v's capacity is reserved to accommodate this temporary vector -- this is probably not relevant, however?
| vector::insert() has an overload that accepts a std::initializer_list as input, which can be constructed from a brace-list, eg:
v.insert(v.end(), {'a', 'k', 'e', 'e', 'f'});
Online Demo
|
71,271,388 | 71,271,473 | Underlining Russian comments in VS code | For me, VS code highlights comments written in Russian. It looks like this:
What does it look like for me
| You should install russian anguage Pack for visual studio code.
|
71,271,829 | 71,271,888 | Error while linking static library to test script | I'm building a static library for a small project, and when I compile it with ar, it correctly links.
When I go to include the relevant header file and link the test script to the archive;
LINK = -lpthread -lcryptopp -L./path/to/archive/ -luttu
r: ../inc/uttu.hpp
g++ -std=c++20 rnet.cpp -o r.out $(LINK)
I get linker errors;
/usr/bin/ld: /tmp/cc7h6RHu.o: in function `main':
rnet.cpp:(.text+0x263): undefined reference to `np::np()'
/usr/bin/ld: rnet.cpp:(.text+0x317): undefined reference to `np::np()'
/usr/bin/ld: ./../exe//libuttu.a(peer.o): in function `Peer::Connect(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
/home/uton/code/Concord/uttu/src/peer.cpp:43: undefined reference to `void np::target<np::_tf>(np::_tf)'
/usr/bin/ld: ./../exe//libuttu.a(relay.o): in function `Relay::Foward()':
/home/uton/code/Concord/uttu/src/relay.cpp:40: undefined reference to `np::np()'
collect2: error: ld returned 1 exit status
make: *** [Makefile:8: r] Error 1
Running ar t libuttu.a returns
linux.o
uttu.o
timeout.o
peer.o
relay.o
sec.o
np.o
My test script includes the main header file, uttu.hpp, which itself refers to the np header file, under the name of protocols.hpp
The path to the archive file is correct, the archive itself contains the correct object file, and the test script refers to the main header file, which includes the correct definitions.
I'm stuck on what could be going wrong.
| After reading this SO question, I realized that I had missed an overridden virtual member.
|
71,271,869 | 71,272,015 | Partial Template Specialization using enable_if | I am trying to understand how to use type traits with std::enable_if to "enable" partial specializations of a class. Here is the example code I am attempting to get workingL
#include <type_traits>
#include <iostream>
class AbstractFoo {
public:
virtual const char* name() const = 0;
};
template <typename T, typename Enable = void>
class Foo;
template <>
class Foo<int> : public AbstractFoo{
public:
const char* name() const override { return "int"; }
};
template <>
class Foo<char> : public AbstractFoo {
public:
const char* name() const override { return "char"; }
};
template <typename T>
class Foo<T, typename std::enable_if<std::is_enum<T>::value, T>::type> : public AbstractFoo {
public:
const char* name() const override { return "enum"; }
};
enum class MyEnum {
VAL1,
VAL2,
VAL3
};
int main() {
Foo<int> v1;
Foo<char> v2;
Foo<MyEnum> v3;
std::cout << "v1.name()=" << v1.name() << std::endl;
std::cout << "v2.name()=" << v2.name() << std::endl;
std::cout << "v3.name()=" << v3.name() << std::endl;
return 0;
};
My goal is to have specific specializations for certain types (e.g., int and char), but, if the type is an enum, to use my partial specialization. However, when I attempt to compile this code, I get the following error
error: aggregate 'Foo v3' has incomplete type and cannot be
defined
Which I assume means my specialization was not chosen and thus never becomes defined. What am I doing wrong?
| In the declaration of Foo the second template parameter defaults to void. That means that the following variable:
Foo<MyEnum> v3;
is actually
Foo<MyEnum, void> v3;
Now the question is: does this correspond to the specialization you want? Not really, because in your specialization for enum:
std::is_enum<T>::value = true when T = MyEnum
std::enable_if<std::is_enum<T>::value, T>::type = T = MyEnum
when T=MyEnum
So, for T=MyEnum, your give the specialization for Foo<T, T>, which does not match the variable above.
As noted in a comment, a simple fix is to declare the specialization as
class Foo<T, typename std::enable_if<std::is_enum<T>::value>::type>
In this way, the second template parameter is void when T=MyEnum, so it matches the variable declaration of v3.
|
71,271,968 | 71,272,000 | Pointers, ampersands and pointers again? | I just cannot get my head around pointers - when and how exactly I am supposed to use pointers. No matter how many videos and literature I read on it, I just do not understand when and how I am supposed to use it. I am that dense apparently...
Let us look at this example here:
int main()
{
int* ptr = new int(10);
std::cout << ptr << std::endl;
std::cout << *ptr << std::endl;
std::cout << &ptr << std::endl;
}
This would return us a value like this:
000001A68ABB5250
10
000000455ADCF828
What do these outputs mean? The first and the third look like they are address number in memory but they are different and I do not understand what are they supposed to do? The second one is the value I assigned but why do I have to get it with a pointer symbol?
Let us have a look at this:
int main()
{
int ptr = 10;
std::cout << ptr << std::endl;
//std::cout << *ptr << std::endl; //gives "Error(active) E0075 operand of '*' must be a pointer but has type 'int'"
std::cout << &ptr << std::endl;
}
Which respectively returns:
10
000000D9242FF5F4
What makes the code above different to this example code? Why don't I have to use pointer to get the value? Ampersand show us the memory address right?
Essentially can someone explain to me in the silliest, easiest to understand way what is the point of pointers and why do we need them in C++.
| If we "draw" the first example it will be something like this:
+------+ +-----+ +--------------+
| &ptr | --> | ptr | --> | *ptr int(10) |
+------+ +-----+ +--------------+
So ptr is pointing to an int value (initialized 10 10). And &ptr is pointing to the variable ptr.
In the second example the variable name ptr is misleading since it's not a pointer. It's a plain int variable.
Drawn it will be like
+------+ +-------------+
| &ptr | --> | ptr int(10) |
+------+ +-------------+
|
71,271,970 | 71,295,670 | Is there a way to align objects in C# same way as in C++ to avoid false sharing? | I am a C++ habitat working on a C# project.
I have encountered the following situation.
I have class MyClass and want to avoid any 2 objects of type MyClass ever to share a cache line even if I have an array or any sequential collection of type MyClass.
In C++ we can declare class alignas(hardware_destructive_interference_size) Myclass and this will make sure that any 2 objects never share a cache line.
Is there any equivalent method in C#?
| No, you can't control the alignment or memory location of classes (reference types). You can't even get the size of a class instance in memory.
It is possible to control the size and alignment of structs (and of the fields within them). Structs are value types and work pretty much the same as in C++. If you create an array of a struct, each entry has the size of the struct, and if that is large enough, you could get what you want. But there's no guarantee that the individual entries are really distributed over cache lines. That will also depend on the size and organisation of the cache.
Note also that the address of a managed instance (whether a class or a struct) can change at runtime. The garbage collector is allowed to move instances around to compact the heap, and it will do this quite often. So there is also no guarantee that the same instance will always end up in the same cache line. It is possible to "pin" an instance while a certain block executes, but this is mostly intended when interfacing with native functions and not in a context of performance optimization.
|
71,272,137 | 71,272,357 | Can we update some object without stopping the program? | There is a program written in C++ and running in linux box. It has a configuration file given to it at starting point. I came to know that it can sometime support updating the configuration file without the need to stop the program.
As the configuration update means eventually updating some of the objects(member variables) inside the running program. I want to understand the idea behind it. How we can update the object inside a running program?
I am a beginner and want to understand the concept behind it? Or is it something trivial that only I am missing the point?
| Scope the configuration so that it is reread when necessary.
Here's a very simple example
void do_work()
{
Configuration config(path_to_config_file);
while (not_changed(path_to_config_file))
{
// do one unit of work
}
}
int main()
{
while (true)
{
do_work();
}
}
Program starts, enters the loop and calls do_work. do_work constructs a Configuration object that reads the configuration file and stores the settings. Then it enters a loop that checks for a change to the configuration file and does work if the file has not changed.
If the file has changed, the loop exits, do_work exits, the Configuration object is destroyed and the loop in main calls do_work to load the new configuration and get back to work.
Precisely how you would implement not_changed depends on the system. It could be as simple as looking for a change in the modification timestamp on the configuration file.
In a real program you'll want to add some extra smarts to allow the user to exit the program.
|
71,272,307 | 71,275,334 | Why is this allocating an unneeded temporary container | I am getting a warning against my foreach loop that I'm "allocating an unneeded temporary container" but I have no idea what that means.
foreach(QString commandName, m_registeredResponseObjects.keys()) {
delete m_registeredResponseObjects[commandName];
};
Does this means the key() method is called on each iteration of the loop? I don't even see the container the warning is referencing...
foreach is a Qt macro defined as
template <typename T>
class QForeachContainer {
public:
inline QForeachContainer(const T& t) : c(t), brk(0), i(c.begin()), e(c.end()) { }
const T c;
int brk;
typename T::const_iterator i, e;
};
| It means that you create a container with this statement: m_registeredResponseObjects.keys() for no good reason. This function iterates over your m_registeredResponseObjects, collects all keys and returns a container where you then iterator over just the get the values from m_registeredResponseObjects by key.
This makes no sense at all - why not simply
for (auto val : qAsConst(m_registeredResponseObjects))
delete val;
or even simpler with the Qt macro qDeleteAll()
qDeleteAll(m_registeredResponseObjects);
?
|
71,272,341 | 71,272,387 | C++ - Is it better to use references in for loops? | If I have something like this :
vector<string> v{"lorem", "ipsum"};
Is it better to do my loop like this :
for(string s : v){ ... }
or like this :
for(string &s : v){ ... }
So my question is, does this type of loop duplicate the data (and so it's better to use a reference) or not ?
| They are functionally very different
Try this
vector<string> v{ "lorem", "ipsum" };
for (string s : v) { s = "dd"; }
cout << v[0];
for (string& s : v) { s = "yy"; }
cout << v[0];
you will see that the first one gives you a copy of the element
The second on a reference to the element in the vector.
So which one to use really comes down to what are you trying to do.
If you are just reading then the second one is better since it doesnt create a copy (I am sure string is very efficient in this case, but its true for the general case)
|
71,272,390 | 71,272,865 | String offset in constructor (C++) | Anyone to give me some advice how to get this? Thank you for any advice.
I am able to get this:
l1 [start]
l2 [start]
l3 [start]
l3 [end]
l4 [start]
l4 [end]
l2 [end]
l1 [end]
But I need this:
l1 [start]
l2 [start]
l3 [start]
l3 [end]
l4 [start]
l4 [end]
l2 [end]
l1 [end]
tasks.h
#pragma once
#include <string>
#include <iostream>
class Logger {
std::ostream& a;
std::string b;
std::string strOffset;
public:
Logger(std::ostream& a, std::string b);
~Logger();
Logger sublogger(std::string sub);
};
tasks.cpp
#include "tasks.h"
Logger::Logger(std::ostream& a, std::string b) : a(a), b(b) {
a << strOffset << b << " [start]" << std::endl;
}
Logger::~Logger() {
a << b << " [end]" << std::endl;
}
Logger Logger::sublogger(std::string sub) {
return Logger(a, sub);
};
This is how test case looks like:
TEST_CASE("Create subloggers") {
std::stringstream ss;
{
Logger logger(ss, "l1");
{
auto logger2 = logger.sublogger("l2");
{
auto logger3 = logger2.sublogger("l3");
}
auto logger4 = logger.sublogger("l4");
}
}
std::string testString = ss.str();
REQUIRE(ss.str() == R"(l1 [start]
l2 [start]
l3 [start]
l3 [end]
l4 [start]
l4 [end]
l2 [end]
l1 [end]
)");
Live test
| class Logger {
std::ostream& out;
const std::string name;
const std::string prefix;
public:
Logger(std::ostream& stream, std::string name);
~Logger();
Logger sublogger(std::string sub);
private:
Logger(std::ostream& stream, std::string name, std::string prefix);
Logger(const Logger&) = default;
Logger(Logger&&) = default;
Logger& operator=(const Logger&) = delete;
Logger& operator=(Logger&&) = delete;
};
Logger::Logger(std::ostream& stream, std::string name, std::string prefix)
: out(stream)
, name(name)
, prefix(prefix)
{
out << prefix << name << " [start]" << std::endl;
}
Logger::Logger(std::ostream& stream, std::string name)
: Logger(stream, name, {})
{
}
Logger::~Logger()
{
out << prefix << name << " [end]" << std::endl;
}
Logger Logger::sublogger(std::string sub)
{
return Logger(out, sub, prefix + " ");
};
https://godbolt.org/z/K9f1Mzrvf
string_view version
|
71,272,401 | 71,272,545 | How should I format the output? | For this code I need to be able to print the output but I am not sure how to complete this task. I can't change the main function at all and there is a certain output that I am looking for. The expected output should be formatted as the widget name, ID, then the address of the widget. I am thinking that I could use a string for the output but I'm not sure how to go about implementing it.
The main.cpp is
#include <iostream>
#include <string>
#include "widget.h"
using namespace std;
int main()
{
//makes three widgets using the regular constructor
const Widget weather( WEATHER );
const Widget quote( QUOTE );
const Widget stock( STOCK );
cout << "weather widget 1: " << weather.getModelName() << endl;
cout << "quote widget 1: " << quote.getModelName() << endl;
cout << "stock widget 1: " << stock.getModelName() << endl;
//makes three widgets using the copy constructor
Widget weather2 = weather;
Widget quote2 = quote;
Widget stock2 = stock;
cout << "weather widget 2: " << weather2.getModelName() << endl;
cout << "quote widget 2: " << quote2.getModelName() << endl;
cout << "stock widget 2: " << stock2.getModelName() << endl;
cin.get();
return 0;
}
The widget.h is
#include <string>
using namespace std;
enum WidgetType
{
INVALID_TYPE = -1,
WEATHER,
QUOTE,
STOCK,
NUM_WIDGET_TYPES
};
const string WIDGET_NAMES[NUM_WIDGET_TYPES] = { "Weather2000",
"Of-The-Day",
"Ups-and-Downs"
};
class Widget
{
public:
Widget( WidgetType type );
//add copy constructor
Widget( const Widget& rhs );
string getModelName() const { return wModelName; };
WidgetType getType() {return wType;};
private:
WidgetType wType;
int wID;
string wModelName;
static int userID;
//add static data member
void generateModelName();
};
Then the widget.cpp is
#include "iostream"
#include "widget.h"
int Widget::userID = 1;
Widget::Widget( WidgetType type )
{
wID = userID;
wType = type;
wModelName = wType;
userID++;
generateModelName();
}
Widget::Widget( const Widget& rhs )
{
wID = userID;
wType = rhs.wType;
wModelName = wType;
userID++;
generateModelName();
}
void Widget::generateModelName()
{
if (getType() == WEATHER)
{
wModelName = "Weather2000";
}
else if (getType() == QUOTE)
{
wModelName = "Of-The-Day";
}
else if (getType() == STOCK)
{
wModelName = "Ups-and-Downs";
}
}
Finally the expected out is
weather widget 1: Weather2000 1 000000145FD3F628
quote widget 1: Of-The-Day 2 000000145FD3F678
stock widget 1: Ups-and-Downs 3 000000145FD3F6C8
weather widget 2: Weather2000 4 000000145FD3F718
quote widget 2: Of-The-Day 5 000000145FD3F768
stock widget 2: Ups-and-Downs 6 000000145FD3F7B8
| You could change getModelName to generate the output you need with the help of a std::ostringstream.
Old implementation:
string getModelName() const { return wModelName; };
New version:
#include <sstream> // std::ostringstream
string getModelName() const {
std::ostringstream os;
os << '\t' << wModelName << '\t' << wID << " " << std::hex << this;
return os.str();
};
Demo
|
71,272,476 | 71,272,780 | dangling reference in nested vector when parent container reallocates | thing contains 2 vectors, one of foo and one of bar.
The bar instances contain references to the foos - the potentially dangling ones.
The foo vector is filled precisely once, in things's constructor initializer list, and the bar vector is filled precisely once in things's constructor body.
main() holds a std::vector<thing> but this vector is filled incrementally without .reserve(), and is therefore periodically reallocating.
I am struggling to reproduce it in the minimal example below, but in the more heavyweight complete code the f1 and f2 references trigger the address sanitizer with "use after free".
I find this "slightly" surprising, because yes, the "direct members" of std::vector<foo> in thing (ie the start_ptr, size, capacity), they get realloc'd when things in main() grows. But I would have thought that the "heap resource" of foos could (?) stay the same when the std::vector<thing> get's realloc'd because there is no need to move them.
Is the answer here, that: "Yes the foo heap objects may not move when things realloc's, but this is by no means guaranteed and that's why I am getting inconsistent results"?
What exactly is and isn't guaranteed here that I can rely on?
#include <iostream>
#include <vector>
struct foo {
int x;
int y;
// more stuff
friend std::ostream& operator<<(std::ostream& os, const foo& f) {
return os << "[" << f.x << "," << f.y << "]";
}
};
struct bar {
foo& f1; // dangerous reference
foo& f2; // dangerous reference
// more stuff
bar(foo& f1_, foo& f2_) : f1(f1_), f2(f2_) {}
friend std::ostream& operator<<(std::ostream& os, const bar& b) {
return os << b.f1 << "=>" << b.f2 << " ";
}
};
struct thing {
std::vector<foo> foos;
std::vector<bar> bars;
explicit thing(std::vector<foo> foos_) : foos(std::move(foos_)) {
bars.reserve(foos.size());
for (auto i = 0UL; i != foos.size(); ++i) {
bars.emplace_back(foos[i], foos[(i + 1) % foos.size()]); // last one links back to start
}
}
friend std::ostream& operator<<(std::ostream& os, const thing& t) {
for (const auto& f: t.foos) os << f;
os << " | ";
for (const auto& b: t.bars) os << b;
return os << "\n";
}
};
int main() {
std::vector<thing> things;
things.push_back(thing({{1, 2}, {3, 4}, {5, 6}}));
std::cout << &things[0] << std::endl;
for (const auto& t: things) std::cout << t;
things.push_back(thing({{1, 2}, {3, 4}, {5, 6}, {7, 8}}));
std::cout << &things[0] << std::endl;
for (const auto& t: things) std::cout << t;
things.push_back(thing({{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}}));
std::cout << &things[0] << std::endl;
for (const auto& t: things) std::cout << t;
things.push_back(thing({{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}}));
std::cout << &things[0] << std::endl;
for (const auto& t: things) std::cout << t;
}
| What you are guaranteed is, upon moving a std::vector, no iterator, pointer or reference will be invalidated. This would apply to the vectors inside thing. See notes in https://en.cppreference.com/w/cpp/container/vector/vector
When a std::vector grows, all iterators, pointers and references to it become invalid. So if you had a reference to a thing, those would be blown away, but you do not have that, so we are good.
While a std::vector grows, it will move the previous elements to the new allocation if the contained type has a noexcept move constructor. For std::vectors, this is the case after C++17. The automatically generated move constructor of thing therefore should also qualify.
Considering these, the code you have posted is correct. As we do not see all the code, there must be an issue somewhere else that interacts with the code you have. Perhaps you have a user defined move constructor in the real code that you did not mark as noexcept, or you push_back to one of the foo vectors.
Also, the reserve call is a no-op: foos.reserve(bars.size());. bars.size() here is 0. Did you mean bars.reserve(foos.size());?
|
71,273,073 | 71,343,225 | how to solve: error: global qualification of class name is invalid before '{' token | I'm trying to build https://android.googlesource.com/device/generic/vulkan-cereal
but have run into an error that seems to only happen with GCC (v8.3 is what I have to work with).
There are related questions, but I still don't understand what's going on well enough to fix the issue:
Global qualification in base specifier
Global qualification in a class declarations class-head
The code:
https://android.googlesource.com/device/generic/vulkan-cereal/+/refs/heads/master/stream-servers/vulkan/vk_fn_info.h
#define REGISTER_VK_FN_INFO(coreName, allNames) \
struct coreName; \
template <> \
struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> { \
static constexpr auto names = std::make_tuple allNames; \
using type = PFN_vk##coreName; \
};
REGISTER_VK_FN_INFO(GetPhysicalDeviceProperties2,
("vkGetPhysicalDeviceProperties2KHR", "vkGetPhysicalDeviceProperties2"))
The Error:
vulkan-cereal/stream-servers/vulkan/vk_fn_info.h:31:57: error: global qualification of class name is invalid before '{' token
struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> { \
^
/vulkan-cereal/stream-servers/vulkan/vk_fn_info.h:36:1: note: in expansion of macro 'REGISTER_VK_FN_INFO'
REGISTER_VK_FN_INFO(GetPhysicalDeviceProperties2,
^~~~~~~~~~~~~~~~~~~
What can I do to get this to build?
| The global qualifier is the two colons at the front:
struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> {
^^
But the answer was to remove all qualifiers:
struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> {
^^^^^^^^^^^^^^^^^^^^^^^
So it becomes:
#define REGISTER_VK_FN_INFO(coreName, allNames) \
struct coreName; \
template <> \
struct GetVkFnInfo<coreName> { \
static constexpr auto names = std::make_tuple allNames; \
using type = PFN_vk##coreName; \
};
The trick was that this revealed knock-on errors caused by the macro being improperly used outside the namespaces in another file:
vk_util_unittest.cpp:28:25: error: expected constructor, destructor, or type conversion before '(' token
REGISTER_VK_FN_INFO_TEST(GfxstreamTestFunc, ("vkGfxstreamTestFunc", "vkGfxstreamTestFuncGOOGLE",
The final change required fixing the namespaces in vk_util_unittest.cpp so that they matched the ones in vk_fn_info.h
As an alternative, I found that the macro could be used outside the namespace as long as it was fully qualified (excluding the invalid global qualification):
#define REGISTER_VK_FN_INFO_EXTERN(coreName, allNames) \
struct coreName; \
template <> \
struct vk_util::vk_fn_info::GetVkFnInfo<coreName> { \
static constexpr auto names = std::make_tuple allNames; \
using type = PFN_vk##coreName; \
};
But this prevented it from being used within the namespace. Two separate macros would be needed to satisfy use within and without the namespace.
|
71,273,185 | 71,273,302 | C++ Regex "Parenthesis is not closed." Error | In a game I'm making, I'm using a Regex expression to be able to parse in level data from a file. To test this, I'm trying to use the Regex expression (?<=(LEVEL_TYPE:\s))(\w+|[+-]*\d+) to try and get the level type data in the file which is formatted like LEVEL_TYPE: UNDERWATER
This is my code:
std::string RegexPattern("(?<=(LEVEL_TYPE:\\s))(\\w+|[+-]*\\d+)");
std::string target = "LEVEL_TYPE: UNDERWATER";
std::regex reg(RegexPattern);
Without even using the regex_match method, the program throws an error why I try to run the code. When I try to run it, it throws the error:
terminate called after throwing an instance of 'std::regex_error'
what(): Parenthesis is not closed.
I'm trying to compile on MinGW on Windows, GCC version 6.3.0
| I can't see a reason for the lookbehind. Isn't this enough?
std::string RegexPattern("(LEVEL_TYPE:\\s)(\\w+|[+-]*\\d+)");
|
71,273,433 | 71,273,677 | Producing a library with a recent gcc and consuming it with an older gcc - Why are there issues despite the same C++ version? | Don't ask me why I am doing what I am doing... that would be a long story.
For now, the purpose of this post is to learn and to understand why things don't work the way I expect. Possibly my expectations are wrong ?
So initially I build my own SystemC 2.3.3 library from source using a recent compiler, say gcc 10.2.0. However, to preserve backwards compatibility with older gccs, I request C++11 :
./configure CXXFLAGS="-DSC_CPLUSPLUS=201103L"
Next I want to build an application using an older gcc that supports C++11 (and the same ABI), say gcc 8.2.0, :
g++ -std=c++11 sc_main.cpp -I/path/to/systemc/include -L/path/to/systemc/lib -lsystemc -lm -o sim
To my surprise, link fails:
libsystemc.so: undefined reference to `std::__cxx11::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::basic_stringstream()
In effect, comparing the outputs of
nm --demangle `/path/to/gcc/10.2.0/bin/g++ --print-file-name libstdc++.so` | grep "std::__cxx11::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::"
and
nm --demangle `/path/to/gcc/8.2.0/bin/g++ --print-file-name libstdc++.so` | grep "std::__cxx11::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::"
reveals some differences. Indeed, the former contains std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::basic_stringstream() whereas the latter doesn't.
Is this expected ? Does it mean that in general, it is necessary but not sufficient for the producer and the consumer of a library to use the same C++ version (and the same ABI) ? Or is there something else going on that I don't understand ?
|
Does it mean that in general, it is necessary but not sufficient for the
producer and the consumer of a library to use the same C++ version (and the > same ABI) ?
Correct. Backwards/forwards compatibility is not defined just by the C++ language version used when compiling source code. Backwards/forwards compatibility is a complicated topic of its own. But I'll just give a simple contrived, example that illustrates some underlying concepts.
Let's simplify what a std::string is. It's basically a pointer, and the number of characters in the string:
namespace std {
class string {
char *chars;
size_t nchars;
public:
// Constructors and other methods.
};
}
The real std::string is somewhat more complicated (and would use symbol names that are reserved for C++ implementations, but that's immaterial). This is just a simplified illustration. std::string existed even before C++11. So, things roll along, over the years, and your C++ compiler has been updated to C++20. For whatever reason its C++ library decided to change this class slightly:
namespace std {
class string {
size_t nchars;
char *chars;
public:
// Constructors and other methods.
};
}
At this point you can choose to instruct your new C++ compiler to compile only at the C++11 language revision. This will allow only C++11 language features. However the resulting binary code still will not be binary-compatible with code that was built by an older version of the C++ compiler, which was compiled with an incompatible class layout.
In general: in order for C++ code built by a new compiler to be binary compatible with code built by an older compiler, an explicit compilation/configuration option would be needed. It's certainly possible that this is this might be the option that specifies the general C++ language version, but just doing that is not generally sufficient. All that does is instruct the compiler which language version to use for compiling the C++ code. Newer language versions obsolete/deprecate features from earlier versions, and the purpose of the language option is to allow source code written for an earlier version of the C++ standard to be compiled, by the current C++ compiler. This is not the same thing as backwards/forwards compatibility.
|
71,274,056 | 71,281,146 | Buildroot cross-compiling - compile works but linking can't find various SDL functions | I have some code that I could cross-compile with an older toolchain that used uClibc, but the project is moving to musl libc, and I can't seem to get the code to compile with that toolchain. It always fails during the linking stage with a bunch of errors along these lines:
/opt/miyoo/bin/../lib/gcc/arm-buildroot-linux-musleabi/11.2.0/../../../../arm-buildroot-linux-musleabi/bin/ld: objs/miyoo/src/touchscreen.o: in function `Touchscreen::poll()':
/__w/gmenunx/gmenunx/src/touchscreen.cpp:87: undefined reference to `SDL_PumpEvents'
/opt/miyoo/bin/../lib/gcc/arm-buildroot-linux-musleabi/11.2.0/../../../../arm-buildroot-linux-musleabi/bin/ld: /__w/gmenunx/gmenunx/src/touchscreen.cpp:89: undefined reference to `SDL_GetMouseState'
/opt/miyoo/bin/../lib/gcc/arm-buildroot-linux-musleabi/11.2.0/../../../../arm-buildroot-linux-musleabi/bin/ld: objs/miyoo/src/surface.o: in function `Surface::Surface(SDL_Surface*, SDL_PixelFormat*, unsigned int)':
/__w/gmenunx/gmenunx/src/surface.cpp:74: undefined reference to `SDL_ConvertSurface'
There are a couple that I'm not sure are SDL things, such as IMG_LoadPNG_RW and TTF_Init, but for the most part, it's all SDL_Whatever that the linker can't find, right after the compiler just found it.
You can see the full output from the failing musl build (linking starts on line 857), and compare it to a working uClibc build (linking starts on line 863).
I tried messing around with changing the buildroot settings from static to dynamic, and also both, but that didn't change anything. I also tried adding SDL2, even though I'm fairly certain the code actually depends on SDL 1, but I couldn't get buildroot to make the toolchain when I had SDL2 enabled. I tried some other things like switching around argument orders, but none of it seemed to solve the issue.
For context, I'm trying to build a docker image that can be used to cross-compile software for MiyooCFW in GitHub Actions.
I tweaked a docker image with the old toolchain and created a new one with the new toolchain so that we could build both in GitHub Actions.
This is the buildroot repo I used for the musl toolchain: https://github.com/nfriedly/buildroot
The uClibc toolchain is available in a .7z file on google drive, but I'm not sure where the source for it is. There is also some (incomplete) documentation.
I'm a noob when it comes to most of this stuff, so there may very well be something obvious that I'm just missing.
| @user17732522 helped me work through a couple of issues:
several flags were out of order:
.o files should come before -l options
-lfreetype must come after -lSDL_ttf)
several flags were missing:
-ljpeg -lpng -lz after -lSDL_image
-lvorbisfile -lvorbis -logg after -lSDL_mixer
-lbz2 -lmpg123 at the end
This PR has the fixes that allow it to compile on the new toolchain (without breaking compiling on the old one): https://github.com/MiyooCFW/gmenunx/pull/12
|
71,274,253 | 71,274,932 | Could you please explain me the the working of following code? | // This is a function to check if the given array is sorted or not by recurssion
#include<iostream>
using namespace std;
bool sorted(int arr[],int n)
{
if(n==1)
{
return true;
}
I am cofused here when n will reach 1 then it will return true to "restArray" after that if array is not sorted then how will "restArray" become false?
bool restArray = sorted(arr+1, n-1);
return (arr[0]<=arr[1] && restArray);
}
int main()
{
int arr[]={1,6,3,4,5};
cout<<sorted(arr,5);
return 0;
}
| As in every recursion there are two cases
First the trivial case if (n == 1): An array of size 1 (ie only a single element) is always sorted. Thus it returns true and stops the recursion
And if n is still greater than 1, you do the recursive call and check if the array without the first element is sorted (bool restArray = sorted(arr+1, n-1)), then you check if the first element of the array is less than the second element (a[0] < a[1]). (btw I'd probably check for <= here) And finally you combine those two checks with &&.
So for your example, it will at some point in time check 6 < 3, which will return false thus the overall result will become false.
But for sake of optimization, I'd suggest to reorder your statements a bit, such that you won't need the recursive call, if the order of the first two elements in the array is already wrong. And as @Scheff's Cat mentioned in the comments: When you convert it to a tail recursion, any decdent compiler will be able to refactor that recursion into a (much cheaper) iteration ...
And I'd also check for n <= 1 otherwise you might end up in an infinite recursion if you method is (wrongly!) called with n = 0.
bool sorted(int arr[],int n)
{
if (n <= 1)
{
return true;
}
return arr[0] <= arr[1] && sorted(arr+1, n-1);
}
or even simpler
bool sorted(int arr[], int n) {
return n <= 1
? true
: arr[0] <= arr[1] && sorted(arr+1, n-1);
}
|
71,274,470 | 71,275,001 | "Guess the number" game with C++ | I have an issue with a "Guess the number" game, as the title suggests.
I need to write a program where the at the beginning of the execution, the program should ask the customer to enter a minimum and the maximum number and tries count (e.g the user will define with how many tries the number will be guessed by themselves),
after the user enters a minimum, maximum and tries count,
the program should generate a random number between the user-defined minimum and maximum and give the user the number of tries to guess the number, which the user defined already.
If the user does not guess the number, output "Game over", if he guesses the number "Congratulations" the program execution should be stopped.
I am stuck at the point where I do not know how to generate the pseudo-random number between the minimum and maximum number which the user will enter and how to give the X number of tries to the user as well.
So far, I am here:
//REQUIREMENTS:
/*In the beginning of the execution, ask the customer to enter min and max number and tries count,
after the user enters min, max, tries count,
the program should generate random number between min and max and to give the user X number of tries to guess the number
If the user does not guess the number, output "Game over", if he guesses the number "Congratulations" and exit code 0!*/
/*------------------------------------------------------------------------------------------------------------------
/*Algorithm:
* 1. Define the variables
* 2. Output to the customer to enter the variable values
* 3. Input with the variables
* 4. for loop (since we know how many tries/iterations will be done as the user will define that)
* 5. The user should guess the generated random number
* 6. Output message depending on if he won or not - "Game over" or "Congratulations"
------------------------------------------------------------------------------------------------------------------*/
#include <iostream>
#include <cstdlib> //this header contains the srand() and rand() methods/functions for random number generation
int main() {
//The minimum and maximum numbers which define the range and the tries counter variables
int minNumber;
int maxNumber;
int triesCounter;
int randomlyGeneratedNumber;
//IO operations
std::cout << "Please, enter minimum number: ";
std::cin >> minNumber;
std::cout << "Please, enter maximum number: ";
std::cin >> maxNumber;
std::cout << "Please, enter the number of tries you will guess the number with: ";
std:: cin >> triesCounter;
/* initialize random seed: */
srand (time(NULL));
/* generate secret number between "minNumber" and "maxNumber": */
randomlyGeneratedNumber = rand() % minNumber + maxNumber;
//Using ternary operator instead of if/else conditionals
//($var==$var1)? std::cout << "Congratulations!" : std::cout << "Game over!";
return 0;
}
/*I've read quite a lot over the web on the stuff, however, most of the information is related to guessing games where the range of numbers is pre-defined, which is not the case with me and I am not an expert, but a beginner. */
//Could you please help me?
| Apart from correction in random number generation, I am only filling in the blank:
/* generate secret number between "minNumber" and "maxNumber": */
randomlyGeneratedNumber = rand() % (maxNumber - minNumber + 1) + minNumber;
int guessedNumber;
do
{
std::cout << "Please, enter your guessed number: ";
std::cin >> guessedNumber;
}
while(randomlyGeneratedNumber != guessedNumber && (--triesCounter > 0))
//Using ternary operator instead of if/else conditionals
(randomlyGeneratedNumber == guessedNumber )
? std::cout << "Congratulations!"
: std::cout << "Game over!";
Operator % will chop the number to a range. In this case range will be from 0 to (maxNumber - minNumber) then we add minNumber to it in order to get correct range.
The loop will break on either the right guess which will make first condition false or when number of tries gets to zero when the second condition will go false.
|
71,274,799 | 71,274,970 | how to store 0 in MSB of int datatype in C++? | #include<iostream>
using namespace std;
int main()
{
int x = 0101;
cout<<x;
return 0;
}
The output I am getting is 101 but I want 0101 instead. what to do??
| First of all, you should get 65 as 0101 is parsed as octal 101 (64+1).
If you want to use binary literal, you can prepend 0b
#include<iostream>
using namespace std;
int main(){
int x = 0b0101;
cout<<x;
return 0;
}
https://godbolt.org/z/5Pxqehz7P
|
71,275,447 | 71,275,521 | std::valarray and type of iterators | Since C++11 std::valarray has iterators, provided through the std::begin() and std::end() interfaces. But what is the type of those iterators (so that I can declare them properly)?
The following does not compile with a no template named 'iterator' in 'valarray<_Tp>' error:
template <typename T>
class A {
private:
std::valarray<T> ar;
std::valarray<T>::iterator iter;
public:
A() : ar{}, iter{std::begin(ar)} {}
};
decltype shows the type of the iterator to be that of a pointer to a ``valarray` element. Indeed, the following does compile and seems to work fine:
template <typename T>
class A {
private:
std::valarray<T> ar;
T* iter;
public:
A() : ar{}, iter{std::begin(ar)} {}
};
What am I missing? Isn't there a proper iterator type to use for the declare in the class?
|
But what is the type of those iterators
The type is unspecified.
(so that I can declare them properly)?
You can use decltype:
using It = decltype(std::begin(ar));
It iter;
Or, in cases where that's possible (not member variables), you should prefer type deduction:
auto iter = std::begin(ar);
|
71,275,877 | 71,276,015 | Problems while printing hollow square | I am trying to print a hollow square, I wrote the following code:
#include <iostream>
using namespace std;
int main () {
int heigth;
cout << "Height: ";
cin >> heigth;
int width;
cout << "Width: ";
cin >> width;
for (int i = 1; i <= heigth; i++) {
for ( int j = 1; j <= width; j++) {
if (i == 1 || j == 1 || i == heigth || j == width) {
cout << " # ";
} else {
cout << " ";
}
}
cout << endl;
}
return 0;
}
When I run it with h=5 and w=5, I get the following shape:
# # # # #
# #
# #
# #
# # # # #
Instead of the a normal square.
I tried to print the value of j, I discovered that in the middle iterations, it jumps from 1 to 5 directly.
Like this:
# 1 # 2 # 3 # 4 # 5
# 1 # 5
# 1 # 5
# 1 # 5
# 1 # 2 # 3 # 4 # 5
The numbers you see are the values of j. Why is this happening?
| Your code is perfectly fine and so is the value of j. The only problem is that you're printing " " while you should be printing " ". This is because " # " has 3 characters, so your space also should be 3 characters long.
Final Code:
#include <iostream>
int main() {
int heigth;
std::cout << "Height: ";
std::cin >> heigth;
int width;
std::cout << "Width: ";
std::cin >> width;
for (int i = 1; i <= heigth; i++) {
for (int j = 1; j <= width; j++) {
if (i == 1 || j == 1 || i == heigth || j == width) {
std::cout << " # ";
}
else {
std::cout << " "; // Replaced " " with " "
}
}
std::cout << std::endl;
}
return 0;
}
In the above code I've also removed the following line:
using namespace std;
..as it's considered as bad practice. For more information on this, see why is "using namespace std" considered as a bad practice.
|
71,275,887 | 71,275,912 | What is the ^@ symbol at the end of my output txt file? | I wrote c++ code to read from a text file and then bash code to output it to another file (specifically './executable &> output.txt'). When I print it on the command line it looks fine, but when I check the output file, it has a '^@' symbol at the end of it.
| You have a bug in your program, it's writing a nul character at the end of your file. Then whatever tool you use to check the output is using: caret notation for non-printable characters.
^@ is the notation for the nul character.
We cannot tell more without seeing the code.
|
71,276,301 | 71,277,069 | Drawing bezier curve using four segments | I am trying to draw a bezier curve which uses 4 control points to draw a curve. However when I run my program, after 4 clicks with mouse I only see one pixel being drawn, am I missing something in my code? How can I get this to work properly?
void MyWindow::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
x0 = event->x();
y0 = event->y();
point.setX(x0);
point.setY(y0);
std::vector<QPoint> myv;
myv.push_back(point);
counter+=1;
std::cout<<counter<<std::endl;
if(counter%4==0) {
drawBezier(myv[0], myv[1], myv[2], myv[3]);
}
}
update();
}
| myv is local variable and you dont save its state to the new mousePressEvent
Get some "debug" info and see what you receive in drawBezier function.
|
71,276,592 | 71,277,561 | Is it possible to pass a reference to a consteval function and use it as additional return value? | Sometimes the result of a function can not be represented by a single return value. For example: A function that intersects two lines. One might want the function to return both the actual point of intersection as well as their relation to each other (that is parallel, identical, intersecting or skewed).
Let us assume this example where the point of intersection is represented by some sort of class and the lines positional relation by an integer holding a specified value for each of the 4 possibilities:
int IntersectLines(Line l1, Line l2, Point& point);
Point point{};
int result = IntersectLines(l1, l2, point);
That is how I would have implemented it to this day but now I am wondering whether it is possible to have a similar implementation but with a consteval function. Line and Point have constexpr constructors and everything and the calculation itself can be compile time evaluated as well. The only problem is that I can't think of a way to have two return values. I already thought of std::pair but a solution more similar to passing a reference would be prefered. If such a solution doesn't exist I will have to fall back to std::pair.
It doesn't work by passing point by reference (Point& point) because "the expression did not evaluate to a constant" but passing by const reference (const Point& point) won't work either because I wouldn't be able to assign the result to point. Is there a way to get this working?
| You can return a std::pair<Point, Relationship>.
Example:
consteval std::pair<Point, Relationship> IntersectLines(const Line& l1, const Line& l2)
{
// replace with the real calc below, this is just for show:
const Point pnt{l1.p1.x + l2.p1.x, l1.p1.y + l2.p1.y};
const Relationship rel = Relationship::parallel;
return {pnt, rel};
}
And call it like so:
int main() {
constexpr Line l1({1,2}, {3,4}), l2({5,6}, {7,8});
constexpr auto pr = IntersectLines(l1, l2);
auto&[pnt, rel] = pr;
return pnt.x + pnt.y; // 14
}
With optimization, the resulting assembly is likely to become something like
main:
mov eax, 14
ret
Demo
|
71,276,707 | 71,276,828 | How to use nested namespace to avoid ambiguity? | I have the following operators defined in the corresponding namespaces:
namespace literals
{
constexpr ID operator"" _ID(const unsigned long long dyngateID)
{
// ...
// return a constructed id
}
namespace multiplied
{
constexpr ID operator"" _ID(const unsigned long long dyngateID)
{
// ...
// return an id constructed in a specific way
}
} // namespace multiplied
} // namespace literals
In a .cpp file I would like to use both functions, hence I've declared using namespace literals and when I am declaring using namespace multiplied in a concrete function I am getting ambiguous call to overloaded function compile error. How can I differentiate these functions?
Test.cpp
using namespace literals;
void f()
{
// here I am using literals' _ID which is fine
const Type id{1_ID};
}
void g()
{
// here I want to use multiplied's _ID, but obviously I am failing to do so
using namespace multiplied;
const Type id{1_ID};
}
| The name lookup rules for using namespace are such that the declarations introduced by it appear to be located in the inner-most namespace scope enclosing both the current namespace scope and the target namespace scope.
Therefore it is no good to disambiguate based on the scoping of multiple reachable using namespace statements.
Instead you can import the declaration with a using declaration:
void g()
{
using multiplied::operator""_ID;
const Type id{1_ID};
}
This will behave as if the operator was declared in the scope, so that name lookup will stop there and won't look at the declaration imported by the outer using namespace.
Alternatively, you can call the user-defined literal operator directly with a qualified call:
void g()
{
const Type id{multiplied::operator""_ID(1)};
}
As another possibility you can always limit the scope of the using namespace statements, so that only one of using namespace literals; or using namespace literals::multiplied; is reachable from any given scope using the operator, e.g.:
// no using namespace at this scope
void f()
{
using namespace literals;
const Type id{1_ID};
}
void g()
{
using namespace literals::multiplied;
const Type id{1_ID};
}
|
71,277,205 | 71,277,963 | How Does std::forward_list::sort Work in NlogN Time? | I can't imagine how to reorder a singly linked list with decent time complexity (The library says it takes "approximately" NlogN). Is there a name for the algorithm used that I could use to find educational material about it? I looked at the code in the standard library, but I couldn't figure much out other than a merge takes place near the end of one of the few functions named sort or sort2. Below are some of the functions used:
template <class _Pr2>
static void _Sort(_Nodeptr _BFirst, _Pr2 _Pred) {
auto _BMid = _Sort2(_BFirst, _Pred);
size_type _Bound = 2;
do {
if (!_BMid->_Next) {
return;
}
const auto _BLast = _Sort(_BMid, _Bound, _Pred);
_BMid = _Inplace_merge(_BFirst, _BMid, _BLast, _Pred);
_Bound <<= 1;
} while (_Bound != 0);
}
template <class _Pr2>
static _Nodeptr _Sort(const _Nodeptr _BFirst, size_type _Bound, _Pr2 _Pred) {
// Sort (_BFirst, _BFirst + _Bound), unless nullptr is encountered.
// Returns a pointer one before the end of the sorted region.
if (_Bound <= 2) {
return _Sort2(_BFirst, _Pred);
}
const auto _Half_bound = _Bound / 2;
const auto _BMid = _Sort(_BFirst, _Half_bound, _Pred);
if (!_BMid->_Next) {
return _BMid;
}
const auto _BLast = _Sort(_BMid, _Half_bound, _Pred);
return _Inplace_merge(_BFirst, _BMid, _BLast, _Pred);
}
template <class _Pr2>
static _Nodeptr _Inplace_merge(_Nodeptr _BFirst1, const _Nodeptr _BMid, const _Nodeptr _BLast, _Pr2 _Pred) {
// Merge the sorted ranges (_BFirst1, _BMid] and (_BMid, _BLast)
// Returns one before the new logical end of the range.
auto _First2 = _BMid->_Next;
for (;;) { // process 1 splice
_Nodeptr _First1;
for (;;) { // advance _BFirst1 over elements already in position
if (_BFirst1 == _BMid) {
return _BLast;
}
_First1 = _BFirst1->_Next;
if (_DEBUG_LT_PRED(_Pred, _First2->_Myval, _First1->_Myval)) {
// _First2->_Myval is out of order
break;
}
// _First1->_Myval is already in position; advance
_BFirst1 = _First1;
}
// find the end of the "run" of elements less than _First1->_Myval in the 2nd range
auto _BRun_end = _First2;
_Nodeptr _Run_end;
for (;;) {
_Run_end = _BRun_end->_Next;
if (_BRun_end == _BLast) {
break;
}
if (!_DEBUG_LT_PRED(_Pred, _Run_end->_Myval, _First1->_Myval)) {
// _Run_end is the first element in (_BMid->_Myval, _BLast->_Myval) that shouldn't precede
// _First1->_Myval.
// After the splice _First1->_Myval will be in position and must not be compared again.
break;
}
_BRun_end = _Run_end;
}
_BMid->_Next = _Run_end; // snip out the run from its old position
_BFirst1->_Next = _First2; // insert into new position
_BRun_end->_Next = _First1;
if (_BRun_end == _BLast) {
return _BMid;
}
_BFirst1 = _First1;
_First2 = _Run_end;
}
}
| "Bottom up" variants of merge sort can sort a linked list in O(n log n) time and O(1) space. See the Wikipedia article. If O(1) space isn't a requirement then you can construct an array of pointers into the list, sort that using any O(n log n) sorting algorithm, and then rebuild the list from your sorted copy.
|
71,277,366 | 71,277,745 | Cmake: how to delete old variables with a new build | I am trying to configure my app with cmake, which depends on
cmake -DVERSION_TO_BUILD ../
In my CMakeList I wrote that checker
if (NOT VERSION_TO_BUILD)
message(FATAL_ERROR "Please, set VERSION_TO_BUILD")
endif()
In first configure all works normally, but in the next time when I try to reconfigre like
cmake ../
When I configure my app without -DVERSION_TO_BUILD=1, cmake throws an error (as expected).
After that, I configure an app with -DVERSION_TO_BUILD=1 and it does not give an error (as expected).
However, when I go back to the first option without -DVERSION_TO_BUILD=1 it does not give an error. I checked it by calling message and found that it exists.
I found out that cmake saved VERSION_TO_BUILD variable. So my checker doesn't work correctly.
Of course, I can't use set in CMakeList because VERSION_TO_BUILD is external dependency.
How can I fix this so that I don't delete the cmake folder?
| Passing a -D option during the configuration of your cmake project sets a cache variable. The cache is persisted for builds and future reconfiguration. Note that cmake does not treat cache variables that were persisted and cache variables that are passed via command line any different during reconfiguration of a project.
In fact after editing the project files building the project may actually cause the version of cmake that causes a reconfiguration of the project without passing any additional information (i.e. cmake <path to build dir>) to be run automatically.
It would be preferrable to simply set up different build directories for both configurations, assuming there are no conflicting files written e.g. to the source tree, if you do this.
Other than that you can simply reconfigure the project explicitly deleting a cache entry using the -U option
cmake -U VERSION_TO_BUILD <path to build dir>
|
71,278,317 | 71,278,532 | What is the difference between CMAKE_CXX_FLAGS_RELEASE (cmake release flag) values? | I was working with CMake. I have seen many CMake files and found there is a different release flag value set.
In one file I found:
set(CMAKE_CXX_FLAGS_RELEASE "-O3")
In another:
set(CMAKE_CXX_FLAGS_RELEASE "-O2")
and in other I found:
set(CMAKE_CXX_FLAGS_RELEASE "-O1")
Please let me know what is the exact difference between these flags values? Can I use any one?
| You can read about those flags here
And shortly -O0, -O1, -O2, -O3 differ with the optimization level at the compile time. -O3 includes optimizations which are specified by -O2. And -O2 includes optimizations which are specified by -O1.
In your projects you can use any of those. You can even use no one of those flags (by default compiler uses -O0 flag).
But in the university I was taught to use -O2 or -O3.
|
71,278,366 | 71,280,081 | Are all tasks that are created in worksharing loop constructs inside a parallel region sibling tasks in OpenMP? | I have this simple self-contained example of a very rudimentary stencil application to work with OpenMP tasks and the dependence clause. At 2 steps one location of an array is added 3 values from another array, one from the corresponding location and its left and right neighbours. To avoid data races I have set up dependencies so that for every section on the second update its task can only be scheduled if the relevant tasks for the sections from the first update step are executed. I get the expected results but I am not sure if my assumptions are correct, because these tasks might be immediately executed by the encountering threads and not spawned. So my question is whether the tasks that are created in worksharing loops all sibling tasks and thus are the dependencies retained just like when the tasks are generated inside a single construct.
#include <iostream>
#include <omp.h>
#include <math.h>
typedef double value_type;
int main(int argc, char * argv[]){
std::size_t size = 100000;
std::size_t part_size = 25;
std::size_t parts = ceil(float(size)/part_size);
std::size_t num_threads = 4;
value_type * A = (value_type *) malloc(sizeof(value_type)*size);
value_type * B = (value_type *) malloc(sizeof(value_type)*size);
value_type * C = (value_type *) malloc(sizeof(value_type)*size);
for (int i = 0; i < size; ++i) {
A[i] = 1;
B[i] = 1;
C[i] = 0;
}
#pragma omp parallel num_threads(num_threads)
{
#pragma omp for schedule(static)
for(int part=0; part<parts; part++){
std::size_t current_part = part * part_size;
std::size_t left_part = part != 0 ? (part-1)*part_size : current_part;
std::size_t right_part = part != parts-1 ? (part+1)*part_size : current_part;
std::size_t start = current_part;
std::size_t end = part == parts-1 ? size-1 : start+part_size;
if(part==0) start = 1;
#pragma omp task depend(in: A[current_part], A[left_part], A[right_part]) depend(out: B[current_part])
{
for(int i=start; i<end; i++){
B[i] += A[i] + A[i-1] + A[i+1];
}
}
}
#pragma omp for schedule(static)
for(int part=0; part<parts; part++){
int current_part = part * part_size;
std::size_t left_part = part != 0 ? (part-1)*part_size : current_part;
std::size_t right_part = part != parts-1 ? (part+1)*part_size : current_part;
std::size_t start = current_part;
std::size_t end = part == parts-1 ? size-1 : start+part_size;
if(part==0) start = 1;
#pragma omp task depend(in: B[current_part], B[left_part], B[right_part]) depend(out: C[current_part])
{
for(int i=start; i<end; i++){
C[i] += B[i] + B[i-1] + B[i+1];
}
}
}
}
value_type sum = 0;
value_type max = -1000000000000;
value_type min = 1000000000000;
for(int i = 0; i < size; i++){
sum+=C[i];
if(C[i]<min) min = C[i];
if(C[i]>max) max = C[i];
}
std::cout << "sum: " << sum << std::endl;
std::cout << "min: " << min << std::endl;
std::cout << "max: " << max << std::endl;
std::cout << "avg: " << sum/(size) << std::endl;
return 0;
}
| In OpenMP specification you can find the corresponding definitions:
sibling tasks - Tasks that are child tasks of the same task region.
child task - A task is a child task of its generating task region. A child task region is not part of its generating task region.
task region - A region consisting of all code encountered during the
execution of a task. COMMENT: A parallel region consists of one or
more implicit task regions
In the description of parallel construct you can read that:
A set of implicit tasks, equal in number to the number of threads in
the team, is generated by the encountering thread. The structured
block of the parallel construct determines the code that will be
executed in each implicit task.
This practically means that in the parallel region many task regions are generated and using #pragma omp for different task region will generate explicit tasks (i.e #pragma omp task...). However, only tasks generated by the same task region are sibling tasks (not all of them!). If you want to be sure that all generated tasks are sibling tasks, you have to use a single task region (e.g. using single construct) to generate all the explicit tasks.
Note that your code gives the correct result, because there is an implicit barrier at the end of worksharing-loop construct (#pragma omp for). To remove this barrier you have to use the nowait clause and you will see that the result will be incorrect in such a case.
Another comment is that in your case the workload is smaller than parallel overheads, so my guess is that your parallel code will be slower than the serial one.
|
71,278,373 | 71,278,467 | Confusion about [expr.static.cast]/13 | I can't understand the quote (specifically, the bold part):
A prvalue of type “pointer to cv1 void” can be converted to a prvalue
of type “pointer to cv2 T”, where T is an object type and cv2 is the
same cv-qualification as, or greater cv-qualification than, cv1. If
the original pointer value represents the address A of a byte in
memory and A does not satisfy the alignment requirement of T, then the
resulting pointer value is unspecified.
int i = 0;
void *vp = &i;
auto *res = static_cast<double*>(vp);
My questions are:
does the address pointed by res (address of int) satisfy the alignment requirement of double?
does the resulting pointer res has an unspecified value?
And when I have something like this: static_cast<double*>(static_cast<void *>(&i))
Does i type is not stricter than the target type double? so that the result of this expression is not unspecified
|
does the address pointed by res (address of int) satisfy the alignment requirement of double?
That would depend on the implementation. Most likely it doesn't. Typically the alignment requirement of int is smaller than that of double.
For example on the x86-64 System V ABI used e.g. on Linux, int has alignment requirement 4 and double has 8.
You can check that the alignment requirement is satisfied for example with the following static_assert:
static_assert(alignof(int) >= alignof(double));
does the resulting pointer res has an unspecified value?
If the alignment requirement is not fulfilled (i.e. the static_assert fails), yes. Otherwise it will point to the object i.
And when I have something like this: static_cast<double*>(static_cast<void *>(&i))
This is exactly equivalent to what is shown in the snippet.
Note that even if the alignment requirements are satisfied, res cannot be used to access the value of the object it points to, because that would violate the pointer aliasing rules. So the result of the cast is very likely not useful for anything.
|
71,278,421 | 71,280,517 | What makes the calling convention different? | From my knowledge, the calling convention is depending on whether the platform is Windows or Linux.
I wanna know,
Compilers make the calling convention different.
Platforms make the calling convention different.
Which one is true?
if only 2 is true, is the calling convention is defined by the platforms, and do the compilers just follow the defined convention?
| Platforms generally define one or more "standard" calling conventions. Compilers need to follow those conventions if they want to interoperate with other tools or components on the platform using those conventions, but can use their own different calling conventions internally.
The only real requirement is that any caller and callee need to agree on the conventions for the call between them.
|
71,278,701 | 71,278,761 | Prompt user to fill in a template? | I've never been able to find anything about this in any language, but what I want to do seems rather simple to me.
I want to prompt the user for input, but have them fill in a sort of template. Let's use a simple DD-MM-YYYY date as an example.
[█ - - ]
█ is where the user writes.
As they write, the [ and - stay where they are, with the cursor jumping past them, and hitting enter submits.
I'm not expecting anyone to write all of this for me, but cin and cout seem to be too crude a tools to do this, and so I'm wondering where I should even start, if not there.
Is there something that already does this, or at least something that gives me more control of the cursor to allow me to write it myself?
I do not want to be drawing a full-on TUI with windows and boarders and colors, so ncurses would just get in the way. I just want a single-line text field that returns the input.
EDIT: The most promising non-ncruses alternative for a helpful library seems to be Terminal.
| Generally what you want is a text-based GUI library, such as ncurses. Doing console work is platform-specific, and every system has its own console API to do this. If you want to implement this yourself, you would have to examine what options does your target operating system give you in terms of console API, and build a custom solution based on that.
|
71,278,842 | 71,278,899 | How can I find out which thread crashed inside my program? | Consider the following program:
#include <atomic>
#include <thread>
#include <iostream>
#include <string>
#include <windows.h>
std::atomic<int> crashId;
void threadFunction(int id) {
while (id != crashId) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
int* p = nullptr;
*p = id;
}
int main() {
std::thread t1(&threadFunction, 1);
std::thread t2(&threadFunction, 1);
int id;
std::cin >> id;
crashId = id;
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
I start the program (built in Release mode) and go to lunch. When I come back a colleague has typed in either 1 or 2.
How can I find out which thread crashed? Alternatively how could I rewrite the program so that I could find out this the next day?
I tried the Event Viewer. That only seemed to report the process id and filepath to my .exe.
If I had each thread running in a separate .dll would I see this in the Event Viewer log?
| On Windows, you can set a registry key associated with your program's name to generate a dump file when a crash happens
Sample instructions here and here (I always recommend generating "full" crash dumps)
With the crash dump in hand, you can load it into a tool such as Windbg or even Visual Studio to observe the call stack and see variable values.
You'll likely need to have the PDB files associated with the EXE in your tool's symbol path to see the function and variable names. Optimized builds are often harder to debug, but there are some compiler switches that generate better (and larger) PDB files that make retail debugging almost as good as non-optimzed builds.
|
71,279,031 | 71,302,589 | Does range-v3's "sliding" view not work with lazy ranges? | I don't understand why the following code does not compile while the commented out version does work.
#include <range/v3/all.hpp>
#include <iostream>
namespace rv = ranges::views;
int main() {
//std::vector<int> fives = {5,5,5,5,5,5,5,5,5,5};
//auto rng = fives | rv::sliding(2);
auto lazy_fives = rv::generate( [](){ return 5;});
auto rng = lazy_fives | rv::sliding(2);
for (auto pair : rng | rv::take(10)) {
for (auto val : pair) {
std::cout << val << " ";
}
std::cout << "\n";
}
}
On godbolt here.
| As @康桓瑋 says in comments, the issue is that sliding_view requires a forward_range, but generate yields an input_range.
A workaround is either to dump the generated range to a vector and create a sliding view of that, or I believe it is possible to use one's own generate written on top of iota like so
#include <range/v3/all.hpp>
#include <iostream>
namespace rv = ranges::views;
template<typename F>
auto generate_forward_range(F func) {
return rv::iota(0) | rv::transform( [func](int n){ return func();});
}
int main() {
auto lazy_fives = generate_forward_range( [](){ return 5;} );
auto rng = lazy_fives | rv::sliding(2);
for (auto pair : rng | rv::take(10)) {
for (auto val : pair) {
std::cout << val << " ";
}
std::cout << "\n";
}
}
On godbolt here. I assume this works because iota generates a forward_range leading to transform yielding a forward range.
|
71,279,139 | 71,279,380 | Do anonymous lambdas maintain their address across calls? | I have some code where I need to create unique-ids in some function to track
some objects manipulated by that function. I thought about using the address of a callback which the function expects.
The callbacks passed to the function are anonymous lambdas.
I call this function in many different places and, in every place, each lambda maintains its address across calls.
That is, even though the lambdas are temporary, each individual lambda has its same address every time it's passed to the function.
This is nice, for my use case. But, why do they have the same address, and not a new one every time? Most importantly, is this reliable across compilers?
Compiler: MSVC 2019
// A method within some class.
void Method() {
// Helper lambda
auto makeSignal = [this](State& state, Data& data, int foo, auto&& onClick) {
DoMakeSignal(state, data, true, foo, 3.14, std::forward<decltype(onClick)>(onClick));
};
// The unique-id will be the address of the lambda.
// Everytime this 'Method' is called, this lambda
// will have the same address. Nice, but why?
makeSignal(GetState(), GetData(), 5, [this] {
log("signal callback");
});
makeSignal(GetState(), GetData(), 42, [this] {
log("signal callback");
});
}
// In another file
void DoMakeSignal(State& state, Data&, bool, int, float, auto&& onClick) {
uintptr_t uid = reinterpret_cast<uintptr_t>(&onClick);
state.mLastObjectUid = uid;
// ...
}
| That's by pure chance. The lambda object lives only until the end of the makeSignal call and after that the address which was occupied by the object can be reused.
There is no guarantee on whether a new lambda object (or any other object) will have the same address or not.
In particular that also means that after the call to makeSignal, if onClick was stored by-pointer or by-reference, calling it will result in UB, since the object is not alive anymore.
However, each lambda expression has its own type and its own call operator function, both of which are properties that could be used to obtain a unique id to identify the specific lambda expression.
If you want unique ids of lambda expressions, and only lambda expressions, then for example the following should work:
struct id_t {};
template<typename> id_t id_var;
template<typename T> constexpr auto id = &id_var<std::remove_cvref_t<T>>;
//...
state.mLastObjectUid = id<decltype(onClick)>; // type: id_t*
|
71,280,025 | 71,280,074 | Two input types - Initializer list (C++) | I need the instance str is able to accept two diferent types. I have to use notation with {}. It should be std::initializer_list.
const UTF8String str{ };
This works:
class UTF8String {
public:
std::string inputString;
};
int main() {
const UTF8String str{ "hello" };
return 0;
}
This works:
class UTF8String {
public:
int inputInt;
};
int main() {
const UTF8String str{ 5 };
return 0;
}
But this doesn't work:
class UTF8String {
public:
std::string inputString;
int inputInt;
};
int main() {
const UTF8String str{ "hello" };
const UTF8String str{ 5 };
return 0;
}
| Not sure if the following meets yours needs, but it seems to work:
#include <iostream>
class UTF8String
{
public:
std::string inputString;
int inputInt;
UTF8String(const char s[]) : inputString(s) {}
UTF8String(int i) : inputInt(i) {}
};
int main()
{
const UTF8String str1{ "hello" };
const UTF8String str2{ 5 };
return 0;
}
|
71,280,161 | 71,287,951 | Press a keyboard key by his char value C++ | I would like to write a function that receives a char and presses it on the keyboard.
void pressKey(const char key){
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
ip.ki.wVk = //What to put here? (receives WORD of the hex value)
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));
}
How can I press the key 'a' (for example) and press it using this method or any other method?
| When simulating keyboard input for text, you should use the KEYEVENTF_UNICODE flag to send Unicode characters as-is, use virtual key codes only for non-textual keys. And you need to send 2 input events per character, one event to press the key down, and one event to release it.
For example:
void pressKey(const char key){
INPUT ip[2] = {};
ip[0].type = INPUT_KEYBOARD;
ip[0].ki.wScan = key;
ip[0].ki. dwFlags = KEYEVENTF_UNICODE;
ip[1] = ip[0];
ip[1].ki.dwFlags |= KEYEVENTF_KEYUP;
SendInput(2, ip, sizeof(INPUT));
}
That being said, since this approach requires Unicode characters, if your key will ever contain a non-ASCII character then you will need to first convert it to Unicode UTF-16, such as with MultiByteToWideChar() or equivalent, and then you can send down/up events for each UTF-16 codeunit, as shown in this answer.
|
71,281,320 | 71,281,397 | does std::map::end() return different results from different threads? | I've got this thread pool that holds a container of objects, and whenever it receives a new piece of data, it updates all the objects with the same new piece of data. The work is preallocated on the construction of the thread pool, and this work is stored in the following data member
std::map<std::thread::id, std::vector<unsigned>> m_work_schedule
So if a thread's element in this map has the elements 1,2 and 3 in its vector<unsigned>, that means it is responsible for updating the objects with indexes 1,2 and 3 every time a new data point arrives.
If I have ten objects and three threads, the work schedule might look something like this
140314357151488... 2, 5, 8,
140314365544192... 1, 4, 7,
140314373936896... 0, 3, 6, 9,
In every worker thread, it does some calculation and then adds its calculation to the shared aggregate variable. I'm confused though, because once all the threads are finished, only the final thread is supposed to put the finishing touches on the calculation. For some reason, this block is occasionally executing twice:
if( std::prev(m_work_schedule.end())->first == std::this_thread::get_id() ){
std::cout << "about to finalize from thread " << std::this_thread::get_id() << ", which supposedly is equal to " << (--m_work_schedule.end())->first << "\n";
m_working_agg = m_final_f(m_working_agg);
m_out.set_value(m_working_agg);
}
The output looks like this:
139680503645952... 2, 5, 8,
139680512038656... 1, 4, 7,
139680520431360... 0, 3, 6, 9,
about to finalize from thread 139680520431360, which supposedly is equal to 139680520431360
................
about to finalize from thread 139680503645952, which supposedly is equal to 139680503645952
terminate called after throwing an instance of 'std::future_error'
what(): std::future_error: Promise already satisfied
How can this block of code run twice, though? I am only reading from m_work_schedule, but the occasional nature of this suggests it's some sort of race condition. I'm struggling to think of any possible explanation for this, though.
Does a std::map::end() return different things in different threads?
Does one thread's reading with std::map::end() affect another thread's?**
If the last thread finalizes before all threads are finished working, can it randomly enter this block of code again?
Can thread ids change?
| I bet your problem is here
for(unsigned i=0; i< m_num_threads; ++i) {
m_threads.push_back( std::thread(&split_data_thread_pool::worker_thread, this));
most_recent_id = m_threads.back().get_id();
m_work_schedule.insert(std::pair<std::thread::id, std::vector<unsigned> >(most_recent_id, std::vector<unsigned>{}));
m_has_new_dyn_input.insert(std::pair<std::thread::id, bool>(most_recent_id, false));
}
you are starting the threads while you are still populating the m_work_schedule_map. And as far as I can see there is no lock. So you have simultaneous readers and writers
|
71,281,614 | 71,281,896 | How do I get which() to work correctly in boost spirit x3 expectation_failure? | Calling which() in expectation_failure returns a strange std::string.
How can I fix it?
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>
#include <iostream>
namespace x3 = boost::spirit::x3;
struct my_error_handler {
template <typename Iterator, typename Context>
auto on_error(Iterator&,
Iterator const&,
const x3::expectation_failure<Iterator>& x,
const Context&)
{
std::cerr << x.which() << '\n';
return x3::error_handler_result::fail;
}
};
struct test_class : my_error_handler {
};
const x3::rule<test_class, int> test{"test"};
const auto test_def = x3::expect[x3::int_];
BOOST_SPIRIT_DEFINE(test)
auto parse(std::string&& input)
{
auto first = std::cbegin(input);
const auto last = std::cend(input);
x3::error_handler<decltype(first)> error_handler{first, last, std::cerr};
const auto parser
= x3::with<x3::error_handler_tag>(std::ref(error_handler))[test];
x3::phrase_parse(std::cbegin(input), std::cend(input), parser, x3::space);
}
int main()
{
parse("a123");
}
Live on wandbox
The execution result is shown below.
N5boost6spirit2x310int_parserIiLj10ELj1ELin1EEE
| That string is the mangled type name of the parser. That's the default name if you don't supply one:
std::cerr << boost::core::demangle(x.which().c_str()) << '\n';
Now it prints Live
boost::spirit::x3::int_parser<int, 10u, 1u, -1>
If you don't want the default, supply one. You can for rules, e.g. "test":
Simplified Demo
#include <boost/spirit/home/x3.hpp>
#include <iostream>
namespace x3 = boost::spirit::x3;
namespace Parser {
x3::rule<struct test_class, int> const test{"test"};
x3::rule<struct parser_class, int> const parser{"parser"};
auto const test_def = x3::int_;
auto const parser_def = x3::skip(x3::space)[x3::expect[test]];
BOOST_SPIRIT_DEFINE(test, parser)
struct my_error_handler {
template <typename It, typename Ctx>
auto on_error(It, It, x3::expectation_failure<It> const& x, Ctx const&) const
{
std::cerr << x.which() << '\n';
return x3::error_handler_result::fail;
}
};
struct test_class : my_error_handler {};
struct parser_class : my_error_handler {};
} // namespace Parser
auto parse(std::string const input)
{
x3::parse(begin(input), cend(input), Parser::parser);
}
int main() { parse("a123"); }
Prints "test"
Even Simpler?
Those rules don't actually require DEFINE macros. Instead, perhaps use some helpers:
Live On Coliru
#include <boost/spirit/home/x3.hpp>
#include <iostream>
namespace x3 = boost::spirit::x3;
namespace Parser {
struct my_error_handler {
template <typename It, typename Ctx>
auto on_error(It, It, x3::expectation_failure<It> const& x, Ctx const&) const
{
std::cerr << "Expected: " << x.which() << '\n';
return x3::error_handler_result::fail;
}
};
template <typename T = x3::unused_type>
auto as(auto p, char const* name = typeid(decltype(p)).name())
{
struct tag : my_error_handler { };
return x3::rule<tag, T>{name} = p;
}
template <typename T>
auto mandatory(auto p, char const* name = typeid(decltype(p)).name())
{
return x3::expect[as<T>(p, name)];
}
auto const test = mandatory<unsigned>(x3::uint_, "non-negative number");
auto const parser = as(x3::skip(x3::space)[test]);
} // namespace Parser
auto parse(std::string const input)
{
x3::parse(begin(input), cend(input), Parser::parser);
}
int main() { parse("a123"); }
Prints
Expected: non-negative number
I'm sure you can vary on this theme. If you don't really emphasize attribute type coercion, perhaps you could name the helper with_errors etc.
|
71,281,628 | 71,281,668 | How is a read system call different from the istream::read function? | My Operating Systems professor was talking today about how a read system call is unbuffered while a istream::read function has a buffer. This left me a bit confused as you still make a buffer for the istream::read function when using it.
The only thing I can think of is that there are more than one buffers in the istream::read function call. Why?
What does the istream::read() function do differently from the read() function system call?
| The professor was talking about buffers internal to the istream rather than the buffer provided by the calling code where the data ends up after the read.
As an example, say you are reading individual int objects out of an istream, the istream is likely to have an internal buffer where some number of bytes is stored and the next read can be satisfied out of that rather than going to the OS. Note, however, that whatever the istream is hooked to very likely has internal buffers as well. Most OSes have means to perform zero-copy reads (that is, read directly from the I/O source to your buffer), but that facility comes with severe restrictions (read size must be multiple of some particular number of bytes, and if reading from a disk file the file pointer must also be on a multiple of that byte count). Most of the time such zero-copy reads are not worth the hassle.
|
71,281,818 | 71,281,892 | How is argv passed to the new process image with execvp()? | The man page does not seem to specify how this is done. I am confused particularly because of this line from here: The argv[] and envp[] arrays of pointers and the strings to which those arrays point shall not be modified by a call to one of the exec functions, except as a consequence of replacing the process image.
Are the argument arrays copied somewhere before the process image is replaced? That line seems to imply that they are always modified because the process image is always replaced.
I see that the document also says the following: The statement about argv[] and envp[] being constants is included to make explicit to future writers of language bindings that these objects are completely constant.
I feel like this could help my understanding but I'm not entirely sure exactly what they are saying is constant here.
In addition I would like to know why it is good or bad to cast the constant c_str() from std::string to pass to execvp() in the argv.
Thanks.
| exec() functions can fail, and return an error indication. This occurs in the calling process, and the calling process continues to run. In this case, exec() simply fails, just like any other system call, like open() or read() can fail. It's just a failed system call.
All that what you quoted means is that in this event the strings that were passed into exec() do not get modified. Upon return from exec() their content remains unaltered by the exec() call itself.
That line seems to imply that they are always modified because the process
image is always replaced
No, the process image is not always replaced. If you pass in a pathname to exec() which does not exist, it should be apparent that it can't possibly be replaced by anything, and an error gets returned.
|
71,281,986 | 71,282,054 | Linked list search function not working properly | I am making a LinkedList class in C++ with its methods, like adding nodes, traversing, and searching. When implementing the search function, it seems not working properly because it does not find the value in linked list when in fact it is inside the linked list. The code is shown below.
#include <iostream>
class Node {
public:
int value;
Node* next;
Node(int value, Node* next) {
this->value = value;
this->next = next;
}
};
class LinkedList {
public:
Node* head;
Node* tail;
LinkedList() {
this->head = nullptr;
this->tail = nullptr;
}
LinkedList(Node* node) {
this->head = node;
this->tail = node;
}
void addNodeFront(Node* node) {
if(head==nullptr && tail==nullptr) {
this->head = node;
this->tail = node;
return;
}
this->tail = this->head;
this->head = node;
node->next = tail;
}
void addNodeBack(Node* node) {
if(head==nullptr && tail==nullptr) {
this->head = node;
this->tail = node;
return;
}
this->tail->next = node;
this->tail = node;
}
void addNodeAfterNode(Node* prevNode, Node* node) {
node->next = prevNode->next;
prevNode->next = node;
}
bool searchVal(int val) {
while(this->head != nullptr) {
if(this->head->value == val) return true;
this->head = this->head->next;
}
return false;
}
void deleteNode(Node* node) {
Node* prevNode = this->head;
while(prevNode->next != node) {
}
}
void traverseLinkedList() {
while(this->head!=nullptr) {
std::cout << this->head->value << "->";
this->head = this->head->next;
}
std::cout << "\n";
}
void sortLinkedList() {
}
};
int main() {
Node node1(2,nullptr);
Node node2(4,nullptr);
Node node3(3,nullptr);
LinkedList ls;
ls.addNodeFront(&node1);
ls.addNodeBack(&node3);
ls.addNodeAfterNode(&node3, &node2);
ls.traverseLinkedList();
if(ls.searchVal(4)) std::cout << "value found\n";
else std::cout << "value not found\n";
}
When I call the searchVal() function inside the main function it outputs value not found while value 4 is inside the linked list. What is wrong with my code?
|
When I call the searchVal() function inside the main function it
outputs value not found while value 4 is inside the linked list. What
is wrong with my code?
Just before you call searchVal(4) you call traverseLinkedList(), and traverseLinkedList() is implemented in such a way that when it returns, this->head will be NULL, which means that at that point your linked list is empty (and you have leaked memory). You'll want to modify traverseLinkedList() and searchVal() to not change the value of this->head (or any other member-variables of the LinkedList object) so that they don't modify the state of the list as a side effect.
|
71,281,993 | 71,283,087 | How to find the maximum difference of an array and print the numbers that gave the difference? | I've been trying to get into coding and need some help with my code. I figured out how to get the maximum difference, but I also want to print the numbers used to get that difference. For example, a-b=diff, I want to print a, b, and diff separately. My friend also challenged me to get the smaller value first, then get the bigger value. Now, once I pick a certain element in the array as the smallest number, I'm only allowed to pick through the next elements for the biggest number. For example, if the array is {2, 3, 4, 15, 8, 1}, it should be 15 - 2, not 15 - 1.
Here is my code to get the maximum difference/what I have so far:
#include <iostream>
using namespace std;
int maximum_difference(int arr[], int n)
{
int max_num = arr[1];
int min_num = arr[0];
int max_difference = max_num - min_num;
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if (arr[j] - arr[i] > max_difference)
{
max_num=arr[j];
min_num=arr[i];
max_difference = max_num - min_num;
}
}
}
return max_difference;
}
int main()
{
int n;
cout<<"elements: ";
cin >> n;
int arr[n];
for(int i=0; i<n; i++)
{
cin >> arr[i];
}
cout << "Maximum difference is " << maximum_difference(arr, n);
return 0;
}
What should I add or replace, so that I could cout max_num and min_num together with the max_difference?
| I will address the algorithm part of this. The C++ part doesn't interest me; once you see the solution you'll know why.
We must choose indices i and j such that i <= j and a[j] - a[i] is maximized.
Your example sequence:
a = [2, 3, 4, 15, 8, 1]
Find the incremental maximum values starting from the right. (Most readers will immediately get the rest of the solution given this one hint).
maxs = [15, 15, 15, 15, 8, 1]
Find the incremental minimum values starting from the left.
mins = [2, 2, 2, 2, 2, 1]
Subtract them to find the greatest possible differences.
diffs = [13, 13, 13, 13, 6, 0]
The maximum element in this array, 13 is the largest value of a[j] - a[i] possible.
To find the actual values of i and j we store the indices of our best value for i and indices for the corresponding best value for j.
bestj = [3, 3, 3, 3, 4, 5]
besti = [0, 0, 0, 0, 0, 5]
We can compute the best difference the same way as before, but indirectly via the indices. For each k, diffs[k] = a[bestj[k]] - a[besti[k]] which still produces the same diffs as before:
diffs = [13, 13, 13, 13, 6, 0]
And when we find the index of the maximum diff, any such index will do. There may be multiple solutions, but this will find one solution (values for i and j) that produces a maximal result. Suppose we identify index k as having the maximal value 13, theni = besti[k] and j = bestj[k].
And therefore one solution is i = 0 and j = 3.
confirm:
a = [2, 3, 4, 15, 8, 1]
^i ^^j
i = 0
j = 3
a[i] = 2
a[j] = 15
a[j] - a[i] = 13
So again, I'm not going to provide the code, but if you can write a loop to scan from right to left computing incremental maximums as you go (as shown above), then you can code it up easily.
|
71,282,079 | 71,282,549 | Why isn't break good enough? | C++
When I first ran this code with a different input value of 881, 643, 743, etc... which are all primes numbers, I got a result of "True" but when I input a higher number like 804047277, it came back as "True" when it should have been "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
I corrected my code (The code below) and received the correct answer, which was "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
return 0;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
Shouldn't the break in the if statement stop the loop overall? I am just trying to understand why the break wasn't good enough, and I had to return 0;
| I would correct your code like following (see description afterwards):
Try it online!
#include <iostream>
int main() {
int num = 0;
std::cin >> num;
for (int i = 2; i < num; ++i)
if (num % i == 0) {
std::cout << "True (Composite)" << std::endl;
return 0;
}
std::cout << "False (Prime)" << std::endl;
return 0;
}
Input:
804047277
Output:
True (Composite)
As it is easy to understand, your program is intended to check primality and compositness of a number.
Mistake in your program is that you show False (Prime) when division by a very first i gives non-zero remainder. Instead, to actually check primality, you need to divide by all possible i and only if ALL of them give non-zero, then number is prime. It means that you shouldn't break or show False on very first non-zero remainder.
If ANY of i gives zero remainder then given number by definition is composite. So unlike the Prime case, this Composite case should break (or return) on very first occurance of zero remainder.
In code above on very first zero remainder I finish program showing to console that number is composite (True).
And only if whole loop finishes (all possible divisors are tested) then I show False (that number is prime).
Regarding question if break; is enough to finish a loop, then Yes, after break loop finishes and you don't need to return 0; after break, this return statement never finishes.
Also it is well known fact that it is enough to check divisibility until divisor equal to Sqrt(num), which will be much faster. So your loop for (int i = 2; i < num; ++i) should become for (int i = 2; i * i <= num; ++i) which is square times faster.
|
71,282,367 | 71,282,579 | How to overload a template function where a parameter could be a vector of any kind | I have a class test which has a vector that contains a bunch of strings. I want to be able to either return the very first value in the vector as any type or an entire vector of any type. (So I could return the first value as an int or the entire data vector as a vector of ints)
What I have right now does not work and I am looking for help overloading the functions:
class test
{
public:
std::string name;
std::vector<std::string> data;
test(const std::string& n) : name(n) {}
void add_data(const std::string& s)
{
data.push_back(s);
}
// return first element of data
template<typename T>
T get()
{
return convert<T>(data[0]); //converts data[0] to appropriate type
}
//return a vector of any type
template<typename T>
std::vector<T> get<std::vector<T>>()
{
std::vector<T> ret_vector;
for (std::string s : data)
{
ret_vector.push_back(convert<T>(s));
}
return ret_vector;
}
};
int main(int argc, char* argv[])
{
test a("first");
test b("second");
a.add_data("2");
b.add_data("bob");
b.add_data("john");
a.get<std::string>();
a.get<int>();
b.get<std::vector<std::string>>();
}
I just am not sure how to properly overload the second get() function. I also think I am doing partial specialization which I have found out is not allowed. Anyway I can get my desired behavior? Right now I get:
test.cpp:30:23: error: expected initializer before ‘<’ token
30 | std::vector<T> get<std::vector<T>>()
| ^
Any help much appreciated.
| I found a solution from a related post which I could not find before...
template <typename T>
T get()
{
return get_helper((T*)0);
}
//return a single value
template <typename T>
T get_helper(T*)
{
return convert<T>(data[0]);
}
//return vector of values
template <typename T>
std::vector<T> get_helper(std::vector<T> *)
{
std::vector<T> ret_vector;
for (const std::string s : data)
ret_vector.push_back(convert<T>(s));
return ret_vector;
}
The related post: ambiguous template overload for template parameter is a container
|
71,282,379 | 71,282,608 | when writing a function in C/C++ that uses inline assembly (x86-64), is it safe to choose any GPRs (rax to r15) when want to? | I'm new to the concept of writing functions that contains inline assembly in C/C++ and I want to know if it's safe to use all of the available general purpose registers. (from rax to r15)
In my knowledge, all of the variables/objects/data are actually stored in the main memory, and it is only loaded in the registers when we are performing operations with it, because of this I assume that it is actually safe to use any of the GP registers with inline assembly inside a function but I'm not sure about it.
I'm worried if it's possible that there might be a case where some registers are still used outside of the function and when that function is invoked those register's value might be overwritten and might case some errors possibly in the program?
Is there any registers that I should avoid when writing inline assembly?
| No, it is not correct that "data are actually stored in the main memory, and it is only loaded in the registers when we are performing operations with it". Compilers work very hard to keep data in the registers and only spill to memory if required.
You have to tell the compiler about all the registers you use in the inline assembly, so it can ensure that they are available for you. None of the registers are available to use freely.
To indicate to the compiler that you are modifying the contents of registers, you list them as outputs or in the clobber list.
|
71,283,266 | 73,921,590 | Auto-deduction of reference template argument from not-reference type in C++ | In the following program there are
struct A<int> template, and
function template f<I> having const int& template argument, and A<I> function argument:
template<int>
struct A {};
template<const int & I>
void f(A<I>) {}
int main() {
const static int a = 0;
f<a>(A<a>{}); // ok in GCC and Clang
f(A<a>{}); // ok in GCC
}
The function can be called explicitly specifying template argument <a> in GCC and Clang.
But auto-deduction of template argument works only in GCC, while Clang complains:
error: no matching function for call to 'f'
note: candidate template ignored: could not match 'const int' against 'int'
Demo: https://gcc.godbolt.org/z/G86dxh9jo
Which compiler is right here?
| I'm pretty sure Clang is right.
According to [temp.deduct.call]/4
In general, the deduction process attempts to find template argument values that will make the deduced A identical to A (after the type A is transformed as described above). However, there are three cases that allow
a difference: [...]
A is the transformed argument type used in the call. The transformations referred to include certain conversions (e.g. array to pointer decay) that are not relevant here. Importantly, only the type A can be considered for the deduction (not the form of the actual argument), and the type A is A<0>. From the type A<0>, how can GCC deduce what the template parameter I (of type const int&) should be?
It can't be a reference to a, because the fact that the 0 came from a is not part of the type of the argument A<a>{}. I think GCC is materializing a temporary and taking I as a reference to that temporary. But [temp.arg.nontype]/3.1 bans this, so the result ought to be a deduction failure.
|
71,283,739 | 71,284,022 | Bit fetching with type punning. Unexpected behaviour | Expected result
The program simply prints anyNum in its binary representation.
We accomplish this by "front popping" the first bit of value and sending it to standard output.
After ≤32 iterations i (=anyNum) will finally fall down to zero. Loop ends.
Problem
The v1 version of this code produces the expected result (111...),
However, in v2, when I used a mask structure to get the first bit, it worked as if the last bit was grabbed (1000...).
Maybe not the last? Anyway why and what is happing in second version of the code?
#include <iostream>
typedef struct{
unsigned b31: 1;
unsigned rest: 31;
} mask;
int main()
{
constexpr unsigned anyNum= -1; //0b111...
for (unsigned i= anyNum; i; i<<=1){
unsigned bit;
//bit= (i>>31); //v1
bit= ((mask*)&i)->b31; //v2 (unexpected behaviour)
std::cout <<bit;
}
}
Environment
IDE & platform: https://replit.com/
Platform: Linux-5.11.0-1029-gcp-x86_64-with-glibc2.27
Machine: x86_64
Compilaltion command: clang++-7 -pthread -std=c++17 -o main main.cpp
| unsigned b31: 1; is the least significant bit.
Maybe not the last?
The last.
why
Because the compiler chose to do so. The order is whatever compiler decides to.
For example, on GCC the order of bits in bitfields is controlled with BITS_BIG_ENDIAN configuration options.
x86 ABI specifies that bit-fields are allocated from right to left.
what is happing in second version of the code?
Undefined behavior, as in, the code is invalid. You should not expect the code to do anything sane. The compiler happens to generate code that is printing the least significant bit from i.
|
71,283,876 | 71,284,067 | function return 2D vector gives Segmentation Fault | I'm trying to get some data and push them into a 2d vector (schedule) in getting_schedule function. In the function, when it reaches the return statement, raises segmentation fault.
I tried resizing the vector but it didn't make a change.
I'm aware that num_of_schedule should not be more than 479 and program raises the error despite of small values for num_of_schedule.
vector<vector<int>> getting_schedule(int &num_of_schedule)
{
int duration;
int period_ID;
int schedule_counter;
vector <vector<int>> schedule(480, vector<int>(2));
while (cin >> duration >> period_ID)
{
schedule[num_of_schedule][0] = duration;
schedule[num_of_schedule][1] = period_ID - 1;
num_of_schedule++;
}
return schedule;
}
int main()
{
vector <vector<int>> input_schedule(480, vector<int>(2));
int num_of_schedules = 0;
input_schedule = getting_schedule(num_of_schedules);
return 0;
}
| Following the recommendation of @WhozCraig
And if you know the inner dimension is always 2, I'd use std::array for that.
I made the following MCVE on coliru:
#include <array>
#include <iostream>
#include <vector>
int main()
{
std::vector<std::array<int, 2>> input;
for (int value1, value2; std::cin >> value1 >> value2;) {
input.emplace_back();
input.back()[0] = value1;
input.back()[1] = value2;
}
std::cout
<< "input[" << input.size() << "]:\n";
for (const std::array<int, 2>& values : input) {
std::cout << " " << values[0] << ", " << values[1] << '\n';
}
}
Input:
1 2 3 4 5 6 7 8
Output:
input[4]:
1, 2
3, 4
5, 6
7, 8
|
71,284,058 | 71,284,975 | Fallback for "std::ostream" and "<<" operator using SFINAE and templates in C++17 | I'm using Catch2 with TEST_CASE blocks from within I sometimes declare local temporary struct for convenience. These struct sometimes needs to be displayed, and to do so Catch2 suggests to implement the << operator with std::ostream. Unfortunately, this becomes quite complicated to implement with local-only struct because such operator can't be defined inline nor in the TEST_CASE block.
I thought of a possible solution which would be to define a template for << which would call toString() instead if that method exists:
#include <iostream>
#include <string>
template <typename T>
auto operator<<(std::ostream& out, const T& obj) -> decltype(obj.toString(), void(), out)
{
out << obj.toString();
return out;
}
struct A {
std::string toString() const {
return "A";
}
};
int main() {
std::cout << A() << std::endl;
return 0;
}
I have a few questions:
Is the decltype trick modern C++ or can we achieve the same using <type_traits> instead?
Is there a way to require for the toString() returned value to be a std::string and thus disable the template substitution otherwise?
Is it guaranteed that a class with a concrete implementation of operator<< will be prioritized over the template if it exists?
Also, I find this solution to be quite fragile (I get errors when compiling my overall project although this simple snippet works), and I think it can lead to errors because of its implicit nature. Unrelated classes may define toString() method without expecting it to be used in << template substitution.
I thought it might be cleaner to do this explicitly using a base class and then SFINAE:
#include <iostream>
#include <string>
#include <type_traits>
struct WithToString {};
template <typename T, typename = std::enable_if_t<std::is_base_of_v<WithToString, T>>>
std::ostream& operator<<(std::ostream& out, const T& obj)
{
out << obj.toString();
return out;
}
struct A : public WithToString {
std::string toString() const {
return "A";
}
};
int main() {
std::cout << A() << std::endl;
return 0;
}
The downside of this solution is that I can't define toString() as a virtual method in the base class otherwise it prevents aggregate initialization (which is super-useful for my test cases). Consequently, WithToString is just an empty struct which serves as a "marker" for std::enable_if. It does not bring any useful information by itself, and it requires documentation to be properly understood and used.
What are your thoughts on this second solution? Can this be improved somehow?
I'm targeting C++17 so I can't use <concepts> yet unfortunately. Also I would like to avoid using the <experimental> header (although I know it contains useful stuff for C++17).
| You can think of both methods as "operator<< on all types with some property".
The first property is "has a toString()" method (and will work in C++11 even. This is still SFINAE, in this case the substitutions are in the return type). You can make it check that toString() returns a std::string with a different style of SFINAE:
template <typename T, std::enable_if_t<
std::is_same_v<std::decay_t<decltype(std::declval<const T&>().toString())>, std::string>,
int> = 0>
std::ostream& operator<<(std::ostream& out, const T& obj)
{
out << obj.toString();
return out;
}
And a non-template operator<< will always be chosen before this template. A more "specialized" template will also be chosen before this one. The rules for overload resolution are a bit complex, but they can be found here: https://en.cppreference.com/w/cpp/language/overload_resolution#Best_viable_function
The second property is "derives from WithToString". As you guessed, this one is more "explicit", and it is harder to accidentally/unexpectedly use the operator<<.
You can actually define the operator inline, with a friend function:
struct A {
std::string toString() const {
return "A";
}
friend std::ostream& operator<<(std::ostream& os, const A& a) {
return os << a.toString();
}
};
And you could also have this friend declaration in WithToString, making it a self-documenting mixin
template<typename T> // (crtp class)
struct OutputFromToStringMixin {
friend std::ostream& operator<<(std::ostream& os, const T& obj) {
return os << obj.toString();
}
};
struct A : OutputFromToStringMixin<A> {
std::string toString() const {
return "A";
}
};
|
71,284,228 | 71,284,626 | Writing contents of an STL Map to output stream using ostream_iterator | I have a map<string, int> object and I want to use ostream_iterator to write the contents of it to the screen or a file. I have overloaded output operator (operator<<) so that it can be used to write objects of type pair<const string, int> to an output stream, but when I try to compile the code I get the following error message:
error: no match for ‘operator<<’ (operand types are
‘std::ostream_iterator<std::pair<const
std::__cxx11::basic_string, int> >::ostream_type’ {aka
‘std::basic_ostream’} and ‘const std::pair<const
std::__cxx11::basic_string, int>’)
207 | *_M_stream << __value;
I ended up using for_each function to write the contents, but I was curious to find out if there's a way to use the stream iterator to do the job.
Here's an excerpt of the code:
typedef map<string, int>::value_type map_value_type;
ostream &operator<<(ostream &out, const map_value_type &value) {
out << value.first << " " << value.second;
return out;
}
int main() {
map<string, int> m;
// code to fill the map
// The following works with no problem
for_each(m.begin(), m.end(), [](const map_value_type &val) { cout << val << endl; });
// This line will not compile
copy(m.begin(), m.end(), ostream_iterator<map_value_type>(cout, "\n"));
}
Curiously, when I force the compiler to give the full type names of parameters used in the operator<< function above, they exactly match the types mentioned in the error message, but for some reason compiler does not recognize to use it. I'm using g++ (Ubuntu 9.3.0-17ubuntu1~20.04) with -std=gnu++17 flag, but Visual Studio compiler (cl.exe version 19.29.30140) will give the same error.
I have also tried the following for operator<< without any success:
ostream &operator<<(ostream &out, const pair<string, int> &val);
ostream &operator<<(ostream &out, const pair<const string, int> &val);
ostream &operator<<(ostream &out, pair<const string, int> &val);
ostream &operator<<(ostream &out, pair<string, int> val);
ostream &operator<<(ostream &out, pair<const string, int> val);
template <typename key, typename value>
ostream &operator<<(ostream &out, const pair<key, value> &val) { ... }
All of the above mentioned functions work with the for_each approach, but none of them work with ostream_iterator.
What am I missing?!
| std::ostream_iterator uses << internally.
When it is instantiated for a type, << will find operator<< overloads only via argument-dependent lookup from the point of instantiation, not via normal unqualified name lookup.
For type pair<const string, int> (the element type of map<string, int>) the namespace considered for argument-dependent lookup is only ::std, because both pair and string are defined in it. Your overload in the global namespace will not be considered.
If you had a type like pair<MyClass, int>, where MyClass is a class you defined yourself at global scope, the overload would work, because then the global namespace scope would be part of argument dependent lookup as associated namespace of the template argument MyClass.
The version using a lambda works because it does normal unqualified lookup from the point of definition of the lambda as well, which finds the overload in the global namespace.
Unfortunately, as far as I am aware, there is no standard-conform way to overload operator<< for a standard library container specialization which doesn't depend on a custom type, so that it will be found via ADL e.g. by std::ostream_iterator.
Standard-conform is the issue, since the standard forbids adding overloads of operator<< to namespace std, which otherwise would technically solve the issue.
|
71,284,270 | 71,285,042 | Is there a way to access QMainWindowPrivate or QMainWindowLayout? | I'm using Qt5 and I am trying to do this:
setCentralWidget(wid);
...
setCentralWidget(nullptr); // i don't want it to do deleteLater() for my wid variable
...
setCentralWidget(wid);
The problem is that, when I call setCentralWidget(nullptr), it does deleteLater() for my wid variable.
So, I found a way to use setCentralWidget() without deleting the wid variable:
Q_D(QMainWindow);
d->layout->setCentralWidget(nullptr);
But the question is: How to use private headers or widgets or whatever? I mean, I don't have access to QMainWindowPrivate or QMainWindowLayout, because they are private. So is there a way to access them?
| OP's issue is caused by using setCentralWidget(nullptr);.
QMainWindow::setCentralWiget():
Sets the given widget to be the main window's central widget.
Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time.
(Emphasis mine.)
Hence, for
setCentralWidget(wid);
...
setCentralWidget(nullptr);
it has to be expected that the QMainWindow will delete the wid. Otherwise, the wid instance could become orphaned i.e. a memory leak.
However, OPs issue can be solved without adventurous accesses to internals of QMainWindow (which is neither intended nor necessary).
In fact, there is an alternative to remove the central widget and take over the ownership again – QMainWindow::takeCentralWidget():
Removes the central widget from this main window.
The ownership of the removed widget is passed to the caller.
(Emphasis mine, again.)
An MCVE to demonstrate this:
#include <QtWidgets>
// main application
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// setup GUI
QMainWindow qWinMain;
qWinMain.setWindowTitle("QMainWindow::takeCentralWidget");
QLabel *pQLbl = new QLabel("The\ncentral\nwidget");
pQLbl->setAlignment(Qt::AlignCenter);
qWinMain.setCentralWidget(pQLbl);
qWinMain.show();
QTimer qTimer;
qTimer.setInterval(1000);
uint n = 10;
// install signal handlers
QObject::connect(&qTimer, &QTimer::timeout,
[&]() {
--n;
if (!n) {
qWinMain.setCentralWidget(nullptr);
app.quit();
} else if (n & 1) qWinMain.setCentralWidget(pQLbl);
else qWinMain.takeCentralWidget();
});
// runtime loop
qTimer.start();
return app.exec();
}
Output:
|
71,284,661 | 71,284,755 | C++ Why wrong override method get called | I define 2 classes
class BaseA {
public:
virtual void methodA() = 0;
};
class BaseB {
public:
virtual void methodB(int val) = 0;
};
Child inherits 2 Base Class
class Child : public BaseA, public BaseB {
public:
void methodA() override {
printf("Child A\n");
}
void methodB(int val) override {
printf("Child B %d\n", val);
}
};
Then I write following code.
void callBaseB(void *p) {
BaseB *b = (BaseB *) p;
b->methodB(0);
}
int main() {
auto child = new Child;
callBaseB(child);
return 0;
}
console print
Child A
Why this happened? Why not call method B?
(This is what happend when a Java engineer try to write C++ code)
| You should just do this: void callBaseB(BaseB *p) {p->methodB(0);}.
If you want to keep void *p as a parameter, you need to cast it to exactly Child * first. Either:
BaseB *b = (Child *)p;
b->methodB(0);
Or:
Child *b = (Child *)p;
b->methodB(0);
Alternatively, cast to BaseB * before converting to void *. Then casting from void * back to Base * will work.
What happens here is that the BaseB subobject is at non-zero offset inside of Child.
When you convert Child * to BaseB * (either explicitly with a cast, or implicitly, either by assigning pointers or by calling a method of BaseB on the pointer), the compiler automatically offsets the pointer by the required amount, to point to the BaseB subobject.
The offset is determined entirely at compile-time (unless virtual inheritance is involved), based on the two types.
When you obscure the source type using void *, the compiler has no way to determine the correct offset, and doesn't even try to apply any offset, so you get weird behavior, because the resulting BaseB * doesn't point to a BaseB instance, but rather to some junk inside of Child.
Even with virtual inheritance, despite the offset being determined at runtime, the calculation depends on the source pointer type being known.
|
71,284,775 | 71,284,912 | SFINAE does not work in a non-type template class | I want to use SFINAE to select specific function to be compiled in a template class with non-type
argument, here is how i do it:
#include<iostream>
#include<type_traits>
template <bool T>
struct is_right
{
template <class Q = std::bool_constant<T>>
typename std::enable_if<std::is_same<Q, std::bool_constant<true>>::value, bool>::type check()
{
return true;
}
template <class Q = std::bool_constant<!T>>
typename std::enable_if<std::is_same<Q, std::bool_constant<false>>::value, bool>::type check()
{
return false;
}
};
int main() {
is_right<false> is_fs;
is_right<true> is_ri;
if(!is_fs.check() && is_ri.check()){
std::cout << "It is right!" << std::endl;
}
return 0;
}
I compile it with g++ 8.1.0 using c++17 standard.
But the compliler gives me a error said "no matching function for call to 'is_right::check()'".
However if I just substitue the non-type template argument with a type argument, it works:
#include<iostream>
#include<type_traits>
template <class T>
struct is_right
{
template <class Q = T>
typename std::enable_if<std::is_same<Q, std::bool_constant<true>>::value, bool>::type check()
{
return true;
}
template <class Q = T>
typename std::enable_if<std::is_same<Q, std::bool_constant<false>>::value, bool>::type check()
{
return false;
}
};
int main() {
is_right<std::bool_constant<false>> is_fs;
is_right<std::bool_constant<true>> is_ri;
if(!is_fs.check() && is_ri.check()){
std::cout << "It is right!" << std::endl;
}
return 0;
}
Is there any essential difference between them?
| The default template parameter for the second check function is wrong, it should be std::bool_constant<T> and not std::bool_constant<!T>.
The call is_fs.check() has no matching function, because you're testing is_same<bool_constant<false>, bool_constant<true>> in the first overload and is_same<bool_constant<true>, bool_constant<false>> in the second overload.
Also note that right now the call is_ri.check() is ambiguous, because both check functions are valid in is_right<true>.
|
71,285,018 | 71,285,146 | Why is stod() shortening the number I am converting from string to double? | I am trying to convert a string to a double, however when i use stod() the double has lost some of it's decimal places.
Here is the relevant code :
cout << line3 << endl;
float temp = stod(line3);
cout << temp << endl;
For example, when line3 is "4.225308642", temp outputs as 4.22531. What is causing the shortening of the number and how can I fix it?
| There are two aspects to consider here.
First, formating on a IOStream by default has a precision of 6 significant digits. That explains your result. You can increase the precision with the manipulator setprecision.
Then, float by itself has a limited precision of about 6 decimal digits as well. Although you can display more, they will be the result of displaying a binary float as decimal, not really an increase of the precision. You can get about 15 decimal digits of precision by using double.
So combining the two, the program
#include <iostream>
#include <string>
#include <iomanip>
int main() {
std::string line3 = "4.225308642";
std::cout << line3 << '\n';
float tempf = stof(line3);
double tempd = stod(line3);
std::cout << "default: float=" << tempf << ", double=" << tempd << '\n';
std::cout << std::setprecision(20);
std::cout << "precision(20): float=" << tempf << ", double=" << tempd << '\n';
}
has for result:
4.225308642
default: float=4.22531, double=4.22531
precision(20): float=4.2253084182739257812, double=4.2253086419999998924
Note again that the last digits result of displaying a binary format. There is a precision after which you can't expect a decimal representation matching the input, and 20 is greater than that. That aspect is explained in more details here.
|
71,285,200 | 71,285,218 | Code not running from terminal in vs code |
Image is showing that when i used terminal to run the code, it wont run. code is running perfectly in output section, opened vs code after a month and shows this type of output in terminal
| You're just compiling the code, not running it. To run the code, type the following:
./exe_name.exe
..or in your case:
./tut4.exe
./tut5.exe
If you're using a mac machine, just replace .exe with .out
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.